clang 22.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/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclGroup.h"
27#include "clang/AST/DeclObjC.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
40#include "clang/AST/Type.h"
41#include "clang/AST/TypeLoc.h"
53#include "clang/Basic/LLVM.h"
55#include "clang/Basic/Module.h"
69#include "clang/Basic/Version.h"
72#include "clang/Lex/MacroInfo.h"
73#include "clang/Lex/ModuleMap.h"
77#include "clang/Lex/Token.h"
79#include "clang/Sema/Scope.h"
80#include "clang/Sema/Sema.h"
81#include "clang/Sema/SemaCUDA.h"
82#include "clang/Sema/SemaObjC.h"
83#include "clang/Sema/Weak.h"
96#include "llvm/ADT/APFloat.h"
97#include "llvm/ADT/APInt.h"
98#include "llvm/ADT/ArrayRef.h"
99#include "llvm/ADT/DenseMap.h"
100#include "llvm/ADT/FoldingSet.h"
101#include "llvm/ADT/IntrusiveRefCntPtr.h"
102#include "llvm/ADT/STLExtras.h"
103#include "llvm/ADT/ScopeExit.h"
104#include "llvm/ADT/Sequence.h"
105#include "llvm/ADT/SmallPtrSet.h"
106#include "llvm/ADT/SmallVector.h"
107#include "llvm/ADT/StringExtras.h"
108#include "llvm/ADT/StringMap.h"
109#include "llvm/ADT/StringRef.h"
110#include "llvm/ADT/iterator_range.h"
111#include "llvm/Bitstream/BitstreamReader.h"
112#include "llvm/Support/Compiler.h"
113#include "llvm/Support/Compression.h"
114#include "llvm/Support/DJB.h"
115#include "llvm/Support/Endian.h"
116#include "llvm/Support/Error.h"
117#include "llvm/Support/ErrorHandling.h"
118#include "llvm/Support/LEB128.h"
119#include "llvm/Support/MemoryBuffer.h"
120#include "llvm/Support/Path.h"
121#include "llvm/Support/SaveAndRestore.h"
122#include "llvm/Support/TimeProfiler.h"
123#include "llvm/Support/Timer.h"
124#include "llvm/Support/VersionTuple.h"
125#include "llvm/Support/raw_ostream.h"
126#include "llvm/TargetParser/Triple.h"
127#include <algorithm>
128#include <cassert>
129#include <cstddef>
130#include <cstdint>
131#include <cstdio>
132#include <ctime>
133#include <iterator>
134#include <limits>
135#include <map>
136#include <memory>
137#include <optional>
138#include <string>
139#include <system_error>
140#include <tuple>
141#include <utility>
142#include <vector>
143
144using namespace clang;
145using namespace clang::serialization;
146using namespace clang::serialization::reader;
147using llvm::BitstreamCursor;
148
149//===----------------------------------------------------------------------===//
150// ChainedASTReaderListener implementation
151//===----------------------------------------------------------------------===//
152
153bool
155 return First->ReadFullVersionInformation(FullVersion) ||
156 Second->ReadFullVersionInformation(FullVersion);
157}
158
160 First->ReadModuleName(ModuleName);
161 Second->ReadModuleName(ModuleName);
162}
163
164void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
165 First->ReadModuleMapFile(ModuleMapPath);
166 Second->ReadModuleMapFile(ModuleMapPath);
167}
168
170 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
171 bool AllowCompatibleDifferences) {
172 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
173 AllowCompatibleDifferences) ||
174 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
175 AllowCompatibleDifferences);
176}
177
179 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
180 bool AllowCompatibleDifferences) {
181 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
182 AllowCompatibleDifferences) ||
183 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
184 AllowCompatibleDifferences);
185}
186
188 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
189 bool AllowCompatibleDifferences) {
190 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
191 AllowCompatibleDifferences) ||
192 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
193 AllowCompatibleDifferences);
194}
195
197 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
198 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
199 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
200}
201
202bool
204 bool Complain) {
205 return First->ReadFileSystemOptions(FSOpts, Complain) ||
206 Second->ReadFileSystemOptions(FSOpts, Complain);
207}
208
210 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
211 StringRef SpecificModuleCachePath, bool Complain) {
212 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
213 SpecificModuleCachePath, Complain) ||
214 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
215 SpecificModuleCachePath, Complain);
216}
217
219 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
220 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
221 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
222 Complain, SuggestedPredefines) ||
223 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
224 Complain, SuggestedPredefines);
225}
226
228 uint32_t Value) {
229 First->ReadCounter(M, Value);
230 Second->ReadCounter(M, Value);
231}
232
234 return First->needsInputFileVisitation() ||
235 Second->needsInputFileVisitation();
236}
237
239 return First->needsSystemInputFileVisitation() ||
240 Second->needsSystemInputFileVisitation();
241}
242
244 ModuleKind Kind) {
245 First->visitModuleFile(Filename, Kind);
246 Second->visitModuleFile(Filename, Kind);
247}
248
250 bool isSystem,
251 bool isOverridden,
252 bool isExplicitModule) {
253 bool Continue = false;
254 if (First->needsInputFileVisitation() &&
255 (!isSystem || First->needsSystemInputFileVisitation()))
256 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
257 isExplicitModule);
258 if (Second->needsInputFileVisitation() &&
259 (!isSystem || Second->needsSystemInputFileVisitation()))
260 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
261 isExplicitModule);
262 return Continue;
263}
264
266 const ModuleFileExtensionMetadata &Metadata) {
267 First->readModuleFileExtension(Metadata);
268 Second->readModuleFileExtension(Metadata);
269}
270
271//===----------------------------------------------------------------------===//
272// PCH validator implementation
273//===----------------------------------------------------------------------===//
274
276
277/// Compare the given set of language options against an existing set of
278/// language options.
279///
280/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
281/// \param AllowCompatibleDifferences If true, differences between compatible
282/// language options will be permitted.
283///
284/// \returns true if the languagae options mis-match, false otherwise.
285static bool checkLanguageOptions(const LangOptions &LangOpts,
286 const LangOptions &ExistingLangOpts,
287 StringRef ModuleFilename,
288 DiagnosticsEngine *Diags,
289 bool AllowCompatibleDifferences = true) {
290 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
292
293#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
294 if constexpr (CK::Compatibility != CK::Benign) { \
295 if ((CK::Compatibility == CK::NotCompatible) || \
296 (CK::Compatibility == CK::Compatible && \
297 !AllowCompatibleDifferences)) { \
298 if (ExistingLangOpts.Name != LangOpts.Name) { \
299 if (Diags) { \
300 if (Bits == 1) \
301 Diags->Report(diag::err_ast_file_langopt_mismatch) \
302 << Description << LangOpts.Name << ExistingLangOpts.Name \
303 << ModuleFilename; \
304 else \
305 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
306 << Description << ModuleFilename; \
307 } \
308 return true; \
309 } \
310 } \
311 }
312
313#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
314 if constexpr (CK::Compatibility != CK::Benign) { \
315 if ((CK::Compatibility == CK::NotCompatible) || \
316 (CK::Compatibility == CK::Compatible && \
317 !AllowCompatibleDifferences)) { \
318 if (ExistingLangOpts.Name != LangOpts.Name) { \
319 if (Diags) \
320 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
321 << Description << ModuleFilename; \
322 return true; \
323 } \
324 } \
325 }
326
327#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
328 if constexpr (CK::Compatibility != CK::Benign) { \
329 if ((CK::Compatibility == CK::NotCompatible) || \
330 (CK::Compatibility == CK::Compatible && \
331 !AllowCompatibleDifferences)) { \
332 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
333 if (Diags) \
334 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
335 << Description << ModuleFilename; \
336 return true; \
337 } \
338 } \
339 }
340
341#include "clang/Basic/LangOptions.def"
342
343 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
344 if (Diags)
345 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
346 << "module features" << ModuleFilename;
347 return true;
348 }
349
350 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
351 if (Diags)
352 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
353 << "target Objective-C runtime" << ModuleFilename;
354 return true;
355 }
356
357 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
359 if (Diags)
360 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
361 << "block command names" << ModuleFilename;
362 return true;
363 }
364
365 // Sanitizer feature mismatches are treated as compatible differences. If
366 // compatible differences aren't allowed, we still only want to check for
367 // mismatches of non-modular sanitizers (the only ones which can affect AST
368 // generation).
369 if (!AllowCompatibleDifferences) {
370 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
371 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
372 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
373 ExistingSanitizers.clear(ModularSanitizers);
374 ImportedSanitizers.clear(ModularSanitizers);
375 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
376 const std::string Flag = "-fsanitize=";
377 if (Diags) {
378#define SANITIZER(NAME, ID) \
379 { \
380 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
381 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
382 if (InExistingModule != InImportedModule) \
383 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
384 << InExistingModule << ModuleFilename << (Flag + NAME); \
385 }
386#include "clang/Basic/Sanitizers.def"
387 }
388 return true;
389 }
390 }
391
392 return false;
393}
394
395static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
396 const CodeGenOptions &ExistingCGOpts,
397 StringRef ModuleFilename,
398 DiagnosticsEngine *Diags,
399 bool AllowCompatibleDifferences = true) {
400 // FIXME: Specify and print a description for each option instead of the name.
401 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
403#define CODEGENOPT(Name, Bits, Default, Compatibility) \
404 if constexpr (CK::Compatibility != CK::Benign) { \
405 if ((CK::Compatibility == CK::NotCompatible) || \
406 (CK::Compatibility == CK::Compatible && \
407 !AllowCompatibleDifferences)) { \
408 if (ExistingCGOpts.Name != CGOpts.Name) { \
409 if (Diags) { \
410 if (Bits == 1) \
411 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
412 << #Name << CGOpts.Name << ExistingCGOpts.Name \
413 << ModuleFilename; \
414 else \
415 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
416 << #Name << ModuleFilename; \
417 } \
418 return true; \
419 } \
420 } \
421 }
422
423#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
424 if constexpr (CK::Compatibility != CK::Benign) { \
425 if ((CK::Compatibility == CK::NotCompatible) || \
426 (CK::Compatibility == CK::Compatible && \
427 !AllowCompatibleDifferences)) { \
428 if (ExistingCGOpts.Name != CGOpts.Name) { \
429 if (Diags) \
430 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
431 << #Name << ModuleFilename; \
432 return true; \
433 } \
434 } \
435 }
436#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
437 if constexpr (CK::Compatibility != CK::Benign) { \
438 if ((CK::Compatibility == CK::NotCompatible) || \
439 (CK::Compatibility == CK::Compatible && \
440 !AllowCompatibleDifferences)) { \
441 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
442 if (Diags) \
443 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
444 << #Name << ModuleFilename; \
445 return true; \
446 } \
447 } \
448 }
449#define DEBUGOPT(Name, Bits, Default, Compatibility)
450#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
451#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
452#include "clang/Basic/CodeGenOptions.def"
453
454 return false;
455}
456
457/// Compare the given set of target options against an existing set of
458/// target options.
459///
460/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
461///
462/// \returns true if the target options mis-match, false otherwise.
463static bool checkTargetOptions(const TargetOptions &TargetOpts,
464 const TargetOptions &ExistingTargetOpts,
465 StringRef ModuleFilename,
466 DiagnosticsEngine *Diags,
467 bool AllowCompatibleDifferences = true) {
468#define CHECK_TARGET_OPT(Field, Name) \
469 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
470 if (Diags) \
471 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
472 << ModuleFilename << Name << TargetOpts.Field \
473 << ExistingTargetOpts.Field; \
474 return true; \
475 }
476
477 // The triple and ABI must match exactly.
478 CHECK_TARGET_OPT(Triple, "target");
479 CHECK_TARGET_OPT(ABI, "target ABI");
480
481 // We can tolerate different CPUs in many cases, notably when one CPU
482 // supports a strict superset of another. When allowing compatible
483 // differences skip this check.
484 if (!AllowCompatibleDifferences) {
485 CHECK_TARGET_OPT(CPU, "target CPU");
486 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
487 }
488
489#undef CHECK_TARGET_OPT
490
491 // Compare feature sets.
492 SmallVector<StringRef, 4> ExistingFeatures(
493 ExistingTargetOpts.FeaturesAsWritten.begin(),
494 ExistingTargetOpts.FeaturesAsWritten.end());
495 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
496 TargetOpts.FeaturesAsWritten.end());
497 llvm::sort(ExistingFeatures);
498 llvm::sort(ReadFeatures);
499
500 // We compute the set difference in both directions explicitly so that we can
501 // diagnose the differences differently.
502 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
503 std::set_difference(
504 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
505 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
506 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
507 ExistingFeatures.begin(), ExistingFeatures.end(),
508 std::back_inserter(UnmatchedReadFeatures));
509
510 // If we are allowing compatible differences and the read feature set is
511 // a strict subset of the existing feature set, there is nothing to diagnose.
512 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
513 return false;
514
515 if (Diags) {
516 for (StringRef Feature : UnmatchedReadFeatures)
517 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
518 << /* is-existing-feature */ false << ModuleFilename << Feature;
519 for (StringRef Feature : UnmatchedExistingFeatures)
520 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
521 << /* is-existing-feature */ true << ModuleFilename << Feature;
522 }
523
524 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
525}
526
528 StringRef ModuleFilename, bool Complain,
529 bool AllowCompatibleDifferences) {
530 const LangOptions &ExistingLangOpts = PP.getLangOpts();
531 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
532 Complain ? &Reader.Diags : nullptr,
533 AllowCompatibleDifferences);
534}
535
537 StringRef ModuleFilename, bool Complain,
538 bool AllowCompatibleDifferences) {
539 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
540 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
541 Complain ? &Reader.Diags : nullptr,
542 AllowCompatibleDifferences);
543}
544
546 StringRef ModuleFilename, bool Complain,
547 bool AllowCompatibleDifferences) {
548 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
549 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
550 Complain ? &Reader.Diags : nullptr,
551 AllowCompatibleDifferences);
552}
553
554namespace {
555
556using MacroDefinitionsMap =
557 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
558using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
559
560} // namespace
561
563 DiagnosticsEngine &Diags,
564 StringRef ModuleFilename,
565 bool Complain) {
566 using Level = DiagnosticsEngine::Level;
567
568 // Check current mappings for new -Werror mappings, and the stored mappings
569 // for cases that were explicitly mapped to *not* be errors that are now
570 // errors because of options like -Werror.
571 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
572
573 for (DiagnosticsEngine *MappingSource : MappingSources) {
574 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
575 diag::kind DiagID = DiagIDMappingPair.first;
576 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
577 if (CurLevel < DiagnosticsEngine::Error)
578 continue; // not significant
579 Level StoredLevel =
580 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
581 if (StoredLevel < DiagnosticsEngine::Error) {
582 if (Complain)
583 Diags.Report(diag::err_ast_file_diagopt_mismatch)
584 << "-Werror=" + Diags.getDiagnosticIDs()
585 ->getWarningOptionForDiag(DiagID)
586 .str()
587 << ModuleFilename;
588 return true;
589 }
590 }
591 }
592
593 return false;
594}
595
598 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
599 return true;
600 return Ext >= diag::Severity::Error;
601}
602
604 DiagnosticsEngine &Diags,
605 StringRef ModuleFilename, bool IsSystem,
606 bool SystemHeaderWarningsInModule,
607 bool Complain) {
608 // Top-level options
609 if (IsSystem) {
610 if (Diags.getSuppressSystemWarnings())
611 return false;
612 // If -Wsystem-headers was not enabled before, and it was not explicit,
613 // be conservative
614 if (StoredDiags.getSuppressSystemWarnings() &&
615 !SystemHeaderWarningsInModule) {
616 if (Complain)
617 Diags.Report(diag::err_ast_file_diagopt_mismatch)
618 << "-Wsystem-headers" << ModuleFilename;
619 return true;
620 }
621 }
622
623 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
624 if (Complain)
625 Diags.Report(diag::err_ast_file_diagopt_mismatch)
626 << "-Werror" << ModuleFilename;
627 return true;
628 }
629
630 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
631 !StoredDiags.getEnableAllWarnings()) {
632 if (Complain)
633 Diags.Report(diag::err_ast_file_diagopt_mismatch)
634 << "-Weverything -Werror" << ModuleFilename;
635 return true;
636 }
637
638 if (isExtHandlingFromDiagsError(Diags) &&
639 !isExtHandlingFromDiagsError(StoredDiags)) {
640 if (Complain)
641 Diags.Report(diag::err_ast_file_diagopt_mismatch)
642 << "-pedantic-errors" << ModuleFilename;
643 return true;
644 }
645
646 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
647 Complain);
648}
649
650/// Return the top import module if it is implicit, nullptr otherwise.
652 Preprocessor &PP) {
653 // If the original import came from a file explicitly generated by the user,
654 // don't check the diagnostic mappings.
655 // FIXME: currently this is approximated by checking whether this is not a
656 // module import of an implicitly-loaded module file.
657 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
658 // the transitive closure of its imports, since unrelated modules cannot be
659 // imported until after this module finishes validation.
660 ModuleFile *TopImport = &*ModuleMgr.rbegin();
661 while (!TopImport->ImportedBy.empty())
662 TopImport = TopImport->ImportedBy[0];
663 if (TopImport->Kind != MK_ImplicitModule)
664 return nullptr;
665
666 StringRef ModuleName = TopImport->ModuleName;
667 assert(!ModuleName.empty() && "diagnostic options read before module name");
668
669 Module *M =
670 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
671 assert(M && "missing module");
672 return M;
673}
674
676 StringRef ModuleFilename,
677 bool Complain) {
678 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
680 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
681 // This should never fail, because we would have processed these options
682 // before writing them to an ASTFile.
683 ProcessWarningOptions(*Diags, DiagOpts,
684 PP.getFileManager().getVirtualFileSystem(),
685 /*Report*/ false);
686
687 ModuleManager &ModuleMgr = Reader.getModuleManager();
688 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
689
690 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
691 if (!TopM)
692 return false;
693
694 Module *Importer = PP.getCurrentModule();
695
696 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
697 bool SystemHeaderWarningsInModule =
698 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
699 Importer->Name);
700
701 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
702 // contains the union of their flags.
703 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
704 TopM->IsSystem, SystemHeaderWarningsInModule,
705 Complain);
706}
707
708/// Collect the macro definitions provided by the given preprocessor
709/// options.
710static void
712 MacroDefinitionsMap &Macros,
713 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
714 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
715 StringRef Macro = PPOpts.Macros[I].first;
716 bool IsUndef = PPOpts.Macros[I].second;
717
718 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
719 StringRef MacroName = MacroPair.first;
720 StringRef MacroBody = MacroPair.second;
721
722 // For an #undef'd macro, we only care about the name.
723 if (IsUndef) {
724 auto [It, Inserted] = Macros.try_emplace(MacroName);
725 if (MacroNames && Inserted)
726 MacroNames->push_back(MacroName);
727
728 It->second = std::make_pair("", true);
729 continue;
730 }
731
732 // For a #define'd macro, figure out the actual definition.
733 if (MacroName.size() == Macro.size())
734 MacroBody = "1";
735 else {
736 // Note: GCC drops anything following an end-of-line character.
737 StringRef::size_type End = MacroBody.find_first_of("\n\r");
738 MacroBody = MacroBody.substr(0, End);
739 }
740
741 auto [It, Inserted] = Macros.try_emplace(MacroName);
742 if (MacroNames && Inserted)
743 MacroNames->push_back(MacroName);
744 It->second = std::make_pair(MacroBody, false);
745 }
746}
747
753
754/// Check the preprocessor options deserialized from the control block
755/// against the preprocessor options in an existing preprocessor.
756///
757/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
758/// \param Validation If set to OptionValidateNone, ignore differences in
759/// preprocessor options. If set to OptionValidateContradictions,
760/// require that options passed both in the AST file and on the command
761/// line (-D or -U) match, but tolerate options missing in one or the
762/// other. If set to OptionValidateContradictions, require that there
763/// are no differences in the options between the two.
765 const PreprocessorOptions &PPOpts,
766 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
767 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
768 std::string &SuggestedPredefines, const LangOptions &LangOpts,
770 if (ReadMacros) {
771 // Check macro definitions.
772 MacroDefinitionsMap ASTFileMacros;
773 collectMacroDefinitions(PPOpts, ASTFileMacros);
774 MacroDefinitionsMap ExistingMacros;
775 SmallVector<StringRef, 4> ExistingMacroNames;
776 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
777 &ExistingMacroNames);
778
779 // Use a line marker to enter the <command line> file, as the defines and
780 // undefines here will have come from the command line.
781 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
782
783 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
784 // Dig out the macro definition in the existing preprocessor options.
785 StringRef MacroName = ExistingMacroNames[I];
786 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
787
788 // Check whether we know anything about this macro name or not.
789 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
790 ASTFileMacros.find(MacroName);
791 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
792 if (Validation == OptionValidateStrictMatches) {
793 // If strict matches are requested, don't tolerate any extra defines
794 // on the command line that are missing in the AST file.
795 if (Diags) {
796 Diags->Report(diag::err_ast_file_macro_def_undef)
797 << MacroName << true << ModuleFilename;
798 }
799 return true;
800 }
801 // FIXME: Check whether this identifier was referenced anywhere in the
802 // AST file. If so, we should reject the AST file. Unfortunately, this
803 // information isn't in the control block. What shall we do about it?
804
805 if (Existing.second) {
806 SuggestedPredefines += "#undef ";
807 SuggestedPredefines += MacroName.str();
808 SuggestedPredefines += '\n';
809 } else {
810 SuggestedPredefines += "#define ";
811 SuggestedPredefines += MacroName.str();
812 SuggestedPredefines += ' ';
813 SuggestedPredefines += Existing.first.str();
814 SuggestedPredefines += '\n';
815 }
816 continue;
817 }
818
819 // If the macro was defined in one but undef'd in the other, we have a
820 // conflict.
821 if (Existing.second != Known->second.second) {
822 if (Diags) {
823 Diags->Report(diag::err_ast_file_macro_def_undef)
824 << MacroName << Known->second.second << ModuleFilename;
825 }
826 return true;
827 }
828
829 // If the macro was #undef'd in both, or if the macro bodies are
830 // identical, it's fine.
831 if (Existing.second || Existing.first == Known->second.first) {
832 ASTFileMacros.erase(Known);
833 continue;
834 }
835
836 // The macro bodies differ; complain.
837 if (Diags) {
838 Diags->Report(diag::err_ast_file_macro_def_conflict)
839 << MacroName << Known->second.first << Existing.first
840 << ModuleFilename;
841 }
842 return true;
843 }
844
845 // Leave the <command line> file and return to <built-in>.
846 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
847
848 if (Validation == OptionValidateStrictMatches) {
849 // If strict matches are requested, don't tolerate any extra defines in
850 // the AST file that are missing on the command line.
851 for (const auto &MacroName : ASTFileMacros.keys()) {
852 if (Diags) {
853 Diags->Report(diag::err_ast_file_macro_def_undef)
854 << MacroName << false << ModuleFilename;
855 }
856 return true;
857 }
858 }
859 }
860
861 // Check whether we're using predefines.
862 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
863 Validation != OptionValidateNone) {
864 if (Diags) {
865 Diags->Report(diag::err_ast_file_undef)
866 << ExistingPPOpts.UsePredefines << ModuleFilename;
867 }
868 return true;
869 }
870
871 // Detailed record is important since it is used for the module cache hash.
872 if (LangOpts.Modules &&
873 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
874 Validation != OptionValidateNone) {
875 if (Diags) {
876 Diags->Report(diag::err_ast_file_pp_detailed_record)
877 << PPOpts.DetailedRecord << ModuleFilename;
878 }
879 return true;
880 }
881
882 // Compute the #include and #include_macros lines we need.
883 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
884 StringRef File = ExistingPPOpts.Includes[I];
885
886 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
887 !ExistingPPOpts.PCHThroughHeader.empty()) {
888 // In case the through header is an include, we must add all the includes
889 // to the predefines so the start point can be determined.
890 SuggestedPredefines += "#include \"";
891 SuggestedPredefines += File;
892 SuggestedPredefines += "\"\n";
893 continue;
894 }
895
896 if (File == ExistingPPOpts.ImplicitPCHInclude)
897 continue;
898
899 if (llvm::is_contained(PPOpts.Includes, File))
900 continue;
901
902 SuggestedPredefines += "#include \"";
903 SuggestedPredefines += File;
904 SuggestedPredefines += "\"\n";
905 }
906
907 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
908 StringRef File = ExistingPPOpts.MacroIncludes[I];
909 if (llvm::is_contained(PPOpts.MacroIncludes, File))
910 continue;
911
912 SuggestedPredefines += "#__include_macros \"";
913 SuggestedPredefines += File;
914 SuggestedPredefines += "\"\n##\n";
915 }
916
917 return false;
918}
919
921 StringRef ModuleFilename,
922 bool ReadMacros, bool Complain,
923 std::string &SuggestedPredefines) {
924 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
925
927 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
928 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
929 SuggestedPredefines, PP.getLangOpts());
930}
931
933 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
934 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
935 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
936 ModuleFilename, ReadMacros, nullptr,
937 PP.getFileManager(), SuggestedPredefines,
938 PP.getLangOpts(), OptionValidateNone);
939}
940
941/// Check that the specified and the existing module cache paths are equivalent.
942///
943/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
944/// \returns true when the module cache paths differ.
945static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
946 StringRef SpecificModuleCachePath,
947 StringRef ExistingModuleCachePath,
948 StringRef ModuleFilename,
949 DiagnosticsEngine *Diags,
950 const LangOptions &LangOpts,
951 const PreprocessorOptions &PPOpts) {
952 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
953 SpecificModuleCachePath == ExistingModuleCachePath)
954 return false;
955 auto EqualOrErr =
956 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
957 if (EqualOrErr && *EqualOrErr)
958 return false;
959 if (Diags)
960 Diags->Report(diag::err_ast_file_modulecache_mismatch)
961 << SpecificModuleCachePath << ExistingModuleCachePath << ModuleFilename;
962 return true;
963}
964
966 StringRef ModuleFilename,
967 StringRef SpecificModuleCachePath,
968 bool Complain) {
970 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath,
971 PP.getHeaderSearchInfo().getModuleCachePath(), ModuleFilename,
972 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(),
973 PP.getPreprocessorOpts());
974}
975
977 PP.setCounterValue(Value);
978}
979
980//===----------------------------------------------------------------------===//
981// AST reader implementation
982//===----------------------------------------------------------------------===//
983
984static uint64_t readULEB(const unsigned char *&P) {
985 unsigned Length = 0;
986 const char *Error = nullptr;
987
988 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
989 if (Error)
990 llvm::report_fatal_error(Error);
991 P += Length;
992 return Val;
993}
994
995/// Read ULEB-encoded key length and data length.
996static std::pair<unsigned, unsigned>
997readULEBKeyDataLength(const unsigned char *&P) {
998 unsigned KeyLen = readULEB(P);
999 if ((unsigned)KeyLen != KeyLen)
1000 llvm::report_fatal_error("key too large");
1001
1002 unsigned DataLen = readULEB(P);
1003 if ((unsigned)DataLen != DataLen)
1004 llvm::report_fatal_error("data too large");
1005
1006 return std::make_pair(KeyLen, DataLen);
1007}
1008
1010 bool TakeOwnership) {
1011 DeserializationListener = Listener;
1012 OwnsDeserializationListener = TakeOwnership;
1013}
1014
1018
1020 LocalDeclID ID(Value);
1021#ifndef NDEBUG
1022 if (!MF.ModuleOffsetMap.empty())
1023 Reader.ReadModuleOffsetMap(MF);
1024
1025 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1026 unsigned LocalDeclID = ID.getLocalDeclIndex();
1027
1028 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1029
1030 ModuleFile *OwningModuleFile =
1031 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1032 assert(OwningModuleFile);
1033
1034 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1035
1036 if (!ModuleFileIndex)
1037 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1038
1039 assert(LocalDeclID < LocalNumDecls);
1040#endif
1041 (void)Reader;
1042 (void)MF;
1043 return ID;
1044}
1045
1046LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1047 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1048 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1049 return LocalDeclID::get(Reader, MF, Value);
1050}
1051
1052std::pair<unsigned, unsigned>
1054 return readULEBKeyDataLength(d);
1055}
1056
1058ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1059 using namespace llvm::support;
1060
1061 SelectorTable &SelTable = Reader.getContext().Selectors;
1062 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1063 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1064 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1065 if (N == 0)
1066 return SelTable.getNullarySelector(FirstII);
1067 else if (N == 1)
1068 return SelTable.getUnarySelector(FirstII);
1069
1071 Args.push_back(FirstII);
1072 for (unsigned I = 1; I != N; ++I)
1073 Args.push_back(Reader.getLocalIdentifier(
1074 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1075
1076 return SelTable.getSelector(N, Args.data());
1077}
1078
1081 unsigned DataLen) {
1082 using namespace llvm::support;
1083
1085
1086 Result.ID = Reader.getGlobalSelectorID(
1087 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1088 unsigned FullInstanceBits =
1089 endian::readNext<uint16_t, llvm::endianness::little>(d);
1090 unsigned FullFactoryBits =
1091 endian::readNext<uint16_t, llvm::endianness::little>(d);
1092 Result.InstanceBits = FullInstanceBits & 0x3;
1093 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1094 Result.FactoryBits = FullFactoryBits & 0x3;
1095 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1096 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1097 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1098
1099 // Load instance methods
1100 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1101 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1103 Reader, F,
1104 endian::readNext<DeclID, llvm::endianness::little>(d))))
1105 Result.Instance.push_back(Method);
1106 }
1107
1108 // Load factory methods
1109 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1110 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1112 Reader, F,
1113 endian::readNext<DeclID, llvm::endianness::little>(d))))
1114 Result.Factory.push_back(Method);
1115 }
1116
1117 return Result;
1118}
1119
1121 return llvm::djbHash(a);
1122}
1123
1124std::pair<unsigned, unsigned>
1126 return readULEBKeyDataLength(d);
1127}
1128
1130ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1131 assert(n >= 2 && d[n-1] == '\0');
1132 return StringRef((const char*) d, n-1);
1133}
1134
1135/// Whether the given identifier is "interesting".
1136static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1137 bool IsModule) {
1138 bool IsInteresting =
1139 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1141 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1142 return II.hadMacroDefinition() || II.isPoisoned() ||
1143 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1144 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1145 II.getFETokenInfo());
1146}
1147
1148static bool readBit(unsigned &Bits) {
1149 bool Value = Bits & 0x1;
1150 Bits >>= 1;
1151 return Value;
1152}
1153
1155 using namespace llvm::support;
1156
1157 IdentifierID RawID =
1158 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1159 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1160}
1161
1163 bool IsModule) {
1164 if (!II.isFromAST()) {
1165 II.setIsFromAST();
1166 if (isInterestingIdentifier(Reader, II, IsModule))
1168 }
1169}
1170
1172 const unsigned char* d,
1173 unsigned DataLen) {
1174 using namespace llvm::support;
1175
1176 IdentifierID RawID =
1177 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1178 bool IsInteresting = RawID & 0x01;
1179
1180 DataLen -= sizeof(IdentifierID);
1181
1182 // Wipe out the "is interesting" bit.
1183 RawID = RawID >> 1;
1184
1185 // Build the IdentifierInfo and link the identifier ID with it.
1186 IdentifierInfo *II = KnownII;
1187 if (!II) {
1188 II = &Reader.getIdentifierTable().getOwn(k);
1189 KnownII = II;
1190 }
1191 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1192 markIdentifierFromAST(Reader, *II, IsModule);
1193 Reader.markIdentifierUpToDate(II);
1194
1195 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1196 if (!IsInteresting) {
1197 // For uninteresting identifiers, there's nothing else to do. Just notify
1198 // the reader that we've finished loading this identifier.
1199 Reader.SetIdentifierInfo(ID, II);
1200 return II;
1201 }
1202
1203 unsigned ObjCOrBuiltinID =
1204 endian::readNext<uint16_t, llvm::endianness::little>(d);
1205 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1206 bool CPlusPlusOperatorKeyword = readBit(Bits);
1207 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1208 bool Poisoned = readBit(Bits);
1209 bool ExtensionToken = readBit(Bits);
1210 bool HasMacroDefinition = readBit(Bits);
1211
1212 assert(Bits == 0 && "Extra bits in the identifier?");
1213 DataLen -= sizeof(uint16_t) * 2;
1214
1215 // Set or check the various bits in the IdentifierInfo structure.
1216 // Token IDs are read-only.
1217 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1219 if (!F.isModule())
1220 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1221 assert(II->isExtensionToken() == ExtensionToken &&
1222 "Incorrect extension token flag");
1223 (void)ExtensionToken;
1224 if (Poisoned)
1225 II->setIsPoisoned(true);
1226 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1227 "Incorrect C++ operator keyword flag");
1228 (void)CPlusPlusOperatorKeyword;
1229
1230 // If this identifier has a macro definition, deserialize it or notify the
1231 // visitor the actual definition is in a different module.
1232 if (HasMacroDefinition) {
1233 uint32_t MacroDirectivesOffset =
1234 endian::readNext<uint32_t, llvm::endianness::little>(d);
1235 DataLen -= 4;
1236
1237 if (MacroDirectivesOffset)
1238 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1239 else
1240 hasMacroDefinitionInDependencies = true;
1241 }
1242
1243 Reader.SetIdentifierInfo(ID, II);
1244
1245 // Read all of the declarations visible at global scope with this
1246 // name.
1247 if (DataLen > 0) {
1249 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1250 DeclIDs.push_back(Reader.getGlobalDeclID(
1252 Reader, F,
1253 endian::readNext<DeclID, llvm::endianness::little>(d))));
1254 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1255 }
1256
1257 return II;
1258}
1259
1261 : Kind(Name.getNameKind()) {
1262 switch (Kind) {
1264 Data = (uint64_t)Name.getAsIdentifierInfo();
1265 break;
1269 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1270 break;
1272 Data = Name.getCXXOverloadedOperator();
1273 break;
1275 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1276 break;
1278 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1280 break;
1285 Data = 0;
1286 break;
1287 }
1288}
1289
1291 llvm::FoldingSetNodeID ID;
1292 ID.AddInteger(Kind);
1293
1294 switch (Kind) {
1298 ID.AddString(((IdentifierInfo*)Data)->getName());
1299 break;
1303 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1304 break;
1306 ID.AddInteger((OverloadedOperatorKind)Data);
1307 break;
1312 break;
1313 }
1314
1315 return ID.computeStableHash();
1316}
1317
1318ModuleFile *
1320 using namespace llvm::support;
1321
1322 uint32_t ModuleFileID =
1323 endian::readNext<uint32_t, llvm::endianness::little>(d);
1324 return Reader.getLocalModuleFile(F, ModuleFileID);
1325}
1326
1327std::pair<unsigned, unsigned>
1331
1334 using namespace llvm::support;
1335
1336 auto Kind = (DeclarationName::NameKind)*d++;
1337 uint64_t Data;
1338 switch (Kind) {
1342 Data = (uint64_t)Reader.getLocalIdentifier(
1343 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1344 break;
1348 Data = (uint64_t)Reader
1349 .getLocalSelector(
1350 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1351 .getAsOpaquePtr();
1352 break;
1354 Data = *d++; // OverloadedOperatorKind
1355 break;
1360 Data = 0;
1361 break;
1362 }
1363
1364 return DeclarationNameKey(Kind, Data);
1365}
1366
1368ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1369 return ReadKeyBase(d);
1370}
1371
1373 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1374 using namespace llvm::support;
1375
1376 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1378 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1379 Val.insert(Reader.getGlobalDeclID(F, ID));
1380 }
1381}
1382
1384 const unsigned char *d,
1385 unsigned DataLen,
1386 data_type_builder &Val) {
1387 ReadDataIntoImpl(d, DataLen, Val);
1388}
1389
1392 llvm::FoldingSetNodeID ID;
1393 ID.AddInteger(Key.first.getHash());
1394 ID.AddInteger(Key.second);
1395 return ID.computeStableHash();
1396}
1397
1400 DeclarationNameKey Name(Key.first);
1401
1402 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1403 if (!ModuleHash)
1404 return {Name, 0};
1405
1406 return {Name, *ModuleHash};
1407}
1408
1410ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1412 unsigned PrimaryModuleHash =
1413 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1414 return {Name, PrimaryModuleHash};
1415}
1416
1418 const unsigned char *d,
1419 unsigned DataLen,
1420 data_type_builder &Val) {
1421 ReadDataIntoImpl(d, DataLen, Val);
1422}
1423
1424ModuleFile *
1426 using namespace llvm::support;
1427
1428 uint32_t ModuleFileID =
1429 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1430 return Reader.getLocalModuleFile(F, ModuleFileID);
1431}
1432
1434LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1435 using namespace llvm::support;
1436 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1437}
1438
1439std::pair<unsigned, unsigned>
1443
1445 const unsigned char *d,
1446 unsigned DataLen,
1447 data_type_builder &Val) {
1448 using namespace llvm::support;
1449
1450 for (unsigned NumDecls =
1452 NumDecls; --NumDecls) {
1453 LocalDeclID LocalID = LocalDeclID::get(
1454 Reader, F,
1455 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1456 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1457 }
1458}
1459
1460bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1461 BitstreamCursor &Cursor,
1462 uint64_t Offset,
1463 DeclContext *DC) {
1464 assert(Offset != 0);
1465
1466 SavedStreamPosition SavedPosition(Cursor);
1467 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1468 Error(std::move(Err));
1469 return true;
1470 }
1471
1472 RecordData Record;
1473 StringRef Blob;
1474 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1475 if (!MaybeCode) {
1476 Error(MaybeCode.takeError());
1477 return true;
1478 }
1479 unsigned Code = MaybeCode.get();
1480
1481 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1482 if (!MaybeRecCode) {
1483 Error(MaybeRecCode.takeError());
1484 return true;
1485 }
1486 unsigned RecCode = MaybeRecCode.get();
1487 if (RecCode != DECL_CONTEXT_LEXICAL) {
1488 Error("Expected lexical block");
1489 return true;
1490 }
1491
1492 assert(!isa<TranslationUnitDecl>(DC) &&
1493 "expected a TU_UPDATE_LEXICAL record for TU");
1494 // If we are handling a C++ class template instantiation, we can see multiple
1495 // lexical updates for the same record. It's important that we select only one
1496 // of them, so that field numbering works properly. Just pick the first one we
1497 // see.
1498 auto &Lex = LexicalDecls[DC];
1499 if (!Lex.first) {
1500 Lex = std::make_pair(
1501 &M, llvm::ArrayRef(
1502 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1503 Blob.size() / sizeof(DeclID)));
1504 }
1506 return false;
1507}
1508
1509bool ASTReader::ReadVisibleDeclContextStorage(
1510 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1511 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1512 assert(Offset != 0);
1513
1514 SavedStreamPosition SavedPosition(Cursor);
1515 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1516 Error(std::move(Err));
1517 return true;
1518 }
1519
1520 RecordData Record;
1521 StringRef Blob;
1522 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1523 if (!MaybeCode) {
1524 Error(MaybeCode.takeError());
1525 return true;
1526 }
1527 unsigned Code = MaybeCode.get();
1528
1529 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1530 if (!MaybeRecCode) {
1531 Error(MaybeRecCode.takeError());
1532 return true;
1533 }
1534 unsigned RecCode = MaybeRecCode.get();
1535 switch (VisibleKind) {
1536 case VisibleDeclContextStorageKind::GenerallyVisible:
1537 if (RecCode != DECL_CONTEXT_VISIBLE) {
1538 Error("Expected visible lookup table block");
1539 return true;
1540 }
1541 break;
1542 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1543 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1544 Error("Expected module local visible lookup table block");
1545 return true;
1546 }
1547 break;
1548 case VisibleDeclContextStorageKind::TULocalVisible:
1549 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1550 Error("Expected TU local lookup table block");
1551 return true;
1552 }
1553 break;
1554 }
1555
1556 // We can't safely determine the primary context yet, so delay attaching the
1557 // lookup table until we're done with recursive deserialization.
1558 auto *Data = (const unsigned char*)Blob.data();
1559 switch (VisibleKind) {
1560 case VisibleDeclContextStorageKind::GenerallyVisible:
1561 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1562 break;
1563 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1564 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1565 break;
1566 case VisibleDeclContextStorageKind::TULocalVisible:
1567 if (M.Kind == MK_MainFile)
1568 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1569 break;
1570 }
1571 return false;
1572}
1573
1574void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1575 ModuleFile &M, bool IsPartial) {
1576 D = D->getCanonicalDecl();
1577 auto &SpecLookups =
1578 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1579 SpecLookups[D].Table.add(&M, Data,
1581}
1582
1583bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1584 uint64_t Offset, Decl *D, bool IsPartial) {
1585 assert(Offset != 0);
1586
1587 SavedStreamPosition SavedPosition(Cursor);
1588 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1589 Error(std::move(Err));
1590 return true;
1591 }
1592
1593 RecordData Record;
1594 StringRef Blob;
1595 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1596 if (!MaybeCode) {
1597 Error(MaybeCode.takeError());
1598 return true;
1599 }
1600 unsigned Code = MaybeCode.get();
1601
1602 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1603 if (!MaybeRecCode) {
1604 Error(MaybeRecCode.takeError());
1605 return true;
1606 }
1607 unsigned RecCode = MaybeRecCode.get();
1608 if (RecCode != DECL_SPECIALIZATIONS &&
1609 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1610 Error("Expected decl specs block");
1611 return true;
1612 }
1613
1614 auto *Data = (const unsigned char *)Blob.data();
1615 AddSpecializations(D, Data, M, IsPartial);
1616 return false;
1617}
1618
1619void ASTReader::Error(StringRef Msg) const {
1620 Error(diag::err_fe_ast_file_malformed, Msg);
1621 if (PP.getLangOpts().Modules &&
1622 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1623 Diag(diag::note_module_cache_path)
1624 << PP.getHeaderSearchInfo().getModuleCachePath();
1625 }
1626}
1627
1628void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1629 StringRef Arg3) const {
1630 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1631}
1632
1633namespace {
1634struct AlreadyReportedDiagnosticError
1635 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1636 static char ID;
1637
1638 void log(raw_ostream &OS) const override {
1639 llvm_unreachable("reporting an already-reported diagnostic error");
1640 }
1641
1642 std::error_code convertToErrorCode() const override {
1643 return llvm::inconvertibleErrorCode();
1644 }
1645};
1646
1647char AlreadyReportedDiagnosticError::ID = 0;
1648} // namespace
1649
1650void ASTReader::Error(llvm::Error &&Err) const {
1651 handleAllErrors(
1652 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1653 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1654}
1655
1656//===----------------------------------------------------------------------===//
1657// Source Manager Deserialization
1658//===----------------------------------------------------------------------===//
1659
1660/// Read the line table in the source manager block.
1661void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1662 unsigned Idx = 0;
1663 LineTableInfo &LineTable = SourceMgr.getLineTable();
1664
1665 // Parse the file names
1666 std::map<int, int> FileIDs;
1667 FileIDs[-1] = -1; // For unspecified filenames.
1668 for (unsigned I = 0; Record[Idx]; ++I) {
1669 // Extract the file name
1670 auto Filename = ReadPath(F, Record, Idx);
1671 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1672 }
1673 ++Idx;
1674
1675 // Parse the line entries
1676 std::vector<LineEntry> Entries;
1677 while (Idx < Record.size()) {
1678 FileID FID = ReadFileID(F, Record, Idx);
1679
1680 // Extract the line entries
1681 unsigned NumEntries = Record[Idx++];
1682 assert(NumEntries && "no line entries for file ID");
1683 Entries.clear();
1684 Entries.reserve(NumEntries);
1685 for (unsigned I = 0; I != NumEntries; ++I) {
1686 unsigned FileOffset = Record[Idx++];
1687 unsigned LineNo = Record[Idx++];
1688 int FilenameID = FileIDs[Record[Idx++]];
1691 unsigned IncludeOffset = Record[Idx++];
1692 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1693 FileKind, IncludeOffset));
1694 }
1695 LineTable.AddEntry(FID, Entries);
1696 }
1697}
1698
1699/// Read a source manager block
1700llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1701 using namespace SrcMgr;
1702
1703 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1704
1705 // Set the source-location entry cursor to the current position in
1706 // the stream. This cursor will be used to read the contents of the
1707 // source manager block initially, and then lazily read
1708 // source-location entries as needed.
1709 SLocEntryCursor = F.Stream;
1710
1711 // The stream itself is going to skip over the source manager block.
1712 if (llvm::Error Err = F.Stream.SkipBlock())
1713 return Err;
1714
1715 // Enter the source manager block.
1716 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1717 return Err;
1718 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1719
1720 RecordData Record;
1721 while (true) {
1722 Expected<llvm::BitstreamEntry> MaybeE =
1723 SLocEntryCursor.advanceSkippingSubblocks();
1724 if (!MaybeE)
1725 return MaybeE.takeError();
1726 llvm::BitstreamEntry E = MaybeE.get();
1727
1728 switch (E.Kind) {
1729 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1730 case llvm::BitstreamEntry::Error:
1731 return llvm::createStringError(std::errc::illegal_byte_sequence,
1732 "malformed block record in AST file");
1733 case llvm::BitstreamEntry::EndBlock:
1734 return llvm::Error::success();
1735 case llvm::BitstreamEntry::Record:
1736 // The interesting case.
1737 break;
1738 }
1739
1740 // Read a record.
1741 Record.clear();
1742 StringRef Blob;
1743 Expected<unsigned> MaybeRecord =
1744 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1745 if (!MaybeRecord)
1746 return MaybeRecord.takeError();
1747 switch (MaybeRecord.get()) {
1748 default: // Default behavior: ignore.
1749 break;
1750
1751 case SM_SLOC_FILE_ENTRY:
1754 // Once we hit one of the source location entries, we're done.
1755 return llvm::Error::success();
1756 }
1757 }
1758}
1759
1760llvm::Expected<SourceLocation::UIntTy>
1762 BitstreamCursor &Cursor = F->SLocEntryCursor;
1763 SavedStreamPosition SavedPosition(Cursor);
1764 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1765 F->SLocEntryOffsets[Index]))
1766 return std::move(Err);
1767
1768 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1769 if (!MaybeEntry)
1770 return MaybeEntry.takeError();
1771
1772 llvm::BitstreamEntry Entry = MaybeEntry.get();
1773 if (Entry.Kind != llvm::BitstreamEntry::Record)
1774 return llvm::createStringError(
1775 std::errc::illegal_byte_sequence,
1776 "incorrectly-formatted source location entry in AST file");
1777
1779 StringRef Blob;
1780 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1781 if (!MaybeSLOC)
1782 return MaybeSLOC.takeError();
1783
1784 switch (MaybeSLOC.get()) {
1785 default:
1786 return llvm::createStringError(
1787 std::errc::illegal_byte_sequence,
1788 "incorrectly-formatted source location entry in AST file");
1789 case SM_SLOC_FILE_ENTRY:
1792 return F->SLocEntryBaseOffset + Record[0];
1793 }
1794}
1795
1797 auto SLocMapI =
1798 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1799 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1800 "Corrupted global sloc offset map");
1801 ModuleFile *F = SLocMapI->second;
1802
1803 bool Invalid = false;
1804
1805 auto It = llvm::upper_bound(
1806 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1807 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1808 int ID = F->SLocEntryBaseID + LocalIndex;
1809 std::size_t Index = -ID - 2;
1810 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1811 assert(!SourceMgr.SLocEntryLoaded[Index]);
1812 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1813 if (!MaybeEntryOffset) {
1814 Error(MaybeEntryOffset.takeError());
1815 Invalid = true;
1816 return true;
1817 }
1818 SourceMgr.LoadedSLocEntryTable[Index] =
1819 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1820 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1821 }
1822 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1823 });
1824
1825 if (Invalid)
1826 return 0;
1827
1828 // The iterator points to the first entry with start offset greater than the
1829 // offset of interest. The previous entry must contain the offset of interest.
1830 return F->SLocEntryBaseID + *std::prev(It);
1831}
1832
1834 if (ID == 0)
1835 return false;
1836
1837 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1838 Error("source location entry ID out-of-range for AST file");
1839 return true;
1840 }
1841
1842 // Local helper to read the (possibly-compressed) buffer data following the
1843 // entry record.
1844 auto ReadBuffer = [this](
1845 BitstreamCursor &SLocEntryCursor,
1846 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1848 StringRef Blob;
1849 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1850 if (!MaybeCode) {
1851 Error(MaybeCode.takeError());
1852 return nullptr;
1853 }
1854 unsigned Code = MaybeCode.get();
1855
1856 Expected<unsigned> MaybeRecCode =
1857 SLocEntryCursor.readRecord(Code, Record, &Blob);
1858 if (!MaybeRecCode) {
1859 Error(MaybeRecCode.takeError());
1860 return nullptr;
1861 }
1862 unsigned RecCode = MaybeRecCode.get();
1863
1864 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1865 // Inspect the first byte to differentiate zlib (\x78) and zstd
1866 // (little-endian 0xFD2FB528).
1867 const llvm::compression::Format F =
1868 Blob.size() > 0 && Blob.data()[0] == 0x78
1869 ? llvm::compression::Format::Zlib
1870 : llvm::compression::Format::Zstd;
1871 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1872 Error(Reason);
1873 return nullptr;
1874 }
1875 SmallVector<uint8_t, 0> Decompressed;
1876 if (llvm::Error E = llvm::compression::decompress(
1877 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1878 Error("could not decompress embedded file contents: " +
1879 llvm::toString(std::move(E)));
1880 return nullptr;
1881 }
1882 return llvm::MemoryBuffer::getMemBufferCopy(
1883 llvm::toStringRef(Decompressed), Name);
1884 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1885 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1886 } else {
1887 Error("AST record has invalid code");
1888 return nullptr;
1889 }
1890 };
1891
1892 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1893 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1895 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1896 Error(std::move(Err));
1897 return true;
1898 }
1899
1900 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1902
1903 ++NumSLocEntriesRead;
1904 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1905 if (!MaybeEntry) {
1906 Error(MaybeEntry.takeError());
1907 return true;
1908 }
1909 llvm::BitstreamEntry Entry = MaybeEntry.get();
1910
1911 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1912 Error("incorrectly-formatted source location entry in AST file");
1913 return true;
1914 }
1915
1917 StringRef Blob;
1918 Expected<unsigned> MaybeSLOC =
1919 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1920 if (!MaybeSLOC) {
1921 Error(MaybeSLOC.takeError());
1922 return true;
1923 }
1924 switch (MaybeSLOC.get()) {
1925 default:
1926 Error("incorrectly-formatted source location entry in AST file");
1927 return true;
1928
1929 case SM_SLOC_FILE_ENTRY: {
1930 // We will detect whether a file changed and return 'Failure' for it, but
1931 // we will also try to fail gracefully by setting up the SLocEntry.
1932 unsigned InputID = Record[4];
1933 InputFile IF = getInputFile(*F, InputID);
1935 bool OverriddenBuffer = IF.isOverridden();
1936
1937 // Note that we only check if a File was returned. If it was out-of-date
1938 // we have complained but we will continue creating a FileID to recover
1939 // gracefully.
1940 if (!File)
1941 return true;
1942
1943 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1944 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1945 // This is the module's main file.
1946 IncludeLoc = getImportLocation(F);
1947 }
1949 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1950 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1951 BaseOffset + Record[0]);
1952 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1953 FileInfo.NumCreatedFIDs = Record[5];
1954 if (Record[3])
1955 FileInfo.setHasLineDirectives();
1956
1957 unsigned NumFileDecls = Record[7];
1958 if (NumFileDecls && ContextObj) {
1959 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1960 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1961 FileDeclIDs[FID] =
1962 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1963 }
1964
1965 const SrcMgr::ContentCache &ContentCache =
1966 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1967 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1968 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1969 !ContentCache.getBufferIfLoaded()) {
1970 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1971 if (!Buffer)
1972 return true;
1973 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1974 }
1975
1976 break;
1977 }
1978
1979 case SM_SLOC_BUFFER_ENTRY: {
1980 const char *Name = Blob.data();
1981 unsigned Offset = Record[0];
1983 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1984 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1985 if (IncludeLoc.isInvalid() && F->isModule()) {
1986 IncludeLoc = getImportLocation(F);
1987 }
1988
1989 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1990 if (!Buffer)
1991 return true;
1992 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1993 BaseOffset + Offset, IncludeLoc);
1994 if (Record[3]) {
1995 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1996 FileInfo.setHasLineDirectives();
1997 }
1998 break;
1999 }
2000
2002 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2003 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2004 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2005 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2006 Record[5], Record[4], ID,
2007 BaseOffset + Record[0]);
2008 break;
2009 }
2010 }
2011
2012 return false;
2013}
2014
2015std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2016 if (ID == 0)
2017 return std::make_pair(SourceLocation(), "");
2018
2019 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2020 Error("source location entry ID out-of-range for AST file");
2021 return std::make_pair(SourceLocation(), "");
2022 }
2023
2024 // Find which module file this entry lands in.
2025 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2026 if (!M->isModule())
2027 return std::make_pair(SourceLocation(), "");
2028
2029 // FIXME: Can we map this down to a particular submodule? That would be
2030 // ideal.
2031 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2032}
2033
2034/// Find the location where the module F is imported.
2035SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2036 if (F->ImportLoc.isValid())
2037 return F->ImportLoc;
2038
2039 // Otherwise we have a PCH. It's considered to be "imported" at the first
2040 // location of its includer.
2041 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2042 // Main file is the importer.
2043 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2044 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2045 }
2046 return F->ImportedBy[0]->FirstLoc;
2047}
2048
2049/// Enter a subblock of the specified BlockID with the specified cursor. Read
2050/// the abbreviations that are at the top of the block and then leave the cursor
2051/// pointing into the block.
2052llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2053 unsigned BlockID,
2054 uint64_t *StartOfBlockOffset) {
2055 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2056 return Err;
2057
2058 if (StartOfBlockOffset)
2059 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2060
2061 while (true) {
2062 uint64_t Offset = Cursor.GetCurrentBitNo();
2063 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2064 if (!MaybeCode)
2065 return MaybeCode.takeError();
2066 unsigned Code = MaybeCode.get();
2067
2068 // We expect all abbrevs to be at the start of the block.
2069 if (Code != llvm::bitc::DEFINE_ABBREV) {
2070 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2071 return Err;
2072 return llvm::Error::success();
2073 }
2074 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2075 return Err;
2076 }
2077}
2078
2080 unsigned &Idx) {
2081 Token Tok;
2082 Tok.startToken();
2083 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2084 Tok.setKind((tok::TokenKind)Record[Idx++]);
2085 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2086
2087 if (Tok.isAnnotation()) {
2088 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2089 switch (Tok.getKind()) {
2090 case tok::annot_pragma_loop_hint: {
2091 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2092 Info->PragmaName = ReadToken(M, Record, Idx);
2093 Info->Option = ReadToken(M, Record, Idx);
2094 unsigned NumTokens = Record[Idx++];
2096 Toks.reserve(NumTokens);
2097 for (unsigned I = 0; I < NumTokens; ++I)
2098 Toks.push_back(ReadToken(M, Record, Idx));
2099 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2100 Tok.setAnnotationValue(static_cast<void *>(Info));
2101 break;
2102 }
2103 case tok::annot_pragma_pack: {
2104 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2105 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2106 auto SlotLabel = ReadString(Record, Idx);
2107 Info->SlotLabel =
2108 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2109 Info->Alignment = ReadToken(M, Record, Idx);
2110 Tok.setAnnotationValue(static_cast<void *>(Info));
2111 break;
2112 }
2113 // Some annotation tokens do not use the PtrData field.
2114 case tok::annot_pragma_openmp:
2115 case tok::annot_pragma_openmp_end:
2116 case tok::annot_pragma_unused:
2117 case tok::annot_pragma_openacc:
2118 case tok::annot_pragma_openacc_end:
2119 case tok::annot_repl_input_end:
2120 break;
2121 default:
2122 llvm_unreachable("missing deserialization code for annotation token");
2123 }
2124 } else {
2125 Tok.setLength(Record[Idx++]);
2126 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2127 Tok.setIdentifierInfo(II);
2128 }
2129 return Tok;
2130}
2131
2133 BitstreamCursor &Stream = F.MacroCursor;
2134
2135 // Keep track of where we are in the stream, then jump back there
2136 // after reading this macro.
2137 SavedStreamPosition SavedPosition(Stream);
2138
2139 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2140 // FIXME this drops errors on the floor.
2141 consumeError(std::move(Err));
2142 return nullptr;
2143 }
2146 MacroInfo *Macro = nullptr;
2147 llvm::MutableArrayRef<Token> MacroTokens;
2148
2149 while (true) {
2150 // Advance to the next record, but if we get to the end of the block, don't
2151 // pop it (removing all the abbreviations from the cursor) since we want to
2152 // be able to reseek within the block and read entries.
2153 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2155 Stream.advanceSkippingSubblocks(Flags);
2156 if (!MaybeEntry) {
2157 Error(MaybeEntry.takeError());
2158 return Macro;
2159 }
2160 llvm::BitstreamEntry Entry = MaybeEntry.get();
2161
2162 switch (Entry.Kind) {
2163 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2164 case llvm::BitstreamEntry::Error:
2165 Error("malformed block record in AST file");
2166 return Macro;
2167 case llvm::BitstreamEntry::EndBlock:
2168 return Macro;
2169 case llvm::BitstreamEntry::Record:
2170 // The interesting case.
2171 break;
2172 }
2173
2174 // Read a record.
2175 Record.clear();
2177 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2178 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2179 else {
2180 Error(MaybeRecType.takeError());
2181 return Macro;
2182 }
2183 switch (RecType) {
2184 case PP_MODULE_MACRO:
2186 return Macro;
2187
2190 // If we already have a macro, that means that we've hit the end
2191 // of the definition of the macro we were looking for. We're
2192 // done.
2193 if (Macro)
2194 return Macro;
2195
2196 unsigned NextIndex = 1; // Skip identifier ID.
2197 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2198 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2199 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2200 MI->setIsUsed(Record[NextIndex++]);
2201 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2202 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2203 PP.getPreprocessorAllocator());
2204 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2205 // Decode function-like macro info.
2206 bool isC99VarArgs = Record[NextIndex++];
2207 bool isGNUVarArgs = Record[NextIndex++];
2208 bool hasCommaPasting = Record[NextIndex++];
2209 MacroParams.clear();
2210 unsigned NumArgs = Record[NextIndex++];
2211 for (unsigned i = 0; i != NumArgs; ++i)
2212 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2213
2214 // Install function-like macro info.
2215 MI->setIsFunctionLike();
2216 if (isC99VarArgs) MI->setIsC99Varargs();
2217 if (isGNUVarArgs) MI->setIsGNUVarargs();
2218 if (hasCommaPasting) MI->setHasCommaPasting();
2219 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2220 }
2221
2222 // Remember that we saw this macro last so that we add the tokens that
2223 // form its body to it.
2224 Macro = MI;
2225
2226 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2227 Record[NextIndex]) {
2228 // We have a macro definition. Register the association
2230 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2231 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2232 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2233 PreprocessingRecord::PPEntityID PPID =
2234 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2235 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2236 PPRec.getPreprocessedEntity(PPID));
2237 if (PPDef)
2238 PPRec.RegisterMacroDefinition(Macro, PPDef);
2239 }
2240
2241 ++NumMacrosRead;
2242 break;
2243 }
2244
2245 case PP_TOKEN: {
2246 // If we see a TOKEN before a PP_MACRO_*, then the file is
2247 // erroneous, just pretend we didn't see this.
2248 if (!Macro) break;
2249 if (MacroTokens.empty()) {
2250 Error("unexpected number of macro tokens for a macro in AST file");
2251 return Macro;
2252 }
2253
2254 unsigned Idx = 0;
2255 MacroTokens[0] = ReadToken(F, Record, Idx);
2256 MacroTokens = MacroTokens.drop_front();
2257 break;
2258 }
2259 }
2260 }
2261}
2262
2265 PreprocessedEntityID LocalID) const {
2266 if (!M.ModuleOffsetMap.empty())
2267 ReadModuleOffsetMap(M);
2268
2269 unsigned ModuleFileIndex = LocalID >> 32;
2270 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2271 ModuleFile *MF =
2272 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2273 assert(MF && "malformed identifier ID encoding?");
2274
2275 if (!ModuleFileIndex) {
2276 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2277 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2278 }
2279
2280 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2281}
2282
2284HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2285 FileManager &FileMgr = Reader.getFileManager();
2286 if (!Key.Imported)
2287 return FileMgr.getOptionalFileRef(Key.Filename);
2288
2289 auto Resolved =
2290 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2291 return FileMgr.getOptionalFileRef(*Resolved);
2292}
2293
2295 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2296 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2297 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2298 return llvm::xxh3_64bits(buf);
2299}
2300
2303 internal_key_type ikey = {ekey.getSize(),
2304 M.HasTimestamps ? ekey.getModificationTime() : 0,
2305 ekey.getName(), /*Imported*/ false};
2306 return ikey;
2307}
2308
2310 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2311 return false;
2312
2313 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2314 return true;
2315
2316 // Determine whether the actual files are equivalent.
2317 OptionalFileEntryRef FEA = getFile(a);
2318 OptionalFileEntryRef FEB = getFile(b);
2319 return FEA && FEA == FEB;
2320}
2321
2322std::pair<unsigned, unsigned>
2324 return readULEBKeyDataLength(d);
2325}
2326
2328HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2329 using namespace llvm::support;
2330
2331 internal_key_type ikey;
2332 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2333 ikey.ModTime =
2334 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2335 ikey.Filename = (const char *)d;
2336 ikey.Imported = true;
2337 return ikey;
2338}
2339
2342 unsigned DataLen) {
2343 using namespace llvm::support;
2344
2345 const unsigned char *End = d + DataLen;
2346 HeaderFileInfo HFI;
2347 unsigned Flags = *d++;
2348
2350 bool Included = (Flags >> 6) & 0x01;
2351 if (Included)
2352 if ((FE = getFile(key)))
2353 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2354 // deserialize this header file info again.
2355 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2356
2357 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2358 HFI.isImport |= (Flags >> 5) & 0x01;
2359 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2360 HFI.DirInfo = (Flags >> 1) & 0x07;
2361 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2362 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2363
2364 assert((End - d) % 4 == 0 &&
2365 "Wrong data length in HeaderFileInfo deserialization");
2366 while (d != End) {
2367 uint32_t LocalSMID =
2368 endian::readNext<uint32_t, llvm::endianness::little>(d);
2369 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2370 LocalSMID >>= 3;
2371
2372 // This header is part of a module. Associate it with the module to enable
2373 // implicit module import.
2374 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2375 Module *Mod = Reader.getSubmodule(GlobalSMID);
2376 ModuleMap &ModMap =
2377 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2378
2379 if (FE || (FE = getFile(key))) {
2380 // FIXME: NameAsWritten
2381 Module::Header H = {std::string(key.Filename), "", *FE};
2382 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2383 }
2384 HFI.mergeModuleMembership(HeaderRole);
2385 }
2386
2387 // This HeaderFileInfo was externally loaded.
2388 HFI.External = true;
2389 HFI.IsValid = true;
2390 return HFI;
2391}
2392
2394 uint32_t MacroDirectivesOffset) {
2395 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2396 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2397}
2398
2400 // Note that we are loading defined macros.
2401 Deserializing Macros(this);
2402
2403 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2404 BitstreamCursor &MacroCursor = I.MacroCursor;
2405
2406 // If there was no preprocessor block, skip this file.
2407 if (MacroCursor.getBitcodeBytes().empty())
2408 continue;
2409
2410 BitstreamCursor Cursor = MacroCursor;
2411 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2412 Error(std::move(Err));
2413 return;
2414 }
2415
2417 while (true) {
2418 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2419 if (!MaybeE) {
2420 Error(MaybeE.takeError());
2421 return;
2422 }
2423 llvm::BitstreamEntry E = MaybeE.get();
2424
2425 switch (E.Kind) {
2426 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2427 case llvm::BitstreamEntry::Error:
2428 Error("malformed block record in AST file");
2429 return;
2430 case llvm::BitstreamEntry::EndBlock:
2431 goto NextCursor;
2432
2433 case llvm::BitstreamEntry::Record: {
2434 Record.clear();
2435 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2436 if (!MaybeRecord) {
2437 Error(MaybeRecord.takeError());
2438 return;
2439 }
2440 switch (MaybeRecord.get()) {
2441 default: // Default behavior: ignore.
2442 break;
2443
2447 if (II->isOutOfDate())
2449 break;
2450 }
2451
2452 case PP_TOKEN:
2453 // Ignore tokens.
2454 break;
2455 }
2456 break;
2457 }
2458 }
2459 }
2460 NextCursor: ;
2461 }
2462}
2463
2464namespace {
2465
2466 /// Visitor class used to look up identifirs in an AST file.
2467 class IdentifierLookupVisitor {
2468 StringRef Name;
2469 unsigned NameHash;
2470 unsigned PriorGeneration;
2471 unsigned &NumIdentifierLookups;
2472 unsigned &NumIdentifierLookupHits;
2473 IdentifierInfo *Found = nullptr;
2474
2475 public:
2476 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2477 unsigned &NumIdentifierLookups,
2478 unsigned &NumIdentifierLookupHits)
2479 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2480 PriorGeneration(PriorGeneration),
2481 NumIdentifierLookups(NumIdentifierLookups),
2482 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2483
2484 bool operator()(ModuleFile &M) {
2485 // If we've already searched this module file, skip it now.
2486 if (M.Generation <= PriorGeneration)
2487 return true;
2488
2491 if (!IdTable)
2492 return false;
2493
2494 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2495 Found);
2496 ++NumIdentifierLookups;
2497 ASTIdentifierLookupTable::iterator Pos =
2498 IdTable->find_hashed(Name, NameHash, &Trait);
2499 if (Pos == IdTable->end())
2500 return false;
2501
2502 // Dereferencing the iterator has the effect of building the
2503 // IdentifierInfo node and populating it with the various
2504 // declarations it needs.
2505 ++NumIdentifierLookupHits;
2506 Found = *Pos;
2507 if (Trait.hasMoreInformationInDependencies()) {
2508 // Look for the identifier in extra modules as they contain more info.
2509 return false;
2510 }
2511 return true;
2512 }
2513
2514 // Retrieve the identifier info found within the module
2515 // files.
2516 IdentifierInfo *getIdentifierInfo() const { return Found; }
2517 };
2518
2519} // namespace
2520
2522 // Note that we are loading an identifier.
2523 Deserializing AnIdentifier(this);
2524
2525 unsigned PriorGeneration = 0;
2526 if (getContext().getLangOpts().Modules)
2527 PriorGeneration = IdentifierGeneration[&II];
2528
2529 // If there is a global index, look there first to determine which modules
2530 // provably do not have any results for this identifier.
2532 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2533 if (!loadGlobalIndex()) {
2534 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2535 HitsPtr = &Hits;
2536 }
2537 }
2538
2539 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2540 NumIdentifierLookups,
2541 NumIdentifierLookupHits);
2542 ModuleMgr.visit(Visitor, HitsPtr);
2544}
2545
2547 if (!II)
2548 return;
2549
2550 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2551
2552 // Update the generation for this identifier.
2553 if (getContext().getLangOpts().Modules)
2554 IdentifierGeneration[II] = getGeneration();
2555}
2556
2558 unsigned &Idx) {
2559 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2560 uint64_t LocalIndex = Record[Idx++];
2561 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2562}
2563
2565 const PendingMacroInfo &PMInfo) {
2566 ModuleFile &M = *PMInfo.M;
2567
2568 BitstreamCursor &Cursor = M.MacroCursor;
2569 SavedStreamPosition SavedPosition(Cursor);
2570 if (llvm::Error Err =
2571 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2572 Error(std::move(Err));
2573 return;
2574 }
2575
2576 struct ModuleMacroRecord {
2577 SubmoduleID SubModID;
2578 MacroInfo *MI;
2580 };
2582
2583 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2584 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2585 // macro histroy.
2587 while (true) {
2589 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2590 if (!MaybeEntry) {
2591 Error(MaybeEntry.takeError());
2592 return;
2593 }
2594 llvm::BitstreamEntry Entry = MaybeEntry.get();
2595
2596 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2597 Error("malformed block record in AST file");
2598 return;
2599 }
2600
2601 Record.clear();
2602 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2603 if (!MaybePP) {
2604 Error(MaybePP.takeError());
2605 return;
2606 }
2607 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2609 break;
2610
2611 case PP_MODULE_MACRO: {
2612 ModuleMacros.push_back(ModuleMacroRecord());
2613 auto &Info = ModuleMacros.back();
2614 unsigned Idx = 0;
2615 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2616 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2617 for (int I = Idx, N = Record.size(); I != N; ++I)
2618 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2619 continue;
2620 }
2621
2622 default:
2623 Error("malformed block record in AST file");
2624 return;
2625 }
2626
2627 // We found the macro directive history; that's the last record
2628 // for this macro.
2629 break;
2630 }
2631
2632 // Module macros are listed in reverse dependency order.
2633 {
2634 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2636 for (auto &MMR : ModuleMacros) {
2637 Overrides.clear();
2638 for (unsigned ModID : MMR.Overrides) {
2639 Module *Mod = getSubmodule(ModID);
2640 auto *Macro = PP.getModuleMacro(Mod, II);
2641 assert(Macro && "missing definition for overridden macro");
2642 Overrides.push_back(Macro);
2643 }
2644
2645 bool Inserted = false;
2646 Module *Owner = getSubmodule(MMR.SubModID);
2647 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2648 }
2649 }
2650
2651 // Don't read the directive history for a module; we don't have anywhere
2652 // to put it.
2653 if (M.isModule())
2654 return;
2655
2656 // Deserialize the macro directives history in reverse source-order.
2657 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2658 unsigned Idx = 0, N = Record.size();
2659 while (Idx < N) {
2660 MacroDirective *MD = nullptr;
2663 switch (K) {
2665 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2666 MD = PP.AllocateDefMacroDirective(MI, Loc);
2667 break;
2668 }
2670 MD = PP.AllocateUndefMacroDirective(Loc);
2671 break;
2673 bool isPublic = Record[Idx++];
2674 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2675 break;
2676 }
2677
2678 if (!Latest)
2679 Latest = MD;
2680 if (Earliest)
2681 Earliest->setPrevious(MD);
2682 Earliest = MD;
2683 }
2684
2685 if (Latest)
2686 PP.setLoadedMacroDirective(II, Earliest, Latest);
2687}
2688
2689bool ASTReader::shouldDisableValidationForFile(
2690 const serialization::ModuleFile &M) const {
2691 if (DisableValidationKind == DisableValidationForModuleKind::None)
2692 return false;
2693
2694 // If a PCH is loaded and validation is disabled for PCH then disable
2695 // validation for the PCH and the modules it loads.
2696 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2697
2698 switch (K) {
2699 case MK_MainFile:
2700 case MK_Preamble:
2701 case MK_PCH:
2702 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2703 case MK_ImplicitModule:
2704 case MK_ExplicitModule:
2705 case MK_PrebuiltModule:
2706 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2707 }
2708
2709 return false;
2710}
2711
2712static std::pair<StringRef, StringRef>
2714 const StringRef InputBlob) {
2715 uint16_t AsRequestedLength = Record[7];
2716 return {InputBlob.substr(0, AsRequestedLength),
2717 InputBlob.substr(AsRequestedLength)};
2718}
2719
2720InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2721 // If this ID is bogus, just return an empty input file.
2722 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2723 return InputFileInfo();
2724
2725 // If we've already loaded this input file, return it.
2726 if (F.InputFileInfosLoaded[ID - 1].isValid())
2727 return F.InputFileInfosLoaded[ID - 1];
2728
2729 // Go find this input file.
2730 BitstreamCursor &Cursor = F.InputFilesCursor;
2731 SavedStreamPosition SavedPosition(Cursor);
2732 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2733 F.InputFileOffsets[ID - 1])) {
2734 // FIXME this drops errors on the floor.
2735 consumeError(std::move(Err));
2736 }
2737
2738 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2739 if (!MaybeCode) {
2740 // FIXME this drops errors on the floor.
2741 consumeError(MaybeCode.takeError());
2742 }
2743 unsigned Code = MaybeCode.get();
2744 RecordData Record;
2745 StringRef Blob;
2746
2747 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2748 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2749 "invalid record type for input file");
2750 else {
2751 // FIXME this drops errors on the floor.
2752 consumeError(Maybe.takeError());
2753 }
2754
2755 assert(Record[0] == ID && "Bogus stored ID or offset");
2756 InputFileInfo R;
2757 R.StoredSize = static_cast<off_t>(Record[1]);
2758 R.StoredTime = static_cast<time_t>(Record[2]);
2759 R.Overridden = static_cast<bool>(Record[3]);
2760 R.Transient = static_cast<bool>(Record[4]);
2761 R.TopLevel = static_cast<bool>(Record[5]);
2762 R.ModuleMap = static_cast<bool>(Record[6]);
2763 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2765 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2766 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2767 ? UnresolvedFilenameAsRequested
2768 : UnresolvedFilename;
2769
2770 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2771 if (!MaybeEntry) // FIXME this drops errors on the floor.
2772 consumeError(MaybeEntry.takeError());
2773 llvm::BitstreamEntry Entry = MaybeEntry.get();
2774 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2775 "expected record type for input file hash");
2776
2777 Record.clear();
2778 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2779 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2780 "invalid record type for input file hash");
2781 else {
2782 // FIXME this drops errors on the floor.
2783 consumeError(Maybe.takeError());
2784 }
2785 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2786 static_cast<uint64_t>(Record[0]);
2787
2788 // Note that we've loaded this input file info.
2789 F.InputFileInfosLoaded[ID - 1] = R;
2790 return R;
2791}
2792
2793static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2794InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2795 // If this ID is bogus, just return an empty input file.
2796 if (ID == 0 || ID > F.InputFilesLoaded.size())
2797 return InputFile();
2798
2799 // If we've already loaded this input file, return it.
2800 if (F.InputFilesLoaded[ID-1].getFile())
2801 return F.InputFilesLoaded[ID-1];
2802
2803 if (F.InputFilesLoaded[ID-1].isNotFound())
2804 return InputFile();
2805
2806 // Go find this input file.
2807 BitstreamCursor &Cursor = F.InputFilesCursor;
2808 SavedStreamPosition SavedPosition(Cursor);
2809 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2810 F.InputFileOffsets[ID - 1])) {
2811 // FIXME this drops errors on the floor.
2812 consumeError(std::move(Err));
2813 }
2814
2815 InputFileInfo FI = getInputFileInfo(F, ID);
2816 off_t StoredSize = FI.StoredSize;
2817 time_t StoredTime = FI.StoredTime;
2818 bool Overridden = FI.Overridden;
2819 bool Transient = FI.Transient;
2820 auto Filename =
2821 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2822 uint64_t StoredContentHash = FI.ContentHash;
2823
2824 // For standard C++ modules, we don't need to check the inputs.
2825 bool SkipChecks = F.StandardCXXModule;
2826
2827 const HeaderSearchOptions &HSOpts =
2828 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2829
2830 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2831 // modules.
2833 SkipChecks = false;
2834 Overridden = false;
2835 }
2836
2837 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2838
2839 // For an overridden file, create a virtual file with the stored
2840 // size/timestamp.
2841 if ((Overridden || Transient || SkipChecks) && !File)
2842 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2843
2844 if (!File) {
2845 if (Complain) {
2846 std::string ErrorStr = "could not find file '";
2847 ErrorStr += *Filename;
2848 ErrorStr += "' referenced by AST file '";
2849 ErrorStr += F.FileName;
2850 ErrorStr += "'";
2851 Error(ErrorStr);
2852 }
2853 // Record that we didn't find the file.
2855 return InputFile();
2856 }
2857
2858 // Check if there was a request to override the contents of the file
2859 // that was part of the precompiled header. Overriding such a file
2860 // can lead to problems when lexing using the source locations from the
2861 // PCH.
2862 SourceManager &SM = getSourceManager();
2863 // FIXME: Reject if the overrides are different.
2864 if ((!Overridden && !Transient) && !SkipChecks &&
2865 SM.isFileOverridden(*File)) {
2866 if (Complain)
2867 Error(diag::err_fe_pch_file_overridden, *Filename);
2868
2869 // After emitting the diagnostic, bypass the overriding file to recover
2870 // (this creates a separate FileEntry).
2871 File = SM.bypassFileContentsOverride(*File);
2872 if (!File) {
2874 return InputFile();
2875 }
2876 }
2877
2878 struct Change {
2879 enum ModificationKind {
2880 Size,
2881 ModTime,
2882 Content,
2883 None,
2884 } Kind;
2885 std::optional<int64_t> Old = std::nullopt;
2886 std::optional<int64_t> New = std::nullopt;
2887 };
2888 auto HasInputContentChanged = [&](Change OriginalChange) {
2889 assert(ValidateASTInputFilesContent &&
2890 "We should only check the content of the inputs with "
2891 "ValidateASTInputFilesContent enabled.");
2892
2893 if (StoredContentHash == 0)
2894 return OriginalChange;
2895
2896 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2897 if (!MemBuffOrError) {
2898 if (!Complain)
2899 return OriginalChange;
2900 std::string ErrorStr = "could not get buffer for file '";
2901 ErrorStr += File->getName();
2902 ErrorStr += "'";
2903 Error(ErrorStr);
2904 return OriginalChange;
2905 }
2906
2907 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2908 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2909 return Change{Change::None};
2910
2911 return Change{Change::Content};
2912 };
2913 auto HasInputFileChanged = [&]() {
2914 if (StoredSize != File->getSize())
2915 return Change{Change::Size, StoredSize, File->getSize()};
2916 if (!shouldDisableValidationForFile(F) && StoredTime &&
2917 StoredTime != File->getModificationTime()) {
2918 Change MTimeChange = {Change::ModTime, StoredTime,
2919 File->getModificationTime()};
2920
2921 // In case the modification time changes but not the content,
2922 // accept the cached file as legit.
2923 if (ValidateASTInputFilesContent)
2924 return HasInputContentChanged(MTimeChange);
2925
2926 return MTimeChange;
2927 }
2928 return Change{Change::None};
2929 };
2930
2931 bool IsOutOfDate = false;
2932 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2933 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2934 // enabled, it is better to check the contents of the inputs. Since we can't
2935 // get correct modified time information for inputs from overriden inputs.
2936 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2937 F.StandardCXXModule && FileChange.Kind == Change::None)
2938 FileChange = HasInputContentChanged(FileChange);
2939
2940 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2941 // it is better to check the content of the input files because we cannot rely
2942 // on the file modification time, which will be the same (zero) for these
2943 // files.
2944 if (!StoredTime && ValidateASTInputFilesContent &&
2945 FileChange.Kind == Change::None)
2946 FileChange = HasInputContentChanged(FileChange);
2947
2948 // For an overridden file, there is nothing to validate.
2949 if (!Overridden && FileChange.Kind != Change::None) {
2950 if (Complain) {
2951 // Build a list of the PCH imports that got us here (in reverse).
2952 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2953 while (!ImportStack.back()->ImportedBy.empty())
2954 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2955
2956 // The top-level AST file is stale.
2957 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2958 Diag(diag::err_fe_ast_file_modified)
2959 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2960 << TopLevelASTFileName << FileChange.Kind
2961 << (FileChange.Old && FileChange.New)
2962 << llvm::itostr(FileChange.Old.value_or(0))
2963 << llvm::itostr(FileChange.New.value_or(0));
2964
2965 // Print the import stack.
2966 if (ImportStack.size() > 1) {
2967 Diag(diag::note_ast_file_required_by)
2968 << *Filename << ImportStack[0]->FileName;
2969 for (unsigned I = 1; I < ImportStack.size(); ++I)
2970 Diag(diag::note_ast_file_required_by)
2971 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
2972 }
2973
2974 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
2975 }
2976
2977 IsOutOfDate = true;
2978 }
2979 // FIXME: If the file is overridden and we've already opened it,
2980 // issue an error (or split it into a separate FileEntry).
2981
2982 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2983
2984 // Note that we've loaded this input file.
2985 F.InputFilesLoaded[ID-1] = IF;
2986 return IF;
2987}
2988
2989ASTReader::TemporarilyOwnedStringRef
2991 ModuleFile &ModF) {
2992 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
2993}
2994
2995ASTReader::TemporarilyOwnedStringRef
2997 StringRef Prefix) {
2998 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
2999
3000 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3001 Path == "<built-in>" || Path == "<command line>")
3002 return {Path, Buf};
3003
3004 Buf.clear();
3005 llvm::sys::path::append(Buf, Prefix, Path);
3006 StringRef ResolvedPath{Buf.data(), Buf.size()};
3007 return {ResolvedPath, Buf};
3008}
3009
3011 StringRef P,
3012 ModuleFile &ModF) {
3013 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3014}
3015
3017 StringRef P,
3018 StringRef Prefix) {
3019 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3020 return ResolvedPath->str();
3021}
3022
3023static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3024 switch (ARR) {
3025 case ASTReader::Failure: return true;
3026 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3027 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3030 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3031 case ASTReader::HadErrors: return true;
3032 case ASTReader::Success: return false;
3033 }
3034
3035 llvm_unreachable("unknown ASTReadResult");
3036}
3037
3038ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3039 BitstreamCursor &Stream, StringRef Filename,
3040 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3041 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3042 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3043 // FIXME this drops errors on the floor.
3044 consumeError(std::move(Err));
3045 return Failure;
3046 }
3047
3048 // Read all of the records in the options block.
3049 RecordData Record;
3050 ASTReadResult Result = Success;
3051 while (true) {
3052 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3053 if (!MaybeEntry) {
3054 // FIXME this drops errors on the floor.
3055 consumeError(MaybeEntry.takeError());
3056 return Failure;
3057 }
3058 llvm::BitstreamEntry Entry = MaybeEntry.get();
3059
3060 switch (Entry.Kind) {
3061 case llvm::BitstreamEntry::Error:
3062 case llvm::BitstreamEntry::SubBlock:
3063 return Failure;
3064
3065 case llvm::BitstreamEntry::EndBlock:
3066 return Result;
3067
3068 case llvm::BitstreamEntry::Record:
3069 // The interesting case.
3070 break;
3071 }
3072
3073 // Read and process a record.
3074 Record.clear();
3075 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3076 if (!MaybeRecordType) {
3077 // FIXME this drops errors on the floor.
3078 consumeError(MaybeRecordType.takeError());
3079 return Failure;
3080 }
3081 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3082 case LANGUAGE_OPTIONS: {
3083 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3084 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3085 AllowCompatibleConfigurationMismatch))
3086 Result = ConfigurationMismatch;
3087 break;
3088 }
3089
3090 case CODEGEN_OPTIONS: {
3091 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3092 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3093 AllowCompatibleConfigurationMismatch))
3094 Result = ConfigurationMismatch;
3095 break;
3096 }
3097
3098 case TARGET_OPTIONS: {
3099 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3100 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3101 AllowCompatibleConfigurationMismatch))
3102 Result = ConfigurationMismatch;
3103 break;
3104 }
3105
3106 case FILE_SYSTEM_OPTIONS: {
3107 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3108 if (!AllowCompatibleConfigurationMismatch &&
3109 ParseFileSystemOptions(Record, Complain, Listener))
3110 Result = ConfigurationMismatch;
3111 break;
3112 }
3113
3114 case HEADER_SEARCH_OPTIONS: {
3115 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3116 if (!AllowCompatibleConfigurationMismatch &&
3117 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3118 Result = ConfigurationMismatch;
3119 break;
3120 }
3121
3123 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3124 if (!AllowCompatibleConfigurationMismatch &&
3125 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3126 SuggestedPredefines))
3127 Result = ConfigurationMismatch;
3128 break;
3129 }
3130 }
3131}
3132
3134ASTReader::ReadControlBlock(ModuleFile &F,
3135 SmallVectorImpl<ImportedModule> &Loaded,
3136 const ModuleFile *ImportedBy,
3137 unsigned ClientLoadCapabilities) {
3138 BitstreamCursor &Stream = F.Stream;
3139
3140 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3141 Error(std::move(Err));
3142 return Failure;
3143 }
3144
3145 // Lambda to read the unhashed control block the first time it's called.
3146 //
3147 // For PCM files, the unhashed control block cannot be read until after the
3148 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3149 // need to look ahead before reading the IMPORTS record. For consistency,
3150 // this block is always read somehow (see BitstreamEntry::EndBlock).
3151 bool HasReadUnhashedControlBlock = false;
3152 auto readUnhashedControlBlockOnce = [&]() {
3153 if (!HasReadUnhashedControlBlock) {
3154 HasReadUnhashedControlBlock = true;
3155 if (ASTReadResult Result =
3156 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3157 return Result;
3158 }
3159 return Success;
3160 };
3161
3162 bool DisableValidation = shouldDisableValidationForFile(F);
3163
3164 // Read all of the records and blocks in the control block.
3165 RecordData Record;
3166 unsigned NumInputs = 0;
3167 unsigned NumUserInputs = 0;
3168 StringRef BaseDirectoryAsWritten;
3169 while (true) {
3170 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3171 if (!MaybeEntry) {
3172 Error(MaybeEntry.takeError());
3173 return Failure;
3174 }
3175 llvm::BitstreamEntry Entry = MaybeEntry.get();
3176
3177 switch (Entry.Kind) {
3178 case llvm::BitstreamEntry::Error:
3179 Error("malformed block record in AST file");
3180 return Failure;
3181 case llvm::BitstreamEntry::EndBlock: {
3182 // Validate the module before returning. This call catches an AST with
3183 // no module name and no imports.
3184 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3185 return Result;
3186
3187 // Validate input files.
3188 const HeaderSearchOptions &HSOpts =
3189 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3190
3191 // All user input files reside at the index range [0, NumUserInputs), and
3192 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3193 // loaded module files, ignore missing inputs.
3194 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3195 F.Kind != MK_PrebuiltModule) {
3196 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3197
3198 // If we are reading a module, we will create a verification timestamp,
3199 // so we verify all input files. Otherwise, verify only user input
3200 // files.
3201
3202 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3206 N = ForceValidateUserInputs ? NumUserInputs : 0;
3207
3208 if (N != 0)
3209 Diag(diag::remark_module_validation)
3210 << N << F.ModuleName << F.FileName;
3211
3212 for (unsigned I = 0; I < N; ++I) {
3213 InputFile IF = getInputFile(F, I+1, Complain);
3214 if (!IF.getFile() || IF.isOutOfDate())
3215 return OutOfDate;
3216 }
3217 }
3218
3219 if (Listener)
3220 Listener->visitModuleFile(F.FileName, F.Kind);
3221
3222 if (Listener && Listener->needsInputFileVisitation()) {
3223 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3224 : NumUserInputs;
3225 for (unsigned I = 0; I < N; ++I) {
3226 bool IsSystem = I >= NumUserInputs;
3227 InputFileInfo FI = getInputFileInfo(F, I + 1);
3228 auto FilenameAsRequested = ResolveImportedPath(
3230 Listener->visitInputFile(
3231 *FilenameAsRequested, IsSystem, FI.Overridden,
3233 }
3234 }
3235
3236 return Success;
3237 }
3238
3239 case llvm::BitstreamEntry::SubBlock:
3240 switch (Entry.ID) {
3242 F.InputFilesCursor = Stream;
3243 if (llvm::Error Err = Stream.SkipBlock()) {
3244 Error(std::move(Err));
3245 return Failure;
3246 }
3247 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3248 Error("malformed block record in AST file");
3249 return Failure;
3250 }
3251 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3252 continue;
3253
3254 case OPTIONS_BLOCK_ID:
3255 // If we're reading the first module for this group, check its options
3256 // are compatible with ours. For modules it imports, no further checking
3257 // is required, because we checked them when we built it.
3258 if (Listener && !ImportedBy) {
3259 // Should we allow the configuration of the module file to differ from
3260 // the configuration of the current translation unit in a compatible
3261 // way?
3262 //
3263 // FIXME: Allow this for files explicitly specified with -include-pch.
3264 bool AllowCompatibleConfigurationMismatch =
3266
3267 ASTReadResult Result =
3268 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3269 AllowCompatibleConfigurationMismatch, *Listener,
3270 SuggestedPredefines);
3271 if (Result == Failure) {
3272 Error("malformed block record in AST file");
3273 return Result;
3274 }
3275
3276 if (DisableValidation ||
3277 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3278 Result = Success;
3279
3280 // If we can't load the module, exit early since we likely
3281 // will rebuild the module anyway. The stream may be in the
3282 // middle of a block.
3283 if (Result != Success)
3284 return Result;
3285 } else if (llvm::Error Err = Stream.SkipBlock()) {
3286 Error(std::move(Err));
3287 return Failure;
3288 }
3289 continue;
3290
3291 default:
3292 if (llvm::Error Err = Stream.SkipBlock()) {
3293 Error(std::move(Err));
3294 return Failure;
3295 }
3296 continue;
3297 }
3298
3299 case llvm::BitstreamEntry::Record:
3300 // The interesting case.
3301 break;
3302 }
3303
3304 // Read and process a record.
3305 Record.clear();
3306 StringRef Blob;
3307 Expected<unsigned> MaybeRecordType =
3308 Stream.readRecord(Entry.ID, Record, &Blob);
3309 if (!MaybeRecordType) {
3310 Error(MaybeRecordType.takeError());
3311 return Failure;
3312 }
3313 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3314 case METADATA: {
3315 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3316 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3317 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3318 : diag::err_ast_file_version_too_new)
3320 return VersionMismatch;
3321 }
3322
3323 bool hasErrors = Record[7];
3324 if (hasErrors && !DisableValidation) {
3325 // If requested by the caller and the module hasn't already been read
3326 // or compiled, mark modules on error as out-of-date.
3327 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3328 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3329 return OutOfDate;
3330
3331 if (!AllowASTWithCompilerErrors) {
3332 Diag(diag::err_ast_file_with_compiler_errors)
3334 return HadErrors;
3335 }
3336 }
3337 if (hasErrors) {
3338 Diags.ErrorOccurred = true;
3339 Diags.UncompilableErrorOccurred = true;
3340 Diags.UnrecoverableErrorOccurred = true;
3341 }
3342
3343 F.RelocatablePCH = Record[4];
3344 // Relative paths in a relocatable PCH are relative to our sysroot.
3345 if (F.RelocatablePCH)
3346 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3347
3349
3350 F.HasTimestamps = Record[6];
3351
3352 const std::string &CurBranch = getClangFullRepositoryVersion();
3353 StringRef ASTBranch = Blob;
3354 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3355 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3356 Diag(diag::err_ast_file_different_branch)
3357 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3358 << CurBranch;
3359 return VersionMismatch;
3360 }
3361 break;
3362 }
3363
3364 case IMPORT: {
3365 // Validate the AST before processing any imports (otherwise, untangling
3366 // them can be error-prone and expensive). A module will have a name and
3367 // will already have been validated, but this catches the PCH case.
3368 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3369 return Result;
3370
3371 unsigned Idx = 0;
3372 // Read information about the AST file.
3373 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3374
3375 // The import location will be the local one for now; we will adjust
3376 // all import locations of module imports after the global source
3377 // location info are setup, in ReadAST.
3378 auto [ImportLoc, ImportModuleFileIndex] =
3379 ReadUntranslatedSourceLocation(Record[Idx++]);
3380 // The import location must belong to the current module file itself.
3381 assert(ImportModuleFileIndex == 0);
3382
3383 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3384
3385 bool IsImportingStdCXXModule = Record[Idx++];
3386
3387 off_t StoredSize = 0;
3388 time_t StoredModTime = 0;
3389 ASTFileSignature StoredSignature;
3390 std::string ImportedFile;
3391 std::string StoredFile;
3392 bool IgnoreImportedByNote = false;
3393
3394 // For prebuilt and explicit modules first consult the file map for
3395 // an override. Note that here we don't search prebuilt module
3396 // directories if we're not importing standard c++ module, only the
3397 // explicit name to file mappings. Also, we will still verify the
3398 // size/signature making sure it is essentially the same file but
3399 // perhaps in a different location.
3400 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3401 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3402 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3403
3404 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3405 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3406 return Missing;
3407 }
3408
3409 if (!IsImportingStdCXXModule) {
3410 StoredSize = (off_t)Record[Idx++];
3411 StoredModTime = (time_t)Record[Idx++];
3412
3413 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3414 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3415 SignatureBytes.end());
3416 Blob = Blob.substr(ASTFileSignature::size);
3417
3418 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3419 // ModuleCache as when writing.
3420 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3421 if (ImportedFile.empty()) {
3422 ImportedFile = StoredFile;
3423 } else if (!getDiags().isIgnored(
3424 diag::warn_module_file_mapping_mismatch,
3425 CurrentImportLoc)) {
3426 auto ImportedFileRef =
3427 PP.getFileManager().getOptionalFileRef(ImportedFile);
3428 auto StoredFileRef =
3429 PP.getFileManager().getOptionalFileRef(StoredFile);
3430 if ((ImportedFileRef && StoredFileRef) &&
3431 (*ImportedFileRef != *StoredFileRef)) {
3432 Diag(diag::warn_module_file_mapping_mismatch)
3433 << ImportedFile << StoredFile;
3434 Diag(diag::note_module_file_imported_by)
3435 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3436 IgnoreImportedByNote = true;
3437 }
3438 }
3439 }
3440
3441 // If our client can't cope with us being out of date, we can't cope with
3442 // our dependency being missing.
3443 unsigned Capabilities = ClientLoadCapabilities;
3444 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3445 Capabilities &= ~ARR_Missing;
3446
3447 // Load the AST file.
3448 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3449 Loaded, StoredSize, StoredModTime,
3450 StoredSignature, Capabilities);
3451
3452 // Check the AST we just read from ImportedFile contains a different
3453 // module than we expected (ImportedName). This can occur for C++20
3454 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3455 if (IsImportingStdCXXModule) {
3456 if (const auto *Imported =
3457 getModuleManager().lookupByFileName(ImportedFile);
3458 Imported != nullptr && Imported->ModuleName != ImportedName) {
3459 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3460 Result = Missing;
3461 }
3462 }
3463
3464 // If we diagnosed a problem, produce a backtrace.
3465 bool recompilingFinalized = Result == OutOfDate &&
3466 (Capabilities & ARR_OutOfDate) &&
3467 getModuleManager()
3468 .getModuleCache()
3469 .getInMemoryModuleCache()
3470 .isPCMFinal(F.FileName);
3471 if (!IgnoreImportedByNote &&
3472 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3473 Diag(diag::note_module_file_imported_by)
3474 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3475
3476 switch (Result) {
3477 case Failure: return Failure;
3478 // If we have to ignore the dependency, we'll have to ignore this too.
3479 case Missing:
3480 case OutOfDate: return OutOfDate;
3481 case VersionMismatch: return VersionMismatch;
3482 case ConfigurationMismatch: return ConfigurationMismatch;
3483 case HadErrors: return HadErrors;
3484 case Success: break;
3485 }
3486 break;
3487 }
3488
3489 case ORIGINAL_FILE:
3490 F.OriginalSourceFileID = FileID::get(Record[0]);
3491 F.ActualOriginalSourceFileName = std::string(Blob);
3492 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3493 PathBuf, F.ActualOriginalSourceFileName, F);
3494 break;
3495
3496 case ORIGINAL_FILE_ID:
3497 F.OriginalSourceFileID = FileID::get(Record[0]);
3498 break;
3499
3500 case MODULE_NAME:
3501 F.ModuleName = std::string(Blob);
3502 Diag(diag::remark_module_import)
3503 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3504 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3505 if (Listener)
3506 Listener->ReadModuleName(F.ModuleName);
3507
3508 // Validate the AST as soon as we have a name so we can exit early on
3509 // failure.
3510 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3511 return Result;
3512
3513 break;
3514
3515 case MODULE_DIRECTORY: {
3516 // Save the BaseDirectory as written in the PCM for computing the module
3517 // filename for the ModuleCache.
3518 BaseDirectoryAsWritten = Blob;
3519 assert(!F.ModuleName.empty() &&
3520 "MODULE_DIRECTORY found before MODULE_NAME");
3521 F.BaseDirectory = std::string(Blob);
3522 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3523 break;
3524 // If we've already loaded a module map file covering this module, we may
3525 // have a better path for it (relative to the current build).
3526 Module *M = PP.getHeaderSearchInfo().lookupModule(
3527 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3528 /*AllowExtraModuleMapSearch*/ true);
3529 if (M && M->Directory) {
3530 // If we're implicitly loading a module, the base directory can't
3531 // change between the build and use.
3532 // Don't emit module relocation error if we have -fno-validate-pch
3533 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3536 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3537 if (!BuildDir || *BuildDir != M->Directory) {
3538 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3539 Diag(diag::err_imported_module_relocated)
3540 << F.ModuleName << Blob << M->Directory->getName();
3541 return OutOfDate;
3542 }
3543 }
3544 F.BaseDirectory = std::string(M->Directory->getName());
3545 }
3546 break;
3547 }
3548
3549 case MODULE_MAP_FILE:
3550 if (ASTReadResult Result =
3551 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3552 return Result;
3553 break;
3554
3555 case INPUT_FILE_OFFSETS:
3556 NumInputs = Record[0];
3557 NumUserInputs = Record[1];
3559 (const llvm::support::unaligned_uint64_t *)Blob.data();
3560 F.InputFilesLoaded.resize(NumInputs);
3561 F.InputFileInfosLoaded.resize(NumInputs);
3562 F.NumUserInputFiles = NumUserInputs;
3563 break;
3564 }
3565 }
3566}
3567
3568llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3569 unsigned ClientLoadCapabilities) {
3570 BitstreamCursor &Stream = F.Stream;
3571
3572 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3573 return Err;
3574 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3575
3576 // Read all of the records and blocks for the AST file.
3577 RecordData Record;
3578 while (true) {
3579 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3580 if (!MaybeEntry)
3581 return MaybeEntry.takeError();
3582 llvm::BitstreamEntry Entry = MaybeEntry.get();
3583
3584 switch (Entry.Kind) {
3585 case llvm::BitstreamEntry::Error:
3586 return llvm::createStringError(
3587 std::errc::illegal_byte_sequence,
3588 "error at end of module block in AST file");
3589 case llvm::BitstreamEntry::EndBlock:
3590 // Outside of C++, we do not store a lookup map for the translation unit.
3591 // Instead, mark it as needing a lookup map to be built if this module
3592 // contains any declarations lexically within it (which it always does!).
3593 // This usually has no cost, since we very rarely need the lookup map for
3594 // the translation unit outside C++.
3595 if (ASTContext *Ctx = ContextObj) {
3596 DeclContext *DC = Ctx->getTranslationUnitDecl();
3597 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3599 }
3600
3601 return llvm::Error::success();
3602 case llvm::BitstreamEntry::SubBlock:
3603 switch (Entry.ID) {
3604 case DECLTYPES_BLOCK_ID:
3605 // We lazily load the decls block, but we want to set up the
3606 // DeclsCursor cursor to point into it. Clone our current bitcode
3607 // cursor to it, enter the block and read the abbrevs in that block.
3608 // With the main cursor, we just skip over it.
3609 F.DeclsCursor = Stream;
3610 if (llvm::Error Err = Stream.SkipBlock())
3611 return Err;
3612 if (llvm::Error Err = ReadBlockAbbrevs(
3614 return Err;
3615 break;
3616
3618 F.MacroCursor = Stream;
3619 if (!PP.getExternalSource())
3620 PP.setExternalSource(this);
3621
3622 if (llvm::Error Err = Stream.SkipBlock())
3623 return Err;
3624 if (llvm::Error Err =
3625 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3626 return Err;
3627 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3628 break;
3629
3631 F.PreprocessorDetailCursor = Stream;
3632
3633 if (llvm::Error Err = Stream.SkipBlock()) {
3634 return Err;
3635 }
3636 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3638 return Err;
3640 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3641
3642 if (!PP.getPreprocessingRecord())
3643 PP.createPreprocessingRecord();
3644 if (!PP.getPreprocessingRecord()->getExternalSource())
3645 PP.getPreprocessingRecord()->SetExternalSource(*this);
3646 break;
3647
3649 if (llvm::Error Err = ReadSourceManagerBlock(F))
3650 return Err;
3651 break;
3652
3653 case SUBMODULE_BLOCK_ID:
3654 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3655 return Err;
3656 break;
3657
3658 case COMMENTS_BLOCK_ID: {
3659 BitstreamCursor C = Stream;
3660
3661 if (llvm::Error Err = Stream.SkipBlock())
3662 return Err;
3663 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3664 return Err;
3665 CommentsCursors.push_back(std::make_pair(C, &F));
3666 break;
3667 }
3668
3669 default:
3670 if (llvm::Error Err = Stream.SkipBlock())
3671 return Err;
3672 break;
3673 }
3674 continue;
3675
3676 case llvm::BitstreamEntry::Record:
3677 // The interesting case.
3678 break;
3679 }
3680
3681 // Read and process a record.
3682 Record.clear();
3683 StringRef Blob;
3684 Expected<unsigned> MaybeRecordType =
3685 Stream.readRecord(Entry.ID, Record, &Blob);
3686 if (!MaybeRecordType)
3687 return MaybeRecordType.takeError();
3688 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3689
3690 // If we're not loading an AST context, we don't care about most records.
3691 if (!ContextObj) {
3692 switch (RecordType) {
3693 case IDENTIFIER_TABLE:
3694 case IDENTIFIER_OFFSET:
3696 case STATISTICS:
3699 case PP_COUNTER_VALUE:
3701 case MODULE_OFFSET_MAP:
3705 case IMPORTED_MODULES:
3706 case MACRO_OFFSET:
3707 break;
3708 default:
3709 continue;
3710 }
3711 }
3712
3713 switch (RecordType) {
3714 default: // Default behavior: ignore.
3715 break;
3716
3717 case TYPE_OFFSET: {
3718 if (F.LocalNumTypes != 0)
3719 return llvm::createStringError(
3720 std::errc::illegal_byte_sequence,
3721 "duplicate TYPE_OFFSET record in AST file");
3722 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3723 F.LocalNumTypes = Record[0];
3724 F.BaseTypeIndex = getTotalNumTypes();
3725
3726 if (F.LocalNumTypes > 0)
3727 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3728
3729 break;
3730 }
3731
3732 case DECL_OFFSET: {
3733 if (F.LocalNumDecls != 0)
3734 return llvm::createStringError(
3735 std::errc::illegal_byte_sequence,
3736 "duplicate DECL_OFFSET record in AST file");
3737 F.DeclOffsets = (const DeclOffset *)Blob.data();
3738 F.LocalNumDecls = Record[0];
3739 F.BaseDeclIndex = getTotalNumDecls();
3740
3741 if (F.LocalNumDecls > 0)
3742 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3743
3744 break;
3745 }
3746
3747 case TU_UPDATE_LEXICAL: {
3748 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3749 LexicalContents Contents(
3750 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3751 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3752 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3754 break;
3755 }
3756
3757 case UPDATE_VISIBLE: {
3758 unsigned Idx = 0;
3759 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3760 auto *Data = (const unsigned char*)Blob.data();
3761 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3762 // If we've already loaded the decl, perform the updates when we finish
3763 // loading this block.
3764 if (Decl *D = GetExistingDecl(ID))
3765 PendingUpdateRecords.push_back(
3766 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3767 break;
3768 }
3769
3771 unsigned Idx = 0;
3772 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3773 auto *Data = (const unsigned char *)Blob.data();
3774 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3775 // If we've already loaded the decl, perform the updates when we finish
3776 // loading this block.
3777 if (Decl *D = GetExistingDecl(ID))
3778 PendingUpdateRecords.push_back(
3779 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3780 break;
3781 }
3782
3784 if (F.Kind != MK_MainFile)
3785 break;
3786 unsigned Idx = 0;
3787 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3788 auto *Data = (const unsigned char *)Blob.data();
3789 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3790 // If we've already loaded the decl, perform the updates when we finish
3791 // loading this block.
3792 if (Decl *D = GetExistingDecl(ID))
3793 PendingUpdateRecords.push_back(
3794 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3795 break;
3796 }
3797
3799 unsigned Idx = 0;
3800 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3801 auto *Data = (const unsigned char *)Blob.data();
3802 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3803 // If we've already loaded the decl, perform the updates when we finish
3804 // loading this block.
3805 if (Decl *D = GetExistingDecl(ID))
3806 PendingUpdateRecords.push_back(
3807 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3808 break;
3809 }
3810
3812 unsigned Idx = 0;
3813 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3814 auto *Data = (const unsigned char *)Blob.data();
3815 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3816 // If we've already loaded the decl, perform the updates when we finish
3817 // loading this block.
3818 if (Decl *D = GetExistingDecl(ID))
3819 PendingUpdateRecords.push_back(
3820 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3821 break;
3822 }
3823
3824 case IDENTIFIER_TABLE:
3826 reinterpret_cast<const unsigned char *>(Blob.data());
3827 if (Record[0]) {
3828 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3830 F.IdentifierTableData + sizeof(uint32_t),
3832 ASTIdentifierLookupTrait(*this, F));
3833
3834 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3835 }
3836 break;
3837
3838 case IDENTIFIER_OFFSET: {
3839 if (F.LocalNumIdentifiers != 0)
3840 return llvm::createStringError(
3841 std::errc::illegal_byte_sequence,
3842 "duplicate IDENTIFIER_OFFSET record in AST file");
3843 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3845 F.BaseIdentifierID = getTotalNumIdentifiers();
3846
3847 if (F.LocalNumIdentifiers > 0)
3848 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3850 break;
3851 }
3852
3854 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3855 break;
3856
3858 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3859 // about "interesting" decls (for instance, if we're building a module).
3860 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3861 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3862 break;
3863
3865 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3866 // them (ie: if we're not codegenerating this module).
3867 if (F.Kind == MK_MainFile ||
3868 getContext().getLangOpts().BuildingPCHWithObjectFile)
3869 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3870 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3871 break;
3872
3873 case SPECIAL_TYPES:
3874 if (SpecialTypes.empty()) {
3875 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3876 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3877 break;
3878 }
3879
3880 if (Record.empty())
3881 break;
3882
3883 if (SpecialTypes.size() != Record.size())
3884 return llvm::createStringError(std::errc::illegal_byte_sequence,
3885 "invalid special-types record");
3886
3887 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3888 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3889 if (!SpecialTypes[I])
3890 SpecialTypes[I] = ID;
3891 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3892 // merge step?
3893 }
3894 break;
3895
3896 case STATISTICS:
3897 TotalNumStatements += Record[0];
3898 TotalNumMacros += Record[1];
3899 TotalLexicalDeclContexts += Record[2];
3900 TotalVisibleDeclContexts += Record[3];
3901 TotalModuleLocalVisibleDeclContexts += Record[4];
3902 TotalTULocalVisibleDeclContexts += Record[5];
3903 break;
3904
3906 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3907 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3908 break;
3909
3910 case DELEGATING_CTORS:
3911 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3912 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3913 break;
3914
3916 if (Record.size() % 3 != 0)
3917 return llvm::createStringError(std::errc::illegal_byte_sequence,
3918 "invalid weak identifiers record");
3919
3920 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3921 // files. This isn't the way to do it :)
3922 WeakUndeclaredIdentifiers.clear();
3923
3924 // Translate the weak, undeclared identifiers into global IDs.
3925 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3926 WeakUndeclaredIdentifiers.push_back(
3927 getGlobalIdentifierID(F, Record[I++]));
3928 WeakUndeclaredIdentifiers.push_back(
3929 getGlobalIdentifierID(F, Record[I++]));
3930 WeakUndeclaredIdentifiers.push_back(
3931 ReadSourceLocation(F, Record, I).getRawEncoding());
3932 }
3933 break;
3934
3935 case SELECTOR_OFFSETS: {
3936 F.SelectorOffsets = (const uint32_t *)Blob.data();
3938 unsigned LocalBaseSelectorID = Record[1];
3939 F.BaseSelectorID = getTotalNumSelectors();
3940
3941 if (F.LocalNumSelectors > 0) {
3942 // Introduce the global -> local mapping for selectors within this
3943 // module.
3944 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3945
3946 // Introduce the local -> global mapping for selectors within this
3947 // module.
3949 std::make_pair(LocalBaseSelectorID,
3950 F.BaseSelectorID - LocalBaseSelectorID));
3951
3952 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3953 }
3954 break;
3955 }
3956
3957 case METHOD_POOL:
3958 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3959 if (Record[0])
3961 = ASTSelectorLookupTable::Create(
3964 ASTSelectorLookupTrait(*this, F));
3965 TotalNumMethodPoolEntries += Record[1];
3966 break;
3967
3969 if (!Record.empty()) {
3970 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3971 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3972 Record[Idx++]));
3973 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3974 getRawEncoding());
3975 }
3976 }
3977 break;
3978
3979 case PP_ASSUME_NONNULL_LOC: {
3980 unsigned Idx = 0;
3981 if (!Record.empty())
3982 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3983 ReadSourceLocation(F, Record, Idx));
3984 break;
3985 }
3986
3988 if (!Record.empty()) {
3989 SmallVector<SourceLocation, 64> SrcLocs;
3990 unsigned Idx = 0;
3991 while (Idx < Record.size())
3992 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
3993 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3994 }
3995 break;
3996 }
3997
3999 if (!Record.empty()) {
4000 unsigned Idx = 0, End = Record.size() - 1;
4001 bool ReachedEOFWhileSkipping = Record[Idx++];
4002 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4003 if (ReachedEOFWhileSkipping) {
4004 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4005 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4006 bool FoundNonSkipPortion = Record[Idx++];
4007 bool FoundElse = Record[Idx++];
4008 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4009 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4010 FoundElse, ElseLoc);
4011 }
4012 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4013 while (Idx < End) {
4014 auto Loc = ReadSourceLocation(F, Record, Idx);
4015 bool WasSkipping = Record[Idx++];
4016 bool FoundNonSkip = Record[Idx++];
4017 bool FoundElse = Record[Idx++];
4018 ConditionalStack.push_back(
4019 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4020 }
4021 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4022 }
4023 break;
4024
4025 case PP_COUNTER_VALUE:
4026 if (!Record.empty() && Listener)
4027 Listener->ReadCounter(F, Record[0]);
4028 break;
4029
4030 case FILE_SORTED_DECLS:
4031 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4033 break;
4034
4036 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4038 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4040 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4041 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4042 SLocSpaceSize);
4043 if (!F.SLocEntryBaseID) {
4044 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4045 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4046 return llvm::createStringError(std::errc::invalid_argument,
4047 "ran out of source locations");
4048 }
4049 // Make our entry in the range map. BaseID is negative and growing, so
4050 // we invert it. Because we invert it, though, we need the other end of
4051 // the range.
4052 unsigned RangeStart =
4053 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4054 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4056
4057 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4058 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4059 GlobalSLocOffsetMap.insert(
4060 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4061 - SLocSpaceSize,&F));
4062
4063 TotalNumSLocEntries += F.LocalNumSLocEntries;
4064 break;
4065 }
4066
4067 case MODULE_OFFSET_MAP:
4068 F.ModuleOffsetMap = Blob;
4069 break;
4070
4072 ParseLineTable(F, Record);
4073 break;
4074
4075 case EXT_VECTOR_DECLS:
4076 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4077 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4078 break;
4079
4080 case VTABLE_USES:
4081 if (Record.size() % 3 != 0)
4082 return llvm::createStringError(std::errc::illegal_byte_sequence,
4083 "Invalid VTABLE_USES record");
4084
4085 // Later tables overwrite earlier ones.
4086 // FIXME: Modules will have some trouble with this. This is clearly not
4087 // the right way to do this.
4088 VTableUses.clear();
4089
4090 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4091 VTableUses.push_back(
4092 {ReadDeclID(F, Record, Idx),
4093 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4094 (bool)Record[Idx++]});
4095 }
4096 break;
4097
4099
4100 if (Record.size() % 2 != 0)
4101 return llvm::createStringError(
4102 std::errc::illegal_byte_sequence,
4103 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4104
4105 // For standard C++20 module, we will only reads the instantiations
4106 // if it is the main file.
4107 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4108 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4109 PendingInstantiations.push_back(
4110 {ReadDeclID(F, Record, I),
4111 ReadSourceLocation(F, Record, I).getRawEncoding()});
4112 }
4113 }
4114 break;
4115
4116 case SEMA_DECL_REFS:
4117 if (Record.size() != 3)
4118 return llvm::createStringError(std::errc::illegal_byte_sequence,
4119 "Invalid SEMA_DECL_REFS block");
4120 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4121 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4122 break;
4123
4124 case PPD_ENTITIES_OFFSETS: {
4125 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4126 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4127 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4128
4129 unsigned StartingID;
4130 if (!PP.getPreprocessingRecord())
4131 PP.createPreprocessingRecord();
4132 if (!PP.getPreprocessingRecord()->getExternalSource())
4133 PP.getPreprocessingRecord()->SetExternalSource(*this);
4134 StartingID
4135 = PP.getPreprocessingRecord()
4136 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4137 F.BasePreprocessedEntityID = StartingID;
4138
4139 if (F.NumPreprocessedEntities > 0) {
4140 // Introduce the global -> local mapping for preprocessed entities in
4141 // this module.
4142 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4143 }
4144
4145 break;
4146 }
4147
4148 case PPD_SKIPPED_RANGES: {
4149 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4150 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4151 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4152
4153 if (!PP.getPreprocessingRecord())
4154 PP.createPreprocessingRecord();
4155 if (!PP.getPreprocessingRecord()->getExternalSource())
4156 PP.getPreprocessingRecord()->SetExternalSource(*this);
4157 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4158 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4159
4161 GlobalSkippedRangeMap.insert(
4162 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4163 break;
4164 }
4165
4167 if (Record.size() % 2 != 0)
4168 return llvm::createStringError(
4169 std::errc::illegal_byte_sequence,
4170 "invalid DECL_UPDATE_OFFSETS block in AST file");
4171 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4172 GlobalDeclID ID = ReadDeclID(F, Record, I);
4173 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4174
4175 // If we've already loaded the decl, perform the updates when we finish
4176 // loading this block.
4177 if (Decl *D = GetExistingDecl(ID))
4178 PendingUpdateRecords.push_back(
4179 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4180 }
4181 break;
4182
4184 if (Record.size() % 5 != 0)
4185 return llvm::createStringError(
4186 std::errc::illegal_byte_sequence,
4187 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4188 "file");
4189 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4190 GlobalDeclID ID = ReadDeclID(F, Record, I);
4191
4192 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4193 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4194 uint64_t LocalLexicalOffset = Record[I++];
4195 uint64_t LexicalOffset =
4196 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4197 uint64_t LocalVisibleOffset = Record[I++];
4198 uint64_t VisibleOffset =
4199 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4200 uint64_t LocalModuleLocalOffset = Record[I++];
4201 uint64_t ModuleLocalOffset =
4202 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4203 uint64_t TULocalLocalOffset = Record[I++];
4204 uint64_t TULocalOffset =
4205 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4206
4207 DelayedNamespaceOffsetMap[ID] = {
4208 {VisibleOffset, TULocalOffset, ModuleLocalOffset}, LexicalOffset};
4209
4210 assert(!GetExistingDecl(ID) &&
4211 "We shouldn't load the namespace in the front of delayed "
4212 "namespace lexical and visible block");
4213 }
4214 break;
4215 }
4216
4217 case RELATED_DECLS_MAP:
4218 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4219 GlobalDeclID ID = ReadDeclID(F, Record, I);
4220 auto &RelatedDecls = RelatedDeclsMap[ID];
4221 unsigned NN = Record[I++];
4222 RelatedDecls.reserve(NN);
4223 for (unsigned II = 0; II < NN; II++)
4224 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4225 }
4226 break;
4227
4229 if (F.LocalNumObjCCategoriesInMap != 0)
4230 return llvm::createStringError(
4231 std::errc::illegal_byte_sequence,
4232 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4233
4235 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4236 break;
4237
4238 case OBJC_CATEGORIES:
4239 F.ObjCCategories.swap(Record);
4240 break;
4241
4243 // Later tables overwrite earlier ones.
4244 // FIXME: Modules will have trouble with this.
4245 CUDASpecialDeclRefs.clear();
4246 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4247 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4248 break;
4249
4251 F.HeaderFileInfoTableData = Blob.data();
4253 if (Record[0]) {
4254 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4255 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4256 (const unsigned char *)F.HeaderFileInfoTableData,
4257 HeaderFileInfoTrait(*this, F));
4258
4259 PP.getHeaderSearchInfo().SetExternalSource(this);
4260 if (!PP.getHeaderSearchInfo().getExternalLookup())
4261 PP.getHeaderSearchInfo().SetExternalLookup(this);
4262 }
4263 break;
4264
4265 case FP_PRAGMA_OPTIONS:
4266 // Later tables overwrite earlier ones.
4267 FPPragmaOptions.swap(Record);
4268 break;
4269
4271 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4272 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4273 break;
4274
4275 case OPENCL_EXTENSIONS:
4276 for (unsigned I = 0, E = Record.size(); I != E; ) {
4277 auto Name = ReadString(Record, I);
4278 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4279 OptInfo.Supported = Record[I++] != 0;
4280 OptInfo.Enabled = Record[I++] != 0;
4281 OptInfo.WithPragma = Record[I++] != 0;
4282 OptInfo.Avail = Record[I++];
4283 OptInfo.Core = Record[I++];
4284 OptInfo.Opt = Record[I++];
4285 }
4286 break;
4287
4289 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4290 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4291 break;
4292
4293 case KNOWN_NAMESPACES:
4294 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4295 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4296 break;
4297
4298 case UNDEFINED_BUT_USED:
4299 if (Record.size() % 2 != 0)
4300 return llvm::createStringError(std::errc::illegal_byte_sequence,
4301 "invalid undefined-but-used record");
4302 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4303 UndefinedButUsed.push_back(
4304 {ReadDeclID(F, Record, I),
4305 ReadSourceLocation(F, Record, I).getRawEncoding()});
4306 }
4307 break;
4308
4310 for (unsigned I = 0, N = Record.size(); I != N;) {
4311 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4312 const uint64_t Count = Record[I++];
4313 DelayedDeleteExprs.push_back(Count);
4314 for (uint64_t C = 0; C < Count; ++C) {
4315 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4316 bool IsArrayForm = Record[I++] == 1;
4317 DelayedDeleteExprs.push_back(IsArrayForm);
4318 }
4319 }
4320 break;
4321
4322 case VTABLES_TO_EMIT:
4323 if (F.Kind == MK_MainFile ||
4324 getContext().getLangOpts().BuildingPCHWithObjectFile)
4325 for (unsigned I = 0, N = Record.size(); I != N;)
4326 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4327 break;
4328
4329 case IMPORTED_MODULES:
4330 if (!F.isModule()) {
4331 // If we aren't loading a module (which has its own exports), make
4332 // all of the imported modules visible.
4333 // FIXME: Deal with macros-only imports.
4334 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4335 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4336 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4337 if (GlobalID) {
4338 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4339 if (DeserializationListener)
4340 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4341 }
4342 }
4343 }
4344 break;
4345
4346 case MACRO_OFFSET: {
4347 if (F.LocalNumMacros != 0)
4348 return llvm::createStringError(
4349 std::errc::illegal_byte_sequence,
4350 "duplicate MACRO_OFFSET record in AST file");
4351 F.MacroOffsets = (const uint32_t *)Blob.data();
4352 F.LocalNumMacros = Record[0];
4354 F.BaseMacroID = getTotalNumMacros();
4355
4356 if (F.LocalNumMacros > 0)
4357 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4358 break;
4359 }
4360
4362 LateParsedTemplates.emplace_back(
4363 std::piecewise_construct, std::forward_as_tuple(&F),
4364 std::forward_as_tuple(Record.begin(), Record.end()));
4365 break;
4366
4368 if (Record.size() != 1)
4369 return llvm::createStringError(std::errc::illegal_byte_sequence,
4370 "invalid pragma optimize record");
4371 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4372 break;
4373
4375 if (Record.size() != 1)
4376 return llvm::createStringError(std::errc::illegal_byte_sequence,
4377 "invalid pragma ms_struct record");
4378 PragmaMSStructState = Record[0];
4379 break;
4380
4382 if (Record.size() != 2)
4383 return llvm::createStringError(
4384 std::errc::illegal_byte_sequence,
4385 "invalid pragma pointers to members record");
4386 PragmaMSPointersToMembersState = Record[0];
4387 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4388 break;
4389
4391 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4392 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4393 break;
4394
4396 if (Record.size() != 1)
4397 return llvm::createStringError(std::errc::illegal_byte_sequence,
4398 "invalid cuda pragma options record");
4399 ForceHostDeviceDepth = Record[0];
4400 break;
4401
4403 if (Record.size() < 3)
4404 return llvm::createStringError(std::errc::illegal_byte_sequence,
4405 "invalid pragma pack record");
4406 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4407 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4408 unsigned NumStackEntries = Record[2];
4409 unsigned Idx = 3;
4410 // Reset the stack when importing a new module.
4411 PragmaAlignPackStack.clear();
4412 for (unsigned I = 0; I < NumStackEntries; ++I) {
4413 PragmaAlignPackStackEntry Entry;
4414 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4415 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4416 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4417 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4418 Entry.SlotLabel = PragmaAlignPackStrings.back();
4419 PragmaAlignPackStack.push_back(Entry);
4420 }
4421 break;
4422 }
4423
4425 if (Record.size() < 3)
4426 return llvm::createStringError(std::errc::illegal_byte_sequence,
4427 "invalid pragma float control record");
4428 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4429 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4430 unsigned NumStackEntries = Record[2];
4431 unsigned Idx = 3;
4432 // Reset the stack when importing a new module.
4433 FpPragmaStack.clear();
4434 for (unsigned I = 0; I < NumStackEntries; ++I) {
4435 FpPragmaStackEntry Entry;
4436 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4437 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4438 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4439 FpPragmaStrings.push_back(ReadString(Record, Idx));
4440 Entry.SlotLabel = FpPragmaStrings.back();
4441 FpPragmaStack.push_back(Entry);
4442 }
4443 break;
4444 }
4445
4447 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4448 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4449 break;
4450 }
4451 }
4452}
4453
4454void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4455 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4456
4457 // Additional remapping information.
4458 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4459 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4460 F.ModuleOffsetMap = StringRef();
4461
4463 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4464 RemapBuilder SelectorRemap(F.SelectorRemap);
4465
4466 auto &ImportedModuleVector = F.TransitiveImports;
4467 assert(ImportedModuleVector.empty());
4468
4469 while (Data < DataEnd) {
4470 // FIXME: Looking up dependency modules by filename is horrible. Let's
4471 // start fixing this with prebuilt, explicit and implicit modules and see
4472 // how it goes...
4473 using namespace llvm::support;
4474 ModuleKind Kind = static_cast<ModuleKind>(
4475 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4476 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4477 StringRef Name = StringRef((const char*)Data, Len);
4478 Data += Len;
4481 ? ModuleMgr.lookupByModuleName(Name)
4482 : ModuleMgr.lookupByFileName(Name));
4483 if (!OM) {
4484 std::string Msg = "refers to unknown module, cannot find ";
4485 Msg.append(std::string(Name));
4486 Error(Msg);
4487 return;
4488 }
4489
4490 ImportedModuleVector.push_back(OM);
4491
4492 uint32_t SubmoduleIDOffset =
4493 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4494 uint32_t SelectorIDOffset =
4495 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4496
4497 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4498 RemapBuilder &Remap) {
4499 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4500 if (Offset != None)
4501 Remap.insert(std::make_pair(Offset,
4502 static_cast<int>(BaseOffset - Offset)));
4503 };
4504
4505 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4506 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4507 }
4508}
4509
4511ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4512 const ModuleFile *ImportedBy,
4513 unsigned ClientLoadCapabilities) {
4514 unsigned Idx = 0;
4515 F.ModuleMapPath = ReadPath(F, Record, Idx);
4516
4517 // Try to resolve ModuleName in the current header search context and
4518 // verify that it is found in the same module map file as we saved. If the
4519 // top-level AST file is a main file, skip this check because there is no
4520 // usable header search context.
4521 assert(!F.ModuleName.empty() &&
4522 "MODULE_NAME should come before MODULE_MAP_FILE");
4523 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4524 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4525 // An implicitly-loaded module file should have its module listed in some
4526 // module map file that we've already loaded.
4527 Module *M =
4528 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4529 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4530 OptionalFileEntryRef ModMap =
4531 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4532 // Don't emit module relocation error if we have -fno-validate-pch
4533 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4535 !ModMap) {
4536 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4537 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4538 // This module was defined by an imported (explicit) module.
4539 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4540 << ASTFE->getName();
4541 // TODO: Add a note with the module map paths if they differ.
4542 } else {
4543 // This module was built with a different module map.
4544 Diag(diag::err_imported_module_not_found)
4545 << F.ModuleName << F.FileName
4546 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4547 << !ImportedBy;
4548 // In case it was imported by a PCH, there's a chance the user is
4549 // just missing to include the search path to the directory containing
4550 // the modulemap.
4551 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4552 Diag(diag::note_imported_by_pch_module_not_found)
4553 << llvm::sys::path::parent_path(F.ModuleMapPath);
4554 }
4555 }
4556 return OutOfDate;
4557 }
4558
4559 assert(M && M->Name == F.ModuleName && "found module with different name");
4560
4561 // Check the primary module map file.
4562 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4563 if (!StoredModMap || *StoredModMap != ModMap) {
4564 assert(ModMap && "found module is missing module map file");
4565 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4566 "top-level import should be verified");
4567 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4568 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4569 Diag(diag::err_imported_module_modmap_changed)
4570 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4571 << ModMap->getName() << F.ModuleMapPath << NotImported;
4572 return OutOfDate;
4573 }
4574
4575 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4576 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4577 // FIXME: we should use input files rather than storing names.
4578 std::string Filename = ReadPath(F, Record, Idx);
4579 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4580 if (!SF) {
4581 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4582 Error("could not find file '" + Filename +"' referenced by AST file");
4583 return OutOfDate;
4584 }
4585 AdditionalStoredMaps.insert(*SF);
4586 }
4587
4588 // Check any additional module map files (e.g. module.private.modulemap)
4589 // that are not in the pcm.
4590 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4591 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4592 // Remove files that match
4593 // Note: SmallPtrSet::erase is really remove
4594 if (!AdditionalStoredMaps.erase(ModMap)) {
4595 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4596 Diag(diag::err_module_different_modmap)
4597 << F.ModuleName << /*new*/0 << ModMap.getName();
4598 return OutOfDate;
4599 }
4600 }
4601 }
4602
4603 // Check any additional module map files that are in the pcm, but not
4604 // found in header search. Cases that match are already removed.
4605 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4606 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4607 Diag(diag::err_module_different_modmap)
4608 << F.ModuleName << /*not new*/1 << ModMap.getName();
4609 return OutOfDate;
4610 }
4611 }
4612
4613 if (Listener)
4614 Listener->ReadModuleMapFile(F.ModuleMapPath);
4615 return Success;
4616}
4617
4618/// Move the given method to the back of the global list of methods.
4620 // Find the entry for this selector in the method pool.
4621 SemaObjC::GlobalMethodPool::iterator Known =
4622 S.ObjC().MethodPool.find(Method->getSelector());
4623 if (Known == S.ObjC().MethodPool.end())
4624 return;
4625
4626 // Retrieve the appropriate method list.
4627 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4628 : Known->second.second;
4629 bool Found = false;
4630 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4631 if (!Found) {
4632 if (List->getMethod() == Method) {
4633 Found = true;
4634 } else {
4635 // Keep searching.
4636 continue;
4637 }
4638 }
4639
4640 if (List->getNext())
4641 List->setMethod(List->getNext()->getMethod());
4642 else
4643 List->setMethod(Method);
4644 }
4645}
4646
4647void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4648 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4649 for (Decl *D : Names) {
4650 bool wasHidden = !D->isUnconditionallyVisible();
4652
4653 if (wasHidden && SemaObj) {
4654 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4656 }
4657 }
4658 }
4659}
4660
4662 Module::NameVisibilityKind NameVisibility,
4663 SourceLocation ImportLoc) {
4666 Stack.push_back(Mod);
4667 while (!Stack.empty()) {
4668 Mod = Stack.pop_back_val();
4669
4670 if (NameVisibility <= Mod->NameVisibility) {
4671 // This module already has this level of visibility (or greater), so
4672 // there is nothing more to do.
4673 continue;
4674 }
4675
4676 if (Mod->isUnimportable()) {
4677 // Modules that aren't importable cannot be made visible.
4678 continue;
4679 }
4680
4681 // Update the module's name visibility.
4682 Mod->NameVisibility = NameVisibility;
4683
4684 // If we've already deserialized any names from this module,
4685 // mark them as visible.
4686 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4687 if (Hidden != HiddenNamesMap.end()) {
4688 auto HiddenNames = std::move(*Hidden);
4689 HiddenNamesMap.erase(Hidden);
4690 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4691 assert(!HiddenNamesMap.contains(Mod) &&
4692 "making names visible added hidden names");
4693 }
4694
4695 // Push any exported modules onto the stack to be marked as visible.
4697 Mod->getExportedModules(Exports);
4699 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4700 Module *Exported = *I;
4701 if (Visited.insert(Exported).second)
4702 Stack.push_back(Exported);
4703 }
4704 }
4705}
4706
4707/// We've merged the definition \p MergedDef into the existing definition
4708/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4709/// visible.
4711 NamedDecl *MergedDef) {
4712 if (!Def->isUnconditionallyVisible()) {
4713 // If MergedDef is visible or becomes visible, make the definition visible.
4714 if (MergedDef->isUnconditionallyVisible())
4716 else {
4717 getContext().mergeDefinitionIntoModule(
4718 Def, MergedDef->getImportedOwningModule(),
4719 /*NotifyListeners*/ false);
4720 PendingMergedDefinitionsToDeduplicate.insert(Def);
4721 }
4722 }
4723}
4724
4726 if (GlobalIndex)
4727 return false;
4728
4729 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4730 !PP.getLangOpts().Modules)
4731 return true;
4732
4733 // Try to load the global index.
4734 TriedLoadingGlobalIndex = true;
4735 StringRef ModuleCachePath
4736 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4737 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4738 GlobalModuleIndex::readIndex(ModuleCachePath);
4739 if (llvm::Error Err = std::move(Result.second)) {
4740 assert(!Result.first);
4741 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4742 return true;
4743 }
4744
4745 GlobalIndex.reset(Result.first);
4746 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4747 return false;
4748}
4749
4751 return PP.getLangOpts().Modules && UseGlobalIndex &&
4752 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4753}
4754
4755/// Given a cursor at the start of an AST file, scan ahead and drop the
4756/// cursor into the start of the given block ID, returning false on success and
4757/// true on failure.
4758static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4759 while (true) {
4760 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4761 if (!MaybeEntry) {
4762 // FIXME this drops errors on the floor.
4763 consumeError(MaybeEntry.takeError());
4764 return true;
4765 }
4766 llvm::BitstreamEntry Entry = MaybeEntry.get();
4767
4768 switch (Entry.Kind) {
4769 case llvm::BitstreamEntry::Error:
4770 case llvm::BitstreamEntry::EndBlock:
4771 return true;
4772
4773 case llvm::BitstreamEntry::Record:
4774 // Ignore top-level records.
4775 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4776 break;
4777 else {
4778 // FIXME this drops errors on the floor.
4779 consumeError(Skipped.takeError());
4780 return true;
4781 }
4782
4783 case llvm::BitstreamEntry::SubBlock:
4784 if (Entry.ID == BlockID) {
4785 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4786 // FIXME this drops the error on the floor.
4787 consumeError(std::move(Err));
4788 return true;
4789 }
4790 // Found it!
4791 return false;
4792 }
4793
4794 if (llvm::Error Err = Cursor.SkipBlock()) {
4795 // FIXME this drops the error on the floor.
4796 consumeError(std::move(Err));
4797 return true;
4798 }
4799 }
4800 }
4801}
4802
4804 SourceLocation ImportLoc,
4805 unsigned ClientLoadCapabilities,
4806 ModuleFile **NewLoadedModuleFile) {
4807 llvm::TimeTraceScope scope("ReadAST", FileName);
4808
4809 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4811 CurrentDeserializingModuleKind, Type);
4812
4813 // Defer any pending actions until we get to the end of reading the AST file.
4814 Deserializing AnASTFile(this);
4815
4816 // Bump the generation number.
4817 unsigned PreviousGeneration = 0;
4818 if (ContextObj)
4819 PreviousGeneration = incrementGeneration(*ContextObj);
4820
4821 unsigned NumModules = ModuleMgr.size();
4823 if (ASTReadResult ReadResult =
4824 ReadASTCore(FileName, Type, ImportLoc,
4825 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4826 ClientLoadCapabilities)) {
4827 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4828
4829 // If we find that any modules are unusable, the global index is going
4830 // to be out-of-date. Just remove it.
4831 GlobalIndex.reset();
4832 ModuleMgr.setGlobalIndex(nullptr);
4833 return ReadResult;
4834 }
4835
4836 if (NewLoadedModuleFile && !Loaded.empty())
4837 *NewLoadedModuleFile = Loaded.back().Mod;
4838
4839 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4840 // remove modules from this point. Various fields are updated during reading
4841 // the AST block and removing the modules would result in dangling pointers.
4842 // They are generally only incidentally dereferenced, ie. a binary search
4843 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4844 // be dereferenced but it wouldn't actually be used.
4845
4846 // Load the AST blocks of all of the modules that we loaded. We can still
4847 // hit errors parsing the ASTs at this point.
4848 for (ImportedModule &M : Loaded) {
4849 ModuleFile &F = *M.Mod;
4850 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4851
4852 // Read the AST block.
4853 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4854 Error(std::move(Err));
4855 return Failure;
4856 }
4857
4858 // The AST block should always have a definition for the main module.
4859 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4860 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4861 return Failure;
4862 }
4863
4864 // Read the extension blocks.
4866 if (llvm::Error Err = ReadExtensionBlock(F)) {
4867 Error(std::move(Err));
4868 return Failure;
4869 }
4870 }
4871
4872 // Once read, set the ModuleFile bit base offset and update the size in
4873 // bits of all files we've seen.
4874 F.GlobalBitOffset = TotalModulesSizeInBits;
4875 TotalModulesSizeInBits += F.SizeInBits;
4876 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4877 }
4878
4879 // Preload source locations and interesting indentifiers.
4880 for (ImportedModule &M : Loaded) {
4881 ModuleFile &F = *M.Mod;
4882
4883 // Map the original source file ID into the ID space of the current
4884 // compilation.
4887
4888 for (auto Offset : F.PreloadIdentifierOffsets) {
4889 const unsigned char *Data = F.IdentifierTableData + Offset;
4890
4891 ASTIdentifierLookupTrait Trait(*this, F);
4892 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4893 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4894
4895 IdentifierInfo *II;
4896 if (!PP.getLangOpts().CPlusPlus) {
4897 // Identifiers present in both the module file and the importing
4898 // instance are marked out-of-date so that they can be deserialized
4899 // on next use via ASTReader::updateOutOfDateIdentifier().
4900 // Identifiers present in the module file but not in the importing
4901 // instance are ignored for now, preventing growth of the identifier
4902 // table. They will be deserialized on first use via ASTReader::get().
4903 auto It = PP.getIdentifierTable().find(Key);
4904 if (It == PP.getIdentifierTable().end())
4905 continue;
4906 II = It->second;
4907 } else {
4908 // With C++ modules, not many identifiers are considered interesting.
4909 // All identifiers in the module file can be placed into the identifier
4910 // table of the importing instance and marked as out-of-date. This makes
4911 // ASTReader::get() a no-op, and deserialization will take place on
4912 // first/next use via ASTReader::updateOutOfDateIdentifier().
4913 II = &PP.getIdentifierTable().getOwn(Key);
4914 }
4915
4916 II->setOutOfDate(true);
4917
4918 // Mark this identifier as being from an AST file so that we can track
4919 // whether we need to serialize it.
4920 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
4921
4922 // Associate the ID with the identifier so that the writer can reuse it.
4923 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4924 SetIdentifierInfo(ID, II);
4925 }
4926 }
4927
4928 // Builtins and library builtins have already been initialized. Mark all
4929 // identifiers as out-of-date, so that they are deserialized on first use.
4930 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4931 for (auto &Id : PP.getIdentifierTable())
4932 Id.second->setOutOfDate(true);
4933
4934 // Mark selectors as out of date.
4935 for (const auto &Sel : SelectorGeneration)
4936 SelectorOutOfDate[Sel.first] = true;
4937
4938 // Setup the import locations and notify the module manager that we've
4939 // committed to these module files.
4940 for (ImportedModule &M : Loaded) {
4941 ModuleFile &F = *M.Mod;
4942
4943 ModuleMgr.moduleFileAccepted(&F);
4944
4945 // Set the import location.
4946 F.DirectImportLoc = ImportLoc;
4947 // FIXME: We assume that locations from PCH / preamble do not need
4948 // any translation.
4949 if (!M.ImportedBy)
4950 F.ImportLoc = M.ImportLoc;
4951 else
4952 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4953 }
4954
4955 // Resolve any unresolved module exports.
4956 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4957 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4959 Module *ResolvedMod = getSubmodule(GlobalID);
4960
4961 switch (Unresolved.Kind) {
4962 case UnresolvedModuleRef::Conflict:
4963 if (ResolvedMod) {
4964 Module::Conflict Conflict;
4965 Conflict.Other = ResolvedMod;
4966 Conflict.Message = Unresolved.String.str();
4967 Unresolved.Mod->Conflicts.push_back(Conflict);
4968 }
4969 continue;
4970
4971 case UnresolvedModuleRef::Import:
4972 if (ResolvedMod)
4973 Unresolved.Mod->Imports.insert(ResolvedMod);
4974 continue;
4975
4976 case UnresolvedModuleRef::Affecting:
4977 if (ResolvedMod)
4978 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4979 continue;
4980
4981 case UnresolvedModuleRef::Export:
4982 if (ResolvedMod || Unresolved.IsWildcard)
4983 Unresolved.Mod->Exports.push_back(
4984 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4985 continue;
4986 }
4987 }
4988 UnresolvedModuleRefs.clear();
4989
4990 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4991 // Might be unnecessary as use declarations are only used to build the
4992 // module itself.
4993
4994 if (ContextObj)
4996
4997 if (SemaObj)
4998 UpdateSema();
4999
5000 if (DeserializationListener)
5001 DeserializationListener->ReaderInitialized(this);
5002
5003 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5004 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5005 // If this AST file is a precompiled preamble, then set the
5006 // preamble file ID of the source manager to the file source file
5007 // from which the preamble was built.
5008 if (Type == MK_Preamble) {
5009 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5010 } else if (Type == MK_MainFile) {
5011 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5012 }
5013 }
5014
5015 // For any Objective-C class definitions we have already loaded, make sure
5016 // that we load any additional categories.
5017 if (ContextObj) {
5018 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5019 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5020 ObjCClassesLoaded[I], PreviousGeneration);
5021 }
5022 }
5023
5024 const HeaderSearchOptions &HSOpts =
5025 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5027 // Now we are certain that the module and all modules it depends on are
5028 // up-to-date. For implicitly-built module files, ensure the corresponding
5029 // timestamp files are up-to-date in this build session.
5030 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5031 ImportedModule &M = Loaded[I];
5032 if (M.Mod->Kind == MK_ImplicitModule &&
5034 getModuleManager().getModuleCache().updateModuleTimestamp(
5035 M.Mod->FileName);
5036 }
5037 }
5038
5039 return Success;
5040}
5041
5042static ASTFileSignature readASTFileSignature(StringRef PCH);
5043
5044/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5045static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5046 // FIXME checking magic headers is done in other places such as
5047 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5048 // always done the same. Unify it all with a helper.
5049 if (!Stream.canSkipToPos(4))
5050 return llvm::createStringError(
5051 std::errc::illegal_byte_sequence,
5052 "file too small to contain precompiled file magic");
5053 for (unsigned C : {'C', 'P', 'C', 'H'})
5054 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5055 if (Res.get() != C)
5056 return llvm::createStringError(
5057 std::errc::illegal_byte_sequence,
5058 "file doesn't start with precompiled file magic");
5059 } else
5060 return Res.takeError();
5061 return llvm::Error::success();
5062}
5063
5065 switch (Kind) {
5066 case MK_PCH:
5067 return 0; // PCH
5068 case MK_ImplicitModule:
5069 case MK_ExplicitModule:
5070 case MK_PrebuiltModule:
5071 return 1; // module
5072 case MK_MainFile:
5073 case MK_Preamble:
5074 return 2; // main source file
5075 }
5076 llvm_unreachable("unknown module kind");
5077}
5078
5080ASTReader::ReadASTCore(StringRef FileName,
5082 SourceLocation ImportLoc,
5083 ModuleFile *ImportedBy,
5084 SmallVectorImpl<ImportedModule> &Loaded,
5085 off_t ExpectedSize, time_t ExpectedModTime,
5086 ASTFileSignature ExpectedSignature,
5087 unsigned ClientLoadCapabilities) {
5088 ModuleFile *M;
5089 std::string ErrorStr;
5091 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
5092 getGeneration(), ExpectedSize, ExpectedModTime,
5093 ExpectedSignature, readASTFileSignature,
5094 M, ErrorStr);
5095
5096 switch (AddResult) {
5098 Diag(diag::remark_module_import)
5099 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5100 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5101 return Success;
5102
5104 // Load module file below.
5105 break;
5106
5108 // The module file was missing; if the client can handle that, return
5109 // it.
5110 if (ClientLoadCapabilities & ARR_Missing)
5111 return Missing;
5112
5113 // Otherwise, return an error.
5114 Diag(diag::err_ast_file_not_found)
5115 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5116 << ErrorStr;
5117 return Failure;
5118
5120 // We couldn't load the module file because it is out-of-date. If the
5121 // client can handle out-of-date, return it.
5122 if (ClientLoadCapabilities & ARR_OutOfDate)
5123 return OutOfDate;
5124
5125 // Otherwise, return an error.
5126 Diag(diag::err_ast_file_out_of_date)
5127 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5128 << ErrorStr;
5129 return Failure;
5130 }
5131
5132 assert(M && "Missing module file");
5133
5134 bool ShouldFinalizePCM = false;
5135 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
5136 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5137 if (ShouldFinalizePCM)
5138 MC.finalizePCM(FileName);
5139 else
5140 MC.tryToDropPCM(FileName);
5141 });
5142 ModuleFile &F = *M;
5143 BitstreamCursor &Stream = F.Stream;
5144 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5145 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5146
5147 // Sniff for the signature.
5148 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5149 Diag(diag::err_ast_file_invalid)
5150 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5151 return Failure;
5152 }
5153
5154 // This is used for compatibility with older PCH formats.
5155 bool HaveReadControlBlock = false;
5156 while (true) {
5157 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5158 if (!MaybeEntry) {
5159 Error(MaybeEntry.takeError());
5160 return Failure;
5161 }
5162 llvm::BitstreamEntry Entry = MaybeEntry.get();
5163
5164 switch (Entry.Kind) {
5165 case llvm::BitstreamEntry::Error:
5166 case llvm::BitstreamEntry::Record:
5167 case llvm::BitstreamEntry::EndBlock:
5168 Error("invalid record at top-level of AST file");
5169 return Failure;
5170
5171 case llvm::BitstreamEntry::SubBlock:
5172 break;
5173 }
5174
5175 switch (Entry.ID) {
5176 case CONTROL_BLOCK_ID:
5177 HaveReadControlBlock = true;
5178 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5179 case Success:
5180 // Check that we didn't try to load a non-module AST file as a module.
5181 //
5182 // FIXME: Should we also perform the converse check? Loading a module as
5183 // a PCH file sort of works, but it's a bit wonky.
5185 Type == MK_PrebuiltModule) &&
5186 F.ModuleName.empty()) {
5187 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
5188 if (Result != OutOfDate ||
5189 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5190 Diag(diag::err_module_file_not_module) << FileName;
5191 return Result;
5192 }
5193 break;
5194
5195 case Failure: return Failure;
5196 case Missing: return Missing;
5197 case OutOfDate: return OutOfDate;
5198 case VersionMismatch: return VersionMismatch;
5199 case ConfigurationMismatch: return ConfigurationMismatch;
5200 case HadErrors: return HadErrors;
5201 }
5202 break;
5203
5204 case AST_BLOCK_ID:
5205 if (!HaveReadControlBlock) {
5206 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5207 Diag(diag::err_ast_file_version_too_old)
5209 return VersionMismatch;
5210 }
5211
5212 // Record that we've loaded this module.
5213 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5214 ShouldFinalizePCM = true;
5215 return Success;
5216
5217 default:
5218 if (llvm::Error Err = Stream.SkipBlock()) {
5219 Error(std::move(Err));
5220 return Failure;
5221 }
5222 break;
5223 }
5224 }
5225
5226 llvm_unreachable("unexpected break; expected return");
5227}
5228
5230ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5231 unsigned ClientLoadCapabilities) {
5232 const HeaderSearchOptions &HSOpts =
5233 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5234 bool AllowCompatibleConfigurationMismatch =
5236 bool DisableValidation = shouldDisableValidationForFile(F);
5237
5238 ASTReadResult Result = readUnhashedControlBlockImpl(
5239 &F, F.Data, F.FileName, ClientLoadCapabilities,
5240 AllowCompatibleConfigurationMismatch, Listener.get(),
5241 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5242
5243 // If F was directly imported by another module, it's implicitly validated by
5244 // the importing module.
5245 if (DisableValidation || WasImportedBy ||
5246 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5247 return Success;
5248
5249 if (Result == Failure) {
5250 Error("malformed block record in AST file");
5251 return Failure;
5252 }
5253
5254 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5255 // If this module has already been finalized in the ModuleCache, we're stuck
5256 // with it; we can only load a single version of each module.
5257 //
5258 // This can happen when a module is imported in two contexts: in one, as a
5259 // user module; in another, as a system module (due to an import from
5260 // another module marked with the [system] flag). It usually indicates a
5261 // bug in the module map: this module should also be marked with [system].
5262 //
5263 // If -Wno-system-headers (the default), and the first import is as a
5264 // system module, then validation will fail during the as-user import,
5265 // since -Werror flags won't have been validated. However, it's reasonable
5266 // to treat this consistently as a system module.
5267 //
5268 // If -Wsystem-headers, the PCM on disk was built with
5269 // -Wno-system-headers, and the first import is as a user module, then
5270 // validation will fail during the as-system import since the PCM on disk
5271 // doesn't guarantee that -Werror was respected. However, the -Werror
5272 // flags were checked during the initial as-user import.
5273 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5274 F.FileName)) {
5275 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5276 return Success;
5277 }
5278 }
5279
5280 return Result;
5281}
5282
5283ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5284 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5285 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5286 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5287 // Initialize a stream.
5288 BitstreamCursor Stream(StreamData);
5289
5290 // Sniff for the signature.
5291 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5292 // FIXME this drops the error on the floor.
5293 consumeError(std::move(Err));
5294 return Failure;
5295 }
5296
5297 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5299 return Failure;
5300
5301 // Read all of the records in the options block.
5302 RecordData Record;
5303 ASTReadResult Result = Success;
5304 while (true) {
5305 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5306 if (!MaybeEntry) {
5307 // FIXME this drops the error on the floor.
5308 consumeError(MaybeEntry.takeError());
5309 return Failure;
5310 }
5311 llvm::BitstreamEntry Entry = MaybeEntry.get();
5312
5313 switch (Entry.Kind) {
5314 case llvm::BitstreamEntry::Error:
5315 case llvm::BitstreamEntry::SubBlock:
5316 return Failure;
5317
5318 case llvm::BitstreamEntry::EndBlock:
5319 return Result;
5320
5321 case llvm::BitstreamEntry::Record:
5322 // The interesting case.
5323 break;
5324 }
5325
5326 // Read and process a record.
5327 Record.clear();
5328 StringRef Blob;
5329 Expected<unsigned> MaybeRecordType =
5330 Stream.readRecord(Entry.ID, Record, &Blob);
5331 if (!MaybeRecordType) {
5332 // FIXME this drops the error.
5333 return Failure;
5334 }
5335 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5336 case SIGNATURE:
5337 if (F) {
5338 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5340 "Dummy AST file signature not backpatched in ASTWriter.");
5341 }
5342 break;
5343 case AST_BLOCK_HASH:
5344 if (F) {
5345 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5347 "Dummy AST block hash not backpatched in ASTWriter.");
5348 }
5349 break;
5350 case DIAGNOSTIC_OPTIONS: {
5351 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5352 if (Listener && ValidateDiagnosticOptions &&
5353 !AllowCompatibleConfigurationMismatch &&
5354 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5355 Result = OutOfDate; // Don't return early. Read the signature.
5356 break;
5357 }
5358 case HEADER_SEARCH_PATHS: {
5359 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5360 if (Listener && !AllowCompatibleConfigurationMismatch &&
5361 ParseHeaderSearchPaths(Record, Complain, *Listener))
5362 Result = ConfigurationMismatch;
5363 break;
5364 }
5366 if (!F)
5367 break;
5368 if (F->PragmaDiagMappings.empty())
5369 F->PragmaDiagMappings.swap(Record);
5370 else
5371 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5372 Record.begin(), Record.end());
5373 break;
5375 if (F)
5376 F->SearchPathUsage = ReadBitVector(Record, Blob);
5377 break;
5378 case VFS_USAGE:
5379 if (F)
5380 F->VFSUsage = ReadBitVector(Record, Blob);
5381 break;
5382 }
5383 }
5384}
5385
5386/// Parse a record and blob containing module file extension metadata.
5389 StringRef Blob,
5390 ModuleFileExtensionMetadata &Metadata) {
5391 if (Record.size() < 4) return true;
5392
5393 Metadata.MajorVersion = Record[0];
5394 Metadata.MinorVersion = Record[1];
5395
5396 unsigned BlockNameLen = Record[2];
5397 unsigned UserInfoLen = Record[3];
5398
5399 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5400
5401 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5402 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5403 Blob.data() + BlockNameLen + UserInfoLen);
5404 return false;
5405}
5406
5407llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5408 BitstreamCursor &Stream = F.Stream;
5409
5410 RecordData Record;
5411 while (true) {
5412 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5413 if (!MaybeEntry)
5414 return MaybeEntry.takeError();
5415 llvm::BitstreamEntry Entry = MaybeEntry.get();
5416
5417 switch (Entry.Kind) {
5418 case llvm::BitstreamEntry::SubBlock:
5419 if (llvm::Error Err = Stream.SkipBlock())
5420 return Err;
5421 continue;
5422 case llvm::BitstreamEntry::EndBlock:
5423 return llvm::Error::success();
5424 case llvm::BitstreamEntry::Error:
5425 return llvm::createStringError(std::errc::illegal_byte_sequence,
5426 "malformed block record in AST file");
5427 case llvm::BitstreamEntry::Record:
5428 break;
5429 }
5430
5431 Record.clear();
5432 StringRef Blob;
5433 Expected<unsigned> MaybeRecCode =
5434 Stream.readRecord(Entry.ID, Record, &Blob);
5435 if (!MaybeRecCode)
5436 return MaybeRecCode.takeError();
5437 switch (MaybeRecCode.get()) {
5438 case EXTENSION_METADATA: {
5439 ModuleFileExtensionMetadata Metadata;
5440 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5441 return llvm::createStringError(
5442 std::errc::illegal_byte_sequence,
5443 "malformed EXTENSION_METADATA in AST file");
5444
5445 // Find a module file extension with this block name.
5446 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5447 if (Known == ModuleFileExtensions.end()) break;
5448
5449 // Form a reader.
5450 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5451 F, Stream)) {
5452 F.ExtensionReaders.push_back(std::move(Reader));
5453 }
5454
5455 break;
5456 }
5457 }
5458 }
5459
5460 llvm_unreachable("ReadExtensionBlock should return from while loop");
5461}
5462
5464 assert(ContextObj && "no context to initialize");
5465 ASTContext &Context = *ContextObj;
5466
5467 // If there's a listener, notify them that we "read" the translation unit.
5468 if (DeserializationListener)
5469 DeserializationListener->DeclRead(
5471 Context.getTranslationUnitDecl());
5472
5473 // FIXME: Find a better way to deal with collisions between these
5474 // built-in types. Right now, we just ignore the problem.
5475
5476 // Load the special types.
5477 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5478 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5479 if (!Context.CFConstantStringTypeDecl)
5480 Context.setCFConstantStringType(GetType(String));
5481 }
5482
5483 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5484 QualType FileType = GetType(File);
5485 if (FileType.isNull()) {
5486 Error("FILE type is NULL");
5487 return;
5488 }
5489
5490 if (!Context.FILEDecl) {
5491 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5492 Context.setFILEDecl(Typedef->getDecl());
5493 else {
5494 const TagType *Tag = FileType->getAs<TagType>();
5495 if (!Tag) {
5496 Error("Invalid FILE type in AST file");
5497 return;
5498 }
5499 Context.setFILEDecl(Tag->getDecl());
5500 }
5501 }
5502 }
5503
5504 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5505 QualType Jmp_bufType = GetType(Jmp_buf);
5506 if (Jmp_bufType.isNull()) {
5507 Error("jmp_buf type is NULL");
5508 return;
5509 }
5510
5511 if (!Context.jmp_bufDecl) {
5512 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5513 Context.setjmp_bufDecl(Typedef->getDecl());
5514 else {
5515 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5516 if (!Tag) {
5517 Error("Invalid jmp_buf type in AST file");
5518 return;
5519 }
5520 Context.setjmp_bufDecl(Tag->getDecl());
5521 }
5522 }
5523 }
5524
5525 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5526 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5527 if (Sigjmp_bufType.isNull()) {
5528 Error("sigjmp_buf type is NULL");
5529 return;
5530 }
5531
5532 if (!Context.sigjmp_bufDecl) {
5533 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5534 Context.setsigjmp_bufDecl(Typedef->getDecl());
5535 else {
5536 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5537 assert(Tag && "Invalid sigjmp_buf type in AST file");
5538 Context.setsigjmp_bufDecl(Tag->getDecl());
5539 }
5540 }
5541 }
5542
5543 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5544 if (Context.ObjCIdRedefinitionType.isNull())
5545 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5546 }
5547
5548 if (TypeID ObjCClassRedef =
5550 if (Context.ObjCClassRedefinitionType.isNull())
5551 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5552 }
5553
5554 if (TypeID ObjCSelRedef =
5555 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5556 if (Context.ObjCSelRedefinitionType.isNull())
5557 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5558 }
5559
5560 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5561 QualType Ucontext_tType = GetType(Ucontext_t);
5562 if (Ucontext_tType.isNull()) {
5563 Error("ucontext_t type is NULL");
5564 return;
5565 }
5566
5567 if (!Context.ucontext_tDecl) {
5568 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5569 Context.setucontext_tDecl(Typedef->getDecl());
5570 else {
5571 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5572 assert(Tag && "Invalid ucontext_t type in AST file");
5573 Context.setucontext_tDecl(Tag->getDecl());
5574 }
5575 }
5576 }
5577 }
5578
5579 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5580
5581 // If there were any CUDA special declarations, deserialize them.
5582 if (!CUDASpecialDeclRefs.empty()) {
5583 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5584 Context.setcudaConfigureCallDecl(
5585 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5586 }
5587
5588 // Re-export any modules that were imported by a non-module AST file.
5589 // FIXME: This does not make macro-only imports visible again.
5590 for (auto &Import : PendingImportedModules) {
5591 if (Module *Imported = getSubmodule(Import.ID)) {
5593 /*ImportLoc=*/Import.ImportLoc);
5594 if (Import.ImportLoc.isValid())
5595 PP.makeModuleVisible(Imported, Import.ImportLoc);
5596 // This updates visibility for Preprocessor only. For Sema, which can be
5597 // nullptr here, we do the same later, in UpdateSema().
5598 }
5599 }
5600
5601 // Hand off these modules to Sema.
5602 PendingImportedModulesSema.append(PendingImportedModules);
5603 PendingImportedModules.clear();
5604}
5605
5607 // Nothing to do for now.
5608}
5609
5610/// Reads and return the signature record from \p PCH's control block, or
5611/// else returns 0.
5613 BitstreamCursor Stream(PCH);
5614 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5615 // FIXME this drops the error on the floor.
5616 consumeError(std::move(Err));
5617 return ASTFileSignature();
5618 }
5619
5620 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5622 return ASTFileSignature();
5623
5624 // Scan for SIGNATURE inside the diagnostic options block.
5626 while (true) {
5628 Stream.advanceSkippingSubblocks();
5629 if (!MaybeEntry) {
5630 // FIXME this drops the error on the floor.
5631 consumeError(MaybeEntry.takeError());
5632 return ASTFileSignature();
5633 }
5634 llvm::BitstreamEntry Entry = MaybeEntry.get();
5635
5636 if (Entry.Kind != llvm::BitstreamEntry::Record)
5637 return ASTFileSignature();
5638
5639 Record.clear();
5640 StringRef Blob;
5641 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5642 if (!MaybeRecord) {
5643 // FIXME this drops the error on the floor.
5644 consumeError(MaybeRecord.takeError());
5645 return ASTFileSignature();
5646 }
5647 if (SIGNATURE == MaybeRecord.get()) {
5648 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5649 assert(Signature != ASTFileSignature::createDummy() &&
5650 "Dummy AST file signature not backpatched in ASTWriter.");
5651 return Signature;
5652 }
5653 }
5654}
5655
5656/// Retrieve the name of the original source file name
5657/// directly from the AST file, without actually loading the AST
5658/// file.
5660 const std::string &ASTFileName, FileManager &FileMgr,
5661 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5662 // Open the AST file.
5663 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5664 /*RequiresNullTerminator=*/false,
5665 /*MaybeLimit=*/std::nullopt,
5666 /*IsText=*/false);
5667 if (!Buffer) {
5668 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5669 << ASTFileName << Buffer.getError().message();
5670 return std::string();
5671 }
5672
5673 // Initialize the stream
5674 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5675
5676 // Sniff for the signature.
5677 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5678 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5679 return std::string();
5680 }
5681
5682 // Scan for the CONTROL_BLOCK_ID block.
5683 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5684 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5685 return std::string();
5686 }
5687
5688 // Scan for ORIGINAL_FILE inside the control block.
5690 while (true) {
5692 Stream.advanceSkippingSubblocks();
5693 if (!MaybeEntry) {
5694 // FIXME this drops errors on the floor.
5695 consumeError(MaybeEntry.takeError());
5696 return std::string();
5697 }
5698 llvm::BitstreamEntry Entry = MaybeEntry.get();
5699
5700 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5701 return std::string();
5702
5703 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5704 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5705 return std::string();
5706 }
5707
5708 Record.clear();
5709 StringRef Blob;
5710 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5711 if (!MaybeRecord) {
5712 // FIXME this drops the errors on the floor.
5713 consumeError(MaybeRecord.takeError());
5714 return std::string();
5715 }
5716 if (ORIGINAL_FILE == MaybeRecord.get())
5717 return Blob.str();
5718 }
5719}
5720
5721namespace {
5722
5723 class SimplePCHValidator : public ASTReaderListener {
5724 const LangOptions &ExistingLangOpts;
5725 const CodeGenOptions &ExistingCGOpts;
5726 const TargetOptions &ExistingTargetOpts;
5727 const PreprocessorOptions &ExistingPPOpts;
5728 std::string ExistingModuleCachePath;
5730 bool StrictOptionMatches;
5731
5732 public:
5733 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5734 const CodeGenOptions &ExistingCGOpts,
5735 const TargetOptions &ExistingTargetOpts,
5736 const PreprocessorOptions &ExistingPPOpts,
5737 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5738 bool StrictOptionMatches)
5739 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5740 ExistingTargetOpts(ExistingTargetOpts),
5741 ExistingPPOpts(ExistingPPOpts),
5742 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5743 StrictOptionMatches(StrictOptionMatches) {}
5744
5745 bool ReadLanguageOptions(const LangOptions &LangOpts,
5746 StringRef ModuleFilename, bool Complain,
5747 bool AllowCompatibleDifferences) override {
5748 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5749 nullptr, AllowCompatibleDifferences);
5750 }
5751
5752 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5753 StringRef ModuleFilename, bool Complain,
5754 bool AllowCompatibleDifferences) override {
5755 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5756 nullptr, AllowCompatibleDifferences);
5757 }
5758
5759 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5760 StringRef ModuleFilename, bool Complain,
5761 bool AllowCompatibleDifferences) override {
5762 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5763 nullptr, AllowCompatibleDifferences);
5764 }
5765
5766 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5767 StringRef ModuleFilename,
5768 StringRef SpecificModuleCachePath,
5769 bool Complain) override {
5771 SpecificModuleCachePath,
5772 ExistingModuleCachePath, ModuleFilename,
5773 nullptr, ExistingLangOpts, ExistingPPOpts);
5774 }
5775
5776 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5777 StringRef ModuleFilename, bool ReadMacros,
5778 bool Complain,
5779 std::string &SuggestedPredefines) override {
5781 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5782 FileMgr, SuggestedPredefines, ExistingLangOpts,
5783 StrictOptionMatches ? OptionValidateStrictMatches
5785 }
5786 };
5787
5788} // namespace
5789
5791 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5792 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5793 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5794 unsigned ClientLoadCapabilities) {
5795 // Open the AST file.
5796 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5797 llvm::MemoryBuffer *Buffer =
5798 ModCache.getInMemoryModuleCache().lookupPCM(Filename);
5799 if (!Buffer) {
5800 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5801 // read again later, but we do not have the context here to determine if it
5802 // is safe to change the result of InMemoryModuleCache::getPCMState().
5803
5804 // FIXME: This allows use of the VFS; we do not allow use of the
5805 // VFS when actually loading a module.
5806 auto Entry =
5807 Filename == "-" ? FileMgr.getSTDIN() : FileMgr.getFileRef(Filename);
5808 if (!Entry) {
5809 llvm::consumeError(Entry.takeError());
5810 return true;
5811 }
5812 auto BufferOrErr = FileMgr.getBufferForFile(*Entry);
5813 if (!BufferOrErr)
5814 return true;
5815 OwnedBuffer = std::move(*BufferOrErr);
5816 Buffer = OwnedBuffer.get();
5817 }
5818
5819 // Initialize the stream
5820 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5821 BitstreamCursor Stream(Bytes);
5822
5823 // Sniff for the signature.
5824 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5825 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5826 return true;
5827 }
5828
5829 // Scan for the CONTROL_BLOCK_ID block.
5831 return true;
5832
5833 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5834 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5835 bool NeedsImports = Listener.needsImportVisitation();
5836 BitstreamCursor InputFilesCursor;
5837 uint64_t InputFilesOffsetBase = 0;
5838
5840 std::string ModuleDir;
5841 bool DoneWithControlBlock = false;
5842 SmallString<0> PathBuf;
5843 PathBuf.reserve(256);
5844 // Additional path buffer to use when multiple paths need to be resolved.
5845 // For example, when deserializing input files that contains a path that was
5846 // resolved from a vfs overlay and an external location.
5847 SmallString<0> AdditionalPathBuf;
5848 AdditionalPathBuf.reserve(256);
5849 while (!DoneWithControlBlock) {
5850 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5851 if (!MaybeEntry) {
5852 // FIXME this drops the error on the floor.
5853 consumeError(MaybeEntry.takeError());
5854 return true;
5855 }
5856 llvm::BitstreamEntry Entry = MaybeEntry.get();
5857
5858 switch (Entry.Kind) {
5859 case llvm::BitstreamEntry::SubBlock: {
5860 switch (Entry.ID) {
5861 case OPTIONS_BLOCK_ID: {
5862 std::string IgnoredSuggestedPredefines;
5863 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5864 /*AllowCompatibleConfigurationMismatch*/ false,
5865 Listener, IgnoredSuggestedPredefines) != Success)
5866 return true;
5867 break;
5868 }
5869
5871 InputFilesCursor = Stream;
5872 if (llvm::Error Err = Stream.SkipBlock()) {
5873 // FIXME this drops the error on the floor.
5874 consumeError(std::move(Err));
5875 return true;
5876 }
5877 if (NeedsInputFiles &&
5878 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5879 return true;
5880 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5881 break;
5882
5883 default:
5884 if (llvm::Error Err = Stream.SkipBlock()) {
5885 // FIXME this drops the error on the floor.
5886 consumeError(std::move(Err));
5887 return true;
5888 }
5889 break;
5890 }
5891
5892 continue;
5893 }
5894
5895 case llvm::BitstreamEntry::EndBlock:
5896 DoneWithControlBlock = true;
5897 break;
5898
5899 case llvm::BitstreamEntry::Error:
5900 return true;
5901
5902 case llvm::BitstreamEntry::Record:
5903 break;
5904 }
5905
5906 if (DoneWithControlBlock) break;
5907
5908 Record.clear();
5909 StringRef Blob;
5910 Expected<unsigned> MaybeRecCode =
5911 Stream.readRecord(Entry.ID, Record, &Blob);
5912 if (!MaybeRecCode) {
5913 // FIXME this drops the error.
5914 return Failure;
5915 }
5916 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5917 case METADATA:
5918 if (Record[0] != VERSION_MAJOR)
5919 return true;
5920 if (Listener.ReadFullVersionInformation(Blob))
5921 return true;
5922 break;
5923 case MODULE_NAME:
5924 Listener.ReadModuleName(Blob);
5925 break;
5926 case MODULE_DIRECTORY:
5927 ModuleDir = std::string(Blob);
5928 break;
5929 case MODULE_MAP_FILE: {
5930 unsigned Idx = 0;
5931 std::string PathStr = ReadString(Record, Idx);
5932 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
5933 Listener.ReadModuleMapFile(*Path);
5934 break;
5935 }
5936 case INPUT_FILE_OFFSETS: {
5937 if (!NeedsInputFiles)
5938 break;
5939
5940 unsigned NumInputFiles = Record[0];
5941 unsigned NumUserFiles = Record[1];
5942 const llvm::support::unaligned_uint64_t *InputFileOffs =
5943 (const llvm::support::unaligned_uint64_t *)Blob.data();
5944 for (unsigned I = 0; I != NumInputFiles; ++I) {
5945 // Go find this input file.
5946 bool isSystemFile = I >= NumUserFiles;
5947
5948 if (isSystemFile && !NeedsSystemInputFiles)
5949 break; // the rest are system input files
5950
5951 BitstreamCursor &Cursor = InputFilesCursor;
5952 SavedStreamPosition SavedPosition(Cursor);
5953 if (llvm::Error Err =
5954 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5955 // FIXME this drops errors on the floor.
5956 consumeError(std::move(Err));
5957 }
5958
5959 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5960 if (!MaybeCode) {
5961 // FIXME this drops errors on the floor.
5962 consumeError(MaybeCode.takeError());
5963 }
5964 unsigned Code = MaybeCode.get();
5965
5967 StringRef Blob;
5968 bool shouldContinue = false;
5969 Expected<unsigned> MaybeRecordType =
5970 Cursor.readRecord(Code, Record, &Blob);
5971 if (!MaybeRecordType) {
5972 // FIXME this drops errors on the floor.
5973 consumeError(MaybeRecordType.takeError());
5974 }
5975 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5976 case INPUT_FILE_HASH:
5977 break;
5978 case INPUT_FILE:
5979 bool Overridden = static_cast<bool>(Record[3]);
5980 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
5982 auto FilenameAsRequestedBuf = ResolveImportedPath(
5983 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
5984 StringRef Filename;
5985 if (UnresolvedFilename.empty())
5986 Filename = *FilenameAsRequestedBuf;
5987 else {
5988 auto FilenameBuf = ResolveImportedPath(
5989 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
5990 Filename = *FilenameBuf;
5991 }
5992 shouldContinue = Listener.visitInputFileAsRequested(
5993 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
5994 /*IsExplicitModule=*/false);
5995 break;
5996 }
5997 if (!shouldContinue)
5998 break;
5999 }
6000 break;
6001 }
6002
6003 case IMPORT: {
6004 if (!NeedsImports)
6005 break;
6006
6007 unsigned Idx = 0;
6008 // Read information about the AST file.
6009
6010 // Skip Kind
6011 Idx++;
6012
6013 // Skip ImportLoc
6014 Idx++;
6015
6016 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6017
6018 bool IsStandardCXXModule = Record[Idx++];
6019
6020 // In C++20 Modules, we don't record the path to imported
6021 // modules in the BMI files.
6022 if (IsStandardCXXModule) {
6023 Listener.visitImport(ModuleName, /*Filename=*/"");
6024 continue;
6025 }
6026
6027 // Skip Size and ModTime.
6028 Idx += 1 + 1;
6029 // Skip signature.
6030 Blob = Blob.substr(ASTFileSignature::size);
6031
6032 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6033 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6034 Listener.visitImport(ModuleName, *Filename);
6035 break;
6036 }
6037
6038 default:
6039 // No other validation to perform.
6040 break;
6041 }
6042 }
6043
6044 // Look for module file extension blocks, if requested.
6045 if (FindModuleFileExtensions) {
6046 BitstreamCursor SavedStream = Stream;
6047 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6048 bool DoneWithExtensionBlock = false;
6049 while (!DoneWithExtensionBlock) {
6050 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6051 if (!MaybeEntry) {
6052 // FIXME this drops the error.
6053 return true;
6054 }
6055 llvm::BitstreamEntry Entry = MaybeEntry.get();
6056
6057 switch (Entry.Kind) {
6058 case llvm::BitstreamEntry::SubBlock:
6059 if (llvm::Error Err = Stream.SkipBlock()) {
6060 // FIXME this drops the error on the floor.
6061 consumeError(std::move(Err));
6062 return true;
6063 }
6064 continue;
6065
6066 case llvm::BitstreamEntry::EndBlock:
6067 DoneWithExtensionBlock = true;
6068 continue;
6069
6070 case llvm::BitstreamEntry::Error:
6071 return true;
6072
6073 case llvm::BitstreamEntry::Record:
6074 break;
6075 }
6076
6077 Record.clear();
6078 StringRef Blob;
6079 Expected<unsigned> MaybeRecCode =
6080 Stream.readRecord(Entry.ID, Record, &Blob);
6081 if (!MaybeRecCode) {
6082 // FIXME this drops the error.
6083 return true;
6084 }
6085 switch (MaybeRecCode.get()) {
6086 case EXTENSION_METADATA: {
6088 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6089 return true;
6090
6091 Listener.readModuleFileExtension(Metadata);
6092 break;
6093 }
6094 }
6095 }
6096 }
6097 Stream = std::move(SavedStream);
6098 }
6099
6100 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6101 if (readUnhashedControlBlockImpl(
6102 nullptr, Bytes, Filename, ClientLoadCapabilities,
6103 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6104 ValidateDiagnosticOptions) != Success)
6105 return true;
6106
6107 return false;
6108}
6109
6111 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6112 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6113 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6114 const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath,
6115 bool RequireStrictOptionMatches) {
6116 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts,
6117 ExistingModuleCachePath, FileMgr,
6118 RequireStrictOptionMatches);
6119 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6120 /*FindModuleFileExtensions=*/false, validator,
6121 /*ValidateDiagnosticOptions=*/true);
6122}
6123
6124llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6125 unsigned ClientLoadCapabilities) {
6126 // Enter the submodule block.
6127 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6128 return Err;
6129
6130 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6131 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6132 // If we don't know the top-level module, there's no point in doing qualified
6133 // lookup of its submodules; it won't find anything anywhere within this tree.
6134 // Let's skip that and avoid some string lookups.
6135 auto CreateModule = !KnowsTopLevelModule
6138
6139 bool First = true;
6140 Module *CurrentModule = nullptr;
6141 RecordData Record;
6142 while (true) {
6144 F.Stream.advanceSkippingSubblocks();
6145 if (!MaybeEntry)
6146 return MaybeEntry.takeError();
6147 llvm::BitstreamEntry Entry = MaybeEntry.get();
6148
6149 switch (Entry.Kind) {
6150 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6151 case llvm::BitstreamEntry::Error:
6152 return llvm::createStringError(std::errc::illegal_byte_sequence,
6153 "malformed block record in AST file");
6154 case llvm::BitstreamEntry::EndBlock:
6155 return llvm::Error::success();
6156 case llvm::BitstreamEntry::Record:
6157 // The interesting case.
6158 break;
6159 }
6160
6161 // Read a record.
6162 StringRef Blob;
6163 Record.clear();
6164 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6165 if (!MaybeKind)
6166 return MaybeKind.takeError();
6167 unsigned Kind = MaybeKind.get();
6168
6169 if ((Kind == SUBMODULE_METADATA) != First)
6170 return llvm::createStringError(
6171 std::errc::illegal_byte_sequence,
6172 "submodule metadata record should be at beginning of block");
6173 First = false;
6174
6175 // Submodule information is only valid if we have a current module.
6176 // FIXME: Should we error on these cases?
6177 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6178 Kind != SUBMODULE_DEFINITION)
6179 continue;
6180
6181 switch (Kind) {
6182 default: // Default behavior: ignore.
6183 break;
6184
6185 case SUBMODULE_DEFINITION: {
6186 if (Record.size() < 13)
6187 return llvm::createStringError(std::errc::illegal_byte_sequence,
6188 "malformed module definition");
6189
6190 StringRef Name = Blob;
6191 unsigned Idx = 0;
6192 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6193 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6195 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6196 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6197 bool IsFramework = Record[Idx++];
6198 bool IsExplicit = Record[Idx++];
6199 bool IsSystem = Record[Idx++];
6200 bool IsExternC = Record[Idx++];
6201 bool InferSubmodules = Record[Idx++];
6202 bool InferExplicitSubmodules = Record[Idx++];
6203 bool InferExportWildcard = Record[Idx++];
6204 bool ConfigMacrosExhaustive = Record[Idx++];
6205 bool ModuleMapIsPrivate = Record[Idx++];
6206 bool NamedModuleHasInit = Record[Idx++];
6207
6208 Module *ParentModule = nullptr;
6209 if (Parent)
6210 ParentModule = getSubmodule(Parent);
6211
6212 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6213 IsFramework, IsExplicit);
6214
6215 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6216 if (GlobalIndex >= SubmodulesLoaded.size() ||
6217 SubmodulesLoaded[GlobalIndex])
6218 return llvm::createStringError(std::errc::invalid_argument,
6219 "too many submodules");
6220
6221 if (!ParentModule) {
6222 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
6223 // Don't emit module relocation error if we have -fno-validate-pch
6224 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6226 assert(CurFile != F.File && "ModuleManager did not de-duplicate");
6227
6228 Diag(diag::err_module_file_conflict)
6229 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
6230 << F.File.getName();
6231
6232 auto CurModMapFile =
6233 ModMap.getContainingModuleMapFile(CurrentModule);
6234 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6235 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6236 Diag(diag::note_module_file_conflict)
6237 << CurModMapFile->getName() << ModMapFile->getName();
6238
6239 return llvm::make_error<AlreadyReportedDiagnosticError>();
6240 }
6241 }
6242
6243 F.DidReadTopLevelSubmodule = true;
6244 CurrentModule->setASTFile(F.File);
6245 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6246 }
6247
6248 CurrentModule->Kind = Kind;
6249 // Note that we may be rewriting an existing location and it is important
6250 // to keep doing that. In particular, we would like to prefer a
6251 // `DefinitionLoc` loaded from the module file instead of the location
6252 // created in the current source manager, because it allows the new
6253 // location to be marked as "unaffecting" when writing and avoid creating
6254 // duplicate locations for the same module map file.
6255 CurrentModule->DefinitionLoc = DefinitionLoc;
6256 CurrentModule->Signature = F.Signature;
6257 CurrentModule->IsFromModuleFile = true;
6258 if (InferredAllowedBy.isValid())
6259 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6260 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6261 CurrentModule->IsExternC = IsExternC;
6262 CurrentModule->InferSubmodules = InferSubmodules;
6263 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6264 CurrentModule->InferExportWildcard = InferExportWildcard;
6265 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6266 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6267 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6268 if (DeserializationListener)
6269 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6270
6271 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6272
6273 // Clear out data that will be replaced by what is in the module file.
6274 CurrentModule->LinkLibraries.clear();
6275 CurrentModule->ConfigMacros.clear();
6276 CurrentModule->UnresolvedConflicts.clear();
6277 CurrentModule->Conflicts.clear();
6278
6279 // The module is available unless it's missing a requirement; relevant
6280 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6281 // Missing headers that were present when the module was built do not
6282 // make it unavailable -- if we got this far, this must be an explicitly
6283 // imported module file.
6284 CurrentModule->Requirements.clear();
6285 CurrentModule->MissingHeaders.clear();
6286 CurrentModule->IsUnimportable =
6287 ParentModule && ParentModule->IsUnimportable;
6288 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6289 break;
6290 }
6291
6293 // FIXME: This doesn't work for framework modules as `Filename` is the
6294 // name as written in the module file and does not include
6295 // `Headers/`, so this path will never exist.
6296 auto Filename = ResolveImportedPath(PathBuf, Blob, F);
6297 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(*Filename)) {
6298 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6299 // FIXME: NameAsWritten
6300 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
6301 }
6302 // Note that it's too late at this point to return out of date if the
6303 // name from the PCM doesn't match up with the one in the module map,
6304 // but also quite unlikely since we will have already checked the
6305 // modification time and size of the module map file itself.
6306 }
6307 break;
6308 }
6309
6310 case SUBMODULE_HEADER:
6313 // We lazily associate headers with their modules via the HeaderInfo table.
6314 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6315 // of complete filenames or remove it entirely.
6316 break;
6317
6320 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6321 // them here.
6322 break;
6323
6324 case SUBMODULE_TOPHEADER: {
6325 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6326 CurrentModule->addTopHeaderFilename(*HeaderName);
6327 break;
6328 }
6329
6331 // See comments in SUBMODULE_UMBRELLA_HEADER
6332 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6333 if (auto Umbrella =
6334 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6335 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6336 // FIXME: NameAsWritten
6337 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6338 }
6339 }
6340 break;
6341 }
6342
6343 case SUBMODULE_METADATA: {
6344 F.BaseSubmoduleID = getTotalNumSubmodules();
6346 unsigned LocalBaseSubmoduleID = Record[1];
6347 if (F.LocalNumSubmodules > 0) {
6348 // Introduce the global -> local mapping for submodules within this
6349 // module.
6350 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6351
6352 // Introduce the local -> global mapping for submodules within this
6353 // module.
6355 std::make_pair(LocalBaseSubmoduleID,
6356 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6357
6358 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6359 }
6360 break;
6361 }
6362
6363 case SUBMODULE_IMPORTS:
6364 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6365 UnresolvedModuleRef Unresolved;
6366 Unresolved.File = &F;
6367 Unresolved.Mod = CurrentModule;
6368 Unresolved.ID = Record[Idx];
6369 Unresolved.Kind = UnresolvedModuleRef::Import;
6370 Unresolved.IsWildcard = false;
6371 UnresolvedModuleRefs.push_back(Unresolved);
6372 }
6373 break;
6374
6376 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6377 UnresolvedModuleRef Unresolved;
6378 Unresolved.File = &F;
6379 Unresolved.Mod = CurrentModule;
6380 Unresolved.ID = Record[Idx];
6381 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6382 Unresolved.IsWildcard = false;
6383 UnresolvedModuleRefs.push_back(Unresolved);
6384 }
6385 break;
6386
6387 case SUBMODULE_EXPORTS:
6388 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6389 UnresolvedModuleRef Unresolved;
6390 Unresolved.File = &F;
6391 Unresolved.Mod = CurrentModule;
6392 Unresolved.ID = Record[Idx];
6393 Unresolved.Kind = UnresolvedModuleRef::Export;
6394 Unresolved.IsWildcard = Record[Idx + 1];
6395 UnresolvedModuleRefs.push_back(Unresolved);
6396 }
6397
6398 // Once we've loaded the set of exports, there's no reason to keep
6399 // the parsed, unresolved exports around.
6400 CurrentModule->UnresolvedExports.clear();
6401 break;
6402
6403 case SUBMODULE_REQUIRES:
6404 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6405 PP.getTargetInfo());
6406 break;
6407
6409 ModMap.resolveLinkAsDependencies(CurrentModule);
6410 CurrentModule->LinkLibraries.push_back(
6411 Module::LinkLibrary(std::string(Blob), Record[0]));
6412 break;
6413
6415 CurrentModule->ConfigMacros.push_back(Blob.str());
6416 break;
6417
6418 case SUBMODULE_CONFLICT: {
6419 UnresolvedModuleRef Unresolved;
6420 Unresolved.File = &F;
6421 Unresolved.Mod = CurrentModule;
6422 Unresolved.ID = Record[0];
6423 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6424 Unresolved.IsWildcard = false;
6425 Unresolved.String = Blob;
6426 UnresolvedModuleRefs.push_back(Unresolved);
6427 break;
6428 }
6429
6431 if (!ContextObj)
6432 break;
6433 // Standard C++ module has its own way to initialize variables.
6434 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6435 SmallVector<GlobalDeclID, 16> Inits;
6436 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6437 Inits.push_back(ReadDeclID(F, Record, I));
6438 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6439 }
6440 break;
6441 }
6442
6444 CurrentModule->ExportAsModule = Blob.str();
6445 ModMap.addLinkAsDependency(CurrentModule);
6446 break;
6447 }
6448 }
6449}
6450
6451/// Parse the record that corresponds to a LangOptions data
6452/// structure.
6453///
6454/// This routine parses the language options from the AST file and then gives
6455/// them to the AST listener if one is set.
6456///
6457/// \returns true if the listener deems the file unacceptable, false otherwise.
6458bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6459 StringRef ModuleFilename, bool Complain,
6460 ASTReaderListener &Listener,
6461 bool AllowCompatibleDifferences) {
6462 LangOptions LangOpts;
6463 unsigned Idx = 0;
6464#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6465 LangOpts.Name = Record[Idx++];
6466#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6467 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6468#include "clang/Basic/LangOptions.def"
6469#define SANITIZER(NAME, ID) \
6470 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6471#include "clang/Basic/Sanitizers.def"
6472
6473 for (unsigned N = Record[Idx++]; N; --N)
6474 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6475
6476 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6477 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6478 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6479
6480 LangOpts.CurrentModule = ReadString(Record, Idx);
6481
6482 // Comment options.
6483 for (unsigned N = Record[Idx++]; N; --N) {
6484 LangOpts.CommentOpts.BlockCommandNames.push_back(
6485 ReadString(Record, Idx));
6486 }
6487 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6488
6489 // OpenMP offloading options.
6490 for (unsigned N = Record[Idx++]; N; --N) {
6491 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6492 }
6493
6494 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6495
6496 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6497 AllowCompatibleDifferences);
6498}
6499
6500bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6501 StringRef ModuleFilename, bool Complain,
6502 ASTReaderListener &Listener,
6503 bool AllowCompatibleDifferences) {
6504 unsigned Idx = 0;
6505 CodeGenOptions CGOpts;
6507#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6508 if constexpr (CK::Compatibility != CK::Benign) \
6509 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6510#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6511 if constexpr (CK::Compatibility != CK::Benign) \
6512 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6513#define DEBUGOPT(Name, Bits, Default, Compatibility)
6514#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6515#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6516#include "clang/Basic/CodeGenOptions.def"
6517
6518 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6519 AllowCompatibleDifferences);
6520}
6521
6522bool ASTReader::ParseTargetOptions(const RecordData &Record,
6523 StringRef ModuleFilename, bool Complain,
6524 ASTReaderListener &Listener,
6525 bool AllowCompatibleDifferences) {
6526 unsigned Idx = 0;
6527 TargetOptions TargetOpts;
6528 TargetOpts.Triple = ReadString(Record, Idx);
6529 TargetOpts.CPU = ReadString(Record, Idx);
6530 TargetOpts.TuneCPU = ReadString(Record, Idx);
6531 TargetOpts.ABI = ReadString(Record, Idx);
6532 for (unsigned N = Record[Idx++]; N; --N) {
6533 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6534 }
6535 for (unsigned N = Record[Idx++]; N; --N) {
6536 TargetOpts.Features.push_back(ReadString(Record, Idx));
6537 }
6538
6539 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6540 AllowCompatibleDifferences);
6541}
6542
6543bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6544 StringRef ModuleFilename, bool Complain,
6545 ASTReaderListener &Listener) {
6546 DiagnosticOptions DiagOpts;
6547 unsigned Idx = 0;
6548#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6549#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6550 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6551#include "clang/Basic/DiagnosticOptions.def"
6552
6553 for (unsigned N = Record[Idx++]; N; --N)
6554 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6555 for (unsigned N = Record[Idx++]; N; --N)
6556 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6557
6558 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6559}
6560
6561bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6562 ASTReaderListener &Listener) {
6563 FileSystemOptions FSOpts;
6564 unsigned Idx = 0;
6565 FSOpts.WorkingDir = ReadString(Record, Idx);
6566 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6567}
6568
6569bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6570 StringRef ModuleFilename,
6571 bool Complain,
6572 ASTReaderListener &Listener) {
6573 HeaderSearchOptions HSOpts;
6574 unsigned Idx = 0;
6575 HSOpts.Sysroot = ReadString(Record, Idx);
6576
6577 HSOpts.ResourceDir = ReadString(Record, Idx);
6578 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6579 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6580 HSOpts.DisableModuleHash = Record[Idx++];
6581 HSOpts.ImplicitModuleMaps = Record[Idx++];
6582 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6583 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6584 HSOpts.UseBuiltinIncludes = Record[Idx++];
6585 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6586 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6587 HSOpts.UseLibcxx = Record[Idx++];
6588 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6589
6590 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6591 SpecificModuleCachePath, Complain);
6592}
6593
6594bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6595 ASTReaderListener &Listener) {
6596 HeaderSearchOptions HSOpts;
6597 unsigned Idx = 0;
6598
6599 // Include entries.
6600 for (unsigned N = Record[Idx++]; N; --N) {
6601 std::string Path = ReadString(Record, Idx);
6603 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6604 bool IsFramework = Record[Idx++];
6605 bool IgnoreSysRoot = Record[Idx++];
6606 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6607 IgnoreSysRoot);
6608 }
6609
6610 // System header prefixes.
6611 for (unsigned N = Record[Idx++]; N; --N) {
6612 std::string Prefix = ReadString(Record, Idx);
6613 bool IsSystemHeader = Record[Idx++];
6614 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6615 }
6616
6617 // VFS overlay files.
6618 for (unsigned N = Record[Idx++]; N; --N) {
6619 std::string VFSOverlayFile = ReadString(Record, Idx);
6620 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6621 }
6622
6623 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6624}
6625
6626bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6627 StringRef ModuleFilename,
6628 bool Complain,
6629 ASTReaderListener &Listener,
6630 std::string &SuggestedPredefines) {
6631 PreprocessorOptions PPOpts;
6632 unsigned Idx = 0;
6633
6634 // Macro definitions/undefs
6635 bool ReadMacros = Record[Idx++];
6636 if (ReadMacros) {
6637 for (unsigned N = Record[Idx++]; N; --N) {
6638 std::string Macro = ReadString(Record, Idx);
6639 bool IsUndef = Record[Idx++];
6640 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6641 }
6642 }
6643
6644 // Includes
6645 for (unsigned N = Record[Idx++]; N; --N) {
6646 PPOpts.Includes.push_back(ReadString(Record, Idx));
6647 }
6648
6649 // Macro Includes
6650 for (unsigned N = Record[Idx++]; N; --N) {
6651 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6652 }
6653
6654 PPOpts.UsePredefines = Record[Idx++];
6655 PPOpts.DetailedRecord = Record[Idx++];
6656 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6658 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6659 SuggestedPredefines.clear();
6660 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6661 Complain, SuggestedPredefines);
6662}
6663
6664std::pair<ModuleFile *, unsigned>
6665ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6666 GlobalPreprocessedEntityMapType::iterator
6667 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6668 assert(I != GlobalPreprocessedEntityMap.end() &&
6669 "Corrupted global preprocessed entity map");
6670 ModuleFile *M = I->second;
6671 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6672 return std::make_pair(M, LocalIndex);
6673}
6674
6675llvm::iterator_range<PreprocessingRecord::iterator>
6676ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6677 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6678 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6680
6681 return llvm::make_range(PreprocessingRecord::iterator(),
6682 PreprocessingRecord::iterator());
6683}
6684
6685bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6686 unsigned int ClientLoadCapabilities) {
6687 return ClientLoadCapabilities & ARR_OutOfDate &&
6688 !getModuleManager()
6689 .getModuleCache()
6690 .getInMemoryModuleCache()
6691 .isPCMFinal(ModuleFileName);
6692}
6693
6694llvm::iterator_range<ASTReader::ModuleDeclIterator>
6696 return llvm::make_range(
6697 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6698 ModuleDeclIterator(this, &Mod,
6700}
6701
6703 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6704 assert(I != GlobalSkippedRangeMap.end() &&
6705 "Corrupted global skipped range map");
6706 ModuleFile *M = I->second;
6707 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6708 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6709 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6710 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6711 ReadSourceLocation(*M, RawRange.getEnd()));
6712 assert(Range.isValid());
6713 return Range;
6714}
6715
6716unsigned
6717ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6718 unsigned ModuleFileIndex = ID >> 32;
6719 assert(ModuleFileIndex && "not translating loaded MacroID?");
6720 assert(getModuleManager().size() > ModuleFileIndex - 1);
6721 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6722
6723 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6724 return MF.BasePreprocessedEntityID + ID;
6725}
6726
6728 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6729 ModuleFile &M = *PPInfo.first;
6730 unsigned LocalIndex = PPInfo.second;
6732 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6733 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6734
6735 if (!PP.getPreprocessingRecord()) {
6736 Error("no preprocessing record");
6737 return nullptr;
6738 }
6739
6741 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6742 M.MacroOffsetsBase + PPOffs.getOffset())) {
6743 Error(std::move(Err));
6744 return nullptr;
6745 }
6746
6748 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6749 if (!MaybeEntry) {
6750 Error(MaybeEntry.takeError());
6751 return nullptr;
6752 }
6753 llvm::BitstreamEntry Entry = MaybeEntry.get();
6754
6755 if (Entry.Kind != llvm::BitstreamEntry::Record)
6756 return nullptr;
6757
6758 // Read the record.
6759 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6760 ReadSourceLocation(M, PPOffs.getEnd()));
6761 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6762 StringRef Blob;
6764 Expected<unsigned> MaybeRecType =
6765 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6766 if (!MaybeRecType) {
6767 Error(MaybeRecType.takeError());
6768 return nullptr;
6769 }
6770 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6771 case PPD_MACRO_EXPANSION: {
6772 bool isBuiltin = Record[0];
6773 IdentifierInfo *Name = nullptr;
6774 MacroDefinitionRecord *Def = nullptr;
6775 if (isBuiltin)
6776 Name = getLocalIdentifier(M, Record[1]);
6777 else {
6778 PreprocessedEntityID GlobalID =
6780 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6781 Def =
6782 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6783 }
6784
6785 MacroExpansion *ME;
6786 if (isBuiltin)
6787 ME = new (PPRec) MacroExpansion(Name, Range);
6788 else
6789 ME = new (PPRec) MacroExpansion(Def, Range);
6790
6791 return ME;
6792 }
6793
6794 case PPD_MACRO_DEFINITION: {
6795 // Decode the identifier info and then check again; if the macro is
6796 // still defined and associated with the identifier,
6798 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6799
6800 if (DeserializationListener)
6801 DeserializationListener->MacroDefinitionRead(PPID, MD);
6802
6803 return MD;
6804 }
6805
6807 const char *FullFileNameStart = Blob.data() + Record[0];
6808 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6810 if (!FullFileName.empty())
6811 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6812
6813 // FIXME: Stable encoding
6815 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6817 = new (PPRec) InclusionDirective(PPRec, Kind,
6818 StringRef(Blob.data(), Record[0]),
6819 Record[1], Record[3],
6820 File,
6821 Range);
6822 return ID;
6823 }
6824 }
6825
6826 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6827}
6828
6829/// Find the next module that contains entities and return the ID
6830/// of the first entry.
6831///
6832/// \param SLocMapI points at a chunk of a module that contains no
6833/// preprocessed entities or the entities it contains are not the ones we are
6834/// looking for.
6835unsigned ASTReader::findNextPreprocessedEntity(
6836 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6837 ++SLocMapI;
6838 for (GlobalSLocOffsetMapType::const_iterator
6839 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6840 ModuleFile &M = *SLocMapI->second;
6842 return M.BasePreprocessedEntityID;
6843 }
6844
6845 return getTotalNumPreprocessedEntities();
6846}
6847
6848namespace {
6849
6850struct PPEntityComp {
6851 const ASTReader &Reader;
6852 ModuleFile &M;
6853
6854 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6855
6856 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6857 SourceLocation LHS = getLoc(L);
6858 SourceLocation RHS = getLoc(R);
6859 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6860 }
6861
6862 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6863 SourceLocation LHS = getLoc(L);
6864 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6865 }
6866
6867 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6868 SourceLocation RHS = getLoc(R);
6869 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6870 }
6871
6872 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6873 return Reader.ReadSourceLocation(M, PPE.getBegin());
6874 }
6875};
6876
6877} // namespace
6878
6879unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
6880 bool EndsAfter) const {
6881 if (SourceMgr.isLocalSourceLocation(Loc))
6882 return getTotalNumPreprocessedEntities();
6883
6884 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6885 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6886 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6887 "Corrupted global sloc offset map");
6888
6889 if (SLocMapI->second->NumPreprocessedEntities == 0)
6890 return findNextPreprocessedEntity(SLocMapI);
6891
6892 ModuleFile &M = *SLocMapI->second;
6893
6894 using pp_iterator = const PPEntityOffset *;
6895
6896 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6897 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6898
6899 size_t Count = M.NumPreprocessedEntities;
6900 size_t Half;
6901 pp_iterator First = pp_begin;
6902 pp_iterator PPI;
6903
6904 if (EndsAfter) {
6905 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6906 PPEntityComp(*this, M));
6907 } else {
6908 // Do a binary search manually instead of using std::lower_bound because
6909 // The end locations of entities may be unordered (when a macro expansion
6910 // is inside another macro argument), but for this case it is not important
6911 // whether we get the first macro expansion or its containing macro.
6912 while (Count > 0) {
6913 Half = Count / 2;
6914 PPI = First;
6915 std::advance(PPI, Half);
6916 if (SourceMgr.isBeforeInTranslationUnit(
6917 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6918 First = PPI;
6919 ++First;
6920 Count = Count - Half - 1;
6921 } else
6922 Count = Half;
6923 }
6924 }
6925
6926 if (PPI == pp_end)
6927 return findNextPreprocessedEntity(SLocMapI);
6928
6929 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6930}
6931
6932/// Returns a pair of [Begin, End) indices of preallocated
6933/// preprocessed entities that \arg Range encompasses.
6934std::pair<unsigned, unsigned>
6936 if (Range.isInvalid())
6937 return std::make_pair(0,0);
6938 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6939
6940 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
6941 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
6942 return std::make_pair(BeginID, EndID);
6943}
6944
6945/// Optionally returns true or false if the preallocated preprocessed
6946/// entity with index \arg Index came from file \arg FID.
6947std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6948 FileID FID) {
6949 if (FID.isInvalid())
6950 return false;
6951
6952 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6953 ModuleFile &M = *PPInfo.first;
6954 unsigned LocalIndex = PPInfo.second;
6955 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6956
6957 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6958 if (Loc.isInvalid())
6959 return false;
6960
6961 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6962 return true;
6963 else
6964 return false;
6965}
6966
6967namespace {
6968
6969 /// Visitor used to search for information about a header file.
6970 class HeaderFileInfoVisitor {
6971 FileEntryRef FE;
6972 std::optional<HeaderFileInfo> HFI;
6973
6974 public:
6975 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6976
6977 bool operator()(ModuleFile &M) {
6980 if (!Table)
6981 return false;
6982
6983 // Look in the on-disk hash table for an entry for this file name.
6984 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6985 if (Pos == Table->end())
6986 return false;
6987
6988 HFI = *Pos;
6989 return true;
6990 }
6991
6992 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6993 };
6994
6995} // namespace
6996
6998 HeaderFileInfoVisitor Visitor(FE);
6999 ModuleMgr.visit(Visitor);
7000 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7001 return *HFI;
7002
7003 return HeaderFileInfo();
7004}
7005
7007 using DiagState = DiagnosticsEngine::DiagState;
7009
7010 for (ModuleFile &F : ModuleMgr) {
7011 unsigned Idx = 0;
7012 auto &Record = F.PragmaDiagMappings;
7013 if (Record.empty())
7014 continue;
7015
7016 DiagStates.clear();
7017
7018 auto ReadDiagState = [&](const DiagState &BasedOn,
7019 bool IncludeNonPragmaStates) {
7020 unsigned BackrefID = Record[Idx++];
7021 if (BackrefID != 0)
7022 return DiagStates[BackrefID - 1];
7023
7024 // A new DiagState was created here.
7025 Diag.DiagStates.push_back(BasedOn);
7026 DiagState *NewState = &Diag.DiagStates.back();
7027 DiagStates.push_back(NewState);
7028 unsigned Size = Record[Idx++];
7029 assert(Idx + Size * 2 <= Record.size() &&
7030 "Invalid data, not enough diag/map pairs");
7031 while (Size--) {
7032 unsigned DiagID = Record[Idx++];
7033 DiagnosticMapping NewMapping =
7035 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7036 continue;
7037
7038 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7039
7040 // If this mapping was specified as a warning but the severity was
7041 // upgraded due to diagnostic settings, simulate the current diagnostic
7042 // settings (and use a warning).
7043 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7045 NewMapping.setUpgradedFromWarning(false);
7046 }
7047
7048 Mapping = NewMapping;
7049 }
7050 return NewState;
7051 };
7052
7053 // Read the first state.
7054 DiagState *FirstState;
7055 if (F.Kind == MK_ImplicitModule) {
7056 // Implicitly-built modules are reused with different diagnostic
7057 // settings. Use the initial diagnostic state from Diag to simulate this
7058 // compilation's diagnostic settings.
7059 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7060 DiagStates.push_back(FirstState);
7061
7062 // Skip the initial diagnostic state from the serialized module.
7063 assert(Record[1] == 0 &&
7064 "Invalid data, unexpected backref in initial state");
7065 Idx = 3 + Record[2] * 2;
7066 assert(Idx < Record.size() &&
7067 "Invalid data, not enough state change pairs in initial state");
7068 } else if (F.isModule()) {
7069 // For an explicit module, preserve the flags from the module build
7070 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7071 // -Wblah flags.
7072 unsigned Flags = Record[Idx++];
7073 DiagState Initial(*Diag.getDiagnosticIDs());
7074 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7075 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7076 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7077 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7078 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7079 Initial.ExtBehavior = (diag::Severity)Flags;
7080 FirstState = ReadDiagState(Initial, true);
7081
7082 assert(F.OriginalSourceFileID.isValid());
7083
7084 // Set up the root buffer of the module to start with the initial
7085 // diagnostic state of the module itself, to cover files that contain no
7086 // explicit transitions (for which we did not serialize anything).
7087 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7088 .StateTransitions.push_back({FirstState, 0});
7089 } else {
7090 // For prefix ASTs, start with whatever the user configured on the
7091 // command line.
7092 Idx++; // Skip flags.
7093 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7094 }
7095
7096 // Read the state transitions.
7097 unsigned NumLocations = Record[Idx++];
7098 while (NumLocations--) {
7099 assert(Idx < Record.size() &&
7100 "Invalid data, missing pragma diagnostic states");
7101 FileID FID = ReadFileID(F, Record, Idx);
7102 assert(FID.isValid() && "invalid FileID for transition");
7103 unsigned Transitions = Record[Idx++];
7104
7105 // Note that we don't need to set up Parent/ParentOffset here, because
7106 // we won't be changing the diagnostic state within imported FileIDs
7107 // (other than perhaps appending to the main source file, which has no
7108 // parent).
7109 auto &F = Diag.DiagStatesByLoc.Files[FID];
7110 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7111 for (unsigned I = 0; I != Transitions; ++I) {
7112 unsigned Offset = Record[Idx++];
7113 auto *State = ReadDiagState(*FirstState, false);
7114 F.StateTransitions.push_back({State, Offset});
7115 }
7116 }
7117
7118 // Read the final state.
7119 assert(Idx < Record.size() &&
7120 "Invalid data, missing final pragma diagnostic state");
7121 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7122 auto *CurState = ReadDiagState(*FirstState, false);
7123
7124 if (!F.isModule()) {
7125 Diag.DiagStatesByLoc.CurDiagState = CurState;
7126 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7127
7128 // Preserve the property that the imaginary root file describes the
7129 // current state.
7130 FileID NullFile;
7131 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7132 if (T.empty())
7133 T.push_back({CurState, 0});
7134 else
7135 T[0].State = CurState;
7136 }
7137
7138 // Don't try to read these mappings again.
7139 Record.clear();
7140 }
7141}
7142
7143/// Get the correct cursor and offset for loading a type.
7144ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7145 auto [M, Index] = translateTypeIDToIndex(ID);
7146 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7148}
7149
7150static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7151 switch (code) {
7152#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7153 case TYPE_##CODE_ID: return Type::CLASS_ID;
7154#include "clang/Serialization/TypeBitCodes.def"
7155 default:
7156 return std::nullopt;
7157 }
7158}
7159
7160/// Read and return the type with the given index..
7161///
7162/// The index is the type ID, shifted and minus the number of predefs. This
7163/// routine actually reads the record corresponding to the type at the given
7164/// location. It is a helper routine for GetType, which deals with reading type
7165/// IDs.
7166QualType ASTReader::readTypeRecord(TypeID ID) {
7167 assert(ContextObj && "reading type with no AST context");
7168 ASTContext &Context = *ContextObj;
7169 RecordLocation Loc = TypeCursorForIndex(ID);
7170 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7171
7172 // Keep track of where we are in the stream, then jump back there
7173 // after reading this type.
7174 SavedStreamPosition SavedPosition(DeclsCursor);
7175
7176 ReadingKindTracker ReadingKind(Read_Type, *this);
7177
7178 // Note that we are loading a type record.
7179 Deserializing AType(this);
7180
7181 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7182 Error(std::move(Err));
7183 return QualType();
7184 }
7185 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7186 if (!RawCode) {
7187 Error(RawCode.takeError());
7188 return QualType();
7189 }
7190
7191 ASTRecordReader Record(*this, *Loc.F);
7192 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7193 if (!Code) {
7194 Error(Code.takeError());
7195 return QualType();
7196 }
7197 if (Code.get() == TYPE_EXT_QUAL) {
7198 QualType baseType = Record.readQualType();
7199 Qualifiers quals = Record.readQualifiers();
7200 return Context.getQualifiedType(baseType, quals);
7201 }
7202
7203 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7204 if (!maybeClass) {
7205 Error("Unexpected code for type");
7206 return QualType();
7207 }
7208
7209 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7210 return TypeReader.read(*maybeClass);
7211}
7212
7213namespace clang {
7214
7215class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7216 ASTRecordReader &Reader;
7217
7218 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7219 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7220
7221 TypeSourceInfo *GetTypeSourceInfo() {
7222 return Reader.readTypeSourceInfo();
7223 }
7224
7225 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7226 return Reader.readNestedNameSpecifierLoc();
7227 }
7228
7229 Attr *ReadAttr() {
7230 return Reader.readAttr();
7231 }
7232
7233public:
7234 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7235
7236 // We want compile-time assurance that we've enumerated all of
7237 // these, so unfortunately we have to declare them first, then
7238 // define them out-of-line.
7239#define ABSTRACT_TYPELOC(CLASS, PARENT)
7240#define TYPELOC(CLASS, PARENT) \
7241 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7242#include "clang/AST/TypeLocNodes.def"
7243
7246 void VisitTagTypeLoc(TagTypeLoc TL);
7247};
7248
7249} // namespace clang
7250
7251void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7252 // nothing to do
7253}
7254
7255void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7256 TL.setBuiltinLoc(readSourceLocation());
7257 if (TL.needsExtraLocalData()) {
7258 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7259 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7260 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7261 TL.setModeAttr(Reader.readInt());
7262 }
7263}
7264
7265void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7266 TL.setNameLoc(readSourceLocation());
7267}
7268
7269void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7270 TL.setStarLoc(readSourceLocation());
7271}
7272
7273void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7274 // nothing to do
7275}
7276
7277void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7278 // nothing to do
7279}
7280
7281void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7282 // nothing to do
7283}
7284
7285void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7286 TL.setExpansionLoc(readSourceLocation());
7287}
7288
7289void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7290 TL.setCaretLoc(readSourceLocation());
7291}
7292
7293void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7294 TL.setAmpLoc(readSourceLocation());
7295}
7296
7297void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7298 TL.setAmpAmpLoc(readSourceLocation());
7299}
7300
7301void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7302 TL.setStarLoc(readSourceLocation());
7303 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7304}
7305
7307 TL.setLBracketLoc(readSourceLocation());
7308 TL.setRBracketLoc(readSourceLocation());
7309 if (Reader.readBool())
7310 TL.setSizeExpr(Reader.readExpr());
7311 else
7312 TL.setSizeExpr(nullptr);
7313}
7314
7315void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7316 VisitArrayTypeLoc(TL);
7317}
7318
7319void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7320 VisitArrayTypeLoc(TL);
7321}
7322
7323void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7324 VisitArrayTypeLoc(TL);
7325}
7326
7327void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7328 DependentSizedArrayTypeLoc TL) {
7329 VisitArrayTypeLoc(TL);
7330}
7331
7332void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7333 DependentAddressSpaceTypeLoc TL) {
7334
7335 TL.setAttrNameLoc(readSourceLocation());
7336 TL.setAttrOperandParensRange(readSourceRange());
7337 TL.setAttrExprOperand(Reader.readExpr());
7338}
7339
7340void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7341 DependentSizedExtVectorTypeLoc TL) {
7342 TL.setNameLoc(readSourceLocation());
7343}
7344
7345void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7346 TL.setNameLoc(readSourceLocation());
7347}
7348
7349void TypeLocReader::VisitDependentVectorTypeLoc(
7350 DependentVectorTypeLoc TL) {
7351 TL.setNameLoc(readSourceLocation());
7352}
7353
7354void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7355 TL.setNameLoc(readSourceLocation());
7356}
7357
7358void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7359 TL.setAttrNameLoc(readSourceLocation());
7360 TL.setAttrOperandParensRange(readSourceRange());
7361 TL.setAttrRowOperand(Reader.readExpr());
7362 TL.setAttrColumnOperand(Reader.readExpr());
7363}
7364
7365void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7366 DependentSizedMatrixTypeLoc TL) {
7367 TL.setAttrNameLoc(readSourceLocation());
7368 TL.setAttrOperandParensRange(readSourceRange());
7369 TL.setAttrRowOperand(Reader.readExpr());
7370 TL.setAttrColumnOperand(Reader.readExpr());
7371}
7372
7374 TL.setLocalRangeBegin(readSourceLocation());
7375 TL.setLParenLoc(readSourceLocation());
7376 TL.setRParenLoc(readSourceLocation());
7377 TL.setExceptionSpecRange(readSourceRange());
7378 TL.setLocalRangeEnd(readSourceLocation());
7379 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7380 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7381 }
7382}
7383
7384void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7385 VisitFunctionTypeLoc(TL);
7386}
7387
7388void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7389 VisitFunctionTypeLoc(TL);
7390}
7391
7392void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7393 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7394 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7395 SourceLocation NameLoc = readSourceLocation();
7396 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7397}
7398
7399void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7400 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7401 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7402 SourceLocation NameLoc = readSourceLocation();
7403 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7404}
7405
7406void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7407 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7408 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7409 SourceLocation NameLoc = readSourceLocation();
7410 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7411}
7412
7413void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7414 TL.setTypeofLoc(readSourceLocation());
7415 TL.setLParenLoc(readSourceLocation());
7416 TL.setRParenLoc(readSourceLocation());
7417}
7418
7419void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7420 TL.setTypeofLoc(readSourceLocation());
7421 TL.setLParenLoc(readSourceLocation());
7422 TL.setRParenLoc(readSourceLocation());
7423 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7424}
7425
7426void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7427 TL.setDecltypeLoc(readSourceLocation());
7428 TL.setRParenLoc(readSourceLocation());
7429}
7430
7431void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7432 TL.setEllipsisLoc(readSourceLocation());
7433}
7434
7435void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7436 TL.setKWLoc(readSourceLocation());
7437 TL.setLParenLoc(readSourceLocation());
7438 TL.setRParenLoc(readSourceLocation());
7439 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7440}
7441
7443 auto NNS = readNestedNameSpecifierLoc();
7444 auto TemplateKWLoc = readSourceLocation();
7445 auto ConceptNameLoc = readDeclarationNameInfo();
7446 auto FoundDecl = readDeclAs<NamedDecl>();
7447 auto NamedConcept = readDeclAs<ConceptDecl>();
7448 auto *CR = ConceptReference::Create(
7449 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7450 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7451 return CR;
7452}
7453
7454void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7455 TL.setNameLoc(readSourceLocation());
7456 if (Reader.readBool())
7457 TL.setConceptReference(Reader.readConceptReference());
7458 if (Reader.readBool())
7459 TL.setRParenLoc(readSourceLocation());
7460}
7461
7462void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7464 TL.setElaboratedKeywordLoc(readSourceLocation());
7465 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7466 TL.setTemplateNameLoc(readSourceLocation());
7467}
7468
7470 TL.setElaboratedKeywordLoc(readSourceLocation());
7471 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7472 TL.setNameLoc(readSourceLocation());
7473}
7474
7475void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7476 VisitTagTypeLoc(TL);
7477}
7478
7479void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7480 VisitTagTypeLoc(TL);
7481}
7482
7483void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7484
7485void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7486 TL.setAttr(ReadAttr());
7487}
7488
7489void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7490 // Nothing to do
7491}
7492
7493void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7494 // Nothing to do.
7495}
7496
7497void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7498 HLSLAttributedResourceTypeLoc TL) {
7499 // Nothing to do.
7500}
7501
7502void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7503 // Nothing to do.
7504}
7505
7506void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7507 TL.setNameLoc(readSourceLocation());
7508}
7509
7510void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7511 SubstTemplateTypeParmTypeLoc TL) {
7512 TL.setNameLoc(readSourceLocation());
7513}
7514
7515void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7516 SubstTemplateTypeParmPackTypeLoc TL) {
7517 TL.setNameLoc(readSourceLocation());
7518}
7519
7520void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7521 SubstBuiltinTemplatePackTypeLoc TL) {
7522 TL.setNameLoc(readSourceLocation());
7523}
7524
7525void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7526 TemplateSpecializationTypeLoc TL) {
7527 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7528 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7529 SourceLocation TemplateKeywordLoc = readSourceLocation();
7530 SourceLocation NameLoc = readSourceLocation();
7531 SourceLocation LAngleLoc = readSourceLocation();
7532 SourceLocation RAngleLoc = readSourceLocation();
7533 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7534 LAngleLoc, RAngleLoc);
7535 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7536 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7537 Args[I] = Reader.readTemplateArgumentLocInfo(
7538 TL.getTypePtr()->template_arguments()[I].getKind());
7539}
7540
7541void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7542 TL.setLParenLoc(readSourceLocation());
7543 TL.setRParenLoc(readSourceLocation());
7544}
7545
7546void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7547 TL.setElaboratedKeywordLoc(readSourceLocation());
7548 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7549 TL.setNameLoc(readSourceLocation());
7550}
7551
7552void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7553 TL.setEllipsisLoc(readSourceLocation());
7554}
7555
7556void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7557 TL.setNameLoc(readSourceLocation());
7558 TL.setNameEndLoc(readSourceLocation());
7559}
7560
7561void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7562 if (TL.getNumProtocols()) {
7563 TL.setProtocolLAngleLoc(readSourceLocation());
7564 TL.setProtocolRAngleLoc(readSourceLocation());
7565 }
7566 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7567 TL.setProtocolLoc(i, readSourceLocation());
7568}
7569
7570void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7571 TL.setHasBaseTypeAsWritten(Reader.readBool());
7572 TL.setTypeArgsLAngleLoc(readSourceLocation());
7573 TL.setTypeArgsRAngleLoc(readSourceLocation());
7574 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7575 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7576 TL.setProtocolLAngleLoc(readSourceLocation());
7577 TL.setProtocolRAngleLoc(readSourceLocation());
7578 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7579 TL.setProtocolLoc(i, readSourceLocation());
7580}
7581
7582void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7583 TL.setStarLoc(readSourceLocation());
7584}
7585
7586void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7587 TL.setKWLoc(readSourceLocation());
7588 TL.setLParenLoc(readSourceLocation());
7589 TL.setRParenLoc(readSourceLocation());
7590}
7591
7592void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7593 TL.setKWLoc(readSourceLocation());
7594}
7595
7596void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7597 TL.setNameLoc(readSourceLocation());
7598}
7599
7600void TypeLocReader::VisitDependentBitIntTypeLoc(
7601 clang::DependentBitIntTypeLoc TL) {
7602 TL.setNameLoc(readSourceLocation());
7603}
7604
7605void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7606 // Nothing to do.
7607}
7608
7610 TypeLocReader TLR(*this);
7611 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7612 TLR.Visit(TL);
7613}
7614
7616 QualType InfoTy = readType();
7617 if (InfoTy.isNull())
7618 return nullptr;
7619
7620 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7621 readTypeLoc(TInfo->getTypeLoc());
7622 return TInfo;
7623}
7624
7626 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7627}
7628
7630 return ID >> 32;
7631}
7632
7634 // We don't need to erase the higher bits since if these bits are not 0,
7635 // it must be larger than NUM_PREDEF_TYPE_IDS.
7637}
7638
7639std::pair<ModuleFile *, unsigned>
7640ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7641 assert(!isPredefinedType(ID) &&
7642 "Predefined type shouldn't be in TypesLoaded");
7643 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7644 assert(ModuleFileIndex && "Untranslated Local Decl?");
7645
7646 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7647 assert(OwningModuleFile &&
7648 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7649
7650 return {OwningModuleFile,
7651 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7652}
7653
7655 assert(ContextObj && "reading type with no AST context");
7656 ASTContext &Context = *ContextObj;
7657
7658 unsigned FastQuals = ID & Qualifiers::FastMask;
7659
7660 if (isPredefinedType(ID)) {
7661 QualType T;
7662 unsigned Index = getIndexForTypeID(ID);
7663 switch ((PredefinedTypeIDs)Index) {
7665 // We should never use this one.
7666 llvm_unreachable("Invalid predefined type");
7667 break;
7669 return QualType();
7671 T = Context.VoidTy;
7672 break;
7674 T = Context.BoolTy;
7675 break;
7678 // FIXME: Check that the signedness of CharTy is correct!
7679 T = Context.CharTy;
7680 break;
7682 T = Context.UnsignedCharTy;
7683 break;
7685 T = Context.UnsignedShortTy;
7686 break;
7688 T = Context.UnsignedIntTy;
7689 break;
7691 T = Context.UnsignedLongTy;
7692 break;
7694 T = Context.UnsignedLongLongTy;
7695 break;
7697 T = Context.UnsignedInt128Ty;
7698 break;
7700 T = Context.SignedCharTy;
7701 break;
7703 T = Context.WCharTy;
7704 break;
7706 T = Context.ShortTy;
7707 break;
7708 case PREDEF_TYPE_INT_ID:
7709 T = Context.IntTy;
7710 break;
7712 T = Context.LongTy;
7713 break;
7715 T = Context.LongLongTy;
7716 break;
7718 T = Context.Int128Ty;
7719 break;
7721 T = Context.BFloat16Ty;
7722 break;
7724 T = Context.HalfTy;
7725 break;
7727 T = Context.FloatTy;
7728 break;
7730 T = Context.DoubleTy;
7731 break;
7733 T = Context.LongDoubleTy;
7734 break;
7736 T = Context.ShortAccumTy;
7737 break;
7739 T = Context.AccumTy;
7740 break;
7742 T = Context.LongAccumTy;
7743 break;
7745 T = Context.UnsignedShortAccumTy;
7746 break;
7748 T = Context.UnsignedAccumTy;
7749 break;
7751 T = Context.UnsignedLongAccumTy;
7752 break;
7754 T = Context.ShortFractTy;
7755 break;
7757 T = Context.FractTy;
7758 break;
7760 T = Context.LongFractTy;
7761 break;
7763 T = Context.UnsignedShortFractTy;
7764 break;
7766 T = Context.UnsignedFractTy;
7767 break;
7769 T = Context.UnsignedLongFractTy;
7770 break;
7772 T = Context.SatShortAccumTy;
7773 break;
7775 T = Context.SatAccumTy;
7776 break;
7778 T = Context.SatLongAccumTy;
7779 break;
7781 T = Context.SatUnsignedShortAccumTy;
7782 break;
7784 T = Context.SatUnsignedAccumTy;
7785 break;
7787 T = Context.SatUnsignedLongAccumTy;
7788 break;
7790 T = Context.SatShortFractTy;
7791 break;
7793 T = Context.SatFractTy;
7794 break;
7796 T = Context.SatLongFractTy;
7797 break;
7799 T = Context.SatUnsignedShortFractTy;
7800 break;
7802 T = Context.SatUnsignedFractTy;
7803 break;
7805 T = Context.SatUnsignedLongFractTy;
7806 break;
7808 T = Context.Float16Ty;
7809 break;
7811 T = Context.Float128Ty;
7812 break;
7814 T = Context.Ibm128Ty;
7815 break;
7817 T = Context.OverloadTy;
7818 break;
7820 T = Context.UnresolvedTemplateTy;
7821 break;
7823 T = Context.BoundMemberTy;
7824 break;
7826 T = Context.PseudoObjectTy;
7827 break;
7829 T = Context.DependentTy;
7830 break;
7832 T = Context.UnknownAnyTy;
7833 break;
7835 T = Context.NullPtrTy;
7836 break;
7838 T = Context.Char8Ty;
7839 break;
7841 T = Context.Char16Ty;
7842 break;
7844 T = Context.Char32Ty;
7845 break;
7847 T = Context.ObjCBuiltinIdTy;
7848 break;
7850 T = Context.ObjCBuiltinClassTy;
7851 break;
7853 T = Context.ObjCBuiltinSelTy;
7854 break;
7855#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7856 case PREDEF_TYPE_##Id##_ID: \
7857 T = Context.SingletonId; \
7858 break;
7859#include "clang/Basic/OpenCLImageTypes.def"
7860#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7861 case PREDEF_TYPE_##Id##_ID: \
7862 T = Context.Id##Ty; \
7863 break;
7864#include "clang/Basic/OpenCLExtensionTypes.def"
7866 T = Context.OCLSamplerTy;
7867 break;
7869 T = Context.OCLEventTy;
7870 break;
7872 T = Context.OCLClkEventTy;
7873 break;
7875 T = Context.OCLQueueTy;
7876 break;
7878 T = Context.OCLReserveIDTy;
7879 break;
7881 T = Context.getAutoDeductType();
7882 break;
7884 T = Context.getAutoRRefDeductType();
7885 break;
7887 T = Context.ARCUnbridgedCastTy;
7888 break;
7890 T = Context.BuiltinFnTy;
7891 break;
7893 T = Context.IncompleteMatrixIdxTy;
7894 break;
7896 T = Context.ArraySectionTy;
7897 break;
7899 T = Context.OMPArrayShapingTy;
7900 break;
7902 T = Context.OMPIteratorTy;
7903 break;
7904#define SVE_TYPE(Name, Id, SingletonId) \
7905 case PREDEF_TYPE_##Id##_ID: \
7906 T = Context.SingletonId; \
7907 break;
7908#include "clang/Basic/AArch64ACLETypes.def"
7909#define PPC_VECTOR_TYPE(Name, Id, Size) \
7910 case PREDEF_TYPE_##Id##_ID: \
7911 T = Context.Id##Ty; \
7912 break;
7913#include "clang/Basic/PPCTypes.def"
7914#define RVV_TYPE(Name, Id, SingletonId) \
7915 case PREDEF_TYPE_##Id##_ID: \
7916 T = Context.SingletonId; \
7917 break;
7918#include "clang/Basic/RISCVVTypes.def"
7919#define WASM_TYPE(Name, Id, SingletonId) \
7920 case PREDEF_TYPE_##Id##_ID: \
7921 T = Context.SingletonId; \
7922 break;
7923#include "clang/Basic/WebAssemblyReferenceTypes.def"
7924#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
7925 case PREDEF_TYPE_##Id##_ID: \
7926 T = Context.SingletonId; \
7927 break;
7928#include "clang/Basic/AMDGPUTypes.def"
7929#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
7930 case PREDEF_TYPE_##Id##_ID: \
7931 T = Context.SingletonId; \
7932 break;
7933#include "clang/Basic/HLSLIntangibleTypes.def"
7934 }
7935
7936 assert(!T.isNull() && "Unknown predefined type");
7937 return T.withFastQualifiers(FastQuals);
7938 }
7939
7940 unsigned Index = translateTypeIDToIndex(ID).second;
7941
7942 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7943 if (TypesLoaded[Index].isNull()) {
7944 TypesLoaded[Index] = readTypeRecord(ID);
7945 if (TypesLoaded[Index].isNull())
7946 return QualType();
7947
7948 TypesLoaded[Index]->setFromAST();
7949 if (DeserializationListener)
7950 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7951 TypesLoaded[Index]);
7952 }
7953
7954 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7955}
7956
7958 return GetType(getGlobalTypeID(F, LocalID));
7959}
7960
7962 LocalTypeID LocalID) const {
7963 if (isPredefinedType(LocalID))
7964 return LocalID;
7965
7966 if (!F.ModuleOffsetMap.empty())
7967 ReadModuleOffsetMap(F);
7968
7969 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
7970 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
7971
7972 if (ModuleFileIndex == 0)
7974
7975 ModuleFile &MF =
7976 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
7977 ModuleFileIndex = MF.Index + 1;
7978 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
7979}
7980
7983 switch (Kind) {
7985 return readExpr();
7987 return readTypeSourceInfo();
7990 SourceLocation TemplateKWLoc = readSourceLocation();
7992 SourceLocation TemplateNameLoc = readSourceLocation();
7995 : SourceLocation();
7996 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
7997 TemplateNameLoc, EllipsisLoc);
7998 }
8005 // FIXME: Is this right?
8006 return TemplateArgumentLocInfo();
8007 }
8008 llvm_unreachable("unexpected template argument loc");
8009}
8010
8020
8023 Result.setLAngleLoc(readSourceLocation());
8024 Result.setRAngleLoc(readSourceLocation());
8025 unsigned NumArgsAsWritten = readInt();
8026 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8027 Result.addArgument(readTemplateArgumentLoc());
8028}
8029
8036
8038
8040 if (NumCurrentElementsDeserializing) {
8041 // We arrange to not care about the complete redeclaration chain while we're
8042 // deserializing. Just remember that the AST has marked this one as complete
8043 // but that it's not actually complete yet, so we know we still need to
8044 // complete it later.
8045 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8046 return;
8047 }
8048
8049 if (!D->getDeclContext()) {
8050 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8051 return;
8052 }
8053
8054 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8055
8056 // If this is a named declaration, complete it by looking it up
8057 // within its context.
8058 //
8059 // FIXME: Merging a function definition should merge
8060 // all mergeable entities within it.
8062 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8063 if (!getContext().getLangOpts().CPlusPlus &&
8065 // Outside of C++, we don't have a lookup table for the TU, so update
8066 // the identifier instead. (For C++ modules, we don't store decls
8067 // in the serialized identifier table, so we do the lookup in the TU.)
8068 auto *II = Name.getAsIdentifierInfo();
8069 assert(II && "non-identifier name in C?");
8070 if (II->isOutOfDate())
8072 } else
8073 DC->lookup(Name);
8075 // Find all declarations of this kind from the relevant context.
8076 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8077 auto *DC = cast<DeclContext>(DCDecl);
8080 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8081 }
8082 }
8083 }
8084
8087 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8088 Template = CTSD->getSpecializedTemplate();
8089 Args = CTSD->getTemplateArgs().asArray();
8090 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8091 Template = VTSD->getSpecializedTemplate();
8092 Args = VTSD->getTemplateArgs().asArray();
8093 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8094 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8095 Template = Tmplt;
8096 Args = FD->getTemplateSpecializationArgs()->asArray();
8097 }
8098 }
8099
8100 if (Template) {
8101 // For partitial specialization, load all the specializations for safety.
8104 Template->loadLazySpecializationsImpl();
8105 else
8106 Template->loadLazySpecializationsImpl(Args);
8107 }
8108}
8109
8112 RecordLocation Loc = getLocalBitOffset(Offset);
8113 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8114 SavedStreamPosition SavedPosition(Cursor);
8115 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8116 Error(std::move(Err));
8117 return nullptr;
8118 }
8119 ReadingKindTracker ReadingKind(Read_Decl, *this);
8120 Deserializing D(this);
8121
8122 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8123 if (!MaybeCode) {
8124 Error(MaybeCode.takeError());
8125 return nullptr;
8126 }
8127 unsigned Code = MaybeCode.get();
8128
8129 ASTRecordReader Record(*this, *Loc.F);
8130 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8131 if (!MaybeRecCode) {
8132 Error(MaybeRecCode.takeError());
8133 return nullptr;
8134 }
8135 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8136 Error("malformed AST file: missing C++ ctor initializers");
8137 return nullptr;
8138 }
8139
8140 return Record.readCXXCtorInitializers();
8141}
8142
8144 assert(ContextObj && "reading base specifiers with no AST context");
8145 ASTContext &Context = *ContextObj;
8146
8147 RecordLocation Loc = getLocalBitOffset(Offset);
8148 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8149 SavedStreamPosition SavedPosition(Cursor);
8150 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8151 Error(std::move(Err));
8152 return nullptr;
8153 }
8154 ReadingKindTracker ReadingKind(Read_Decl, *this);
8155 Deserializing D(this);
8156
8157 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8158 if (!MaybeCode) {
8159 Error(MaybeCode.takeError());
8160 return nullptr;
8161 }
8162 unsigned Code = MaybeCode.get();
8163
8164 ASTRecordReader Record(*this, *Loc.F);
8165 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8166 if (!MaybeRecCode) {
8167 Error(MaybeCode.takeError());
8168 return nullptr;
8169 }
8170 unsigned RecCode = MaybeRecCode.get();
8171
8172 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8173 Error("malformed AST file: missing C++ base specifiers");
8174 return nullptr;
8175 }
8176
8177 unsigned NumBases = Record.readInt();
8178 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8179 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8180 for (unsigned I = 0; I != NumBases; ++I)
8181 Bases[I] = Record.readCXXBaseSpecifier();
8182 return Bases;
8183}
8184
8186 LocalDeclID LocalID) const {
8187 if (LocalID < NUM_PREDEF_DECL_IDS)
8188 return GlobalDeclID(LocalID.getRawValue());
8189
8190 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8191 DeclID ID = LocalID.getLocalDeclIndex();
8192
8193 if (!F.ModuleOffsetMap.empty())
8194 ReadModuleOffsetMap(F);
8195
8196 ModuleFile *OwningModuleFile =
8197 OwningModuleFileIndex == 0
8198 ? &F
8199 : F.TransitiveImports[OwningModuleFileIndex - 1];
8200
8201 if (OwningModuleFileIndex == 0)
8202 ID -= NUM_PREDEF_DECL_IDS;
8203
8204 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8205 return GlobalDeclID(NewModuleFileIndex, ID);
8206}
8207
8209 // Predefined decls aren't from any module.
8210 if (ID < NUM_PREDEF_DECL_IDS)
8211 return false;
8212
8213 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8214 return M.Index == ModuleFileIndex - 1;
8215}
8216
8218 // Predefined decls aren't from any module.
8219 if (ID < NUM_PREDEF_DECL_IDS)
8220 return nullptr;
8221
8222 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8223 assert(ModuleFileIndex && "Untranslated Local Decl?");
8224
8225 return &getModuleManager()[ModuleFileIndex - 1];
8226}
8227
8229 if (!D->isFromASTFile())
8230 return nullptr;
8231
8232 return getOwningModuleFile(D->getGlobalID());
8233}
8234
8236 if (ID < NUM_PREDEF_DECL_IDS)
8237 return SourceLocation();
8238
8239 if (Decl *D = GetExistingDecl(ID))
8240 return D->getLocation();
8241
8242 SourceLocation Loc;
8243 DeclCursorForID(ID, Loc);
8244 return Loc;
8245}
8246
8247Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8248 assert(ContextObj && "reading predefined decl without AST context");
8249 ASTContext &Context = *ContextObj;
8250 Decl *NewLoaded = nullptr;
8251 switch (ID) {
8253 return nullptr;
8254
8256 return Context.getTranslationUnitDecl();
8257
8259 if (Context.ObjCIdDecl)
8260 return Context.ObjCIdDecl;
8261 NewLoaded = Context.getObjCIdDecl();
8262 break;
8263
8265 if (Context.ObjCSelDecl)
8266 return Context.ObjCSelDecl;
8267 NewLoaded = Context.getObjCSelDecl();
8268 break;
8269
8271 if (Context.ObjCClassDecl)
8272 return Context.ObjCClassDecl;
8273 NewLoaded = Context.getObjCClassDecl();
8274 break;
8275
8277 if (Context.ObjCProtocolClassDecl)
8278 return Context.ObjCProtocolClassDecl;
8279 NewLoaded = Context.getObjCProtocolDecl();
8280 break;
8281
8283 if (Context.Int128Decl)
8284 return Context.Int128Decl;
8285 NewLoaded = Context.getInt128Decl();
8286 break;
8287
8289 if (Context.UInt128Decl)
8290 return Context.UInt128Decl;
8291 NewLoaded = Context.getUInt128Decl();
8292 break;
8293
8295 if (Context.ObjCInstanceTypeDecl)
8296 return Context.ObjCInstanceTypeDecl;
8297 NewLoaded = Context.getObjCInstanceTypeDecl();
8298 break;
8299
8301 if (Context.BuiltinVaListDecl)
8302 return Context.BuiltinVaListDecl;
8303 NewLoaded = Context.getBuiltinVaListDecl();
8304 break;
8305
8307 if (Context.VaListTagDecl)
8308 return Context.VaListTagDecl;
8309 NewLoaded = Context.getVaListTagDecl();
8310 break;
8311
8313 if (Context.BuiltinMSVaListDecl)
8314 return Context.BuiltinMSVaListDecl;
8315 NewLoaded = Context.getBuiltinMSVaListDecl();
8316 break;
8317
8319 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8320 return Context.getMSGuidTagDecl();
8321
8323 if (Context.ExternCContext)
8324 return Context.ExternCContext;
8325 NewLoaded = Context.getExternCContextDecl();
8326 break;
8327
8329 if (Context.CFConstantStringTypeDecl)
8330 return Context.CFConstantStringTypeDecl;
8331 NewLoaded = Context.getCFConstantStringDecl();
8332 break;
8333
8335 if (Context.CFConstantStringTagDecl)
8336 return Context.CFConstantStringTagDecl;
8337 NewLoaded = Context.getCFConstantStringTagDecl();
8338 break;
8339
8341 return Context.getMSTypeInfoTagDecl();
8342
8343#define BuiltinTemplate(BTName) \
8344 case PREDEF_DECL##BTName##_ID: \
8345 if (Context.Decl##BTName) \
8346 return Context.Decl##BTName; \
8347 NewLoaded = Context.get##BTName##Decl(); \
8348 break;
8349#include "clang/Basic/BuiltinTemplates.inc"
8350
8352 llvm_unreachable("Invalid decl ID");
8353 break;
8354 }
8355
8356 assert(NewLoaded && "Failed to load predefined decl?");
8357
8358 if (DeserializationListener)
8359 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8360
8361 return NewLoaded;
8362}
8363
8364unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8365 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8366 if (!OwningModuleFile) {
8367 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8368 return GlobalID.getRawValue();
8369 }
8370
8371 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8372}
8373
8375 assert(ContextObj && "reading decl with no AST context");
8376
8377 if (ID < NUM_PREDEF_DECL_IDS) {
8378 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8379 if (D) {
8380 // Track that we have merged the declaration with ID \p ID into the
8381 // pre-existing predefined declaration \p D.
8382 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8383 if (Merged.empty())
8384 Merged.push_back(ID);
8385 }
8386 return D;
8387 }
8388
8389 unsigned Index = translateGlobalDeclIDToIndex(ID);
8390
8391 if (Index >= DeclsLoaded.size()) {
8392 assert(0 && "declaration ID out-of-range for AST file");
8393 Error("declaration ID out-of-range for AST file");
8394 return nullptr;
8395 }
8396
8397 return DeclsLoaded[Index];
8398}
8399
8401 if (ID < NUM_PREDEF_DECL_IDS)
8402 return GetExistingDecl(ID);
8403
8404 unsigned Index = translateGlobalDeclIDToIndex(ID);
8405
8406 if (Index >= DeclsLoaded.size()) {
8407 assert(0 && "declaration ID out-of-range for AST file");
8408 Error("declaration ID out-of-range for AST file");
8409 return nullptr;
8410 }
8411
8412 if (!DeclsLoaded[Index]) {
8413 ReadDeclRecord(ID);
8414 if (DeserializationListener)
8415 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8416 }
8417
8418 return DeclsLoaded[Index];
8419}
8420
8422 GlobalDeclID GlobalID) {
8423 if (GlobalID < NUM_PREDEF_DECL_IDS)
8424 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8425
8426 if (!M.ModuleOffsetMap.empty())
8427 ReadModuleOffsetMap(M);
8428
8429 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8430 DeclID ID = GlobalID.getLocalDeclIndex();
8431
8432 if (Owner == &M) {
8433 ID += NUM_PREDEF_DECL_IDS;
8434 return LocalDeclID::get(*this, M, ID);
8435 }
8436
8437 uint64_t OrignalModuleFileIndex = 0;
8438 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8439 if (M.TransitiveImports[I] == Owner) {
8440 OrignalModuleFileIndex = I + 1;
8441 break;
8442 }
8443
8444 if (!OrignalModuleFileIndex)
8445 return LocalDeclID();
8446
8447 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8448}
8449
8451 unsigned &Idx) {
8452 if (Idx >= Record.size()) {
8453 Error("Corrupted AST file");
8454 return GlobalDeclID(0);
8455 }
8456
8457 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8458}
8459
8460/// Resolve the offset of a statement into a statement.
8461///
8462/// This operation will read a new statement from the external
8463/// source each time it is called, and is meant to be used via a
8464/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8466 // Switch case IDs are per Decl.
8468
8469 // Offset here is a global offset across the entire chain.
8470 RecordLocation Loc = getLocalBitOffset(Offset);
8471 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8472 Error(std::move(Err));
8473 return nullptr;
8474 }
8475 assert(NumCurrentElementsDeserializing == 0 &&
8476 "should not be called while already deserializing");
8477 Deserializing D(this);
8478 return ReadStmtFromStream(*Loc.F);
8479}
8480
8481bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8482 const Decl *D) {
8483 assert(D);
8484
8485 auto It = SpecLookups.find(D);
8486 if (It == SpecLookups.end())
8487 return false;
8488
8489 // Get Decl may violate the iterator from SpecializationsLookups so we store
8490 // the DeclIDs in ahead.
8492 It->second.Table.findAll();
8493
8494 // Since we've loaded all the specializations, we can erase it from
8495 // the lookup table.
8496 SpecLookups.erase(It);
8497
8498 bool NewSpecsFound = false;
8499 Deserializing LookupResults(this);
8500 for (auto &Info : Infos) {
8501 if (GetExistingDecl(Info))
8502 continue;
8503 NewSpecsFound = true;
8504 GetDecl(Info);
8505 }
8506
8507 return NewSpecsFound;
8508}
8509
8510bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) {
8511 assert(D);
8512
8514 bool NewSpecsFound =
8515 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8516 if (OnlyPartial)
8517 return NewSpecsFound;
8518
8519 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8520 return NewSpecsFound;
8521}
8522
8523bool ASTReader::LoadExternalSpecializationsImpl(
8524 SpecLookupTableTy &SpecLookups, const Decl *D,
8525 ArrayRef<TemplateArgument> TemplateArgs) {
8526 assert(D);
8527
8528 auto It = SpecLookups.find(D);
8529 if (It == SpecLookups.end())
8530 return false;
8531
8532 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8533 std::string Name;
8534 llvm::raw_string_ostream OS(Name);
8535 auto *ND = cast<NamedDecl>(D);
8536 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(),
8537 /*Qualified=*/true);
8538 return Name;
8539 });
8540
8541 Deserializing LookupResults(this);
8542 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8543
8544 // Get Decl may violate the iterator from SpecLookups
8546 It->second.Table.find(HashValue);
8547
8548 bool NewSpecsFound = false;
8549 for (auto &Info : Infos) {
8550 if (GetExistingDecl(Info))
8551 continue;
8552 NewSpecsFound = true;
8553 GetDecl(Info);
8554 }
8555
8556 return NewSpecsFound;
8557}
8558
8560 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8561 assert(D);
8562
8563 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8564 PartialSpecializationsLookups, D, TemplateArgs);
8565 NewDeclsFound |=
8566 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8567
8568 return NewDeclsFound;
8569}
8570
8572 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8573 SmallVectorImpl<Decl *> &Decls) {
8574 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8575
8576 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8577 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8578 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8579 auto K = (Decl::Kind)+LexicalDecls[I];
8580 if (!IsKindWeWant(K))
8581 continue;
8582
8583 auto ID = (DeclID) + LexicalDecls[I + 1];
8584
8585 // Don't add predefined declarations to the lexical context more
8586 // than once.
8587 if (ID < NUM_PREDEF_DECL_IDS) {
8588 if (PredefsVisited[ID])
8589 continue;
8590
8591 PredefsVisited[ID] = true;
8592 }
8593
8594 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8595 assert(D->getKind() == K && "wrong kind for lexical decl");
8596 if (!DC->isDeclInLexicalTraversal(D))
8597 Decls.push_back(D);
8598 }
8599 }
8600 };
8601
8602 if (isa<TranslationUnitDecl>(DC)) {
8603 for (const auto &Lexical : TULexicalDecls)
8604 Visit(Lexical.first, Lexical.second);
8605 } else {
8606 auto I = LexicalDecls.find(DC);
8607 if (I != LexicalDecls.end())
8608 Visit(I->second.first, I->second.second);
8609 }
8610
8611 ++NumLexicalDeclContextsRead;
8612}
8613
8614namespace {
8615
8616class UnalignedDeclIDComp {
8617 ASTReader &Reader;
8618 ModuleFile &Mod;
8619
8620public:
8621 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8622 : Reader(Reader), Mod(M) {}
8623
8624 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8625 SourceLocation LHS = getLocation(L);
8626 SourceLocation RHS = getLocation(R);
8627 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8628 }
8629
8630 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8631 SourceLocation RHS = getLocation(R);
8632 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8633 }
8634
8635 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8636 SourceLocation LHS = getLocation(L);
8637 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8638 }
8639
8640 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8641 return Reader.getSourceManager().getFileLoc(
8643 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8644 }
8645};
8646
8647} // namespace
8648
8650 unsigned Offset, unsigned Length,
8651 SmallVectorImpl<Decl *> &Decls) {
8653
8654 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8655 if (I == FileDeclIDs.end())
8656 return;
8657
8658 FileDeclsInfo &DInfo = I->second;
8659 if (DInfo.Decls.empty())
8660 return;
8661
8663 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8664 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8665
8666 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8668 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8669 if (BeginIt != DInfo.Decls.begin())
8670 --BeginIt;
8671
8672 // If we are pointing at a top-level decl inside an objc container, we need
8673 // to backtrack until we find it otherwise we will fail to report that the
8674 // region overlaps with an objc container.
8675 while (BeginIt != DInfo.Decls.begin() &&
8676 GetDecl(getGlobalDeclID(*DInfo.Mod,
8677 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8678 ->isTopLevelDeclInObjCContainer())
8679 --BeginIt;
8680
8682 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8683 if (EndIt != DInfo.Decls.end())
8684 ++EndIt;
8685
8686 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8687 ++DIt)
8688 Decls.push_back(GetDecl(getGlobalDeclID(
8689 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8690}
8691
8693 DeclarationName Name,
8694 const DeclContext *OriginalDC) {
8695 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8696 "DeclContext has no visible decls in storage");
8697 if (!Name)
8698 return false;
8699
8700 // Load the list of declarations.
8703
8704 auto Find = [&, this](auto &&Table, auto &&Key) {
8705 for (GlobalDeclID ID : Table.find(Key)) {
8707 if (ND->getDeclName() == Name && Found.insert(ND).second)
8708 Decls.push_back(ND);
8709 }
8710 };
8711
8712 Deserializing LookupResults(this);
8713
8714 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8715 // available.
8716 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8717 ++NumVisibleDeclContextsRead;
8718 Find(It->second.Table, Name);
8719 }
8720
8721 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8722 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8723 ++NumModuleLocalVisibleDeclContexts;
8724 Find(It->second.Table, std::make_pair(Name, NamedModule));
8725 }
8726 };
8727 if (auto *NamedModule =
8728 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8729 : nullptr)
8730 FindModuleLocalLookup(NamedModule);
8731 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8732 // We're going to find a decl but the decl context of the lookup is
8733 // unspecified. In this case, the OriginalDC may be the decl context in other
8734 // module.
8735 if (ContextObj && ContextObj->getCurrentNamedModule())
8736 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8737
8738 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8739 ++NumTULocalVisibleDeclContexts;
8740 Find(It->second.Table, Name);
8741 }
8742
8743 SetExternalVisibleDeclsForName(DC, Name, Decls);
8744 return !Decls.empty();
8745}
8746
8748 if (!DC->hasExternalVisibleStorage())
8749 return;
8750
8751 DeclsMap Decls;
8752
8753 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8754 auto It = LookupTables.find(DC);
8755 if (It == LookupTables.end())
8756 return;
8757
8758 NumRead++;
8759
8760 for (GlobalDeclID ID : It->second.Table.findAll()) {
8762 Decls[ND->getDeclName()].push_back(ND);
8763 }
8764
8765 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8766 };
8767
8768 findAll(Lookups, NumVisibleDeclContextsRead);
8769 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8770 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8771
8772 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8773 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8774 }
8775 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8776}
8777
8780 auto I = Lookups.find(Primary);
8781 return I == Lookups.end() ? nullptr : &I->second;
8782}
8783
8786 auto I = ModuleLocalLookups.find(Primary);
8787 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8788}
8789
8792 auto I = TULocalLookups.find(Primary);
8793 return I == TULocalLookups.end() ? nullptr : &I->second;
8794}
8795
8798 assert(D->isCanonicalDecl());
8799 auto &LookupTable =
8800 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8801 auto I = LookupTable.find(D);
8802 return I == LookupTable.end() ? nullptr : &I->second;
8803}
8804
8806 assert(D->isCanonicalDecl());
8807 return PartialSpecializationsLookups.contains(D) ||
8808 SpecializationsLookups.contains(D);
8809}
8810
8811/// Under non-PCH compilation the consumer receives the objc methods
8812/// before receiving the implementation, and codegen depends on this.
8813/// We simulate this by deserializing and passing to consumer the methods of the
8814/// implementation before passing the deserialized implementation decl.
8816 ASTConsumer *Consumer) {
8817 assert(ImplD && Consumer);
8818
8819 for (auto *I : ImplD->methods())
8820 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8821
8822 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8823}
8824
8825void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8826 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8827 PassObjCImplDeclToConsumer(ImplD, Consumer);
8828 else
8829 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8830}
8831
8832void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8833 Consumer->HandleVTable(RD);
8834}
8835
8837 this->Consumer = Consumer;
8838
8839 if (Consumer)
8840 PassInterestingDeclsToConsumer();
8841
8842 if (DeserializationListener)
8843 DeserializationListener->ReaderInitialized(this);
8844}
8845
8847 std::fprintf(stderr, "*** AST File Statistics:\n");
8848
8849 unsigned NumTypesLoaded =
8850 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8851 unsigned NumDeclsLoaded =
8852 DeclsLoaded.size() -
8853 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8854 unsigned NumIdentifiersLoaded =
8855 IdentifiersLoaded.size() -
8856 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8857 unsigned NumMacrosLoaded =
8858 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8859 unsigned NumSelectorsLoaded =
8860 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8861
8862 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8863 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8864 NumSLocEntriesRead, TotalNumSLocEntries,
8865 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8866 if (!TypesLoaded.empty())
8867 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8868 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8869 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8870 if (!DeclsLoaded.empty())
8871 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8872 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8873 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8874 if (!IdentifiersLoaded.empty())
8875 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8876 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8877 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8878 if (!MacrosLoaded.empty())
8879 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8880 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8881 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8882 if (!SelectorsLoaded.empty())
8883 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8884 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8885 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8886 if (TotalNumStatements)
8887 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8888 NumStatementsRead, TotalNumStatements,
8889 ((float)NumStatementsRead/TotalNumStatements * 100));
8890 if (TotalNumMacros)
8891 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8892 NumMacrosRead, TotalNumMacros,
8893 ((float)NumMacrosRead/TotalNumMacros * 100));
8894 if (TotalLexicalDeclContexts)
8895 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8896 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8897 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8898 * 100));
8899 if (TotalVisibleDeclContexts)
8900 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8901 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8902 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8903 * 100));
8904 if (TotalModuleLocalVisibleDeclContexts)
8905 std::fprintf(
8906 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
8907 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
8908 ((float)NumModuleLocalVisibleDeclContexts /
8909 TotalModuleLocalVisibleDeclContexts * 100));
8910 if (TotalTULocalVisibleDeclContexts)
8911 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
8912 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
8913 ((float)NumTULocalVisibleDeclContexts /
8914 TotalTULocalVisibleDeclContexts * 100));
8915 if (TotalNumMethodPoolEntries)
8916 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8917 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8918 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8919 * 100));
8920 if (NumMethodPoolLookups)
8921 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8922 NumMethodPoolHits, NumMethodPoolLookups,
8923 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8924 if (NumMethodPoolTableLookups)
8925 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8926 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8927 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8928 * 100.0));
8929 if (NumIdentifierLookupHits)
8930 std::fprintf(stderr,
8931 " %u / %u identifier table lookups succeeded (%f%%)\n",
8932 NumIdentifierLookupHits, NumIdentifierLookups,
8933 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8934
8935 if (GlobalIndex) {
8936 std::fprintf(stderr, "\n");
8937 GlobalIndex->printStats();
8938 }
8939
8940 std::fprintf(stderr, "\n");
8941 dump();
8942 std::fprintf(stderr, "\n");
8943}
8944
8945template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8946LLVM_DUMP_METHOD static void
8947dumpModuleIDMap(StringRef Name,
8948 const ContinuousRangeMap<Key, ModuleFile *,
8949 InitialCapacity> &Map) {
8950 if (Map.begin() == Map.end())
8951 return;
8952
8954
8955 llvm::errs() << Name << ":\n";
8956 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8957 I != IEnd; ++I)
8958 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
8959 << "\n";
8960}
8961
8962LLVM_DUMP_METHOD void ASTReader::dump() {
8963 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8964 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8965 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8966 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8967 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8968 dumpModuleIDMap("Global preprocessed entity map",
8969 GlobalPreprocessedEntityMap);
8970
8971 llvm::errs() << "\n*** PCH/Modules Loaded:";
8972 for (ModuleFile &M : ModuleMgr)
8973 M.dump();
8974}
8975
8976/// Return the amount of memory used by memory buffers, breaking down
8977/// by heap-backed versus mmap'ed memory.
8979 for (ModuleFile &I : ModuleMgr) {
8980 if (llvm::MemoryBuffer *buf = I.Buffer) {
8981 size_t bytes = buf->getBufferSize();
8982 switch (buf->getBufferKind()) {
8983 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8984 sizes.malloc_bytes += bytes;
8985 break;
8986 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8987 sizes.mmap_bytes += bytes;
8988 break;
8989 }
8990 }
8991 }
8992}
8993
8995 SemaObj = &S;
8996 S.addExternalSource(this);
8997
8998 // Makes sure any declarations that were deserialized "too early"
8999 // still get added to the identifier's declaration chains.
9000 for (GlobalDeclID ID : PreloadedDeclIDs) {
9002 pushExternalDeclIntoScope(D, D->getDeclName());
9003 }
9004 PreloadedDeclIDs.clear();
9005
9006 // FIXME: What happens if these are changed by a module import?
9007 if (!FPPragmaOptions.empty()) {
9008 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9009 FPOptionsOverride NewOverrides =
9010 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9011 SemaObj->CurFPFeatures =
9012 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9013 }
9014
9015 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9016 Decl *D = GetDecl(ID);
9017 if (auto *FD = dyn_cast<FunctionDecl>(D))
9018 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9019 else if (auto *BD = dyn_cast<BlockDecl>(D))
9020 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9021 else
9022 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9023 }
9024 DeclsWithEffectsToVerify.clear();
9025
9026 SemaObj->OpenCLFeatures = OpenCLExtensions;
9027
9028 UpdateSema();
9029}
9030
9032 assert(SemaObj && "no Sema to update");
9033
9034 // Load the offsets of the declarations that Sema references.
9035 // They will be lazily deserialized when needed.
9036 if (!SemaDeclRefs.empty()) {
9037 assert(SemaDeclRefs.size() % 3 == 0);
9038 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9039 if (!SemaObj->StdNamespace)
9040 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9041 if (!SemaObj->StdBadAlloc)
9042 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9043 if (!SemaObj->StdAlignValT)
9044 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9045 }
9046 SemaDeclRefs.clear();
9047 }
9048
9049 // Update the state of pragmas. Use the same API as if we had encountered the
9050 // pragma in the source.
9051 if(OptimizeOffPragmaLocation.isValid())
9052 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9053 if (PragmaMSStructState != -1)
9054 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9055 if (PointersToMembersPragmaLocation.isValid()) {
9056 SemaObj->ActOnPragmaMSPointersToMembers(
9058 PragmaMSPointersToMembersState,
9059 PointersToMembersPragmaLocation);
9060 }
9061 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9062
9063 if (PragmaAlignPackCurrentValue) {
9064 // The bottom of the stack might have a default value. It must be adjusted
9065 // to the current value to ensure that the packing state is preserved after
9066 // popping entries that were included/imported from a PCH/module.
9067 bool DropFirst = false;
9068 if (!PragmaAlignPackStack.empty() &&
9069 PragmaAlignPackStack.front().Location.isInvalid()) {
9070 assert(PragmaAlignPackStack.front().Value ==
9071 SemaObj->AlignPackStack.DefaultValue &&
9072 "Expected a default alignment value");
9073 SemaObj->AlignPackStack.Stack.emplace_back(
9074 PragmaAlignPackStack.front().SlotLabel,
9075 SemaObj->AlignPackStack.CurrentValue,
9076 SemaObj->AlignPackStack.CurrentPragmaLocation,
9077 PragmaAlignPackStack.front().PushLocation);
9078 DropFirst = true;
9079 }
9080 for (const auto &Entry :
9081 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9082 SemaObj->AlignPackStack.Stack.emplace_back(
9083 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9084 }
9085 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9086 assert(*PragmaAlignPackCurrentValue ==
9087 SemaObj->AlignPackStack.DefaultValue &&
9088 "Expected a default align and pack value");
9089 // Keep the current values.
9090 } else {
9091 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9092 SemaObj->AlignPackStack.CurrentPragmaLocation =
9093 PragmaAlignPackCurrentLocation;
9094 }
9095 }
9096 if (FpPragmaCurrentValue) {
9097 // The bottom of the stack might have a default value. It must be adjusted
9098 // to the current value to ensure that fp-pragma state is preserved after
9099 // popping entries that were included/imported from a PCH/module.
9100 bool DropFirst = false;
9101 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9102 assert(FpPragmaStack.front().Value ==
9103 SemaObj->FpPragmaStack.DefaultValue &&
9104 "Expected a default pragma float_control value");
9105 SemaObj->FpPragmaStack.Stack.emplace_back(
9106 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9107 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9108 FpPragmaStack.front().PushLocation);
9109 DropFirst = true;
9110 }
9111 for (const auto &Entry :
9112 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9113 SemaObj->FpPragmaStack.Stack.emplace_back(
9114 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9115 if (FpPragmaCurrentLocation.isInvalid()) {
9116 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9117 "Expected a default pragma float_control value");
9118 // Keep the current values.
9119 } else {
9120 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9121 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9122 }
9123 }
9124
9125 // For non-modular AST files, restore visiblity of modules.
9126 for (auto &Import : PendingImportedModulesSema) {
9127 if (Import.ImportLoc.isInvalid())
9128 continue;
9129 if (Module *Imported = getSubmodule(Import.ID)) {
9130 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9131 }
9132 }
9133 PendingImportedModulesSema.clear();
9134}
9135
9137 // Note that we are loading an identifier.
9138 Deserializing AnIdentifier(this);
9139
9140 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9141 NumIdentifierLookups,
9142 NumIdentifierLookupHits);
9143
9144 // We don't need to do identifier table lookups in C++ modules (we preload
9145 // all interesting declarations, and don't need to use the scope for name
9146 // lookups). Perform the lookup in PCH files, though, since we don't build
9147 // a complete initial identifier table if we're carrying on from a PCH.
9148 if (PP.getLangOpts().CPlusPlus) {
9149 for (auto *F : ModuleMgr.pch_modules())
9150 if (Visitor(*F))
9151 break;
9152 } else {
9153 // If there is a global index, look there first to determine which modules
9154 // provably do not have any results for this identifier.
9156 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9157 if (!loadGlobalIndex()) {
9158 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9159 HitsPtr = &Hits;
9160 }
9161 }
9162
9163 ModuleMgr.visit(Visitor, HitsPtr);
9164 }
9165
9166 IdentifierInfo *II = Visitor.getIdentifierInfo();
9168 return II;
9169}
9170
9171namespace clang {
9172
9173 /// An identifier-lookup iterator that enumerates all of the
9174 /// identifiers stored within a set of AST files.
9176 /// The AST reader whose identifiers are being enumerated.
9177 const ASTReader &Reader;
9178
9179 /// The current index into the chain of AST files stored in
9180 /// the AST reader.
9181 unsigned Index;
9182
9183 /// The current position within the identifier lookup table
9184 /// of the current AST file.
9185 ASTIdentifierLookupTable::key_iterator Current;
9186
9187 /// The end position within the identifier lookup table of
9188 /// the current AST file.
9189 ASTIdentifierLookupTable::key_iterator End;
9190
9191 /// Whether to skip any modules in the ASTReader.
9192 bool SkipModules;
9193
9194 public:
9195 explicit ASTIdentifierIterator(const ASTReader &Reader,
9196 bool SkipModules = false);
9197
9198 StringRef Next() override;
9199 };
9200
9201} // namespace clang
9202
9204 bool SkipModules)
9205 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9206}
9207
9209 while (Current == End) {
9210 // If we have exhausted all of our AST files, we're done.
9211 if (Index == 0)
9212 return StringRef();
9213
9214 --Index;
9215 ModuleFile &F = Reader.ModuleMgr[Index];
9216 if (SkipModules && F.isModule())
9217 continue;
9218
9219 ASTIdentifierLookupTable *IdTable =
9221 Current = IdTable->key_begin();
9222 End = IdTable->key_end();
9223 }
9224
9225 // We have any identifiers remaining in the current AST file; return
9226 // the next one.
9227 StringRef Result = *Current;
9228 ++Current;
9229 return Result;
9230}
9231
9232namespace {
9233
9234/// A utility for appending two IdentifierIterators.
9235class ChainedIdentifierIterator : public IdentifierIterator {
9236 std::unique_ptr<IdentifierIterator> Current;
9237 std::unique_ptr<IdentifierIterator> Queued;
9238
9239public:
9240 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9241 std::unique_ptr<IdentifierIterator> Second)
9242 : Current(std::move(First)), Queued(std::move(Second)) {}
9243
9244 StringRef Next() override {
9245 if (!Current)
9246 return StringRef();
9247
9248 StringRef result = Current->Next();
9249 if (!result.empty())
9250 return result;
9251
9252 // Try the queued iterator, which may itself be empty.
9253 Current.reset();
9254 std::swap(Current, Queued);
9255 return Next();
9256 }
9257};
9258
9259} // namespace
9260
9262 if (!loadGlobalIndex()) {
9263 std::unique_ptr<IdentifierIterator> ReaderIter(
9264 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9265 std::unique_ptr<IdentifierIterator> ModulesIter(
9266 GlobalIndex->createIdentifierIterator());
9267 return new ChainedIdentifierIterator(std::move(ReaderIter),
9268 std::move(ModulesIter));
9269 }
9270
9271 return new ASTIdentifierIterator(*this);
9272}
9273
9274namespace clang {
9275namespace serialization {
9276
9278 ASTReader &Reader;
9279 Selector Sel;
9280 unsigned PriorGeneration;
9281 unsigned InstanceBits = 0;
9282 unsigned FactoryBits = 0;
9283 bool InstanceHasMoreThanOneDecl = false;
9284 bool FactoryHasMoreThanOneDecl = false;
9285 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9286 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9287
9288 public:
9290 unsigned PriorGeneration)
9291 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9292
9294 if (!M.SelectorLookupTable)
9295 return false;
9296
9297 // If we've already searched this module file, skip it now.
9298 if (M.Generation <= PriorGeneration)
9299 return true;
9300
9301 ++Reader.NumMethodPoolTableLookups;
9302 ASTSelectorLookupTable *PoolTable
9304 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9305 if (Pos == PoolTable->end())
9306 return false;
9307
9308 ++Reader.NumMethodPoolTableHits;
9309 ++Reader.NumSelectorsRead;
9310 // FIXME: Not quite happy with the statistics here. We probably should
9311 // disable this tracking when called via LoadSelector.
9312 // Also, should entries without methods count as misses?
9313 ++Reader.NumMethodPoolEntriesRead;
9315 if (Reader.DeserializationListener)
9316 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9317
9318 // Append methods in the reverse order, so that later we can process them
9319 // in the order they appear in the source code by iterating through
9320 // the vector in the reverse order.
9321 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9322 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9323 InstanceBits = Data.InstanceBits;
9324 FactoryBits = Data.FactoryBits;
9325 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9326 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9327 return false;
9328 }
9329
9330 /// Retrieve the instance methods found by this visitor.
9332 return InstanceMethods;
9333 }
9334
9335 /// Retrieve the instance methods found by this visitor.
9337 return FactoryMethods;
9338 }
9339
9340 unsigned getInstanceBits() const { return InstanceBits; }
9341 unsigned getFactoryBits() const { return FactoryBits; }
9342
9344 return InstanceHasMoreThanOneDecl;
9345 }
9346
9347 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9348 };
9349
9350} // namespace serialization
9351} // namespace clang
9352
9353/// Add the given set of methods to the method list.
9355 ObjCMethodList &List) {
9356 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9357 S.ObjC().addMethodToGlobalList(&List, M);
9358}
9359
9361 // Get the selector generation and update it to the current generation.
9362 unsigned &Generation = SelectorGeneration[Sel];
9363 unsigned PriorGeneration = Generation;
9364 Generation = getGeneration();
9365 SelectorOutOfDate[Sel] = false;
9366
9367 // Search for methods defined with this selector.
9368 ++NumMethodPoolLookups;
9369 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9370 ModuleMgr.visit(Visitor);
9371
9372 if (Visitor.getInstanceMethods().empty() &&
9373 Visitor.getFactoryMethods().empty())
9374 return;
9375
9376 ++NumMethodPoolHits;
9377
9378 if (!getSema())
9379 return;
9380
9381 Sema &S = *getSema();
9382 auto &Methods = S.ObjC().MethodPool[Sel];
9383
9384 Methods.first.setBits(Visitor.getInstanceBits());
9385 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9386 Methods.second.setBits(Visitor.getFactoryBits());
9387 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9388
9389 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9390 // when building a module we keep every method individually and may need to
9391 // update hasMoreThanOneDecl as we add the methods.
9392 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9393 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9394}
9395
9397 if (SelectorOutOfDate[Sel])
9398 ReadMethodPool(Sel);
9399}
9400
9403 Namespaces.clear();
9404
9405 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9406 if (NamespaceDecl *Namespace
9407 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9408 Namespaces.push_back(Namespace);
9409 }
9410}
9411
9413 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9414 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9415 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9418 Undefined.insert(std::make_pair(D, Loc));
9419 }
9420 UndefinedButUsed.clear();
9421}
9422
9424 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9425 Exprs) {
9426 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9427 FieldDecl *FD =
9428 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9429 uint64_t Count = DelayedDeleteExprs[Idx++];
9430 for (uint64_t C = 0; C < Count; ++C) {
9431 SourceLocation DeleteLoc =
9432 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9433 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9434 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9435 }
9436 }
9437}
9438
9440 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9441 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9442 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9443 if (Var)
9444 TentativeDefs.push_back(Var);
9445 }
9446 TentativeDefinitions.clear();
9447}
9448
9451 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9453 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9454 if (D)
9455 Decls.push_back(D);
9456 }
9457 UnusedFileScopedDecls.clear();
9458}
9459
9462 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9464 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9465 if (D)
9466 Decls.push_back(D);
9467 }
9468 DelegatingCtorDecls.clear();
9469}
9470
9472 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9474 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9475 if (D)
9476 Decls.push_back(D);
9477 }
9478 ExtVectorDecls.clear();
9479}
9480
9483 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9484 ++I) {
9485 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9486 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9487 if (D)
9488 Decls.insert(D);
9489 }
9490 UnusedLocalTypedefNameCandidates.clear();
9491}
9492
9495 for (auto I : DeclsToCheckForDeferredDiags) {
9496 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9497 if (D)
9498 Decls.insert(D);
9499 }
9500 DeclsToCheckForDeferredDiags.clear();
9501}
9502
9504 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9505 if (ReferencedSelectorsData.empty())
9506 return;
9507
9508 // If there are @selector references added them to its pool. This is for
9509 // implementation of -Wselector.
9510 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9511 unsigned I = 0;
9512 while (I < DataSize) {
9513 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9514 SourceLocation SelLoc
9515 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9516 Sels.push_back(std::make_pair(Sel, SelLoc));
9517 }
9518 ReferencedSelectorsData.clear();
9519}
9520
9522 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9523 if (WeakUndeclaredIdentifiers.empty())
9524 return;
9525
9526 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9527 IdentifierInfo *WeakId
9528 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9529 IdentifierInfo *AliasId
9530 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9531 SourceLocation Loc =
9532 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9533 WeakInfo WI(AliasId, Loc);
9534 WeakIDs.push_back(std::make_pair(WeakId, WI));
9535 }
9536 WeakUndeclaredIdentifiers.clear();
9537}
9538
9540 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9542 VTableUse &TableInfo = VTableUses[Idx++];
9543 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9544 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9545 VT.DefinitionRequired = TableInfo.Used;
9546 VTables.push_back(VT);
9547 }
9548
9549 VTableUses.clear();
9550}
9551
9553 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9554 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9555 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9556 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9558
9559 Pending.push_back(std::make_pair(D, Loc));
9560 }
9561 PendingInstantiations.clear();
9562}
9563
9565 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9566 &LPTMap) {
9567 for (auto &LPT : LateParsedTemplates) {
9568 ModuleFile *FMod = LPT.first;
9569 RecordDataImpl &LateParsed = LPT.second;
9570 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9571 /* In loop */) {
9572 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9573
9574 auto LT = std::make_unique<LateParsedTemplate>();
9575 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9576 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9577
9578 ModuleFile *F = getOwningModuleFile(LT->D);
9579 assert(F && "No module");
9580
9581 unsigned TokN = LateParsed[Idx++];
9582 LT->Toks.reserve(TokN);
9583 for (unsigned T = 0; T < TokN; ++T)
9584 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9585
9586 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9587 }
9588 }
9589
9590 LateParsedTemplates.clear();
9591}
9592
9594 if (!Lambda->getLambdaContextDecl())
9595 return;
9596
9597 auto LambdaInfo =
9598 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9599 Lambda->getLambdaIndexInContext());
9600
9601 // Handle the import and then include case for lambdas.
9602 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9603 Iter != LambdaDeclarationsForMerging.end() &&
9604 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9606 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9607 Lambda->setPreviousDecl(Previous);
9608 return;
9609 }
9610
9611 // Keep track of this lambda so it can be merged with another lambda that
9612 // is loaded later.
9613 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9614}
9615
9617 // It would be complicated to avoid reading the methods anyway. So don't.
9618 ReadMethodPool(Sel);
9619}
9620
9622 assert(ID && "Non-zero identifier ID required");
9623 unsigned Index = translateIdentifierIDToIndex(ID).second;
9624 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9625 IdentifiersLoaded[Index] = II;
9626 if (DeserializationListener)
9627 DeserializationListener->IdentifierRead(ID, II);
9628}
9629
9630/// Set the globally-visible declarations associated with the given
9631/// identifier.
9632///
9633/// If the AST reader is currently in a state where the given declaration IDs
9634/// cannot safely be resolved, they are queued until it is safe to resolve
9635/// them.
9636///
9637/// \param II an IdentifierInfo that refers to one or more globally-visible
9638/// declarations.
9639///
9640/// \param DeclIDs the set of declaration IDs with the name @p II that are
9641/// visible at global scope.
9642///
9643/// \param Decls if non-null, this vector will be populated with the set of
9644/// deserialized declarations. These declarations will not be pushed into
9645/// scope.
9648 SmallVectorImpl<Decl *> *Decls) {
9649 if (NumCurrentElementsDeserializing && !Decls) {
9650 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9651 return;
9652 }
9653
9654 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9655 if (!SemaObj) {
9656 // Queue this declaration so that it will be added to the
9657 // translation unit scope and identifier's declaration chain
9658 // once a Sema object is known.
9659 PreloadedDeclIDs.push_back(DeclIDs[I]);
9660 continue;
9661 }
9662
9663 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9664
9665 // If we're simply supposed to record the declarations, do so now.
9666 if (Decls) {
9667 Decls->push_back(D);
9668 continue;
9669 }
9670
9671 // Introduce this declaration into the translation-unit scope
9672 // and add it to the declaration chain for this identifier, so
9673 // that (unqualified) name lookup will find it.
9674 pushExternalDeclIntoScope(D, II);
9675 }
9676}
9677
9678std::pair<ModuleFile *, unsigned>
9679ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9680 if (ID == 0)
9681 return {nullptr, 0};
9682
9683 unsigned ModuleFileIndex = ID >> 32;
9684 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9685
9686 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9687 assert(getModuleManager().size() > ModuleFileIndex - 1);
9688
9689 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9690 assert(LocalID < MF.LocalNumIdentifiers);
9691 return {&MF, MF.BaseIdentifierID + LocalID};
9692}
9693
9695 if (ID == 0)
9696 return nullptr;
9697
9698 if (IdentifiersLoaded.empty()) {
9699 Error("no identifier table in AST file");
9700 return nullptr;
9701 }
9702
9703 auto [M, Index] = translateIdentifierIDToIndex(ID);
9704 if (!IdentifiersLoaded[Index]) {
9705 assert(M != nullptr && "Untranslated Identifier ID?");
9706 assert(Index >= M->BaseIdentifierID);
9707 unsigned LocalIndex = Index - M->BaseIdentifierID;
9708 const unsigned char *Data =
9709 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9710
9711 ASTIdentifierLookupTrait Trait(*this, *M);
9712 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9713 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9714 auto &II = PP.getIdentifierTable().get(Key);
9715 IdentifiersLoaded[Index] = &II;
9716 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9717 markIdentifierFromAST(*this, II, IsModule);
9718 if (DeserializationListener)
9719 DeserializationListener->IdentifierRead(ID, &II);
9720 }
9721
9722 return IdentifiersLoaded[Index];
9723}
9724
9728
9730 if (LocalID < NUM_PREDEF_IDENT_IDS)
9731 return LocalID;
9732
9733 if (!M.ModuleOffsetMap.empty())
9734 ReadModuleOffsetMap(M);
9735
9736 unsigned ModuleFileIndex = LocalID >> 32;
9737 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9738 ModuleFile *MF =
9739 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9740 assert(MF && "malformed identifier ID encoding?");
9741
9742 if (!ModuleFileIndex)
9743 LocalID -= NUM_PREDEF_IDENT_IDS;
9744
9745 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9746}
9747
9748std::pair<ModuleFile *, unsigned>
9749ASTReader::translateMacroIDToIndex(MacroID ID) const {
9750 if (ID == 0)
9751 return {nullptr, 0};
9752
9753 unsigned ModuleFileIndex = ID >> 32;
9754 assert(ModuleFileIndex && "not translating loaded MacroID?");
9755 assert(getModuleManager().size() > ModuleFileIndex - 1);
9756 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9757
9758 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
9759 assert(LocalID < MF.LocalNumMacros);
9760 return {&MF, MF.BaseMacroID + LocalID};
9761}
9762
9764 if (ID == 0)
9765 return nullptr;
9766
9767 if (MacrosLoaded.empty()) {
9768 Error("no macro table in AST file");
9769 return nullptr;
9770 }
9771
9772 auto [M, Index] = translateMacroIDToIndex(ID);
9773 if (!MacrosLoaded[Index]) {
9774 assert(M != nullptr && "Untranslated Macro ID?");
9775 assert(Index >= M->BaseMacroID);
9776 unsigned LocalIndex = Index - M->BaseMacroID;
9777 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
9778 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
9779
9780 if (DeserializationListener)
9781 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
9782 }
9783
9784 return MacrosLoaded[Index];
9785}
9786
9788 if (LocalID < NUM_PREDEF_MACRO_IDS)
9789 return LocalID;
9790
9791 if (!M.ModuleOffsetMap.empty())
9792 ReadModuleOffsetMap(M);
9793
9794 unsigned ModuleFileIndex = LocalID >> 32;
9795 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
9796 ModuleFile *MF =
9797 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9798 assert(MF && "malformed identifier ID encoding?");
9799
9800 if (!ModuleFileIndex) {
9801 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
9802 LocalID -= NUM_PREDEF_MACRO_IDS;
9803 }
9804
9805 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
9806}
9807
9809ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9810 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9811 return LocalID;
9812
9813 if (!M.ModuleOffsetMap.empty())
9814 ReadModuleOffsetMap(M);
9815
9818 assert(I != M.SubmoduleRemap.end()
9819 && "Invalid index into submodule index remap");
9820
9821 return LocalID + I->second;
9822}
9823
9825 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9826 assert(GlobalID == 0 && "Unhandled global submodule ID");
9827 return nullptr;
9828 }
9829
9830 if (GlobalID > SubmodulesLoaded.size()) {
9831 Error("submodule ID out of range in AST file");
9832 return nullptr;
9833 }
9834
9835 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9836}
9837
9839 return getSubmodule(ID);
9840}
9841
9843 if (ID & 1) {
9844 // It's a module, look it up by submodule ID.
9845 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9846 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9847 } else {
9848 // It's a prefix (preamble, PCH, ...). Look it up by index.
9849 int IndexFromEnd = static_cast<int>(ID >> 1);
9850 assert(IndexFromEnd && "got reference to unknown module file");
9851 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9852 }
9853}
9854
9856 if (!M)
9857 return 1;
9858
9859 // For a file representing a module, use the submodule ID of the top-level
9860 // module as the file ID. For any other kind of file, the number of such
9861 // files loaded beforehand will be the same on reload.
9862 // FIXME: Is this true even if we have an explicit module file and a PCH?
9863 if (M->isModule())
9864 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9865
9866 auto PCHModules = getModuleManager().pch_modules();
9867 auto I = llvm::find(PCHModules, M);
9868 assert(I != PCHModules.end() && "emitting reference to unknown file");
9869 return std::distance(I, PCHModules.end()) << 1;
9870}
9871
9872std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9873 if (Module *M = getSubmodule(ID))
9874 return ASTSourceDescriptor(*M);
9875
9876 // If there is only a single PCH, return it instead.
9877 // Chained PCH are not supported.
9878 const auto &PCHChain = ModuleMgr.pch_modules();
9879 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9880 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9881 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9882 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9883 return ASTSourceDescriptor(ModuleName,
9884 llvm::sys::path::parent_path(MF.FileName),
9885 FileName, MF.Signature);
9886 }
9887 return std::nullopt;
9888}
9889
9891 auto I = DefinitionSource.find(FD);
9892 if (I == DefinitionSource.end())
9893 return EK_ReplyHazy;
9894 return I->second ? EK_Never : EK_Always;
9895}
9896
9898 return ThisDeclarationWasADefinitionSet.contains(FD);
9899}
9900
9902 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9903}
9904
9906 if (ID == 0)
9907 return Selector();
9908
9909 if (ID > SelectorsLoaded.size()) {
9910 Error("selector ID out of range in AST file");
9911 return Selector();
9912 }
9913
9914 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9915 // Load this selector from the selector table.
9916 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9917 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9918 ModuleFile &M = *I->second;
9919 ASTSelectorLookupTrait Trait(*this, M);
9920 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9921 SelectorsLoaded[ID - 1] =
9922 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9923 if (DeserializationListener)
9924 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9925 }
9926
9927 return SelectorsLoaded[ID - 1];
9928}
9929
9933
9935 // ID 0 (the null selector) is considered an external selector.
9936 return getTotalNumSelectors() + 1;
9937}
9938
9940ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9941 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9942 return LocalID;
9943
9944 if (!M.ModuleOffsetMap.empty())
9945 ReadModuleOffsetMap(M);
9946
9949 assert(I != M.SelectorRemap.end()
9950 && "Invalid index into selector index remap");
9951
9952 return LocalID + I->second;
9953}
9954
9980
9982 DeclarationNameInfo NameInfo;
9983 NameInfo.setName(readDeclarationName());
9984 NameInfo.setLoc(readSourceLocation());
9985 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9986 return NameInfo;
9987}
9988
9992
9994 auto Kind = readInt();
9995 auto ResultType = readQualType();
9996 auto Value = readAPInt();
9997 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
9998 assert(Op.isValid());
9999 return Op;
10000}
10001
10004 unsigned NumTPLists = readInt();
10005 Info.NumTemplParamLists = NumTPLists;
10006 if (NumTPLists) {
10007 Info.TemplParamLists =
10008 new (getContext()) TemplateParameterList *[NumTPLists];
10009 for (unsigned i = 0; i != NumTPLists; ++i)
10011 }
10012}
10013
10016 SourceLocation TemplateLoc = readSourceLocation();
10017 SourceLocation LAngleLoc = readSourceLocation();
10018 SourceLocation RAngleLoc = readSourceLocation();
10019
10020 unsigned NumParams = readInt();
10022 Params.reserve(NumParams);
10023 while (NumParams--)
10024 Params.push_back(readDeclAs<NamedDecl>());
10025
10026 bool HasRequiresClause = readBool();
10027 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10028
10030 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10031 return TemplateParams;
10032}
10033
10036 bool Canonicalize) {
10037 unsigned NumTemplateArgs = readInt();
10038 TemplArgs.reserve(NumTemplateArgs);
10039 while (NumTemplateArgs--)
10040 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10041}
10042
10043/// Read a UnresolvedSet structure.
10045 unsigned NumDecls = readInt();
10046 Set.reserve(getContext(), NumDecls);
10047 while (NumDecls--) {
10048 GlobalDeclID ID = readDeclID();
10050 Set.addLazyDecl(getContext(), ID, AS);
10051 }
10052}
10053
10056 bool isVirtual = readBool();
10057 bool isBaseOfClass = readBool();
10058 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10059 bool inheritConstructors = readBool();
10061 SourceRange Range = readSourceRange();
10062 SourceLocation EllipsisLoc = readSourceLocation();
10063 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10064 EllipsisLoc);
10065 Result.setInheritConstructors(inheritConstructors);
10066 return Result;
10067}
10068
10071 ASTContext &Context = getContext();
10072 unsigned NumInitializers = readInt();
10073 assert(NumInitializers && "wrote ctor initializers but have no inits");
10074 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10075 for (unsigned i = 0; i != NumInitializers; ++i) {
10076 TypeSourceInfo *TInfo = nullptr;
10077 bool IsBaseVirtual = false;
10078 FieldDecl *Member = nullptr;
10079 IndirectFieldDecl *IndirectMember = nullptr;
10080
10082 switch (Type) {
10084 TInfo = readTypeSourceInfo();
10085 IsBaseVirtual = readBool();
10086 break;
10087
10089 TInfo = readTypeSourceInfo();
10090 break;
10091
10094 break;
10095
10097 IndirectMember = readDeclAs<IndirectFieldDecl>();
10098 break;
10099 }
10100
10101 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10102 Expr *Init = readExpr();
10103 SourceLocation LParenLoc = readSourceLocation();
10104 SourceLocation RParenLoc = readSourceLocation();
10105
10106 CXXCtorInitializer *BOMInit;
10108 BOMInit = new (Context)
10109 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10110 RParenLoc, MemberOrEllipsisLoc);
10112 BOMInit = new (Context)
10113 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10114 else if (Member)
10115 BOMInit = new (Context)
10116 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10117 Init, RParenLoc);
10118 else
10119 BOMInit = new (Context)
10120 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10121 LParenLoc, Init, RParenLoc);
10122
10123 if (/*IsWritten*/readBool()) {
10124 unsigned SourceOrder = readInt();
10125 BOMInit->setSourceOrder(SourceOrder);
10126 }
10127
10128 CtorInitializers[i] = BOMInit;
10129 }
10130
10131 return CtorInitializers;
10132}
10133
10136 ASTContext &Context = getContext();
10137 unsigned N = readInt();
10139 for (unsigned I = 0; I != N; ++I) {
10140 auto Kind = readNestedNameSpecifierKind();
10141 switch (Kind) {
10143 auto *NS = readDeclAs<NamespaceBaseDecl>();
10144 SourceRange Range = readSourceRange();
10145 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10146 break;
10147 }
10148
10151 if (!T)
10152 return NestedNameSpecifierLoc();
10153 SourceLocation ColonColonLoc = readSourceLocation();
10154 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10155 break;
10156 }
10157
10159 SourceLocation ColonColonLoc = readSourceLocation();
10160 Builder.MakeGlobal(Context, ColonColonLoc);
10161 break;
10162 }
10163
10166 SourceRange Range = readSourceRange();
10167 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10168 break;
10169 }
10170
10172 llvm_unreachable("unexpected null nested name specifier");
10173 }
10174 }
10175
10176 return Builder.getWithLocInContext(Context);
10177}
10178
10180 unsigned &Idx) {
10183 return SourceRange(beg, end);
10184}
10185
10187 const StringRef Blob) {
10188 unsigned Count = Record[0];
10189 const char *Byte = Blob.data();
10190 llvm::BitVector Ret = llvm::BitVector(Count, false);
10191 for (unsigned I = 0; I < Count; ++Byte)
10192 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10193 if (*Byte & (1 << Bit))
10194 Ret[I] = true;
10195 return Ret;
10196}
10197
10198/// Read a floating-point value
10199llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10200 return llvm::APFloat(Sem, readAPInt());
10201}
10202
10203// Read a string
10204std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10205 unsigned Len = Record[Idx++];
10206 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10207 Idx += Len;
10208 return Result;
10209}
10210
10211StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10212 StringRef &Blob) {
10213 unsigned Len = Record[Idx++];
10214 StringRef Result = Blob.substr(0, Len);
10215 Blob = Blob.substr(Len);
10216 return Result;
10217}
10218
10220 unsigned &Idx) {
10221 return ReadPath(F.BaseDirectory, Record, Idx);
10222}
10223
10224std::string ASTReader::ReadPath(StringRef BaseDirectory,
10225 const RecordData &Record, unsigned &Idx) {
10226 std::string Filename = ReadString(Record, Idx);
10227 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10228}
10229
10230std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10231 const RecordData &Record, unsigned &Idx,
10232 StringRef &Blob) {
10233 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10234 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10235}
10236
10238 unsigned &Idx) {
10239 unsigned Major = Record[Idx++];
10240 unsigned Minor = Record[Idx++];
10241 unsigned Subminor = Record[Idx++];
10242 if (Minor == 0)
10243 return VersionTuple(Major);
10244 if (Subminor == 0)
10245 return VersionTuple(Major, Minor - 1);
10246 return VersionTuple(Major, Minor - 1, Subminor - 1);
10247}
10248
10255
10256DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10257 return Diag(CurrentImportLoc, DiagID);
10258}
10259
10261 return Diags.Report(Loc, DiagID);
10262}
10263
10265 llvm::function_ref<void()> Fn) {
10266 // When Sema is available, avoid duplicate errors.
10267 if (SemaObj) {
10268 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10269 return;
10270 }
10271
10272 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10273}
10274
10275/// Retrieve the identifier table associated with the
10276/// preprocessor.
10278 return PP.getIdentifierTable();
10279}
10280
10281/// Record that the given ID maps to the given switch-case
10282/// statement.
10284 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10285 "Already have a SwitchCase with this ID");
10286 (*CurrSwitchCaseStmts)[ID] = SC;
10287}
10288
10289/// Retrieve the switch-case statement with the given ID.
10291 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10292 return (*CurrSwitchCaseStmts)[ID];
10293}
10294
10296 CurrSwitchCaseStmts->clear();
10297}
10298
10300 ASTContext &Context = getContext();
10301 std::vector<RawComment *> Comments;
10302 for (SmallVectorImpl<std::pair<BitstreamCursor,
10304 I = CommentsCursors.begin(),
10305 E = CommentsCursors.end();
10306 I != E; ++I) {
10307 Comments.clear();
10308 BitstreamCursor &Cursor = I->first;
10309 serialization::ModuleFile &F = *I->second;
10310 SavedStreamPosition SavedPosition(Cursor);
10311
10313 while (true) {
10315 Cursor.advanceSkippingSubblocks(
10316 BitstreamCursor::AF_DontPopBlockAtEnd);
10317 if (!MaybeEntry) {
10318 Error(MaybeEntry.takeError());
10319 return;
10320 }
10321 llvm::BitstreamEntry Entry = MaybeEntry.get();
10322
10323 switch (Entry.Kind) {
10324 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10325 case llvm::BitstreamEntry::Error:
10326 Error("malformed block record in AST file");
10327 return;
10328 case llvm::BitstreamEntry::EndBlock:
10329 goto NextCursor;
10330 case llvm::BitstreamEntry::Record:
10331 // The interesting case.
10332 break;
10333 }
10334
10335 // Read a record.
10336 Record.clear();
10337 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10338 if (!MaybeComment) {
10339 Error(MaybeComment.takeError());
10340 return;
10341 }
10342 switch ((CommentRecordTypes)MaybeComment.get()) {
10343 case COMMENTS_RAW_COMMENT: {
10344 unsigned Idx = 0;
10345 SourceRange SR = ReadSourceRange(F, Record, Idx);
10348 bool IsTrailingComment = Record[Idx++];
10349 bool IsAlmostTrailingComment = Record[Idx++];
10350 Comments.push_back(new (Context) RawComment(
10351 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10352 break;
10353 }
10354 }
10355 }
10356 NextCursor:
10357 for (RawComment *C : Comments) {
10358 SourceLocation CommentLoc = C->getBeginLoc();
10359 if (CommentLoc.isValid()) {
10360 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10361 if (Loc.first.isValid())
10362 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10363 }
10364 }
10365 }
10366}
10367
10369 serialization::ModuleFile &MF, bool IncludeSystem,
10370 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10371 bool IsSystem)>
10372 Visitor) {
10373 unsigned NumUserInputs = MF.NumUserInputFiles;
10374 unsigned NumInputs = MF.InputFilesLoaded.size();
10375 assert(NumUserInputs <= NumInputs);
10376 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10377 for (unsigned I = 0; I < N; ++I) {
10378 bool IsSystem = I >= NumUserInputs;
10379 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10380 Visitor(IFI, IsSystem);
10381 }
10382}
10383
10385 bool IncludeSystem, bool Complain,
10386 llvm::function_ref<void(const serialization::InputFile &IF,
10387 bool isSystem)> Visitor) {
10388 unsigned NumUserInputs = MF.NumUserInputFiles;
10389 unsigned NumInputs = MF.InputFilesLoaded.size();
10390 assert(NumUserInputs <= NumInputs);
10391 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10392 for (unsigned I = 0; I < N; ++I) {
10393 bool IsSystem = I >= NumUserInputs;
10394 InputFile IF = getInputFile(MF, I+1, Complain);
10395 Visitor(IF, IsSystem);
10396 }
10397}
10398
10401 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10402 unsigned NumInputs = MF.InputFilesLoaded.size();
10403 for (unsigned I = 0; I < NumInputs; ++I) {
10404 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10405 if (IFI.TopLevel && IFI.ModuleMap)
10406 if (auto FE = getInputFile(MF, I + 1).getFile())
10407 Visitor(*FE);
10408 }
10409}
10410
10411void ASTReader::finishPendingActions() {
10412 while (!PendingIdentifierInfos.empty() ||
10413 !PendingDeducedFunctionTypes.empty() ||
10414 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10415 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10416 !PendingUpdateRecords.empty() ||
10417 !PendingObjCExtensionIvarRedeclarations.empty()) {
10418 // If any identifiers with corresponding top-level declarations have
10419 // been loaded, load those declarations now.
10420 using TopLevelDeclsMap =
10421 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10422 TopLevelDeclsMap TopLevelDecls;
10423
10424 while (!PendingIdentifierInfos.empty()) {
10425 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10427 std::move(PendingIdentifierInfos.back().second);
10428 PendingIdentifierInfos.pop_back();
10429
10430 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10431 }
10432
10433 // Load each function type that we deferred loading because it was a
10434 // deduced type that might refer to a local type declared within itself.
10435 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10436 auto *FD = PendingDeducedFunctionTypes[I].first;
10437 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10438
10439 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10440 // If we gave a function a deduced return type, remember that we need to
10441 // propagate that along the redeclaration chain.
10442 if (DT->isDeduced()) {
10443 PendingDeducedTypeUpdates.insert(
10444 {FD->getCanonicalDecl(), FD->getReturnType()});
10445 continue;
10446 }
10447
10448 // The function has undeduced DeduceType return type. We hope we can
10449 // find the deduced type by iterating the redecls in other modules
10450 // later.
10451 PendingUndeducedFunctionDecls.push_back(FD);
10452 continue;
10453 }
10454 }
10455 PendingDeducedFunctionTypes.clear();
10456
10457 // Load each variable type that we deferred loading because it was a
10458 // deduced type that might refer to a local type declared within itself.
10459 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10460 auto *VD = PendingDeducedVarTypes[I].first;
10461 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10462 }
10463 PendingDeducedVarTypes.clear();
10464
10465 // Load pending declaration chains.
10466 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10467 loadPendingDeclChain(PendingDeclChains[I].first,
10468 PendingDeclChains[I].second);
10469 PendingDeclChains.clear();
10470
10471 // Make the most recent of the top-level declarations visible.
10472 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10473 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10474 IdentifierInfo *II = TLD->first;
10475 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10476 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10477 }
10478 }
10479
10480 // Load any pending macro definitions.
10481 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10482 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10483 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10484 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10485 // Initialize the macro history from chained-PCHs ahead of module imports.
10486 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10487 ++IDIdx) {
10488 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10489 if (!Info.M->isModule())
10490 resolvePendingMacro(II, Info);
10491 }
10492 // Handle module imports.
10493 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10494 ++IDIdx) {
10495 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10496 if (Info.M->isModule())
10497 resolvePendingMacro(II, Info);
10498 }
10499 }
10500 PendingMacroIDs.clear();
10501
10502 // Wire up the DeclContexts for Decls that we delayed setting until
10503 // recursive loading is completed.
10504 while (!PendingDeclContextInfos.empty()) {
10505 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10506 PendingDeclContextInfos.pop_front();
10507 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10508 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10509 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10510 }
10511
10512 // Perform any pending declaration updates.
10513 while (!PendingUpdateRecords.empty()) {
10514 auto Update = PendingUpdateRecords.pop_back_val();
10515 ReadingKindTracker ReadingKind(Read_Decl, *this);
10516 loadDeclUpdateRecords(Update);
10517 }
10518
10519 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10520 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10521 auto DuplicateIvars =
10522 PendingObjCExtensionIvarRedeclarations.back().second;
10524 StructuralEquivalenceContext Ctx(
10525 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10526 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10527 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10528 /*Complain =*/false,
10529 /*ErrorOnTagTypeMismatch =*/true);
10530 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10531 // Merge redeclared ivars with their predecessors.
10532 for (auto IvarPair : DuplicateIvars) {
10533 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10534 // Change semantic DeclContext but keep the lexical one.
10535 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10536 Ivar->getLexicalDeclContext(),
10537 getContext());
10538 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10539 }
10540 // Invalidate duplicate extension and the cached ivar list.
10541 ExtensionsPair.first->setInvalidDecl();
10542 ExtensionsPair.second->getClassInterface()
10543 ->getDefinition()
10544 ->setIvarList(nullptr);
10545 } else {
10546 for (auto IvarPair : DuplicateIvars) {
10547 Diag(IvarPair.first->getLocation(),
10548 diag::err_duplicate_ivar_declaration)
10549 << IvarPair.first->getIdentifier();
10550 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10551 }
10552 }
10553 PendingObjCExtensionIvarRedeclarations.pop_back();
10554 }
10555 }
10556
10557 // At this point, all update records for loaded decls are in place, so any
10558 // fake class definitions should have become real.
10559 assert(PendingFakeDefinitionData.empty() &&
10560 "faked up a class definition but never saw the real one");
10561
10562 // If we deserialized any C++ or Objective-C class definitions, any
10563 // Objective-C protocol definitions, or any redeclarable templates, make sure
10564 // that all redeclarations point to the definitions. Note that this can only
10565 // happen now, after the redeclaration chains have been fully wired.
10566 for (Decl *D : PendingDefinitions) {
10567 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10568 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10569 for (auto *R = getMostRecentExistingDecl(RD); R;
10570 R = R->getPreviousDecl()) {
10571 assert((R == D) ==
10572 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10573 "declaration thinks it's the definition but it isn't");
10574 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10575 }
10576 }
10577
10578 continue;
10579 }
10580
10581 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10582 // Make sure that the ObjCInterfaceType points at the definition.
10583 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10584 ->Decl = ID;
10585
10586 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10587 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10588
10589 continue;
10590 }
10591
10592 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10593 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10594 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10595
10596 continue;
10597 }
10598
10599 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10600 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10601 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10602 }
10603 PendingDefinitions.clear();
10604
10605 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10606 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10607 if (auto *VD = dyn_cast<VarDecl>(D))
10608 return VD->isThisDeclarationADefinition() ||
10609 VD->isThisDeclarationADemotedDefinition();
10610
10611 if (auto *TD = dyn_cast<TagDecl>(D))
10612 return TD->isThisDeclarationADefinition() ||
10613 TD->isThisDeclarationADemotedDefinition();
10614
10615 if (auto *FD = dyn_cast<FunctionDecl>(D))
10616 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10617
10618 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10619 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10620
10621 // Conservatively return false here.
10622 return false;
10623 };
10624
10625 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10626 return hasDefinitionImpl(D, hasDefinitionImpl);
10627 };
10628
10629 // It is not good to prevent multiple declarations since the forward
10630 // declaration is common. Let's try to avoid duplicated definitions
10631 // only.
10633 continue;
10634
10635 Module *PM = Previous->getOwningModule();
10636 Module *DM = D->getOwningModule();
10637 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10639 << (DM ? DM->getTopLevelModuleName() : "global module");
10640 Diag(Previous->getLocation(), diag::note_also_found);
10641 }
10642 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10643
10644 // Load the bodies of any functions or methods we've encountered. We do
10645 // this now (delayed) so that we can be sure that the declaration chains
10646 // have been fully wired up (hasBody relies on this).
10647 // FIXME: We shouldn't require complete redeclaration chains here.
10648 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10649 PBEnd = PendingBodies.end();
10650 PB != PBEnd; ++PB) {
10651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10652 // FIXME: Check for =delete/=default?
10653 const FunctionDecl *Defn = nullptr;
10654 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10655 FD->setLazyBody(PB->second);
10656 } else {
10657 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10658 mergeDefinitionVisibility(NonConstDefn, FD);
10659
10660 if (!FD->isLateTemplateParsed() &&
10661 !NonConstDefn->isLateTemplateParsed() &&
10662 // We only perform ODR checks for decls not in the explicit
10663 // global module fragment.
10664 !shouldSkipCheckingODR(FD) &&
10665 !shouldSkipCheckingODR(NonConstDefn) &&
10666 FD->getODRHash() != NonConstDefn->getODRHash()) {
10667 if (!isa<CXXMethodDecl>(FD)) {
10668 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10669 } else if (FD->getLexicalParent()->isFileContext() &&
10670 NonConstDefn->getLexicalParent()->isFileContext()) {
10671 // Only diagnose out-of-line method definitions. If they are
10672 // in class definitions, then an error will be generated when
10673 // processing the class bodies.
10674 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10675 }
10676 }
10677 }
10678 continue;
10679 }
10680
10681 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10682 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10683 MD->setLazyBody(PB->second);
10684 }
10685 PendingBodies.clear();
10686
10687 // Inform any classes that had members added that they now have more members.
10688 for (auto [RD, MD] : PendingAddedClassMembers) {
10689 RD->addedMember(MD);
10690 }
10691 PendingAddedClassMembers.clear();
10692
10693 // Do some cleanup.
10694 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10696 PendingMergedDefinitionsToDeduplicate.clear();
10697
10698 // For each decl chain that we wanted to complete while deserializing, mark
10699 // it as "still needs to be completed".
10700 for (Decl *D : PendingIncompleteDeclChains)
10701 markIncompleteDeclChain(D);
10702 PendingIncompleteDeclChains.clear();
10703
10704 assert(PendingIdentifierInfos.empty() &&
10705 "Should be empty at the end of finishPendingActions");
10706 assert(PendingDeducedFunctionTypes.empty() &&
10707 "Should be empty at the end of finishPendingActions");
10708 assert(PendingDeducedVarTypes.empty() &&
10709 "Should be empty at the end of finishPendingActions");
10710 assert(PendingDeclChains.empty() &&
10711 "Should be empty at the end of finishPendingActions");
10712 assert(PendingMacroIDs.empty() &&
10713 "Should be empty at the end of finishPendingActions");
10714 assert(PendingDeclContextInfos.empty() &&
10715 "Should be empty at the end of finishPendingActions");
10716 assert(PendingUpdateRecords.empty() &&
10717 "Should be empty at the end of finishPendingActions");
10718 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10719 "Should be empty at the end of finishPendingActions");
10720 assert(PendingFakeDefinitionData.empty() &&
10721 "Should be empty at the end of finishPendingActions");
10722 assert(PendingDefinitions.empty() &&
10723 "Should be empty at the end of finishPendingActions");
10724 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10725 "Should be empty at the end of finishPendingActions");
10726 assert(PendingBodies.empty() &&
10727 "Should be empty at the end of finishPendingActions");
10728 assert(PendingAddedClassMembers.empty() &&
10729 "Should be empty at the end of finishPendingActions");
10730 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10731 "Should be empty at the end of finishPendingActions");
10732 assert(PendingIncompleteDeclChains.empty() &&
10733 "Should be empty at the end of finishPendingActions");
10734}
10735
10736void ASTReader::diagnoseOdrViolations() {
10737 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10738 PendingRecordOdrMergeFailures.empty() &&
10739 PendingFunctionOdrMergeFailures.empty() &&
10740 PendingEnumOdrMergeFailures.empty() &&
10741 PendingObjCInterfaceOdrMergeFailures.empty() &&
10742 PendingObjCProtocolOdrMergeFailures.empty())
10743 return;
10744
10745 // Trigger the import of the full definition of each class that had any
10746 // odr-merging problems, so we can produce better diagnostics for them.
10747 // These updates may in turn find and diagnose some ODR failures, so take
10748 // ownership of the set first.
10749 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10750 PendingOdrMergeFailures.clear();
10751 for (auto &Merge : OdrMergeFailures) {
10752 Merge.first->buildLookup();
10753 Merge.first->decls_begin();
10754 Merge.first->bases_begin();
10755 Merge.first->vbases_begin();
10756 for (auto &RecordPair : Merge.second) {
10757 auto *RD = RecordPair.first;
10758 RD->decls_begin();
10759 RD->bases_begin();
10760 RD->vbases_begin();
10761 }
10762 }
10763
10764 // Trigger the import of the full definition of each record in C/ObjC.
10765 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10766 PendingRecordOdrMergeFailures.clear();
10767 for (auto &Merge : RecordOdrMergeFailures) {
10768 Merge.first->decls_begin();
10769 for (auto &D : Merge.second)
10770 D->decls_begin();
10771 }
10772
10773 // Trigger the import of the full interface definition.
10774 auto ObjCInterfaceOdrMergeFailures =
10775 std::move(PendingObjCInterfaceOdrMergeFailures);
10776 PendingObjCInterfaceOdrMergeFailures.clear();
10777 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10778 Merge.first->decls_begin();
10779 for (auto &InterfacePair : Merge.second)
10780 InterfacePair.first->decls_begin();
10781 }
10782
10783 // Trigger the import of functions.
10784 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10785 PendingFunctionOdrMergeFailures.clear();
10786 for (auto &Merge : FunctionOdrMergeFailures) {
10787 Merge.first->buildLookup();
10788 Merge.first->decls_begin();
10789 Merge.first->getBody();
10790 for (auto &FD : Merge.second) {
10791 FD->buildLookup();
10792 FD->decls_begin();
10793 FD->getBody();
10794 }
10795 }
10796
10797 // Trigger the import of enums.
10798 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10799 PendingEnumOdrMergeFailures.clear();
10800 for (auto &Merge : EnumOdrMergeFailures) {
10801 Merge.first->decls_begin();
10802 for (auto &Enum : Merge.second) {
10803 Enum->decls_begin();
10804 }
10805 }
10806
10807 // Trigger the import of the full protocol definition.
10808 auto ObjCProtocolOdrMergeFailures =
10809 std::move(PendingObjCProtocolOdrMergeFailures);
10810 PendingObjCProtocolOdrMergeFailures.clear();
10811 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10812 Merge.first->decls_begin();
10813 for (auto &ProtocolPair : Merge.second)
10814 ProtocolPair.first->decls_begin();
10815 }
10816
10817 // For each declaration from a merged context, check that the canonical
10818 // definition of that context also contains a declaration of the same
10819 // entity.
10820 //
10821 // Caution: this loop does things that might invalidate iterators into
10822 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10823 while (!PendingOdrMergeChecks.empty()) {
10824 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10825
10826 // FIXME: Skip over implicit declarations for now. This matters for things
10827 // like implicitly-declared special member functions. This isn't entirely
10828 // correct; we can end up with multiple unmerged declarations of the same
10829 // implicit entity.
10830 if (D->isImplicit())
10831 continue;
10832
10833 DeclContext *CanonDef = D->getDeclContext();
10834
10835 bool Found = false;
10836 const Decl *DCanon = D->getCanonicalDecl();
10837
10838 for (auto *RI : D->redecls()) {
10839 if (RI->getLexicalDeclContext() == CanonDef) {
10840 Found = true;
10841 break;
10842 }
10843 }
10844 if (Found)
10845 continue;
10846
10847 // Quick check failed, time to do the slow thing. Note, we can't just
10848 // look up the name of D in CanonDef here, because the member that is
10849 // in CanonDef might not be found by name lookup (it might have been
10850 // replaced by a more recent declaration in the lookup table), and we
10851 // can't necessarily find it in the redeclaration chain because it might
10852 // be merely mergeable, not redeclarable.
10853 llvm::SmallVector<const NamedDecl*, 4> Candidates;
10854 for (auto *CanonMember : CanonDef->decls()) {
10855 if (CanonMember->getCanonicalDecl() == DCanon) {
10856 // This can happen if the declaration is merely mergeable and not
10857 // actually redeclarable (we looked for redeclarations earlier).
10858 //
10859 // FIXME: We should be able to detect this more efficiently, without
10860 // pulling in all of the members of CanonDef.
10861 Found = true;
10862 break;
10863 }
10864 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10865 if (ND->getDeclName() == D->getDeclName())
10866 Candidates.push_back(ND);
10867 }
10868
10869 if (!Found) {
10870 // The AST doesn't like TagDecls becoming invalid after they've been
10871 // completed. We only really need to mark FieldDecls as invalid here.
10872 if (!isa<TagDecl>(D))
10873 D->setInvalidDecl();
10874
10875 // Ensure we don't accidentally recursively enter deserialization while
10876 // we're producing our diagnostic.
10877 Deserializing RecursionGuard(this);
10878
10879 std::string CanonDefModule =
10881 cast<Decl>(CanonDef));
10882 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10884 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10885
10886 if (Candidates.empty())
10887 Diag(cast<Decl>(CanonDef)->getLocation(),
10888 diag::note_module_odr_violation_no_possible_decls) << D;
10889 else {
10890 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10891 Diag(Candidates[I]->getLocation(),
10892 diag::note_module_odr_violation_possible_decl)
10893 << Candidates[I];
10894 }
10895
10896 DiagnosedOdrMergeFailures.insert(CanonDef);
10897 }
10898 }
10899
10900 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10901 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10902 ObjCInterfaceOdrMergeFailures.empty() &&
10903 ObjCProtocolOdrMergeFailures.empty())
10904 return;
10905
10906 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10907 getPreprocessor().getLangOpts());
10908
10909 // Issue any pending ODR-failure diagnostics.
10910 for (auto &Merge : OdrMergeFailures) {
10911 // If we've already pointed out a specific problem with this class, don't
10912 // bother issuing a general "something's different" diagnostic.
10913 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10914 continue;
10915
10916 bool Diagnosed = false;
10917 CXXRecordDecl *FirstRecord = Merge.first;
10918 for (auto &RecordPair : Merge.second) {
10919 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10920 RecordPair.second)) {
10921 Diagnosed = true;
10922 break;
10923 }
10924 }
10925
10926 if (!Diagnosed) {
10927 // All definitions are updates to the same declaration. This happens if a
10928 // module instantiates the declaration of a class template specialization
10929 // and two or more other modules instantiate its definition.
10930 //
10931 // FIXME: Indicate which modules had instantiations of this definition.
10932 // FIXME: How can this even happen?
10933 Diag(Merge.first->getLocation(),
10934 diag::err_module_odr_violation_different_instantiations)
10935 << Merge.first;
10936 }
10937 }
10938
10939 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10940 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10941 for (auto &Merge : RecordOdrMergeFailures) {
10942 // If we've already pointed out a specific problem with this class, don't
10943 // bother issuing a general "something's different" diagnostic.
10944 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10945 continue;
10946
10947 RecordDecl *FirstRecord = Merge.first;
10948 bool Diagnosed = false;
10949 for (auto *SecondRecord : Merge.second) {
10950 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10951 Diagnosed = true;
10952 break;
10953 }
10954 }
10955 (void)Diagnosed;
10956 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10957 }
10958
10959 // Issue ODR failures diagnostics for functions.
10960 for (auto &Merge : FunctionOdrMergeFailures) {
10961 FunctionDecl *FirstFunction = Merge.first;
10962 bool Diagnosed = false;
10963 for (auto &SecondFunction : Merge.second) {
10964 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10965 Diagnosed = true;
10966 break;
10967 }
10968 }
10969 (void)Diagnosed;
10970 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10971 }
10972
10973 // Issue ODR failures diagnostics for enums.
10974 for (auto &Merge : EnumOdrMergeFailures) {
10975 // If we've already pointed out a specific problem with this enum, don't
10976 // bother issuing a general "something's different" diagnostic.
10977 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10978 continue;
10979
10980 EnumDecl *FirstEnum = Merge.first;
10981 bool Diagnosed = false;
10982 for (auto &SecondEnum : Merge.second) {
10983 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10984 Diagnosed = true;
10985 break;
10986 }
10987 }
10988 (void)Diagnosed;
10989 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10990 }
10991
10992 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10993 // If we've already pointed out a specific problem with this interface,
10994 // don't bother issuing a general "something's different" diagnostic.
10995 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10996 continue;
10997
10998 bool Diagnosed = false;
10999 ObjCInterfaceDecl *FirstID = Merge.first;
11000 for (auto &InterfacePair : Merge.second) {
11001 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11002 InterfacePair.second)) {
11003 Diagnosed = true;
11004 break;
11005 }
11006 }
11007 (void)Diagnosed;
11008 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11009 }
11010
11011 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11012 // If we've already pointed out a specific problem with this protocol,
11013 // don't bother issuing a general "something's different" diagnostic.
11014 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11015 continue;
11016
11017 ObjCProtocolDecl *FirstProtocol = Merge.first;
11018 bool Diagnosed = false;
11019 for (auto &ProtocolPair : Merge.second) {
11020 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11021 ProtocolPair.second)) {
11022 Diagnosed = true;
11023 break;
11024 }
11025 }
11026 (void)Diagnosed;
11027 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11028 }
11029}
11030
11032 if (llvm::Timer *T = ReadTimer.get();
11033 ++NumCurrentElementsDeserializing == 1 && T)
11034 ReadTimeRegion.emplace(T);
11035}
11036
11038 assert(NumCurrentElementsDeserializing &&
11039 "FinishedDeserializing not paired with StartedDeserializing");
11040 if (NumCurrentElementsDeserializing == 1) {
11041 // We decrease NumCurrentElementsDeserializing only after pending actions
11042 // are finished, to avoid recursively re-calling finishPendingActions().
11043 finishPendingActions();
11044 }
11045 --NumCurrentElementsDeserializing;
11046
11047 if (NumCurrentElementsDeserializing == 0) {
11048 {
11049 // Guard variable to avoid recursively entering the process of passing
11050 // decls to consumer.
11051 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11052 /*NewValue=*/false);
11053
11054 // Propagate exception specification and deduced type updates along
11055 // redeclaration chains.
11056 //
11057 // We do this now rather than in finishPendingActions because we want to
11058 // be able to walk the complete redeclaration chains of the updated decls.
11059 while (!PendingExceptionSpecUpdates.empty() ||
11060 !PendingDeducedTypeUpdates.empty() ||
11061 !PendingUndeducedFunctionDecls.empty()) {
11062 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11063 PendingExceptionSpecUpdates.clear();
11064 for (auto Update : ESUpdates) {
11065 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11066 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11067 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11068 if (auto *Listener = getContext().getASTMutationListener())
11069 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11070 for (auto *Redecl : Update.second->redecls())
11072 }
11073
11074 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11075 PendingDeducedTypeUpdates.clear();
11076 for (auto Update : DTUpdates) {
11077 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11078 // FIXME: If the return type is already deduced, check that it
11079 // matches.
11081 Update.second);
11082 }
11083
11084 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11085 PendingUndeducedFunctionDecls.clear();
11086 // We hope we can find the deduced type for the functions by iterating
11087 // redeclarations in other modules.
11088 for (FunctionDecl *UndeducedFD : UDTUpdates)
11089 (void)UndeducedFD->getMostRecentDecl();
11090 }
11091
11092 ReadTimeRegion.reset();
11093
11094 diagnoseOdrViolations();
11095 }
11096
11097 // We are not in recursive loading, so it's safe to pass the "interesting"
11098 // decls to the consumer.
11099 if (Consumer)
11100 PassInterestingDeclsToConsumer();
11101 }
11102}
11103
11104void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11105 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11106 // Remove any fake results before adding any real ones.
11107 auto It = PendingFakeLookupResults.find(II);
11108 if (It != PendingFakeLookupResults.end()) {
11109 for (auto *ND : It->second)
11110 SemaObj->IdResolver.RemoveDecl(ND);
11111 // FIXME: this works around module+PCH performance issue.
11112 // Rather than erase the result from the map, which is O(n), just clear
11113 // the vector of NamedDecls.
11114 It->second.clear();
11115 }
11116 }
11117
11118 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11119 SemaObj->TUScope->AddDecl(D);
11120 } else if (SemaObj->TUScope) {
11121 // Adding the decl to IdResolver may have failed because it was already in
11122 // (even though it was not added in scope). If it is already in, make sure
11123 // it gets in the scope as well.
11124 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11125 SemaObj->TUScope->AddDecl(D);
11126 }
11127}
11128
11130 ASTContext *Context,
11131 const PCHContainerReader &PCHContainerRdr,
11132 const CodeGenOptions &CodeGenOpts,
11133 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11134 StringRef isysroot,
11135 DisableValidationForModuleKind DisableValidationKind,
11136 bool AllowASTWithCompilerErrors,
11137 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11138 bool ForceValidateUserInputs,
11139 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11140 std::unique_ptr<llvm::Timer> ReadTimer)
11141 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11143 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11144 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11145 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11146 StackHandler(Diags), PP(PP), ContextObj(Context),
11147 CodeGenOpts(CodeGenOpts),
11148 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11149 PP.getHeaderSearchInfo()),
11150 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11151 DisableValidationKind(DisableValidationKind),
11152 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11153 AllowConfigurationMismatch(AllowConfigurationMismatch),
11154 ValidateSystemInputs(ValidateSystemInputs),
11155 ForceValidateUserInputs(ForceValidateUserInputs),
11156 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11157 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11158 SourceMgr.setExternalSLocEntrySource(this);
11159
11160 PathBuf.reserve(256);
11161
11162 for (const auto &Ext : Extensions) {
11163 auto BlockName = Ext->getExtensionMetadata().BlockName;
11164 auto Known = ModuleFileExtensions.find(BlockName);
11165 if (Known != ModuleFileExtensions.end()) {
11166 Diags.Report(diag::warn_duplicate_module_file_extension)
11167 << BlockName;
11168 continue;
11169 }
11170
11171 ModuleFileExtensions.insert({BlockName, Ext});
11172 }
11173}
11174
11176 if (OwnsDeserializationListener)
11177 delete DeserializationListener;
11178}
11179
11181 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11182}
11183
11185 unsigned AbbrevID) {
11186 Idx = 0;
11187 Record.clear();
11188 return Cursor.readRecord(AbbrevID, Record);
11189}
11190//===----------------------------------------------------------------------===//
11191//// OMPClauseReader implementation
11192////===----------------------------------------------------------------------===//
11193
11194// This has to be in namespace clang because it's friended by all
11195// of the OMP clauses.
11196namespace clang {
11197
11198class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11199 ASTRecordReader &Record;
11200 ASTContext &Context;
11201
11202public:
11204 : Record(Record), Context(Record.getContext()) {}
11205#define GEN_CLANG_CLAUSE_CLASS
11206#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11207#include "llvm/Frontend/OpenMP/OMP.inc"
11211};
11212
11213} // end namespace clang
11214
11218
11220 OMPClause *C = nullptr;
11221 switch (llvm::omp::Clause(Record.readInt())) {
11222 case llvm::omp::OMPC_if:
11223 C = new (Context) OMPIfClause();
11224 break;
11225 case llvm::omp::OMPC_final:
11226 C = new (Context) OMPFinalClause();
11227 break;
11228 case llvm::omp::OMPC_num_threads:
11229 C = new (Context) OMPNumThreadsClause();
11230 break;
11231 case llvm::omp::OMPC_safelen:
11232 C = new (Context) OMPSafelenClause();
11233 break;
11234 case llvm::omp::OMPC_simdlen:
11235 C = new (Context) OMPSimdlenClause();
11236 break;
11237 case llvm::omp::OMPC_sizes: {
11238 unsigned NumSizes = Record.readInt();
11239 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11240 break;
11241 }
11242 case llvm::omp::OMPC_permutation: {
11243 unsigned NumLoops = Record.readInt();
11244 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11245 break;
11246 }
11247 case llvm::omp::OMPC_full:
11248 C = OMPFullClause::CreateEmpty(Context);
11249 break;
11250 case llvm::omp::OMPC_partial:
11252 break;
11253 case llvm::omp::OMPC_looprange:
11255 break;
11256 case llvm::omp::OMPC_allocator:
11257 C = new (Context) OMPAllocatorClause();
11258 break;
11259 case llvm::omp::OMPC_collapse:
11260 C = new (Context) OMPCollapseClause();
11261 break;
11262 case llvm::omp::OMPC_default:
11263 C = new (Context) OMPDefaultClause();
11264 break;
11265 case llvm::omp::OMPC_proc_bind:
11266 C = new (Context) OMPProcBindClause();
11267 break;
11268 case llvm::omp::OMPC_schedule:
11269 C = new (Context) OMPScheduleClause();
11270 break;
11271 case llvm::omp::OMPC_ordered:
11272 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11273 break;
11274 case llvm::omp::OMPC_nowait:
11275 C = new (Context) OMPNowaitClause();
11276 break;
11277 case llvm::omp::OMPC_untied:
11278 C = new (Context) OMPUntiedClause();
11279 break;
11280 case llvm::omp::OMPC_mergeable:
11281 C = new (Context) OMPMergeableClause();
11282 break;
11283 case llvm::omp::OMPC_threadset:
11284 C = new (Context) OMPThreadsetClause();
11285 break;
11286 case llvm::omp::OMPC_read:
11287 C = new (Context) OMPReadClause();
11288 break;
11289 case llvm::omp::OMPC_write:
11290 C = new (Context) OMPWriteClause();
11291 break;
11292 case llvm::omp::OMPC_update:
11293 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11294 break;
11295 case llvm::omp::OMPC_capture:
11296 C = new (Context) OMPCaptureClause();
11297 break;
11298 case llvm::omp::OMPC_compare:
11299 C = new (Context) OMPCompareClause();
11300 break;
11301 case llvm::omp::OMPC_fail:
11302 C = new (Context) OMPFailClause();
11303 break;
11304 case llvm::omp::OMPC_seq_cst:
11305 C = new (Context) OMPSeqCstClause();
11306 break;
11307 case llvm::omp::OMPC_acq_rel:
11308 C = new (Context) OMPAcqRelClause();
11309 break;
11310 case llvm::omp::OMPC_absent: {
11311 unsigned NumKinds = Record.readInt();
11312 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11313 break;
11314 }
11315 case llvm::omp::OMPC_holds:
11316 C = new (Context) OMPHoldsClause();
11317 break;
11318 case llvm::omp::OMPC_contains: {
11319 unsigned NumKinds = Record.readInt();
11320 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11321 break;
11322 }
11323 case llvm::omp::OMPC_no_openmp:
11324 C = new (Context) OMPNoOpenMPClause();
11325 break;
11326 case llvm::omp::OMPC_no_openmp_routines:
11327 C = new (Context) OMPNoOpenMPRoutinesClause();
11328 break;
11329 case llvm::omp::OMPC_no_openmp_constructs:
11330 C = new (Context) OMPNoOpenMPConstructsClause();
11331 break;
11332 case llvm::omp::OMPC_no_parallelism:
11333 C = new (Context) OMPNoParallelismClause();
11334 break;
11335 case llvm::omp::OMPC_acquire:
11336 C = new (Context) OMPAcquireClause();
11337 break;
11338 case llvm::omp::OMPC_release:
11339 C = new (Context) OMPReleaseClause();
11340 break;
11341 case llvm::omp::OMPC_relaxed:
11342 C = new (Context) OMPRelaxedClause();
11343 break;
11344 case llvm::omp::OMPC_weak:
11345 C = new (Context) OMPWeakClause();
11346 break;
11347 case llvm::omp::OMPC_threads:
11348 C = new (Context) OMPThreadsClause();
11349 break;
11350 case llvm::omp::OMPC_simd:
11351 C = new (Context) OMPSIMDClause();
11352 break;
11353 case llvm::omp::OMPC_nogroup:
11354 C = new (Context) OMPNogroupClause();
11355 break;
11356 case llvm::omp::OMPC_unified_address:
11357 C = new (Context) OMPUnifiedAddressClause();
11358 break;
11359 case llvm::omp::OMPC_unified_shared_memory:
11360 C = new (Context) OMPUnifiedSharedMemoryClause();
11361 break;
11362 case llvm::omp::OMPC_reverse_offload:
11363 C = new (Context) OMPReverseOffloadClause();
11364 break;
11365 case llvm::omp::OMPC_dynamic_allocators:
11366 C = new (Context) OMPDynamicAllocatorsClause();
11367 break;
11368 case llvm::omp::OMPC_atomic_default_mem_order:
11369 C = new (Context) OMPAtomicDefaultMemOrderClause();
11370 break;
11371 case llvm::omp::OMPC_self_maps:
11372 C = new (Context) OMPSelfMapsClause();
11373 break;
11374 case llvm::omp::OMPC_at:
11375 C = new (Context) OMPAtClause();
11376 break;
11377 case llvm::omp::OMPC_severity:
11378 C = new (Context) OMPSeverityClause();
11379 break;
11380 case llvm::omp::OMPC_message:
11381 C = new (Context) OMPMessageClause();
11382 break;
11383 case llvm::omp::OMPC_private:
11384 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11385 break;
11386 case llvm::omp::OMPC_firstprivate:
11387 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11388 break;
11389 case llvm::omp::OMPC_lastprivate:
11390 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11391 break;
11392 case llvm::omp::OMPC_shared:
11393 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11394 break;
11395 case llvm::omp::OMPC_reduction: {
11396 unsigned N = Record.readInt();
11397 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11398 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11399 break;
11400 }
11401 case llvm::omp::OMPC_task_reduction:
11402 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11403 break;
11404 case llvm::omp::OMPC_in_reduction:
11405 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11406 break;
11407 case llvm::omp::OMPC_linear:
11408 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11409 break;
11410 case llvm::omp::OMPC_aligned:
11411 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11412 break;
11413 case llvm::omp::OMPC_copyin:
11414 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11415 break;
11416 case llvm::omp::OMPC_copyprivate:
11417 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11418 break;
11419 case llvm::omp::OMPC_flush:
11420 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11421 break;
11422 case llvm::omp::OMPC_depobj:
11424 break;
11425 case llvm::omp::OMPC_depend: {
11426 unsigned NumVars = Record.readInt();
11427 unsigned NumLoops = Record.readInt();
11428 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11429 break;
11430 }
11431 case llvm::omp::OMPC_device:
11432 C = new (Context) OMPDeviceClause();
11433 break;
11434 case llvm::omp::OMPC_map: {
11436 Sizes.NumVars = Record.readInt();
11437 Sizes.NumUniqueDeclarations = Record.readInt();
11438 Sizes.NumComponentLists = Record.readInt();
11439 Sizes.NumComponents = Record.readInt();
11440 C = OMPMapClause::CreateEmpty(Context, Sizes);
11441 break;
11442 }
11443 case llvm::omp::OMPC_num_teams:
11444 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11445 break;
11446 case llvm::omp::OMPC_thread_limit:
11447 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11448 break;
11449 case llvm::omp::OMPC_priority:
11450 C = new (Context) OMPPriorityClause();
11451 break;
11452 case llvm::omp::OMPC_grainsize:
11453 C = new (Context) OMPGrainsizeClause();
11454 break;
11455 case llvm::omp::OMPC_num_tasks:
11456 C = new (Context) OMPNumTasksClause();
11457 break;
11458 case llvm::omp::OMPC_hint:
11459 C = new (Context) OMPHintClause();
11460 break;
11461 case llvm::omp::OMPC_dist_schedule:
11462 C = new (Context) OMPDistScheduleClause();
11463 break;
11464 case llvm::omp::OMPC_defaultmap:
11465 C = new (Context) OMPDefaultmapClause();
11466 break;
11467 case llvm::omp::OMPC_to: {
11469 Sizes.NumVars = Record.readInt();
11470 Sizes.NumUniqueDeclarations = Record.readInt();
11471 Sizes.NumComponentLists = Record.readInt();
11472 Sizes.NumComponents = Record.readInt();
11473 C = OMPToClause::CreateEmpty(Context, Sizes);
11474 break;
11475 }
11476 case llvm::omp::OMPC_from: {
11478 Sizes.NumVars = Record.readInt();
11479 Sizes.NumUniqueDeclarations = Record.readInt();
11480 Sizes.NumComponentLists = Record.readInt();
11481 Sizes.NumComponents = Record.readInt();
11482 C = OMPFromClause::CreateEmpty(Context, Sizes);
11483 break;
11484 }
11485 case llvm::omp::OMPC_use_device_ptr: {
11487 Sizes.NumVars = Record.readInt();
11488 Sizes.NumUniqueDeclarations = Record.readInt();
11489 Sizes.NumComponentLists = Record.readInt();
11490 Sizes.NumComponents = Record.readInt();
11491 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11492 break;
11493 }
11494 case llvm::omp::OMPC_use_device_addr: {
11496 Sizes.NumVars = Record.readInt();
11497 Sizes.NumUniqueDeclarations = Record.readInt();
11498 Sizes.NumComponentLists = Record.readInt();
11499 Sizes.NumComponents = Record.readInt();
11500 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11501 break;
11502 }
11503 case llvm::omp::OMPC_is_device_ptr: {
11505 Sizes.NumVars = Record.readInt();
11506 Sizes.NumUniqueDeclarations = Record.readInt();
11507 Sizes.NumComponentLists = Record.readInt();
11508 Sizes.NumComponents = Record.readInt();
11509 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11510 break;
11511 }
11512 case llvm::omp::OMPC_has_device_addr: {
11514 Sizes.NumVars = Record.readInt();
11515 Sizes.NumUniqueDeclarations = Record.readInt();
11516 Sizes.NumComponentLists = Record.readInt();
11517 Sizes.NumComponents = Record.readInt();
11518 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11519 break;
11520 }
11521 case llvm::omp::OMPC_allocate:
11522 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11523 break;
11524 case llvm::omp::OMPC_nontemporal:
11525 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11526 break;
11527 case llvm::omp::OMPC_inclusive:
11528 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11529 break;
11530 case llvm::omp::OMPC_exclusive:
11531 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11532 break;
11533 case llvm::omp::OMPC_order:
11534 C = new (Context) OMPOrderClause();
11535 break;
11536 case llvm::omp::OMPC_init:
11537 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11538 break;
11539 case llvm::omp::OMPC_use:
11540 C = new (Context) OMPUseClause();
11541 break;
11542 case llvm::omp::OMPC_destroy:
11543 C = new (Context) OMPDestroyClause();
11544 break;
11545 case llvm::omp::OMPC_novariants:
11546 C = new (Context) OMPNovariantsClause();
11547 break;
11548 case llvm::omp::OMPC_nocontext:
11549 C = new (Context) OMPNocontextClause();
11550 break;
11551 case llvm::omp::OMPC_detach:
11552 C = new (Context) OMPDetachClause();
11553 break;
11554 case llvm::omp::OMPC_uses_allocators:
11555 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11556 break;
11557 case llvm::omp::OMPC_affinity:
11558 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11559 break;
11560 case llvm::omp::OMPC_filter:
11561 C = new (Context) OMPFilterClause();
11562 break;
11563 case llvm::omp::OMPC_bind:
11564 C = OMPBindClause::CreateEmpty(Context);
11565 break;
11566 case llvm::omp::OMPC_align:
11567 C = new (Context) OMPAlignClause();
11568 break;
11569 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11570 C = new (Context) OMPXDynCGroupMemClause();
11571 break;
11572 case llvm::omp::OMPC_dyn_groupprivate:
11573 C = new (Context) OMPDynGroupprivateClause();
11574 break;
11575 case llvm::omp::OMPC_doacross: {
11576 unsigned NumVars = Record.readInt();
11577 unsigned NumLoops = Record.readInt();
11578 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11579 break;
11580 }
11581 case llvm::omp::OMPC_ompx_attribute:
11582 C = new (Context) OMPXAttributeClause();
11583 break;
11584 case llvm::omp::OMPC_ompx_bare:
11585 C = new (Context) OMPXBareClause();
11586 break;
11587#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11588 case llvm::omp::Enum: \
11589 break;
11590#include "llvm/Frontend/OpenMP/OMPKinds.def"
11591 default:
11592 break;
11593 }
11594 assert(C && "Unknown OMPClause type");
11595
11596 Visit(C);
11597 C->setLocStart(Record.readSourceLocation());
11598 C->setLocEnd(Record.readSourceLocation());
11599
11600 return C;
11601}
11602
11604 C->setPreInitStmt(Record.readSubStmt(),
11605 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11606}
11607
11610 C->setPostUpdateExpr(Record.readSubExpr());
11611}
11612
11613void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11615 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11616 C->setNameModifierLoc(Record.readSourceLocation());
11617 C->setColonLoc(Record.readSourceLocation());
11618 C->setCondition(Record.readSubExpr());
11619 C->setLParenLoc(Record.readSourceLocation());
11620}
11621
11622void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11624 C->setCondition(Record.readSubExpr());
11625 C->setLParenLoc(Record.readSourceLocation());
11626}
11627
11628void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11630 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11631 C->setNumThreads(Record.readSubExpr());
11632 C->setModifierLoc(Record.readSourceLocation());
11633 C->setLParenLoc(Record.readSourceLocation());
11634}
11635
11636void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11637 C->setSafelen(Record.readSubExpr());
11638 C->setLParenLoc(Record.readSourceLocation());
11639}
11640
11641void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11642 C->setSimdlen(Record.readSubExpr());
11643 C->setLParenLoc(Record.readSourceLocation());
11644}
11645
11646void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11647 for (Expr *&E : C->getSizesRefs())
11648 E = Record.readSubExpr();
11649 C->setLParenLoc(Record.readSourceLocation());
11650}
11651
11652void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11653 for (Expr *&E : C->getArgsRefs())
11654 E = Record.readSubExpr();
11655 C->setLParenLoc(Record.readSourceLocation());
11656}
11657
11658void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11659
11660void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11661 C->setFactor(Record.readSubExpr());
11662 C->setLParenLoc(Record.readSourceLocation());
11663}
11664
11665void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11666 C->setFirst(Record.readSubExpr());
11667 C->setCount(Record.readSubExpr());
11668 C->setLParenLoc(Record.readSourceLocation());
11669 C->setFirstLoc(Record.readSourceLocation());
11670 C->setCountLoc(Record.readSourceLocation());
11671}
11672
11673void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11674 C->setAllocator(Record.readExpr());
11675 C->setLParenLoc(Record.readSourceLocation());
11676}
11677
11678void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11679 C->setNumForLoops(Record.readSubExpr());
11680 C->setLParenLoc(Record.readSourceLocation());
11681}
11682
11683void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11684 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11685 C->setLParenLoc(Record.readSourceLocation());
11686 C->setDefaultKindKwLoc(Record.readSourceLocation());
11687 C->setDefaultVariableCategory(
11688 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11689 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11690}
11691
11692// Read the parameter of threadset clause. This will have been saved when
11693// OMPClauseWriter is called.
11694void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11695 C->setLParenLoc(Record.readSourceLocation());
11696 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11697 C->setThreadsetKindLoc(ThreadsetKindLoc);
11698 OpenMPThreadsetKind TKind =
11699 static_cast<OpenMPThreadsetKind>(Record.readInt());
11700 C->setThreadsetKind(TKind);
11701}
11702
11703void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11704 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11705 C->setLParenLoc(Record.readSourceLocation());
11706 C->setProcBindKindKwLoc(Record.readSourceLocation());
11707}
11708
11709void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11711 C->setScheduleKind(
11712 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11713 C->setFirstScheduleModifier(
11714 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11715 C->setSecondScheduleModifier(
11716 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11717 C->setChunkSize(Record.readSubExpr());
11718 C->setLParenLoc(Record.readSourceLocation());
11719 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11720 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11721 C->setScheduleKindLoc(Record.readSourceLocation());
11722 C->setCommaLoc(Record.readSourceLocation());
11723}
11724
11725void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11726 C->setNumForLoops(Record.readSubExpr());
11727 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11728 C->setLoopNumIterations(I, Record.readSubExpr());
11729 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11730 C->setLoopCounter(I, Record.readSubExpr());
11731 C->setLParenLoc(Record.readSourceLocation());
11732}
11733
11734void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11735 C->setEventHandler(Record.readSubExpr());
11736 C->setLParenLoc(Record.readSourceLocation());
11737}
11738
11739void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
11740 C->setCondition(Record.readSubExpr());
11741 C->setLParenLoc(Record.readSourceLocation());
11742}
11743
11744void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11745
11746void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11747
11748void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11749
11750void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11751
11752void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11753 if (C->isExtended()) {
11754 C->setLParenLoc(Record.readSourceLocation());
11755 C->setArgumentLoc(Record.readSourceLocation());
11756 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11757 }
11758}
11759
11760void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11761
11762void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11763
11764// Read the parameter of fail clause. This will have been saved when
11765// OMPClauseWriter is called.
11766void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11767 C->setLParenLoc(Record.readSourceLocation());
11768 SourceLocation FailParameterLoc = Record.readSourceLocation();
11769 C->setFailParameterLoc(FailParameterLoc);
11770 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11771 C->setFailParameter(CKind);
11772}
11773
11774void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11775 unsigned Count = C->getDirectiveKinds().size();
11776 C->setLParenLoc(Record.readSourceLocation());
11777 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11778 DKVec.reserve(Count);
11779 for (unsigned I = 0; I < Count; I++) {
11780 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11781 }
11782 C->setDirectiveKinds(DKVec);
11783}
11784
11785void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11786 C->setExpr(Record.readExpr());
11787 C->setLParenLoc(Record.readSourceLocation());
11788}
11789
11790void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11791 unsigned Count = C->getDirectiveKinds().size();
11792 C->setLParenLoc(Record.readSourceLocation());
11793 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11794 DKVec.reserve(Count);
11795 for (unsigned I = 0; I < Count; I++) {
11796 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11797 }
11798 C->setDirectiveKinds(DKVec);
11799}
11800
11801void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11802
11803void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11805
11806void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
11808
11809void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11810
11811void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11812
11813void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11814
11815void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11816
11817void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11818
11819void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11820
11821void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11822
11823void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11824
11825void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11826
11827void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11828
11829void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11830 unsigned NumVars = C->varlist_size();
11831 SmallVector<Expr *, 16> Vars;
11832 Vars.reserve(NumVars);
11833 for (unsigned I = 0; I != NumVars; ++I)
11834 Vars.push_back(Record.readSubExpr());
11835 C->setVarRefs(Vars);
11836 C->setIsTarget(Record.readBool());
11837 C->setIsTargetSync(Record.readBool());
11838 C->setLParenLoc(Record.readSourceLocation());
11839 C->setVarLoc(Record.readSourceLocation());
11840}
11841
11842void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11843 C->setInteropVar(Record.readSubExpr());
11844 C->setLParenLoc(Record.readSourceLocation());
11845 C->setVarLoc(Record.readSourceLocation());
11846}
11847
11848void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11849 C->setInteropVar(Record.readSubExpr());
11850 C->setLParenLoc(Record.readSourceLocation());
11851 C->setVarLoc(Record.readSourceLocation());
11852}
11853
11854void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11856 C->setCondition(Record.readSubExpr());
11857 C->setLParenLoc(Record.readSourceLocation());
11858}
11859
11860void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11862 C->setCondition(Record.readSubExpr());
11863 C->setLParenLoc(Record.readSourceLocation());
11864}
11865
11866void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11867
11868void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11870
11871void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11872
11873void
11874OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11875}
11876
11877void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11879 C->setAtomicDefaultMemOrderKind(
11880 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11881 C->setLParenLoc(Record.readSourceLocation());
11882 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11883}
11884
11885void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
11886
11887void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
11888 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
11889 C->setLParenLoc(Record.readSourceLocation());
11890 C->setAtKindKwLoc(Record.readSourceLocation());
11891}
11892
11893void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
11894 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
11895 C->setLParenLoc(Record.readSourceLocation());
11896 C->setSeverityKindKwLoc(Record.readSourceLocation());
11897}
11898
11899void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
11901 C->setMessageString(Record.readSubExpr());
11902 C->setLParenLoc(Record.readSourceLocation());
11903}
11904
11905void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11906 C->setLParenLoc(Record.readSourceLocation());
11907 unsigned NumVars = C->varlist_size();
11908 SmallVector<Expr *, 16> Vars;
11909 Vars.reserve(NumVars);
11910 for (unsigned i = 0; i != NumVars; ++i)
11911 Vars.push_back(Record.readSubExpr());
11912 C->setVarRefs(Vars);
11913 Vars.clear();
11914 for (unsigned i = 0; i != NumVars; ++i)
11915 Vars.push_back(Record.readSubExpr());
11916 C->setPrivateCopies(Vars);
11917}
11918
11919void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11921 C->setLParenLoc(Record.readSourceLocation());
11922 unsigned NumVars = C->varlist_size();
11923 SmallVector<Expr *, 16> Vars;
11924 Vars.reserve(NumVars);
11925 for (unsigned i = 0; i != NumVars; ++i)
11926 Vars.push_back(Record.readSubExpr());
11927 C->setVarRefs(Vars);
11928 Vars.clear();
11929 for (unsigned i = 0; i != NumVars; ++i)
11930 Vars.push_back(Record.readSubExpr());
11931 C->setPrivateCopies(Vars);
11932 Vars.clear();
11933 for (unsigned i = 0; i != NumVars; ++i)
11934 Vars.push_back(Record.readSubExpr());
11935 C->setInits(Vars);
11936}
11937
11938void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11940 C->setLParenLoc(Record.readSourceLocation());
11941 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11942 C->setKindLoc(Record.readSourceLocation());
11943 C->setColonLoc(Record.readSourceLocation());
11944 unsigned NumVars = C->varlist_size();
11945 SmallVector<Expr *, 16> Vars;
11946 Vars.reserve(NumVars);
11947 for (unsigned i = 0; i != NumVars; ++i)
11948 Vars.push_back(Record.readSubExpr());
11949 C->setVarRefs(Vars);
11950 Vars.clear();
11951 for (unsigned i = 0; i != NumVars; ++i)
11952 Vars.push_back(Record.readSubExpr());
11953 C->setPrivateCopies(Vars);
11954 Vars.clear();
11955 for (unsigned i = 0; i != NumVars; ++i)
11956 Vars.push_back(Record.readSubExpr());
11957 C->setSourceExprs(Vars);
11958 Vars.clear();
11959 for (unsigned i = 0; i != NumVars; ++i)
11960 Vars.push_back(Record.readSubExpr());
11961 C->setDestinationExprs(Vars);
11962 Vars.clear();
11963 for (unsigned i = 0; i != NumVars; ++i)
11964 Vars.push_back(Record.readSubExpr());
11965 C->setAssignmentOps(Vars);
11966}
11967
11968void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11969 C->setLParenLoc(Record.readSourceLocation());
11970 unsigned NumVars = C->varlist_size();
11971 SmallVector<Expr *, 16> Vars;
11972 Vars.reserve(NumVars);
11973 for (unsigned i = 0; i != NumVars; ++i)
11974 Vars.push_back(Record.readSubExpr());
11975 C->setVarRefs(Vars);
11976}
11977
11978void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11980 C->setLParenLoc(Record.readSourceLocation());
11981 C->setModifierLoc(Record.readSourceLocation());
11982 C->setColonLoc(Record.readSourceLocation());
11983 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11984 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11985 C->setQualifierLoc(NNSL);
11986 C->setNameInfo(DNI);
11987
11988 unsigned NumVars = C->varlist_size();
11989 SmallVector<Expr *, 16> Vars;
11990 Vars.reserve(NumVars);
11991 for (unsigned i = 0; i != NumVars; ++i)
11992 Vars.push_back(Record.readSubExpr());
11993 C->setVarRefs(Vars);
11994 Vars.clear();
11995 for (unsigned i = 0; i != NumVars; ++i)
11996 Vars.push_back(Record.readSubExpr());
11997 C->setPrivates(Vars);
11998 Vars.clear();
11999 for (unsigned i = 0; i != NumVars; ++i)
12000 Vars.push_back(Record.readSubExpr());
12001 C->setLHSExprs(Vars);
12002 Vars.clear();
12003 for (unsigned i = 0; i != NumVars; ++i)
12004 Vars.push_back(Record.readSubExpr());
12005 C->setRHSExprs(Vars);
12006 Vars.clear();
12007 for (unsigned i = 0; i != NumVars; ++i)
12008 Vars.push_back(Record.readSubExpr());
12009 C->setReductionOps(Vars);
12010 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12011 Vars.clear();
12012 for (unsigned i = 0; i != NumVars; ++i)
12013 Vars.push_back(Record.readSubExpr());
12014 C->setInscanCopyOps(Vars);
12015 Vars.clear();
12016 for (unsigned i = 0; i != NumVars; ++i)
12017 Vars.push_back(Record.readSubExpr());
12018 C->setInscanCopyArrayTemps(Vars);
12019 Vars.clear();
12020 for (unsigned i = 0; i != NumVars; ++i)
12021 Vars.push_back(Record.readSubExpr());
12022 C->setInscanCopyArrayElems(Vars);
12023 }
12024 unsigned NumFlags = Record.readInt();
12025 SmallVector<bool, 16> Flags;
12026 Flags.reserve(NumFlags);
12027 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12028 Flags.push_back(Record.readInt());
12029 C->setPrivateVariableReductionFlags(Flags);
12030}
12031
12032void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12034 C->setLParenLoc(Record.readSourceLocation());
12035 C->setColonLoc(Record.readSourceLocation());
12036 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12037 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12038 C->setQualifierLoc(NNSL);
12039 C->setNameInfo(DNI);
12040
12041 unsigned NumVars = C->varlist_size();
12042 SmallVector<Expr *, 16> Vars;
12043 Vars.reserve(NumVars);
12044 for (unsigned I = 0; I != NumVars; ++I)
12045 Vars.push_back(Record.readSubExpr());
12046 C->setVarRefs(Vars);
12047 Vars.clear();
12048 for (unsigned I = 0; I != NumVars; ++I)
12049 Vars.push_back(Record.readSubExpr());
12050 C->setPrivates(Vars);
12051 Vars.clear();
12052 for (unsigned I = 0; I != NumVars; ++I)
12053 Vars.push_back(Record.readSubExpr());
12054 C->setLHSExprs(Vars);
12055 Vars.clear();
12056 for (unsigned I = 0; I != NumVars; ++I)
12057 Vars.push_back(Record.readSubExpr());
12058 C->setRHSExprs(Vars);
12059 Vars.clear();
12060 for (unsigned I = 0; I != NumVars; ++I)
12061 Vars.push_back(Record.readSubExpr());
12062 C->setReductionOps(Vars);
12063}
12064
12065void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12067 C->setLParenLoc(Record.readSourceLocation());
12068 C->setColonLoc(Record.readSourceLocation());
12069 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12070 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12071 C->setQualifierLoc(NNSL);
12072 C->setNameInfo(DNI);
12073
12074 unsigned NumVars = C->varlist_size();
12075 SmallVector<Expr *, 16> Vars;
12076 Vars.reserve(NumVars);
12077 for (unsigned I = 0; I != NumVars; ++I)
12078 Vars.push_back(Record.readSubExpr());
12079 C->setVarRefs(Vars);
12080 Vars.clear();
12081 for (unsigned I = 0; I != NumVars; ++I)
12082 Vars.push_back(Record.readSubExpr());
12083 C->setPrivates(Vars);
12084 Vars.clear();
12085 for (unsigned I = 0; I != NumVars; ++I)
12086 Vars.push_back(Record.readSubExpr());
12087 C->setLHSExprs(Vars);
12088 Vars.clear();
12089 for (unsigned I = 0; I != NumVars; ++I)
12090 Vars.push_back(Record.readSubExpr());
12091 C->setRHSExprs(Vars);
12092 Vars.clear();
12093 for (unsigned I = 0; I != NumVars; ++I)
12094 Vars.push_back(Record.readSubExpr());
12095 C->setReductionOps(Vars);
12096 Vars.clear();
12097 for (unsigned I = 0; I != NumVars; ++I)
12098 Vars.push_back(Record.readSubExpr());
12099 C->setTaskgroupDescriptors(Vars);
12100}
12101
12102void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12104 C->setLParenLoc(Record.readSourceLocation());
12105 C->setColonLoc(Record.readSourceLocation());
12106 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12107 C->setModifierLoc(Record.readSourceLocation());
12108 unsigned NumVars = C->varlist_size();
12109 SmallVector<Expr *, 16> Vars;
12110 Vars.reserve(NumVars);
12111 for (unsigned i = 0; i != NumVars; ++i)
12112 Vars.push_back(Record.readSubExpr());
12113 C->setVarRefs(Vars);
12114 Vars.clear();
12115 for (unsigned i = 0; i != NumVars; ++i)
12116 Vars.push_back(Record.readSubExpr());
12117 C->setPrivates(Vars);
12118 Vars.clear();
12119 for (unsigned i = 0; i != NumVars; ++i)
12120 Vars.push_back(Record.readSubExpr());
12121 C->setInits(Vars);
12122 Vars.clear();
12123 for (unsigned i = 0; i != NumVars; ++i)
12124 Vars.push_back(Record.readSubExpr());
12125 C->setUpdates(Vars);
12126 Vars.clear();
12127 for (unsigned i = 0; i != NumVars; ++i)
12128 Vars.push_back(Record.readSubExpr());
12129 C->setFinals(Vars);
12130 C->setStep(Record.readSubExpr());
12131 C->setCalcStep(Record.readSubExpr());
12132 Vars.clear();
12133 for (unsigned I = 0; I != NumVars + 1; ++I)
12134 Vars.push_back(Record.readSubExpr());
12135 C->setUsedExprs(Vars);
12136}
12137
12138void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12139 C->setLParenLoc(Record.readSourceLocation());
12140 C->setColonLoc(Record.readSourceLocation());
12141 unsigned NumVars = C->varlist_size();
12142 SmallVector<Expr *, 16> Vars;
12143 Vars.reserve(NumVars);
12144 for (unsigned i = 0; i != NumVars; ++i)
12145 Vars.push_back(Record.readSubExpr());
12146 C->setVarRefs(Vars);
12147 C->setAlignment(Record.readSubExpr());
12148}
12149
12150void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12151 C->setLParenLoc(Record.readSourceLocation());
12152 unsigned NumVars = C->varlist_size();
12153 SmallVector<Expr *, 16> Exprs;
12154 Exprs.reserve(NumVars);
12155 for (unsigned i = 0; i != NumVars; ++i)
12156 Exprs.push_back(Record.readSubExpr());
12157 C->setVarRefs(Exprs);
12158 Exprs.clear();
12159 for (unsigned i = 0; i != NumVars; ++i)
12160 Exprs.push_back(Record.readSubExpr());
12161 C->setSourceExprs(Exprs);
12162 Exprs.clear();
12163 for (unsigned i = 0; i != NumVars; ++i)
12164 Exprs.push_back(Record.readSubExpr());
12165 C->setDestinationExprs(Exprs);
12166 Exprs.clear();
12167 for (unsigned i = 0; i != NumVars; ++i)
12168 Exprs.push_back(Record.readSubExpr());
12169 C->setAssignmentOps(Exprs);
12170}
12171
12172void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12173 C->setLParenLoc(Record.readSourceLocation());
12174 unsigned NumVars = C->varlist_size();
12175 SmallVector<Expr *, 16> Exprs;
12176 Exprs.reserve(NumVars);
12177 for (unsigned i = 0; i != NumVars; ++i)
12178 Exprs.push_back(Record.readSubExpr());
12179 C->setVarRefs(Exprs);
12180 Exprs.clear();
12181 for (unsigned i = 0; i != NumVars; ++i)
12182 Exprs.push_back(Record.readSubExpr());
12183 C->setSourceExprs(Exprs);
12184 Exprs.clear();
12185 for (unsigned i = 0; i != NumVars; ++i)
12186 Exprs.push_back(Record.readSubExpr());
12187 C->setDestinationExprs(Exprs);
12188 Exprs.clear();
12189 for (unsigned i = 0; i != NumVars; ++i)
12190 Exprs.push_back(Record.readSubExpr());
12191 C->setAssignmentOps(Exprs);
12192}
12193
12194void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12195 C->setLParenLoc(Record.readSourceLocation());
12196 unsigned NumVars = C->varlist_size();
12197 SmallVector<Expr *, 16> Vars;
12198 Vars.reserve(NumVars);
12199 for (unsigned i = 0; i != NumVars; ++i)
12200 Vars.push_back(Record.readSubExpr());
12201 C->setVarRefs(Vars);
12202}
12203
12204void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12205 C->setDepobj(Record.readSubExpr());
12206 C->setLParenLoc(Record.readSourceLocation());
12207}
12208
12209void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12210 C->setLParenLoc(Record.readSourceLocation());
12211 C->setModifier(Record.readSubExpr());
12212 C->setDependencyKind(
12213 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12214 C->setDependencyLoc(Record.readSourceLocation());
12215 C->setColonLoc(Record.readSourceLocation());
12216 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12217 unsigned NumVars = C->varlist_size();
12218 SmallVector<Expr *, 16> Vars;
12219 Vars.reserve(NumVars);
12220 for (unsigned I = 0; I != NumVars; ++I)
12221 Vars.push_back(Record.readSubExpr());
12222 C->setVarRefs(Vars);
12223 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12224 C->setLoopData(I, Record.readSubExpr());
12225}
12226
12227void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12229 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12230 C->setDevice(Record.readSubExpr());
12231 C->setModifierLoc(Record.readSourceLocation());
12232 C->setLParenLoc(Record.readSourceLocation());
12233}
12234
12235void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12236 C->setLParenLoc(Record.readSourceLocation());
12237 bool HasIteratorModifier = false;
12238 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12239 C->setMapTypeModifier(
12240 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12241 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12242 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12243 HasIteratorModifier = true;
12244 }
12245 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12246 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12247 C->setMapType(
12248 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12249 C->setMapLoc(Record.readSourceLocation());
12250 C->setColonLoc(Record.readSourceLocation());
12251 auto NumVars = C->varlist_size();
12252 auto UniqueDecls = C->getUniqueDeclarationsNum();
12253 auto TotalLists = C->getTotalComponentListNum();
12254 auto TotalComponents = C->getTotalComponentsNum();
12255
12256 SmallVector<Expr *, 16> Vars;
12257 Vars.reserve(NumVars);
12258 for (unsigned i = 0; i != NumVars; ++i)
12259 Vars.push_back(Record.readExpr());
12260 C->setVarRefs(Vars);
12261
12262 SmallVector<Expr *, 16> UDMappers;
12263 UDMappers.reserve(NumVars);
12264 for (unsigned I = 0; I < NumVars; ++I)
12265 UDMappers.push_back(Record.readExpr());
12266 C->setUDMapperRefs(UDMappers);
12267
12268 if (HasIteratorModifier)
12269 C->setIteratorModifier(Record.readExpr());
12270
12271 SmallVector<ValueDecl *, 16> Decls;
12272 Decls.reserve(UniqueDecls);
12273 for (unsigned i = 0; i < UniqueDecls; ++i)
12274 Decls.push_back(Record.readDeclAs<ValueDecl>());
12275 C->setUniqueDecls(Decls);
12276
12277 SmallVector<unsigned, 16> ListsPerDecl;
12278 ListsPerDecl.reserve(UniqueDecls);
12279 for (unsigned i = 0; i < UniqueDecls; ++i)
12280 ListsPerDecl.push_back(Record.readInt());
12281 C->setDeclNumLists(ListsPerDecl);
12282
12283 SmallVector<unsigned, 32> ListSizes;
12284 ListSizes.reserve(TotalLists);
12285 for (unsigned i = 0; i < TotalLists; ++i)
12286 ListSizes.push_back(Record.readInt());
12287 C->setComponentListSizes(ListSizes);
12288
12289 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12290 Components.reserve(TotalComponents);
12291 for (unsigned i = 0; i < TotalComponents; ++i) {
12292 Expr *AssociatedExprPr = Record.readExpr();
12293 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12294 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12295 /*IsNonContiguous=*/false);
12296 }
12297 C->setComponents(Components, ListSizes);
12298}
12299
12300void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12301 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12302 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12303 C->setLParenLoc(Record.readSourceLocation());
12304 C->setColonLoc(Record.readSourceLocation());
12305 C->setAllocator(Record.readSubExpr());
12306 C->setAlignment(Record.readSubExpr());
12307 unsigned NumVars = C->varlist_size();
12308 SmallVector<Expr *, 16> Vars;
12309 Vars.reserve(NumVars);
12310 for (unsigned i = 0; i != NumVars; ++i)
12311 Vars.push_back(Record.readSubExpr());
12312 C->setVarRefs(Vars);
12313}
12314
12315void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12317 C->setLParenLoc(Record.readSourceLocation());
12318 unsigned NumVars = C->varlist_size();
12319 SmallVector<Expr *, 16> Vars;
12320 Vars.reserve(NumVars);
12321 for (unsigned I = 0; I != NumVars; ++I)
12322 Vars.push_back(Record.readSubExpr());
12323 C->setVarRefs(Vars);
12324}
12325
12326void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12328 C->setLParenLoc(Record.readSourceLocation());
12329 unsigned NumVars = C->varlist_size();
12330 SmallVector<Expr *, 16> Vars;
12331 Vars.reserve(NumVars);
12332 for (unsigned I = 0; I != NumVars; ++I)
12333 Vars.push_back(Record.readSubExpr());
12334 C->setVarRefs(Vars);
12335}
12336
12337void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12339 C->setPriority(Record.readSubExpr());
12340 C->setLParenLoc(Record.readSourceLocation());
12341}
12342
12343void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12345 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12346 C->setGrainsize(Record.readSubExpr());
12347 C->setModifierLoc(Record.readSourceLocation());
12348 C->setLParenLoc(Record.readSourceLocation());
12349}
12350
12351void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12353 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12354 C->setNumTasks(Record.readSubExpr());
12355 C->setModifierLoc(Record.readSourceLocation());
12356 C->setLParenLoc(Record.readSourceLocation());
12357}
12358
12359void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12360 C->setHint(Record.readSubExpr());
12361 C->setLParenLoc(Record.readSourceLocation());
12362}
12363
12364void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12366 C->setDistScheduleKind(
12367 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12368 C->setChunkSize(Record.readSubExpr());
12369 C->setLParenLoc(Record.readSourceLocation());
12370 C->setDistScheduleKindLoc(Record.readSourceLocation());
12371 C->setCommaLoc(Record.readSourceLocation());
12372}
12373
12374void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12375 C->setDefaultmapKind(
12376 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12377 C->setDefaultmapModifier(
12378 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12379 C->setLParenLoc(Record.readSourceLocation());
12380 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12381 C->setDefaultmapKindLoc(Record.readSourceLocation());
12382}
12383
12384void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12385 C->setLParenLoc(Record.readSourceLocation());
12386 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12387 C->setMotionModifier(
12388 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12389 C->setMotionModifierLoc(I, Record.readSourceLocation());
12390 }
12391 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12392 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12393 C->setColonLoc(Record.readSourceLocation());
12394 auto NumVars = C->varlist_size();
12395 auto UniqueDecls = C->getUniqueDeclarationsNum();
12396 auto TotalLists = C->getTotalComponentListNum();
12397 auto TotalComponents = C->getTotalComponentsNum();
12398
12399 SmallVector<Expr *, 16> Vars;
12400 Vars.reserve(NumVars);
12401 for (unsigned i = 0; i != NumVars; ++i)
12402 Vars.push_back(Record.readSubExpr());
12403 C->setVarRefs(Vars);
12404
12405 SmallVector<Expr *, 16> UDMappers;
12406 UDMappers.reserve(NumVars);
12407 for (unsigned I = 0; I < NumVars; ++I)
12408 UDMappers.push_back(Record.readSubExpr());
12409 C->setUDMapperRefs(UDMappers);
12410
12411 SmallVector<ValueDecl *, 16> Decls;
12412 Decls.reserve(UniqueDecls);
12413 for (unsigned i = 0; i < UniqueDecls; ++i)
12414 Decls.push_back(Record.readDeclAs<ValueDecl>());
12415 C->setUniqueDecls(Decls);
12416
12417 SmallVector<unsigned, 16> ListsPerDecl;
12418 ListsPerDecl.reserve(UniqueDecls);
12419 for (unsigned i = 0; i < UniqueDecls; ++i)
12420 ListsPerDecl.push_back(Record.readInt());
12421 C->setDeclNumLists(ListsPerDecl);
12422
12423 SmallVector<unsigned, 32> ListSizes;
12424 ListSizes.reserve(TotalLists);
12425 for (unsigned i = 0; i < TotalLists; ++i)
12426 ListSizes.push_back(Record.readInt());
12427 C->setComponentListSizes(ListSizes);
12428
12429 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12430 Components.reserve(TotalComponents);
12431 for (unsigned i = 0; i < TotalComponents; ++i) {
12432 Expr *AssociatedExprPr = Record.readSubExpr();
12433 bool IsNonContiguous = Record.readBool();
12434 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12435 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12436 }
12437 C->setComponents(Components, ListSizes);
12438}
12439
12440void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12441 C->setLParenLoc(Record.readSourceLocation());
12442 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12443 C->setMotionModifier(
12444 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12445 C->setMotionModifierLoc(I, Record.readSourceLocation());
12446 }
12447 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12448 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12449 C->setColonLoc(Record.readSourceLocation());
12450 auto NumVars = C->varlist_size();
12451 auto UniqueDecls = C->getUniqueDeclarationsNum();
12452 auto TotalLists = C->getTotalComponentListNum();
12453 auto TotalComponents = C->getTotalComponentsNum();
12454
12455 SmallVector<Expr *, 16> Vars;
12456 Vars.reserve(NumVars);
12457 for (unsigned i = 0; i != NumVars; ++i)
12458 Vars.push_back(Record.readSubExpr());
12459 C->setVarRefs(Vars);
12460
12461 SmallVector<Expr *, 16> UDMappers;
12462 UDMappers.reserve(NumVars);
12463 for (unsigned I = 0; I < NumVars; ++I)
12464 UDMappers.push_back(Record.readSubExpr());
12465 C->setUDMapperRefs(UDMappers);
12466
12467 SmallVector<ValueDecl *, 16> Decls;
12468 Decls.reserve(UniqueDecls);
12469 for (unsigned i = 0; i < UniqueDecls; ++i)
12470 Decls.push_back(Record.readDeclAs<ValueDecl>());
12471 C->setUniqueDecls(Decls);
12472
12473 SmallVector<unsigned, 16> ListsPerDecl;
12474 ListsPerDecl.reserve(UniqueDecls);
12475 for (unsigned i = 0; i < UniqueDecls; ++i)
12476 ListsPerDecl.push_back(Record.readInt());
12477 C->setDeclNumLists(ListsPerDecl);
12478
12479 SmallVector<unsigned, 32> ListSizes;
12480 ListSizes.reserve(TotalLists);
12481 for (unsigned i = 0; i < TotalLists; ++i)
12482 ListSizes.push_back(Record.readInt());
12483 C->setComponentListSizes(ListSizes);
12484
12485 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12486 Components.reserve(TotalComponents);
12487 for (unsigned i = 0; i < TotalComponents; ++i) {
12488 Expr *AssociatedExprPr = Record.readSubExpr();
12489 bool IsNonContiguous = Record.readBool();
12490 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12491 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12492 }
12493 C->setComponents(Components, ListSizes);
12494}
12495
12496void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12497 C->setLParenLoc(Record.readSourceLocation());
12498 auto NumVars = C->varlist_size();
12499 auto UniqueDecls = C->getUniqueDeclarationsNum();
12500 auto TotalLists = C->getTotalComponentListNum();
12501 auto TotalComponents = C->getTotalComponentsNum();
12502
12503 SmallVector<Expr *, 16> Vars;
12504 Vars.reserve(NumVars);
12505 for (unsigned i = 0; i != NumVars; ++i)
12506 Vars.push_back(Record.readSubExpr());
12507 C->setVarRefs(Vars);
12508 Vars.clear();
12509 for (unsigned i = 0; i != NumVars; ++i)
12510 Vars.push_back(Record.readSubExpr());
12511 C->setPrivateCopies(Vars);
12512 Vars.clear();
12513 for (unsigned i = 0; i != NumVars; ++i)
12514 Vars.push_back(Record.readSubExpr());
12515 C->setInits(Vars);
12516
12517 SmallVector<ValueDecl *, 16> Decls;
12518 Decls.reserve(UniqueDecls);
12519 for (unsigned i = 0; i < UniqueDecls; ++i)
12520 Decls.push_back(Record.readDeclAs<ValueDecl>());
12521 C->setUniqueDecls(Decls);
12522
12523 SmallVector<unsigned, 16> ListsPerDecl;
12524 ListsPerDecl.reserve(UniqueDecls);
12525 for (unsigned i = 0; i < UniqueDecls; ++i)
12526 ListsPerDecl.push_back(Record.readInt());
12527 C->setDeclNumLists(ListsPerDecl);
12528
12529 SmallVector<unsigned, 32> ListSizes;
12530 ListSizes.reserve(TotalLists);
12531 for (unsigned i = 0; i < TotalLists; ++i)
12532 ListSizes.push_back(Record.readInt());
12533 C->setComponentListSizes(ListSizes);
12534
12535 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12536 Components.reserve(TotalComponents);
12537 for (unsigned i = 0; i < TotalComponents; ++i) {
12538 auto *AssociatedExprPr = Record.readSubExpr();
12539 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12540 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12541 /*IsNonContiguous=*/false);
12542 }
12543 C->setComponents(Components, ListSizes);
12544}
12545
12546void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12547 C->setLParenLoc(Record.readSourceLocation());
12548 auto NumVars = C->varlist_size();
12549 auto UniqueDecls = C->getUniqueDeclarationsNum();
12550 auto TotalLists = C->getTotalComponentListNum();
12551 auto TotalComponents = C->getTotalComponentsNum();
12552
12553 SmallVector<Expr *, 16> Vars;
12554 Vars.reserve(NumVars);
12555 for (unsigned i = 0; i != NumVars; ++i)
12556 Vars.push_back(Record.readSubExpr());
12557 C->setVarRefs(Vars);
12558
12559 SmallVector<ValueDecl *, 16> Decls;
12560 Decls.reserve(UniqueDecls);
12561 for (unsigned i = 0; i < UniqueDecls; ++i)
12562 Decls.push_back(Record.readDeclAs<ValueDecl>());
12563 C->setUniqueDecls(Decls);
12564
12565 SmallVector<unsigned, 16> ListsPerDecl;
12566 ListsPerDecl.reserve(UniqueDecls);
12567 for (unsigned i = 0; i < UniqueDecls; ++i)
12568 ListsPerDecl.push_back(Record.readInt());
12569 C->setDeclNumLists(ListsPerDecl);
12570
12571 SmallVector<unsigned, 32> ListSizes;
12572 ListSizes.reserve(TotalLists);
12573 for (unsigned i = 0; i < TotalLists; ++i)
12574 ListSizes.push_back(Record.readInt());
12575 C->setComponentListSizes(ListSizes);
12576
12577 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12578 Components.reserve(TotalComponents);
12579 for (unsigned i = 0; i < TotalComponents; ++i) {
12580 Expr *AssociatedExpr = Record.readSubExpr();
12581 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12582 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12583 /*IsNonContiguous*/ false);
12584 }
12585 C->setComponents(Components, ListSizes);
12586}
12587
12588void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12589 C->setLParenLoc(Record.readSourceLocation());
12590 auto NumVars = C->varlist_size();
12591 auto UniqueDecls = C->getUniqueDeclarationsNum();
12592 auto TotalLists = C->getTotalComponentListNum();
12593 auto TotalComponents = C->getTotalComponentsNum();
12594
12595 SmallVector<Expr *, 16> Vars;
12596 Vars.reserve(NumVars);
12597 for (unsigned i = 0; i != NumVars; ++i)
12598 Vars.push_back(Record.readSubExpr());
12599 C->setVarRefs(Vars);
12600 Vars.clear();
12601
12602 SmallVector<ValueDecl *, 16> Decls;
12603 Decls.reserve(UniqueDecls);
12604 for (unsigned i = 0; i < UniqueDecls; ++i)
12605 Decls.push_back(Record.readDeclAs<ValueDecl>());
12606 C->setUniqueDecls(Decls);
12607
12608 SmallVector<unsigned, 16> ListsPerDecl;
12609 ListsPerDecl.reserve(UniqueDecls);
12610 for (unsigned i = 0; i < UniqueDecls; ++i)
12611 ListsPerDecl.push_back(Record.readInt());
12612 C->setDeclNumLists(ListsPerDecl);
12613
12614 SmallVector<unsigned, 32> ListSizes;
12615 ListSizes.reserve(TotalLists);
12616 for (unsigned i = 0; i < TotalLists; ++i)
12617 ListSizes.push_back(Record.readInt());
12618 C->setComponentListSizes(ListSizes);
12619
12620 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12621 Components.reserve(TotalComponents);
12622 for (unsigned i = 0; i < TotalComponents; ++i) {
12623 Expr *AssociatedExpr = Record.readSubExpr();
12624 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12625 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12626 /*IsNonContiguous=*/false);
12627 }
12628 C->setComponents(Components, ListSizes);
12629}
12630
12631void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12632 C->setLParenLoc(Record.readSourceLocation());
12633 auto NumVars = C->varlist_size();
12634 auto UniqueDecls = C->getUniqueDeclarationsNum();
12635 auto TotalLists = C->getTotalComponentListNum();
12636 auto TotalComponents = C->getTotalComponentsNum();
12637
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 Vars.clear();
12644
12645 SmallVector<ValueDecl *, 16> Decls;
12646 Decls.reserve(UniqueDecls);
12647 for (unsigned I = 0; I < UniqueDecls; ++I)
12648 Decls.push_back(Record.readDeclAs<ValueDecl>());
12649 C->setUniqueDecls(Decls);
12650
12651 SmallVector<unsigned, 16> ListsPerDecl;
12652 ListsPerDecl.reserve(UniqueDecls);
12653 for (unsigned I = 0; I < UniqueDecls; ++I)
12654 ListsPerDecl.push_back(Record.readInt());
12655 C->setDeclNumLists(ListsPerDecl);
12656
12657 SmallVector<unsigned, 32> ListSizes;
12658 ListSizes.reserve(TotalLists);
12659 for (unsigned i = 0; i < TotalLists; ++i)
12660 ListSizes.push_back(Record.readInt());
12661 C->setComponentListSizes(ListSizes);
12662
12663 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12664 Components.reserve(TotalComponents);
12665 for (unsigned I = 0; I < TotalComponents; ++I) {
12666 Expr *AssociatedExpr = Record.readSubExpr();
12667 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12668 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12669 /*IsNonContiguous=*/false);
12670 }
12671 C->setComponents(Components, ListSizes);
12672}
12673
12674void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12675 C->setLParenLoc(Record.readSourceLocation());
12676 unsigned NumVars = C->varlist_size();
12677 SmallVector<Expr *, 16> Vars;
12678 Vars.reserve(NumVars);
12679 for (unsigned i = 0; i != NumVars; ++i)
12680 Vars.push_back(Record.readSubExpr());
12681 C->setVarRefs(Vars);
12682 Vars.clear();
12683 Vars.reserve(NumVars);
12684 for (unsigned i = 0; i != NumVars; ++i)
12685 Vars.push_back(Record.readSubExpr());
12686 C->setPrivateRefs(Vars);
12687}
12688
12689void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12690 C->setLParenLoc(Record.readSourceLocation());
12691 unsigned NumVars = C->varlist_size();
12692 SmallVector<Expr *, 16> Vars;
12693 Vars.reserve(NumVars);
12694 for (unsigned i = 0; i != NumVars; ++i)
12695 Vars.push_back(Record.readSubExpr());
12696 C->setVarRefs(Vars);
12697}
12698
12699void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12700 C->setLParenLoc(Record.readSourceLocation());
12701 unsigned NumVars = C->varlist_size();
12702 SmallVector<Expr *, 16> Vars;
12703 Vars.reserve(NumVars);
12704 for (unsigned i = 0; i != NumVars; ++i)
12705 Vars.push_back(Record.readSubExpr());
12706 C->setVarRefs(Vars);
12707}
12708
12709void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12710 C->setLParenLoc(Record.readSourceLocation());
12711 unsigned NumOfAllocators = C->getNumberOfAllocators();
12712 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12713 Data.reserve(NumOfAllocators);
12714 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12715 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12716 D.Allocator = Record.readSubExpr();
12717 D.AllocatorTraits = Record.readSubExpr();
12718 D.LParenLoc = Record.readSourceLocation();
12719 D.RParenLoc = Record.readSourceLocation();
12720 }
12721 C->setAllocatorsData(Data);
12722}
12723
12724void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12725 C->setLParenLoc(Record.readSourceLocation());
12726 C->setModifier(Record.readSubExpr());
12727 C->setColonLoc(Record.readSourceLocation());
12728 unsigned NumOfLocators = C->varlist_size();
12729 SmallVector<Expr *, 4> Locators;
12730 Locators.reserve(NumOfLocators);
12731 for (unsigned I = 0; I != NumOfLocators; ++I)
12732 Locators.push_back(Record.readSubExpr());
12733 C->setVarRefs(Locators);
12734}
12735
12736void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12737 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12738 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12739 C->setLParenLoc(Record.readSourceLocation());
12740 C->setKindKwLoc(Record.readSourceLocation());
12741 C->setModifierKwLoc(Record.readSourceLocation());
12742}
12743
12744void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12746 C->setThreadID(Record.readSubExpr());
12747 C->setLParenLoc(Record.readSourceLocation());
12748}
12749
12750void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12751 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12752 C->setLParenLoc(Record.readSourceLocation());
12753 C->setBindKindLoc(Record.readSourceLocation());
12754}
12755
12756void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12757 C->setAlignment(Record.readExpr());
12758 C->setLParenLoc(Record.readSourceLocation());
12759}
12760
12761void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12763 C->setSize(Record.readSubExpr());
12764 C->setLParenLoc(Record.readSourceLocation());
12765}
12766
12767void OMPClauseReader::VisitOMPDynGroupprivateClause(
12770 C->setDynGroupprivateModifier(
12771 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
12772 C->setDynGroupprivateFallbackModifier(
12774 C->setSize(Record.readSubExpr());
12775 C->setLParenLoc(Record.readSourceLocation());
12776 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
12777 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
12778}
12779
12780void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12781 C->setLParenLoc(Record.readSourceLocation());
12782 C->setDependenceType(
12783 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12784 C->setDependenceLoc(Record.readSourceLocation());
12785 C->setColonLoc(Record.readSourceLocation());
12786 unsigned NumVars = C->varlist_size();
12787 SmallVector<Expr *, 16> Vars;
12788 Vars.reserve(NumVars);
12789 for (unsigned I = 0; I != NumVars; ++I)
12790 Vars.push_back(Record.readSubExpr());
12791 C->setVarRefs(Vars);
12792 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12793 C->setLoopData(I, Record.readSubExpr());
12794}
12795
12796void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12797 AttrVec Attrs;
12798 Record.readAttributes(Attrs);
12799 C->setAttrs(Attrs);
12800 C->setLocStart(Record.readSourceLocation());
12801 C->setLParenLoc(Record.readSourceLocation());
12802 C->setLocEnd(Record.readSourceLocation());
12803}
12804
12805void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12806
12809 TI.Sets.resize(readUInt32());
12810 for (auto &Set : TI.Sets) {
12812 Set.Selectors.resize(readUInt32());
12813 for (auto &Selector : Set.Selectors) {
12815 Selector.ScoreOrCondition = nullptr;
12816 if (readBool())
12817 Selector.ScoreOrCondition = readExprRef();
12818 Selector.Properties.resize(readUInt32());
12819 for (auto &Property : Selector.Properties)
12821 }
12822 }
12823 return &TI;
12824}
12825
12827 if (!Data)
12828 return;
12829 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12830 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12831 skipInts(3);
12832 }
12833 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12834 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12835 Clauses[I] = readOMPClause();
12836 Data->setClauses(Clauses);
12837 if (Data->hasAssociatedStmt())
12838 Data->setAssociatedStmt(readStmt());
12839 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12840 Data->getChildren()[I] = readStmt();
12841}
12842
12844 unsigned NumVars = readInt();
12846 for (unsigned I = 0; I < NumVars; ++I)
12847 VarList.push_back(readExpr());
12848 return VarList;
12849}
12850
12852 unsigned NumExprs = readInt();
12854 for (unsigned I = 0; I < NumExprs; ++I)
12855 ExprList.push_back(readSubExpr());
12856 return ExprList;
12857}
12858
12863
12864 switch (ClauseKind) {
12866 SourceLocation LParenLoc = readSourceLocation();
12868 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
12869 EndLoc);
12870 }
12871 case OpenACCClauseKind::If: {
12872 SourceLocation LParenLoc = readSourceLocation();
12873 Expr *CondExpr = readSubExpr();
12874 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
12875 EndLoc);
12876 }
12878 SourceLocation LParenLoc = readSourceLocation();
12879 bool isConditionExprClause = readBool();
12880 if (isConditionExprClause) {
12881 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
12882 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
12883 CondExpr, EndLoc);
12884 }
12885 unsigned NumVars = readInt();
12887 for (unsigned I = 0; I < NumVars; ++I)
12888 VarList.push_back(readSubExpr());
12889 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12890 EndLoc);
12891 }
12893 SourceLocation LParenLoc = readSourceLocation();
12894 unsigned NumClauses = readInt();
12896 for (unsigned I = 0; I < NumClauses; ++I)
12897 IntExprs.push_back(readSubExpr());
12898 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
12899 IntExprs, EndLoc);
12900 }
12902 SourceLocation LParenLoc = readSourceLocation();
12903 Expr *IntExpr = readSubExpr();
12904 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
12905 IntExpr, EndLoc);
12906 }
12908 SourceLocation LParenLoc = readSourceLocation();
12909 Expr *IntExpr = readSubExpr();
12910 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
12911 IntExpr, EndLoc);
12912 }
12914 SourceLocation LParenLoc = readSourceLocation();
12915 Expr *IntExpr = readSubExpr();
12916 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12917 IntExpr, EndLoc);
12918 }
12920 SourceLocation LParenLoc = readSourceLocation();
12921 Expr *IntExpr = readSubExpr();
12922 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
12923 IntExpr, EndLoc);
12924 }
12926 SourceLocation LParenLoc = readSourceLocation();
12928
12930 for (unsigned I = 0; I < VarList.size(); ++I) {
12931 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
12932 VarDecl *Alloca = readDeclAs<VarDecl>();
12933 RecipeList.push_back({Alloca});
12934 }
12935
12936 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12937 VarList, RecipeList, EndLoc);
12938 }
12940 SourceLocation LParenLoc = readSourceLocation();
12942 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12943 EndLoc);
12944 }
12946 SourceLocation LParenLoc = readSourceLocation();
12948 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
12949 VarList, EndLoc);
12950 }
12952 SourceLocation LParenLoc = readSourceLocation();
12955 for (unsigned I = 0; I < VarList.size(); ++I) {
12956 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
12957 VarDecl *Recipe = readDeclAs<VarDecl>();
12958 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
12959 RecipeList.push_back({Recipe, RecipeTemp});
12960 }
12961
12962 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12963 VarList, RecipeList, EndLoc);
12964 }
12966 SourceLocation LParenLoc = readSourceLocation();
12968 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
12969 VarList, EndLoc);
12970 }
12972 SourceLocation LParenLoc = readSourceLocation();
12974 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
12975 VarList, EndLoc);
12976 }
12978 SourceLocation LParenLoc = readSourceLocation();
12980 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
12981 VarList, EndLoc);
12982 }
12984 SourceLocation LParenLoc = readSourceLocation();
12986 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
12987 VarList, EndLoc);
12988 }
12990 SourceLocation LParenLoc = readSourceLocation();
12992 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
12993 VarList, EndLoc);
12994 }
12996 SourceLocation LParenLoc = readSourceLocation();
12998 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
12999 VarList, EndLoc);
13000 }
13002 SourceLocation LParenLoc = readSourceLocation();
13004 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13005 VarList, EndLoc);
13006 }
13010 SourceLocation LParenLoc = readSourceLocation();
13013 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13014 LParenLoc, ModList, VarList, EndLoc);
13015 }
13019 SourceLocation LParenLoc = readSourceLocation();
13022 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13023 LParenLoc, ModList, VarList, EndLoc);
13024 }
13028 SourceLocation LParenLoc = readSourceLocation();
13031 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13032 LParenLoc, ModList, VarList, EndLoc);
13033 }
13037 SourceLocation LParenLoc = readSourceLocation();
13040 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13041 LParenLoc, ModList, VarList, EndLoc);
13042 }
13044 SourceLocation LParenLoc = readSourceLocation();
13045 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13046 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13047 AsyncExpr, EndLoc);
13048 }
13050 SourceLocation LParenLoc = readSourceLocation();
13051 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13052 SourceLocation QueuesLoc = readSourceLocation();
13054 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13055 DevNumExpr, QueuesLoc, QueueIdExprs,
13056 EndLoc);
13057 }
13060 SourceLocation LParenLoc = readSourceLocation();
13062 unsigned NumArchs = readInt();
13063
13064 for (unsigned I = 0; I < NumArchs; ++I) {
13065 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13067 Archs.emplace_back(Loc, Ident);
13068 }
13069
13070 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13071 LParenLoc, Archs, EndLoc);
13072 }
13074 SourceLocation LParenLoc = readSourceLocation();
13078
13079 for (unsigned I = 0; I < VarList.size(); ++I) {
13080 VarDecl *Recipe = readDeclAs<VarDecl>();
13081
13082 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13083 3 * sizeof(int *));
13084
13086 unsigned NumCombiners = readInt();
13087 for (unsigned I = 0; I < NumCombiners; ++I) {
13090 Expr *Op = readExpr();
13091
13092 Combiners.push_back({LHS, RHS, Op});
13093 }
13094
13095 RecipeList.push_back({Recipe, Combiners});
13096 }
13097
13098 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13099 VarList, RecipeList, EndLoc);
13100 }
13102 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13104 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13106 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13108 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13110 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13112 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13114 SourceLocation LParenLoc = readSourceLocation();
13115 bool HasForce = readBool();
13116 Expr *LoopCount = readSubExpr();
13117 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13118 HasForce, LoopCount, EndLoc);
13119 }
13121 SourceLocation LParenLoc = readSourceLocation();
13122 unsigned NumClauses = readInt();
13123 llvm::SmallVector<Expr *> SizeExprs;
13124 for (unsigned I = 0; I < NumClauses; ++I)
13125 SizeExprs.push_back(readSubExpr());
13126 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13127 SizeExprs, EndLoc);
13128 }
13130 SourceLocation LParenLoc = readSourceLocation();
13131 unsigned NumExprs = readInt();
13134 for (unsigned I = 0; I < NumExprs; ++I) {
13135 GangKinds.push_back(readEnum<OpenACCGangKind>());
13136 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13137 Exprs.push_back(readExpr());
13138 }
13139 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13140 GangKinds, Exprs, EndLoc);
13141 }
13143 SourceLocation LParenLoc = readSourceLocation();
13144 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13145 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13146 WorkerExpr, EndLoc);
13147 }
13149 SourceLocation LParenLoc = readSourceLocation();
13150 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13151 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13152 VectorExpr, EndLoc);
13153 }
13155 SourceLocation LParenLoc = readSourceLocation();
13157 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13158 EndLoc);
13159 }
13161 SourceLocation LParenLoc = readSourceLocation();
13164 LParenLoc, VarList, EndLoc);
13165 }
13166
13168 SourceLocation LParenLoc = readSourceLocation();
13169 bool IsString = readBool();
13170 if (IsString)
13171 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13172 cast<StringLiteral>(readExpr()), EndLoc);
13173 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13174 readIdentifier(), EndLoc);
13175 }
13178 llvm_unreachable("Clause serialization not yet implemented");
13179 }
13180 llvm_unreachable("Invalid Clause Kind");
13181}
13182
13185 for (unsigned I = 0; I < Clauses.size(); ++I)
13186 Clauses[I] = readOpenACCClause();
13187}
13188
13189void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13190 unsigned NumVars = readInt();
13191 A->Clauses.resize(NumVars);
13192 readOpenACCClauseList(A->Clauses);
13193}
13194
13195static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13196 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13197 // module name?
13198 llvm::FoldingSetNodeID ID;
13199 ID.AddString(PrimaryModuleName);
13200 return ID.computeStableHash();
13201}
13202
13204 if (!M)
13205 return std::nullopt;
13206
13207 if (M->isHeaderLikeModule())
13208 return std::nullopt;
13209
13210 if (M->isGlobalModule())
13211 return std::nullopt;
13212
13213 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13214 return getStableHashForModuleName(PrimaryModuleName);
13215}
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 bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, StringRef ModuleFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts)
Check that the specified and the existing module cache paths are equivalent.
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 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)
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.
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:628
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)
__device__ __2f16 b
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:34
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:220
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,...
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 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:202
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:215
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition ASTReader.h:227
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:223
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:430
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:446
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:1989
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:435
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:2607
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:2181
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:1831
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1844
@ 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:1835
@ 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:1839
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:2641
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:2191
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
friend class LocalDeclID
Definition ASTReader.h:443
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:477
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1815
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.
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:2619
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:2057
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:439
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:441
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:2493
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.
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, StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
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:2087
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.
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
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.
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:2614
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)
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:1997
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:440
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
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:450
@ Success
The control block was read successfully.
Definition ASTReader.h:453
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:470
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:463
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:456
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:466
@ HadErrors
The AST file has errors.
Definition ASTReader.h:473
@ Missing
The AST file was missing.
Definition ASTReader.h:459
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:2521
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:2145
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:2477
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:1993
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...
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
void PrintStats() override
Print some statistics about AST usage.
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:436
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:445
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2515
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:1816
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.
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:476
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1952
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:1748
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1754
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1762
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1774
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2660
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2652
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2644
Attr - This represents one attribute.
Definition Attr.h:45
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2376
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2370
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1503
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:2604
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2556
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
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:1828
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition DeclCXX.h:1790
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:1460
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1113
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 SpecificModuleCachePath, 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.
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.
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
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)
typename Representation::iterator iterator
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
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:2700
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:2673
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2688
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:2373
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2694
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:2714
decl_iterator decls_begin() const
unsigned getModuleFileIndex() const
Definition DeclID.h:125
DeclID getRawValue() const
Definition DeclID.h:115
unsigned getLocalDeclIndex() const
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition DeclID.h:108
TypeSpecifierType TST
Definition DeclSpec.h:247
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
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:859
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:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:793
SourceLocation getLocation() const
Definition DeclBase.h:439
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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:870
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:2262
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2259
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2502
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2484
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2490
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1948
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1969
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2572
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2552
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2561
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2067
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2039
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:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:597
bool getEnableAllWarnings() const
Definition Diagnostic.h:697
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:237
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:966
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:723
bool getWarningsAsErrors() const
Definition Diagnostic.h:705
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:810
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
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:3160
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:354
off_t getSize() const
Definition FileEntry.h:346
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:53
llvm::vfs::FileSystem & getVirtualFileSystem() const
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,...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
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...
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:2000
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
Wrapper for source info for functions.
Definition TypeLoc.h:1615
unsigned getNumParams() const
Definition TypeLoc.h:1687
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1635
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1651
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1694
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1659
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1643
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1673
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.
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
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) const
Get a pointer to the pCM if it exists; else nullptr.
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:3467
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1585
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.
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:313
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:351
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
void setUsedForHeaderGuard(bool Val)
Definition MacroInfo.h:296
void setHasCommaPasting()
Definition MacroInfo.h:220
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition MacroInfo.h:128
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition MacroInfo.h:166
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition MacroInfo.h:254
void setIsFunctionLike()
Function/Object-likeness.
Definition MacroInfo.h:200
void setIsGNUVarargs()
Definition MacroInfo.h:206
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition MacroInfo.h:205
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:154
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1354
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2102
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2108
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2117
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2096
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1521
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1530
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:26
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
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:62
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
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:539
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:51
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:126
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Describes a module or submodule.
Definition Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:732
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:313
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:406
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:528
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:361
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:451
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:443
@ Hidden
All of the names in this module are hidden.
Definition Module.h:445
@ AllVisible
All of the names in this module are visible.
Definition Module.h:447
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
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:341
ModuleKind Kind
The kind of this module.
Definition Module.h:189
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:772
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:563
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition Module.h:742
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:389
std::string Name
The name of this module.
Definition Module.h:147
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:395
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:434
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:520
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:489
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:756
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:352
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:198
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:439
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:687
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:424
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:202
ASTFileSignature Signature
The module signature.
Definition Module.h:208
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:239
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:416
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:383
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:541
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:376
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition Module.h:468
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:748
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:218
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:372
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:411
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition Module.h:737
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:553
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
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 'absent' clause in the 'pragma omp assume' directive.
static OMPAbsentClause * CreateEmpty(const ASTContext &C, unsigned NumKinds)
This represents 'acq_rel' clause in the 'pragma omp atomic|flush' directives.
This represents 'acquire' clause in the 'pragma omp atomic|flush' directives.
This represents clause 'affinity' in the 'pragma omp task'-based directives.
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'aligned' in the 'pragma omp ...' directives.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
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.
This represents 'at' clause in the 'pragma omp error' directive.
This represents 'atomic_default_mem_order' clause in the 'pragma omp requires' directive.
This represents 'bind' clause in the 'pragma omp ...' directives.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
This represents 'capture' clause in the 'pragma omp atomic' directive.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
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 'compare' clause in the 'pragma omp atomic' directive.
This represents the 'contains' clause in the 'pragma omp assume' directive.
static OMPContainsClause * CreateEmpty(const ASTContext &C, unsigned NumKinds)
This represents clause 'copyin' in the 'pragma omp ...' directives.
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'copyprivate' in the 'pragma omp ...' directives.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents 'defaultmap' clause in the 'pragma omp ...' directive.
This represents implicit clause 'depend' for the 'pragma omp task' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
This represents implicit clause 'depobj' for the 'pragma omp depobj' directive.
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.
This represents the 'doacross' clause for the 'pragma omp ordered' 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 ....
This represents 'dynamic_allocators' clause in the 'pragma omp requires' directive.
This represents clause 'exclusive' in the 'pragma omp scan' directive.
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'fail' clause in the 'pragma omp atomic' directive.
This represents 'filter' clause in the 'pragma omp ...' directive.
This represents 'final' clause in the 'pragma omp ...' directive.
This represents clause 'firstprivate' in the 'pragma omp ...' directives.
static OMPFirstprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents implicit clause 'flush' for the 'pragma omp flush' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'from' in the 'pragma omp ...' directives.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
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 'grainsize' clause in the 'pragma omp ...' directive.
This represents clause 'has_device_ptr' in the 'pragma omp ...' directives.
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.
This represents the 'holds' clause in the 'pragma omp assume' directive.
This represents 'if' clause in the 'pragma omp ...' directive.
This represents clause 'in_reduction' in the 'pragma omp task' directives.
static OMPInReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'inclusive' in the 'pragma omp scan' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents the 'init' clause in 'pragma omp ...' directives.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
This represents clause 'is_device_ptr' in the 'pragma omp ...' directives.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'lastprivate' in the 'pragma omp ...' directives.
static OMPLastprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'linear' in the 'pragma omp ...' directives.
static OMPLinearClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
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 clause 'map' in the 'pragma omp ...' directives.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'mergeable' clause in the 'pragma omp ...' directive.
This represents the 'message' clause in the 'pragma omp error' and the 'pragma omp parallel' directiv...
This represents the 'no_openmp' clause in the 'pragma omp assume' directive.
This represents the 'no_openmp_constructs' clause in the.
This represents the 'no_openmp_routines' clause in the 'pragma omp assume' directive.
This represents the 'no_parallelism' clause in the 'pragma omp assume' directive.
This represents 'nocontext' clause in the 'pragma omp ...' directive.
This represents 'nogroup' clause in the 'pragma omp ...' directive.
This represents clause 'nontemporal' in the 'pragma omp ...' directives.
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 'nowait' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
This represents 'num_teams' clause in the 'pragma omp ...' directive.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents 'ordered' clause in the 'pragma omp ...' directive.
static OMPOrderedClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty clause.
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 'priority' clause in the 'pragma omp ...' directive.
This represents clause 'private' in the 'pragma omp ...' directives.
static OMPPrivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'proc_bind' clause in the 'pragma omp ...' directive.
This represents 'read' clause in the 'pragma omp atomic' directive.
This represents clause 'reduction' in the 'pragma omp ...' directives.
static OMPReductionClause * CreateEmpty(const ASTContext &C, unsigned N, OpenMPReductionClauseModifier Modifier)
Creates an empty clause with the place for N variables.
This represents 'relaxed' clause in the 'pragma omp atomic' directives.
This represents 'release' clause in the 'pragma omp atomic|flush' directives.
This represents 'reverse_offload' clause in the 'pragma omp requires' directive.
This represents 'simd' clause in the 'pragma omp ...' directive.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'schedule' clause in the 'pragma omp ...' directive.
This represents 'self_maps' clause in the 'pragma omp requires' directive.
This represents 'seq_cst' clause in the 'pragma omp atomic|flush' directives.
This represents the 'severity' clause in the 'pragma omp error' and the 'pragma omp parallel' directi...
This represents clause 'shared' in the 'pragma omp ...' directives.
static OMPSharedClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
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 clause 'task_reduction' in the 'pragma omp taskgroup' directives.
static OMPTaskReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'thread_limit' 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.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
This represents clause 'to' in the 'pragma omp ...' directives.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents 'unified_address' clause in the 'pragma omp requires' directive.
This represents 'unified_shared_memory' clause in the 'pragma omp requires' directive.
This represents 'untied' clause in the 'pragma omp ...' directive.
This represents 'update' clause in the 'pragma omp atomic' directive.
static OMPUpdateClause * CreateEmpty(const ASTContext &C, bool IsExtended)
Creates an empty clause with the place for N variables.
This represents the 'use' clause in 'pragma omp ...' directives.
This represents clause 'use_device_addr' in the 'pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'use_device_ptr' in the 'pragma omp ...' directives.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'uses_allocators' in the 'pragma omp target'-based directives.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'weak' clause in the 'pragma omp atomic' directives.
This represents 'write' clause in the 'pragma omp atomic' directive.
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.
method_range methods() const
Definition DeclObjC.h:1016
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1284
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1296
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:1563
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1167
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1171
unsigned getNumProtocols() const
Definition TypeLoc.h:1201
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1159
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition TypeLoc.h:1180
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1189
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1197
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition TypeLoc.h:1229
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:1210
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)
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.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search 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 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:2604
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2287
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1386
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1382
Represents a parameter to a function.
Definition Decl.h:1790
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2696
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1490
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:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
@ FastWidth
The width of the "fast" qualifier mask.
Definition TypeBase.h:376
@ FastMask
The fast qualifier mask.
Definition TypeBase.h:379
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1599
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:5312
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:854
SemaObjC & ObjC()
Definition Sema.h:1486
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:655
IdentifierResolver IdResolver
Definition Sema.h:3460
PragmaMsStackAction
Definition Sema.h:1817
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:362
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:1884
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:644
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:3356
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:2236
A container of type source information.
Definition TypeBase.h:8249
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:1833
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2179
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2171
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2187
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2321
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2315
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2327
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2318
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:926
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2016
Captures information about a #pragma weak directive.
Definition Weak.h:25
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:84
OptionalFileEntryRef getFile() const
Definition ModuleFile.h:113
static InputFile getNotFound()
Definition ModuleFile.h:107
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:130
const PPEntityOffset * PreprocessedEntityOffsets
Definition ModuleFile.h:372
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:327
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:435
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:246
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:236
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:222
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:463
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:291
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:317
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:370
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:483
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:466
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:344
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:261
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:331
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:307
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:442
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:323
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:298
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:255
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:264
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:420
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:491
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:391
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:239
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:458
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:302
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:337
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:168
FileEntryRef File
The file entry for the module file.
Definition ModuleFile.h:185
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:164
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:366
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:267
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:400
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:242
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:193
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:285
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:182
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:160
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:509
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:179
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:258
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:282
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:173
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:417
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:455
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:288
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:395
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:139
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition ModuleFile.h:225
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:403
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:213
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:479
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:216
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:176
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:475
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:250
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:378
std::string FileName
The file name of the module file.
Definition ModuleFile.h:145
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:277
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:363
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:294
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:452
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:357
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:189
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:340
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:428
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:448
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:384
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:196
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:206
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:314
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:423
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:351
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:219
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:406
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:199
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:445
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:488
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:376
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:413
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:142
std::string ModuleName
The name of the module.
Definition ModuleFile.h:148
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:354
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:470
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:151
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:502
Manages the set of modules loaded by an AST reader.
AddModuleResult
The result of attempting to add a new module.
@ 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.
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)
#define bool
Definition gpuintrin.h:32
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.
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.
@ 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_METADATA
Metadata for submodules as a whole.
@ 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_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
@ 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.
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:43
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:51
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:54
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition ModuleFile.h:57
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:48
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:45
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:60
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.
@ 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.
@ 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.
@ 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:25
@ ModuleFile
The module file (.pcm). Required.
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:208
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:3648
@ 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:123
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',...
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.
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:87
@ 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
@ Property
The type of a property.
Definition TypeBase.h:911
@ Result
The result type of a method or function.
Definition TypeBase.h:905
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
const FunctionProtoType * T
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
@ Type
The name was classified as a type.
Definition Sema.h:562
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:46
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:47
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition OpenMPKinds.h:92
PragmaMSStructKind
Definition PragmaKinds.h:23
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:50
OpenMPDynGroupprivateClauseModifier
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:2711
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:178
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:5867
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
unsigned int uint32_t
#define true
Definition stdbool.h:25
__LIBC_ATTRS FILE * stderr
The signature of a module, which is a hash of the AST content.
Definition Module.h:58
static constexpr size_t size
Definition Module.h:61
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:81
static ASTFileSignature createDummy()
Definition Module.h:91
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:544
Module * Other
The module that this module conflicts with.
Definition Module.h:546
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:549
Information about a header directive as found in the module map file.
Definition Module.h:287
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponentLists
Number of component lists.
unsigned NumVars
Number of expressions listed.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumComponents
Total number of expression components.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
Expr * AllocatorTraits
Allocator traits.
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:1828
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
Location information for a TemplateArgument.
The input file info that has been loaded from an AST file.
Definition ModuleFile.h:64
Describes the categories of an Objective-C class.
#define log(__x)
Definition tgmath.h:460