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 unsigned 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,
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
752};
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) {
936 ModuleFilename, ReadMacros, nullptr,
937 PP.getFileManager(), SuggestedPredefines,
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(),
974}
975
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
1016 return serialization::ComputeHash(Sel);
1017}
1018
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
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()
1279 ->getDeclName().getAsIdentifierInfo();
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 *
1319ASTDeclContextNameLookupTraitBase::ReadFileRef(const unsigned char *&d) {
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>
1328ASTDeclContextNameLookupTraitBase::ReadKeyDataLength(const unsigned char *&d) {
1329 return readULEBKeyDataLength(d);
1330}
1331
1333ASTDeclContextNameLookupTraitBase::ReadKeyBase(const unsigned char *&d) {
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
1372void ASTDeclContextNameLookupTraitBase::ReadDataIntoImpl(
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
1383void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
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) {
1411 DeclarationNameKey Name = ReadKeyBase(d);
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 *
1425LazySpecializationInfoLookupTrait::ReadFileRef(const unsigned char *&d) {
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>
1440LazySpecializationInfoLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1441 return readULEBKeyDataLength(d);
1442}
1443
1444void LazySpecializationInfoLookupTrait::ReadDataInto(internal_key_type,
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) {
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
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 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2232 PreprocessingRecord::PPEntityID PPID =
2233 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
2234 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2235 PPRec.getPreprocessedEntity(PPID));
2236 if (PPDef)
2237 PPRec.RegisterMacroDefinition(Macro, PPDef);
2238 }
2239
2240 ++NumMacrosRead;
2241 break;
2242 }
2243
2244 case PP_TOKEN: {
2245 // If we see a TOKEN before a PP_MACRO_*, then the file is
2246 // erroneous, just pretend we didn't see this.
2247 if (!Macro) break;
2248 if (MacroTokens.empty()) {
2249 Error("unexpected number of macro tokens for a macro in AST file");
2250 return Macro;
2251 }
2252
2253 unsigned Idx = 0;
2254 MacroTokens[0] = ReadToken(F, Record, Idx);
2255 MacroTokens = MacroTokens.drop_front();
2256 break;
2257 }
2258 }
2259 }
2260}
2261
2264 unsigned LocalID) const {
2265 if (!M.ModuleOffsetMap.empty())
2266 ReadModuleOffsetMap(M);
2267
2270 assert(I != M.PreprocessedEntityRemap.end()
2271 && "Invalid index into preprocessed entity index remap");
2272
2273 return LocalID + I->second;
2274}
2275
2277HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2278 FileManager &FileMgr = Reader.getFileManager();
2279 if (!Key.Imported)
2280 return FileMgr.getOptionalFileRef(Key.Filename);
2281
2282 auto Resolved =
2283 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2284 return FileMgr.getOptionalFileRef(*Resolved);
2285}
2286
2287unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
2288 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2289 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2290 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2291 return llvm::xxh3_64bits(buf);
2292}
2293
2295HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
2296 internal_key_type ikey = {ekey.getSize(),
2297 M.HasTimestamps ? ekey.getModificationTime() : 0,
2298 ekey.getName(), /*Imported*/ false};
2299 return ikey;
2300}
2301
2302bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2303 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2304 return false;
2305
2306 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2307 return true;
2308
2309 // Determine whether the actual files are equivalent.
2310 OptionalFileEntryRef FEA = getFile(a);
2311 OptionalFileEntryRef FEB = getFile(b);
2312 return FEA && FEA == FEB;
2313}
2314
2315std::pair<unsigned, unsigned>
2316HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2317 return readULEBKeyDataLength(d);
2318}
2319
2321HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2322 using namespace llvm::support;
2323
2324 internal_key_type ikey;
2325 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2326 ikey.ModTime =
2327 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2328 ikey.Filename = (const char *)d;
2329 ikey.Imported = true;
2330 return ikey;
2331}
2332
2334HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2335 unsigned DataLen) {
2336 using namespace llvm::support;
2337
2338 const unsigned char *End = d + DataLen;
2339 HeaderFileInfo HFI;
2340 unsigned Flags = *d++;
2341
2343 bool Included = (Flags >> 6) & 0x01;
2344 if (Included)
2345 if ((FE = getFile(key)))
2346 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2347 // deserialize this header file info again.
2348 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2349
2350 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2351 HFI.isImport |= (Flags >> 5) & 0x01;
2352 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2353 HFI.DirInfo = (Flags >> 1) & 0x07;
2354 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2355 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2356
2357 assert((End - d) % 4 == 0 &&
2358 "Wrong data length in HeaderFileInfo deserialization");
2359 while (d != End) {
2360 uint32_t LocalSMID =
2361 endian::readNext<uint32_t, llvm::endianness::little>(d);
2362 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2363 LocalSMID >>= 3;
2364
2365 // This header is part of a module. Associate it with the module to enable
2366 // implicit module import.
2367 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2368 Module *Mod = Reader.getSubmodule(GlobalSMID);
2369 ModuleMap &ModMap =
2370 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2371
2372 if (FE || (FE = getFile(key))) {
2373 // FIXME: NameAsWritten
2374 Module::Header H = {std::string(key.Filename), "", *FE};
2375 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2376 }
2377 HFI.mergeModuleMembership(HeaderRole);
2378 }
2379
2380 // This HeaderFileInfo was externally loaded.
2381 HFI.External = true;
2382 HFI.IsValid = true;
2383 return HFI;
2384}
2385
2387 uint32_t MacroDirectivesOffset) {
2388 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2389 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2390}
2391
2393 // Note that we are loading defined macros.
2394 Deserializing Macros(this);
2395
2396 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2397 BitstreamCursor &MacroCursor = I.MacroCursor;
2398
2399 // If there was no preprocessor block, skip this file.
2400 if (MacroCursor.getBitcodeBytes().empty())
2401 continue;
2402
2403 BitstreamCursor Cursor = MacroCursor;
2404 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2405 Error(std::move(Err));
2406 return;
2407 }
2408
2410 while (true) {
2411 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2412 if (!MaybeE) {
2413 Error(MaybeE.takeError());
2414 return;
2415 }
2416 llvm::BitstreamEntry E = MaybeE.get();
2417
2418 switch (E.Kind) {
2419 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2420 case llvm::BitstreamEntry::Error:
2421 Error("malformed block record in AST file");
2422 return;
2423 case llvm::BitstreamEntry::EndBlock:
2424 goto NextCursor;
2425
2426 case llvm::BitstreamEntry::Record: {
2427 Record.clear();
2428 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2429 if (!MaybeRecord) {
2430 Error(MaybeRecord.takeError());
2431 return;
2432 }
2433 switch (MaybeRecord.get()) {
2434 default: // Default behavior: ignore.
2435 break;
2436
2439 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2440 if (II->isOutOfDate())
2441 updateOutOfDateIdentifier(*II);
2442 break;
2443 }
2444
2445 case PP_TOKEN:
2446 // Ignore tokens.
2447 break;
2448 }
2449 break;
2450 }
2451 }
2452 }
2453 NextCursor: ;
2454 }
2455}
2456
2457namespace {
2458
2459 /// Visitor class used to look up identifirs in an AST file.
2460 class IdentifierLookupVisitor {
2461 StringRef Name;
2462 unsigned NameHash;
2463 unsigned PriorGeneration;
2464 unsigned &NumIdentifierLookups;
2465 unsigned &NumIdentifierLookupHits;
2466 IdentifierInfo *Found = nullptr;
2467
2468 public:
2469 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2470 unsigned &NumIdentifierLookups,
2471 unsigned &NumIdentifierLookupHits)
2472 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2473 PriorGeneration(PriorGeneration),
2474 NumIdentifierLookups(NumIdentifierLookups),
2475 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2476
2477 bool operator()(ModuleFile &M) {
2478 // If we've already searched this module file, skip it now.
2479 if (M.Generation <= PriorGeneration)
2480 return true;
2481
2484 if (!IdTable)
2485 return false;
2486
2487 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2488 Found);
2489 ++NumIdentifierLookups;
2490 ASTIdentifierLookupTable::iterator Pos =
2491 IdTable->find_hashed(Name, NameHash, &Trait);
2492 if (Pos == IdTable->end())
2493 return false;
2494
2495 // Dereferencing the iterator has the effect of building the
2496 // IdentifierInfo node and populating it with the various
2497 // declarations it needs.
2498 ++NumIdentifierLookupHits;
2499 Found = *Pos;
2500 if (Trait.hasMoreInformationInDependencies()) {
2501 // Look for the identifier in extra modules as they contain more info.
2502 return false;
2503 }
2504 return true;
2505 }
2506
2507 // Retrieve the identifier info found within the module
2508 // files.
2509 IdentifierInfo *getIdentifierInfo() const { return Found; }
2510 };
2511
2512} // namespace
2513
2515 // Note that we are loading an identifier.
2516 Deserializing AnIdentifier(this);
2517
2518 unsigned PriorGeneration = 0;
2519 if (getContext().getLangOpts().Modules)
2520 PriorGeneration = IdentifierGeneration[&II];
2521
2522 // If there is a global index, look there first to determine which modules
2523 // provably do not have any results for this identifier.
2525 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2526 if (!loadGlobalIndex()) {
2527 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2528 HitsPtr = &Hits;
2529 }
2530 }
2531
2532 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2533 NumIdentifierLookups,
2534 NumIdentifierLookupHits);
2535 ModuleMgr.visit(Visitor, HitsPtr);
2536 markIdentifierUpToDate(&II);
2537}
2538
2540 if (!II)
2541 return;
2542
2543 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2544
2545 // Update the generation for this identifier.
2546 if (getContext().getLangOpts().Modules)
2547 IdentifierGeneration[II] = getGeneration();
2548}
2549
2551 const PendingMacroInfo &PMInfo) {
2552 ModuleFile &M = *PMInfo.M;
2553
2554 BitstreamCursor &Cursor = M.MacroCursor;
2555 SavedStreamPosition SavedPosition(Cursor);
2556 if (llvm::Error Err =
2557 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2558 Error(std::move(Err));
2559 return;
2560 }
2561
2562 struct ModuleMacroRecord {
2563 SubmoduleID SubModID;
2564 MacroInfo *MI;
2566 };
2568
2569 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2570 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2571 // macro histroy.
2573 while (true) {
2575 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2576 if (!MaybeEntry) {
2577 Error(MaybeEntry.takeError());
2578 return;
2579 }
2580 llvm::BitstreamEntry Entry = MaybeEntry.get();
2581
2582 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2583 Error("malformed block record in AST file");
2584 return;
2585 }
2586
2587 Record.clear();
2588 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2589 if (!MaybePP) {
2590 Error(MaybePP.takeError());
2591 return;
2592 }
2593 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2595 break;
2596
2597 case PP_MODULE_MACRO: {
2598 ModuleMacros.push_back(ModuleMacroRecord());
2599 auto &Info = ModuleMacros.back();
2600 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2601 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2602 for (int I = 2, N = Record.size(); I != N; ++I)
2603 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2604 continue;
2605 }
2606
2607 default:
2608 Error("malformed block record in AST file");
2609 return;
2610 }
2611
2612 // We found the macro directive history; that's the last record
2613 // for this macro.
2614 break;
2615 }
2616
2617 // Module macros are listed in reverse dependency order.
2618 {
2619 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2621 for (auto &MMR : ModuleMacros) {
2622 Overrides.clear();
2623 for (unsigned ModID : MMR.Overrides) {
2624 Module *Mod = getSubmodule(ModID);
2625 auto *Macro = PP.getModuleMacro(Mod, II);
2626 assert(Macro && "missing definition for overridden macro");
2627 Overrides.push_back(Macro);
2628 }
2629
2630 bool Inserted = false;
2631 Module *Owner = getSubmodule(MMR.SubModID);
2632 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2633 }
2634 }
2635
2636 // Don't read the directive history for a module; we don't have anywhere
2637 // to put it.
2638 if (M.isModule())
2639 return;
2640
2641 // Deserialize the macro directives history in reverse source-order.
2642 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2643 unsigned Idx = 0, N = Record.size();
2644 while (Idx < N) {
2645 MacroDirective *MD = nullptr;
2646 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2648 switch (K) {
2650 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2651 MD = PP.AllocateDefMacroDirective(MI, Loc);
2652 break;
2653 }
2655 MD = PP.AllocateUndefMacroDirective(Loc);
2656 break;
2658 bool isPublic = Record[Idx++];
2659 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2660 break;
2661 }
2662
2663 if (!Latest)
2664 Latest = MD;
2665 if (Earliest)
2666 Earliest->setPrevious(MD);
2667 Earliest = MD;
2668 }
2669
2670 if (Latest)
2671 PP.setLoadedMacroDirective(II, Earliest, Latest);
2672}
2673
2674bool ASTReader::shouldDisableValidationForFile(
2675 const serialization::ModuleFile &M) const {
2676 if (DisableValidationKind == DisableValidationForModuleKind::None)
2677 return false;
2678
2679 // If a PCH is loaded and validation is disabled for PCH then disable
2680 // validation for the PCH and the modules it loads.
2681 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2682
2683 switch (K) {
2684 case MK_MainFile:
2685 case MK_Preamble:
2686 case MK_PCH:
2687 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2688 case MK_ImplicitModule:
2689 case MK_ExplicitModule:
2690 case MK_PrebuiltModule:
2691 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2692 }
2693
2694 return false;
2695}
2696
2697static std::pair<StringRef, StringRef>
2699 const StringRef InputBlob) {
2700 uint16_t AsRequestedLength = Record[7];
2701 return {InputBlob.substr(0, AsRequestedLength),
2702 InputBlob.substr(AsRequestedLength)};
2703}
2704
2705InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2706 // If this ID is bogus, just return an empty input file.
2707 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2708 return InputFileInfo();
2709
2710 // If we've already loaded this input file, return it.
2711 if (F.InputFileInfosLoaded[ID - 1].isValid())
2712 return F.InputFileInfosLoaded[ID - 1];
2713
2714 // Go find this input file.
2715 BitstreamCursor &Cursor = F.InputFilesCursor;
2716 SavedStreamPosition SavedPosition(Cursor);
2717 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2718 F.InputFileOffsets[ID - 1])) {
2719 // FIXME this drops errors on the floor.
2720 consumeError(std::move(Err));
2721 }
2722
2723 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2724 if (!MaybeCode) {
2725 // FIXME this drops errors on the floor.
2726 consumeError(MaybeCode.takeError());
2727 }
2728 unsigned Code = MaybeCode.get();
2729 RecordData Record;
2730 StringRef Blob;
2731
2732 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2733 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2734 "invalid record type for input file");
2735 else {
2736 // FIXME this drops errors on the floor.
2737 consumeError(Maybe.takeError());
2738 }
2739
2740 assert(Record[0] == ID && "Bogus stored ID or offset");
2741 InputFileInfo R;
2742 R.StoredSize = static_cast<off_t>(Record[1]);
2743 R.StoredTime = static_cast<time_t>(Record[2]);
2744 R.Overridden = static_cast<bool>(Record[3]);
2745 R.Transient = static_cast<bool>(Record[4]);
2746 R.TopLevel = static_cast<bool>(Record[5]);
2747 R.ModuleMap = static_cast<bool>(Record[6]);
2748 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2750 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2751 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2752 ? UnresolvedFilenameAsRequested
2753 : UnresolvedFilename;
2754
2755 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2756 if (!MaybeEntry) // FIXME this drops errors on the floor.
2757 consumeError(MaybeEntry.takeError());
2758 llvm::BitstreamEntry Entry = MaybeEntry.get();
2759 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2760 "expected record type for input file hash");
2761
2762 Record.clear();
2763 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2764 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2765 "invalid record type for input file hash");
2766 else {
2767 // FIXME this drops errors on the floor.
2768 consumeError(Maybe.takeError());
2769 }
2770 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2771 static_cast<uint64_t>(Record[0]);
2772
2773 // Note that we've loaded this input file info.
2774 F.InputFileInfosLoaded[ID - 1] = R;
2775 return R;
2776}
2777
2778static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2779InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2780 // If this ID is bogus, just return an empty input file.
2781 if (ID == 0 || ID > F.InputFilesLoaded.size())
2782 return InputFile();
2783
2784 // If we've already loaded this input file, return it.
2785 if (F.InputFilesLoaded[ID-1].getFile())
2786 return F.InputFilesLoaded[ID-1];
2787
2788 if (F.InputFilesLoaded[ID-1].isNotFound())
2789 return InputFile();
2790
2791 // Go find this input file.
2792 BitstreamCursor &Cursor = F.InputFilesCursor;
2793 SavedStreamPosition SavedPosition(Cursor);
2794 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2795 F.InputFileOffsets[ID - 1])) {
2796 // FIXME this drops errors on the floor.
2797 consumeError(std::move(Err));
2798 }
2799
2800 InputFileInfo FI = getInputFileInfo(F, ID);
2801 off_t StoredSize = FI.StoredSize;
2802 time_t StoredTime = FI.StoredTime;
2803 bool Overridden = FI.Overridden;
2804 bool Transient = FI.Transient;
2805 auto Filename =
2806 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2807 uint64_t StoredContentHash = FI.ContentHash;
2808
2809 // For standard C++ modules, we don't need to check the inputs.
2810 bool SkipChecks = F.StandardCXXModule;
2811
2812 const HeaderSearchOptions &HSOpts =
2813 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2814
2815 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2816 // modules.
2818 SkipChecks = false;
2819 Overridden = false;
2820 }
2821
2822 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2823
2824 // For an overridden file, create a virtual file with the stored
2825 // size/timestamp.
2826 if ((Overridden || Transient || SkipChecks) && !File)
2827 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2828
2829 if (!File) {
2830 if (Complain) {
2831 std::string ErrorStr = "could not find file '";
2832 ErrorStr += *Filename;
2833 ErrorStr += "' referenced by AST file '";
2834 ErrorStr += F.FileName;
2835 ErrorStr += "'";
2836 Error(ErrorStr);
2837 }
2838 // Record that we didn't find the file.
2840 return InputFile();
2841 }
2842
2843 // Check if there was a request to override the contents of the file
2844 // that was part of the precompiled header. Overriding such a file
2845 // can lead to problems when lexing using the source locations from the
2846 // PCH.
2847 SourceManager &SM = getSourceManager();
2848 // FIXME: Reject if the overrides are different.
2849 if ((!Overridden && !Transient) && !SkipChecks &&
2850 SM.isFileOverridden(*File)) {
2851 if (Complain)
2852 Error(diag::err_fe_pch_file_overridden, *Filename);
2853
2854 // After emitting the diagnostic, bypass the overriding file to recover
2855 // (this creates a separate FileEntry).
2856 File = SM.bypassFileContentsOverride(*File);
2857 if (!File) {
2859 return InputFile();
2860 }
2861 }
2862
2863 struct Change {
2864 enum ModificationKind {
2865 Size,
2866 ModTime,
2867 Content,
2868 None,
2869 } Kind;
2870 std::optional<int64_t> Old = std::nullopt;
2871 std::optional<int64_t> New = std::nullopt;
2872 };
2873 auto HasInputContentChanged = [&](Change OriginalChange) {
2874 assert(ValidateASTInputFilesContent &&
2875 "We should only check the content of the inputs with "
2876 "ValidateASTInputFilesContent enabled.");
2877
2878 if (StoredContentHash == 0)
2879 return OriginalChange;
2880
2881 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2882 if (!MemBuffOrError) {
2883 if (!Complain)
2884 return OriginalChange;
2885 std::string ErrorStr = "could not get buffer for file '";
2886 ErrorStr += File->getName();
2887 ErrorStr += "'";
2888 Error(ErrorStr);
2889 return OriginalChange;
2890 }
2891
2892 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2893 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2894 return Change{Change::None};
2895
2896 return Change{Change::Content};
2897 };
2898 auto HasInputFileChanged = [&]() {
2899 if (StoredSize != File->getSize())
2900 return Change{Change::Size, StoredSize, File->getSize()};
2901 if (!shouldDisableValidationForFile(F) && StoredTime &&
2902 StoredTime != File->getModificationTime()) {
2903 Change MTimeChange = {Change::ModTime, StoredTime,
2904 File->getModificationTime()};
2905
2906 // In case the modification time changes but not the content,
2907 // accept the cached file as legit.
2908 if (ValidateASTInputFilesContent)
2909 return HasInputContentChanged(MTimeChange);
2910
2911 return MTimeChange;
2912 }
2913 return Change{Change::None};
2914 };
2915
2916 bool IsOutOfDate = false;
2917 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2918 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2919 // enabled, it is better to check the contents of the inputs. Since we can't
2920 // get correct modified time information for inputs from overriden inputs.
2921 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2922 F.StandardCXXModule && FileChange.Kind == Change::None)
2923 FileChange = HasInputContentChanged(FileChange);
2924
2925 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2926 // it is better to check the content of the input files because we cannot rely
2927 // on the file modification time, which will be the same (zero) for these
2928 // files.
2929 if (!StoredTime && ValidateASTInputFilesContent &&
2930 FileChange.Kind == Change::None)
2931 FileChange = HasInputContentChanged(FileChange);
2932
2933 // For an overridden file, there is nothing to validate.
2934 if (!Overridden && FileChange.Kind != Change::None) {
2935 if (Complain) {
2936 // Build a list of the PCH imports that got us here (in reverse).
2937 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2938 while (!ImportStack.back()->ImportedBy.empty())
2939 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2940
2941 // The top-level AST file is stale.
2942 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2943 Diag(diag::err_fe_ast_file_modified)
2944 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2945 << TopLevelASTFileName << FileChange.Kind
2946 << (FileChange.Old && FileChange.New)
2947 << llvm::itostr(FileChange.Old.value_or(0))
2948 << llvm::itostr(FileChange.New.value_or(0));
2949
2950 // Print the import stack.
2951 if (ImportStack.size() > 1) {
2952 Diag(diag::note_ast_file_required_by)
2953 << *Filename << ImportStack[0]->FileName;
2954 for (unsigned I = 1; I < ImportStack.size(); ++I)
2955 Diag(diag::note_ast_file_required_by)
2956 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
2957 }
2958
2959 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
2960 }
2961
2962 IsOutOfDate = true;
2963 }
2964 // FIXME: If the file is overridden and we've already opened it,
2965 // issue an error (or split it into a separate FileEntry).
2966
2967 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2968
2969 // Note that we've loaded this input file.
2970 F.InputFilesLoaded[ID-1] = IF;
2971 return IF;
2972}
2973
2974ASTReader::TemporarilyOwnedStringRef
2976 ModuleFile &ModF) {
2977 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
2978}
2979
2980ASTReader::TemporarilyOwnedStringRef
2982 StringRef Prefix) {
2983 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
2984
2985 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
2986 Path == "<built-in>" || Path == "<command line>")
2987 return {Path, Buf};
2988
2989 Buf.clear();
2990 llvm::sys::path::append(Buf, Prefix, Path);
2991 StringRef ResolvedPath{Buf.data(), Buf.size()};
2992 return {ResolvedPath, Buf};
2993}
2994
2996 StringRef P,
2997 ModuleFile &ModF) {
2998 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
2999}
3000
3002 StringRef P,
3003 StringRef Prefix) {
3004 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3005 return ResolvedPath->str();
3006}
3007
3008static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3009 switch (ARR) {
3010 case ASTReader::Failure: return true;
3011 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3012 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3015 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3016 case ASTReader::HadErrors: return true;
3017 case ASTReader::Success: return false;
3018 }
3019
3020 llvm_unreachable("unknown ASTReadResult");
3021}
3022
3023ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3024 BitstreamCursor &Stream, StringRef Filename,
3025 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3026 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3027 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3028 // FIXME this drops errors on the floor.
3029 consumeError(std::move(Err));
3030 return Failure;
3031 }
3032
3033 // Read all of the records in the options block.
3034 RecordData Record;
3035 ASTReadResult Result = Success;
3036 while (true) {
3037 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3038 if (!MaybeEntry) {
3039 // FIXME this drops errors on the floor.
3040 consumeError(MaybeEntry.takeError());
3041 return Failure;
3042 }
3043 llvm::BitstreamEntry Entry = MaybeEntry.get();
3044
3045 switch (Entry.Kind) {
3046 case llvm::BitstreamEntry::Error:
3047 case llvm::BitstreamEntry::SubBlock:
3048 return Failure;
3049
3050 case llvm::BitstreamEntry::EndBlock:
3051 return Result;
3052
3053 case llvm::BitstreamEntry::Record:
3054 // The interesting case.
3055 break;
3056 }
3057
3058 // Read and process a record.
3059 Record.clear();
3060 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3061 if (!MaybeRecordType) {
3062 // FIXME this drops errors on the floor.
3063 consumeError(MaybeRecordType.takeError());
3064 return Failure;
3065 }
3066 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3067 case LANGUAGE_OPTIONS: {
3068 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3069 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3070 AllowCompatibleConfigurationMismatch))
3071 Result = ConfigurationMismatch;
3072 break;
3073 }
3074
3075 case CODEGEN_OPTIONS: {
3076 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3077 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3078 AllowCompatibleConfigurationMismatch))
3079 Result = ConfigurationMismatch;
3080 break;
3081 }
3082
3083 case TARGET_OPTIONS: {
3084 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3085 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3086 AllowCompatibleConfigurationMismatch))
3087 Result = ConfigurationMismatch;
3088 break;
3089 }
3090
3091 case FILE_SYSTEM_OPTIONS: {
3092 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3093 if (!AllowCompatibleConfigurationMismatch &&
3094 ParseFileSystemOptions(Record, Complain, Listener))
3095 Result = ConfigurationMismatch;
3096 break;
3097 }
3098
3099 case HEADER_SEARCH_OPTIONS: {
3100 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3101 if (!AllowCompatibleConfigurationMismatch &&
3102 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3103 Result = ConfigurationMismatch;
3104 break;
3105 }
3106
3108 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3109 if (!AllowCompatibleConfigurationMismatch &&
3110 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3111 SuggestedPredefines))
3112 Result = ConfigurationMismatch;
3113 break;
3114 }
3115 }
3116}
3117
3119ASTReader::ReadControlBlock(ModuleFile &F,
3121 const ModuleFile *ImportedBy,
3122 unsigned ClientLoadCapabilities) {
3123 BitstreamCursor &Stream = F.Stream;
3124
3125 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3126 Error(std::move(Err));
3127 return Failure;
3128 }
3129
3130 // Lambda to read the unhashed control block the first time it's called.
3131 //
3132 // For PCM files, the unhashed control block cannot be read until after the
3133 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3134 // need to look ahead before reading the IMPORTS record. For consistency,
3135 // this block is always read somehow (see BitstreamEntry::EndBlock).
3136 bool HasReadUnhashedControlBlock = false;
3137 auto readUnhashedControlBlockOnce = [&]() {
3138 if (!HasReadUnhashedControlBlock) {
3139 HasReadUnhashedControlBlock = true;
3140 if (ASTReadResult Result =
3141 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3142 return Result;
3143 }
3144 return Success;
3145 };
3146
3147 bool DisableValidation = shouldDisableValidationForFile(F);
3148
3149 // Read all of the records and blocks in the control block.
3150 RecordData Record;
3151 unsigned NumInputs = 0;
3152 unsigned NumUserInputs = 0;
3153 StringRef BaseDirectoryAsWritten;
3154 while (true) {
3155 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3156 if (!MaybeEntry) {
3157 Error(MaybeEntry.takeError());
3158 return Failure;
3159 }
3160 llvm::BitstreamEntry Entry = MaybeEntry.get();
3161
3162 switch (Entry.Kind) {
3163 case llvm::BitstreamEntry::Error:
3164 Error("malformed block record in AST file");
3165 return Failure;
3166 case llvm::BitstreamEntry::EndBlock: {
3167 // Validate the module before returning. This call catches an AST with
3168 // no module name and no imports.
3169 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3170 return Result;
3171
3172 // Validate input files.
3173 const HeaderSearchOptions &HSOpts =
3174 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3175
3176 // All user input files reside at the index range [0, NumUserInputs), and
3177 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3178 // loaded module files, ignore missing inputs.
3179 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3180 F.Kind != MK_PrebuiltModule) {
3181 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3182
3183 // If we are reading a module, we will create a verification timestamp,
3184 // so we verify all input files. Otherwise, verify only user input
3185 // files.
3186
3187 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3191 N = ForceValidateUserInputs ? NumUserInputs : 0;
3192
3193 for (unsigned I = 0; I < N; ++I) {
3194 InputFile IF = getInputFile(F, I+1, Complain);
3195 if (!IF.getFile() || IF.isOutOfDate())
3196 return OutOfDate;
3197 }
3198 }
3199
3200 if (Listener)
3201 Listener->visitModuleFile(F.FileName, F.Kind);
3202
3203 if (Listener && Listener->needsInputFileVisitation()) {
3204 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3205 : NumUserInputs;
3206 for (unsigned I = 0; I < N; ++I) {
3207 bool IsSystem = I >= NumUserInputs;
3208 InputFileInfo FI = getInputFileInfo(F, I + 1);
3209 auto FilenameAsRequested = ResolveImportedPath(
3211 Listener->visitInputFile(
3212 *FilenameAsRequested, IsSystem, FI.Overridden,
3214 }
3215 }
3216
3217 return Success;
3218 }
3219
3220 case llvm::BitstreamEntry::SubBlock:
3221 switch (Entry.ID) {
3223 F.InputFilesCursor = Stream;
3224 if (llvm::Error Err = Stream.SkipBlock()) {
3225 Error(std::move(Err));
3226 return Failure;
3227 }
3228 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3229 Error("malformed block record in AST file");
3230 return Failure;
3231 }
3232 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3233 continue;
3234
3235 case OPTIONS_BLOCK_ID:
3236 // If we're reading the first module for this group, check its options
3237 // are compatible with ours. For modules it imports, no further checking
3238 // is required, because we checked them when we built it.
3239 if (Listener && !ImportedBy) {
3240 // Should we allow the configuration of the module file to differ from
3241 // the configuration of the current translation unit in a compatible
3242 // way?
3243 //
3244 // FIXME: Allow this for files explicitly specified with -include-pch.
3245 bool AllowCompatibleConfigurationMismatch =
3247
3248 ASTReadResult Result =
3249 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3250 AllowCompatibleConfigurationMismatch, *Listener,
3251 SuggestedPredefines);
3252 if (Result == Failure) {
3253 Error("malformed block record in AST file");
3254 return Result;
3255 }
3256
3257 if (DisableValidation ||
3258 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3259 Result = Success;
3260
3261 // If we can't load the module, exit early since we likely
3262 // will rebuild the module anyway. The stream may be in the
3263 // middle of a block.
3264 if (Result != Success)
3265 return Result;
3266 } else if (llvm::Error Err = Stream.SkipBlock()) {
3267 Error(std::move(Err));
3268 return Failure;
3269 }
3270 continue;
3271
3272 default:
3273 if (llvm::Error Err = Stream.SkipBlock()) {
3274 Error(std::move(Err));
3275 return Failure;
3276 }
3277 continue;
3278 }
3279
3280 case llvm::BitstreamEntry::Record:
3281 // The interesting case.
3282 break;
3283 }
3284
3285 // Read and process a record.
3286 Record.clear();
3287 StringRef Blob;
3288 Expected<unsigned> MaybeRecordType =
3289 Stream.readRecord(Entry.ID, Record, &Blob);
3290 if (!MaybeRecordType) {
3291 Error(MaybeRecordType.takeError());
3292 return Failure;
3293 }
3294 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3295 case METADATA: {
3296 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3297 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3298 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3299 : diag::err_ast_file_version_too_new)
3301 return VersionMismatch;
3302 }
3303
3304 bool hasErrors = Record[7];
3305 if (hasErrors && !DisableValidation) {
3306 // If requested by the caller and the module hasn't already been read
3307 // or compiled, mark modules on error as out-of-date.
3308 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3309 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3310 return OutOfDate;
3311
3312 if (!AllowASTWithCompilerErrors) {
3313 Diag(diag::err_ast_file_with_compiler_errors)
3315 return HadErrors;
3316 }
3317 }
3318 if (hasErrors) {
3319 Diags.ErrorOccurred = true;
3320 Diags.UncompilableErrorOccurred = true;
3321 Diags.UnrecoverableErrorOccurred = true;
3322 }
3323
3324 F.RelocatablePCH = Record[4];
3325 // Relative paths in a relocatable PCH are relative to our sysroot.
3326 if (F.RelocatablePCH)
3327 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3328
3330
3331 F.HasTimestamps = Record[6];
3332
3333 const std::string &CurBranch = getClangFullRepositoryVersion();
3334 StringRef ASTBranch = Blob;
3335 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3336 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3337 Diag(diag::err_ast_file_different_branch)
3338 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3339 << CurBranch;
3340 return VersionMismatch;
3341 }
3342 break;
3343 }
3344
3345 case IMPORT: {
3346 // Validate the AST before processing any imports (otherwise, untangling
3347 // them can be error-prone and expensive). A module will have a name and
3348 // will already have been validated, but this catches the PCH case.
3349 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3350 return Result;
3351
3352 unsigned Idx = 0;
3353 // Read information about the AST file.
3354 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3355
3356 // The import location will be the local one for now; we will adjust
3357 // all import locations of module imports after the global source
3358 // location info are setup, in ReadAST.
3359 auto [ImportLoc, ImportModuleFileIndex] =
3360 ReadUntranslatedSourceLocation(Record[Idx++]);
3361 // The import location must belong to the current module file itself.
3362 assert(ImportModuleFileIndex == 0);
3363
3364 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3365
3366 bool IsImportingStdCXXModule = Record[Idx++];
3367
3368 off_t StoredSize = 0;
3369 time_t StoredModTime = 0;
3370 ASTFileSignature StoredSignature;
3371 std::string ImportedFile;
3372 std::string StoredFile;
3373 bool IgnoreImportedByNote = false;
3374
3375 // For prebuilt and explicit modules first consult the file map for
3376 // an override. Note that here we don't search prebuilt module
3377 // directories if we're not importing standard c++ module, only the
3378 // explicit name to file mappings. Also, we will still verify the
3379 // size/signature making sure it is essentially the same file but
3380 // perhaps in a different location.
3381 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3382 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3383 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3384
3385 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3386 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3387 return Missing;
3388 }
3389
3390 if (!IsImportingStdCXXModule) {
3391 StoredSize = (off_t)Record[Idx++];
3392 StoredModTime = (time_t)Record[Idx++];
3393
3394 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3395 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3396 SignatureBytes.end());
3397 Blob = Blob.substr(ASTFileSignature::size);
3398
3399 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3400 // ModuleCache as when writing.
3401 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3402 if (ImportedFile.empty()) {
3403 ImportedFile = StoredFile;
3404 } else if (!getDiags().isIgnored(
3405 diag::warn_module_file_mapping_mismatch,
3406 CurrentImportLoc)) {
3407 auto ImportedFileRef =
3408 PP.getFileManager().getOptionalFileRef(ImportedFile);
3409 auto StoredFileRef =
3410 PP.getFileManager().getOptionalFileRef(StoredFile);
3411 if ((ImportedFileRef && StoredFileRef) &&
3412 (*ImportedFileRef != *StoredFileRef)) {
3413 Diag(diag::warn_module_file_mapping_mismatch)
3414 << ImportedFile << StoredFile;
3415 Diag(diag::note_module_file_imported_by)
3416 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3417 IgnoreImportedByNote = true;
3418 }
3419 }
3420 }
3421
3422 // If our client can't cope with us being out of date, we can't cope with
3423 // our dependency being missing.
3424 unsigned Capabilities = ClientLoadCapabilities;
3425 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3426 Capabilities &= ~ARR_Missing;
3427
3428 // Load the AST file.
3429 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3430 Loaded, StoredSize, StoredModTime,
3431 StoredSignature, Capabilities);
3432
3433 // Check the AST we just read from ImportedFile contains a different
3434 // module than we expected (ImportedName). This can occur for C++20
3435 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3436 if (IsImportingStdCXXModule) {
3437 if (const auto *Imported =
3438 getModuleManager().lookupByFileName(ImportedFile);
3439 Imported != nullptr && Imported->ModuleName != ImportedName) {
3440 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3441 Result = Missing;
3442 }
3443 }
3444
3445 // If we diagnosed a problem, produce a backtrace.
3446 bool recompilingFinalized = Result == OutOfDate &&
3447 (Capabilities & ARR_OutOfDate) &&
3448 getModuleManager()
3449 .getModuleCache()
3450 .getInMemoryModuleCache()
3451 .isPCMFinal(F.FileName);
3452 if (!IgnoreImportedByNote &&
3453 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3454 Diag(diag::note_module_file_imported_by)
3455 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3456
3457 switch (Result) {
3458 case Failure: return Failure;
3459 // If we have to ignore the dependency, we'll have to ignore this too.
3460 case Missing:
3461 case OutOfDate: return OutOfDate;
3462 case VersionMismatch: return VersionMismatch;
3463 case ConfigurationMismatch: return ConfigurationMismatch;
3464 case HadErrors: return HadErrors;
3465 case Success: break;
3466 }
3467 break;
3468 }
3469
3470 case ORIGINAL_FILE:
3471 F.OriginalSourceFileID = FileID::get(Record[0]);
3472 F.ActualOriginalSourceFileName = std::string(Blob);
3473 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3474 PathBuf, F.ActualOriginalSourceFileName, F);
3475 break;
3476
3477 case ORIGINAL_FILE_ID:
3478 F.OriginalSourceFileID = FileID::get(Record[0]);
3479 break;
3480
3481 case MODULE_NAME:
3482 F.ModuleName = std::string(Blob);
3483 Diag(diag::remark_module_import)
3484 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3485 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3486 if (Listener)
3487 Listener->ReadModuleName(F.ModuleName);
3488
3489 // Validate the AST as soon as we have a name so we can exit early on
3490 // failure.
3491 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3492 return Result;
3493
3494 break;
3495
3496 case MODULE_DIRECTORY: {
3497 // Save the BaseDirectory as written in the PCM for computing the module
3498 // filename for the ModuleCache.
3499 BaseDirectoryAsWritten = Blob;
3500 assert(!F.ModuleName.empty() &&
3501 "MODULE_DIRECTORY found before MODULE_NAME");
3502 F.BaseDirectory = std::string(Blob);
3503 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3504 break;
3505 // If we've already loaded a module map file covering this module, we may
3506 // have a better path for it (relative to the current build).
3507 Module *M = PP.getHeaderSearchInfo().lookupModule(
3508 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3509 /*AllowExtraModuleMapSearch*/ true);
3510 if (M && M->Directory) {
3511 // If we're implicitly loading a module, the base directory can't
3512 // change between the build and use.
3513 // Don't emit module relocation error if we have -fno-validate-pch
3514 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3517 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3518 if (!BuildDir || *BuildDir != M->Directory) {
3519 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3520 Diag(diag::err_imported_module_relocated)
3521 << F.ModuleName << Blob << M->Directory->getName();
3522 return OutOfDate;
3523 }
3524 }
3525 F.BaseDirectory = std::string(M->Directory->getName());
3526 }
3527 break;
3528 }
3529
3530 case MODULE_MAP_FILE:
3531 if (ASTReadResult Result =
3532 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3533 return Result;
3534 break;
3535
3536 case INPUT_FILE_OFFSETS:
3537 NumInputs = Record[0];
3538 NumUserInputs = Record[1];
3540 (const llvm::support::unaligned_uint64_t *)Blob.data();
3541 F.InputFilesLoaded.resize(NumInputs);
3542 F.InputFileInfosLoaded.resize(NumInputs);
3543 F.NumUserInputFiles = NumUserInputs;
3544 break;
3545 }
3546 }
3547}
3548
3549llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3550 unsigned ClientLoadCapabilities) {
3551 BitstreamCursor &Stream = F.Stream;
3552
3553 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3554 return Err;
3555 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3556
3557 // Read all of the records and blocks for the AST file.
3558 RecordData Record;
3559 while (true) {
3560 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3561 if (!MaybeEntry)
3562 return MaybeEntry.takeError();
3563 llvm::BitstreamEntry Entry = MaybeEntry.get();
3564
3565 switch (Entry.Kind) {
3566 case llvm::BitstreamEntry::Error:
3567 return llvm::createStringError(
3568 std::errc::illegal_byte_sequence,
3569 "error at end of module block in AST file");
3570 case llvm::BitstreamEntry::EndBlock:
3571 // Outside of C++, we do not store a lookup map for the translation unit.
3572 // Instead, mark it as needing a lookup map to be built if this module
3573 // contains any declarations lexically within it (which it always does!).
3574 // This usually has no cost, since we very rarely need the lookup map for
3575 // the translation unit outside C++.
3576 if (ASTContext *Ctx = ContextObj) {
3578 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3580 }
3581
3582 return llvm::Error::success();
3583 case llvm::BitstreamEntry::SubBlock:
3584 switch (Entry.ID) {
3585 case DECLTYPES_BLOCK_ID:
3586 // We lazily load the decls block, but we want to set up the
3587 // DeclsCursor cursor to point into it. Clone our current bitcode
3588 // cursor to it, enter the block and read the abbrevs in that block.
3589 // With the main cursor, we just skip over it.
3590 F.DeclsCursor = Stream;
3591 if (llvm::Error Err = Stream.SkipBlock())
3592 return Err;
3593 if (llvm::Error Err = ReadBlockAbbrevs(
3595 return Err;
3596 break;
3597
3599 F.MacroCursor = Stream;
3600 if (!PP.getExternalSource())
3601 PP.setExternalSource(this);
3602
3603 if (llvm::Error Err = Stream.SkipBlock())
3604 return Err;
3605 if (llvm::Error Err =
3606 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3607 return Err;
3608 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3609 break;
3610
3612 F.PreprocessorDetailCursor = Stream;
3613
3614 if (llvm::Error Err = Stream.SkipBlock()) {
3615 return Err;
3616 }
3617 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3619 return Err;
3621 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3622
3623 if (!PP.getPreprocessingRecord())
3624 PP.createPreprocessingRecord();
3625 if (!PP.getPreprocessingRecord()->getExternalSource())
3626 PP.getPreprocessingRecord()->SetExternalSource(*this);
3627 break;
3628
3630 if (llvm::Error Err = ReadSourceManagerBlock(F))
3631 return Err;
3632 break;
3633
3634 case SUBMODULE_BLOCK_ID:
3635 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3636 return Err;
3637 break;
3638
3639 case COMMENTS_BLOCK_ID: {
3640 BitstreamCursor C = Stream;
3641
3642 if (llvm::Error Err = Stream.SkipBlock())
3643 return Err;
3644 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3645 return Err;
3646 CommentsCursors.push_back(std::make_pair(C, &F));
3647 break;
3648 }
3649
3650 default:
3651 if (llvm::Error Err = Stream.SkipBlock())
3652 return Err;
3653 break;
3654 }
3655 continue;
3656
3657 case llvm::BitstreamEntry::Record:
3658 // The interesting case.
3659 break;
3660 }
3661
3662 // Read and process a record.
3663 Record.clear();
3664 StringRef Blob;
3665 Expected<unsigned> MaybeRecordType =
3666 Stream.readRecord(Entry.ID, Record, &Blob);
3667 if (!MaybeRecordType)
3668 return MaybeRecordType.takeError();
3669 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3670
3671 // If we're not loading an AST context, we don't care about most records.
3672 if (!ContextObj) {
3673 switch (RecordType) {
3674 case IDENTIFIER_TABLE:
3675 case IDENTIFIER_OFFSET:
3677 case STATISTICS:
3680 case PP_COUNTER_VALUE:
3682 case MODULE_OFFSET_MAP:
3686 case IMPORTED_MODULES:
3687 case MACRO_OFFSET:
3688 break;
3689 default:
3690 continue;
3691 }
3692 }
3693
3694 switch (RecordType) {
3695 default: // Default behavior: ignore.
3696 break;
3697
3698 case TYPE_OFFSET: {
3699 if (F.LocalNumTypes != 0)
3700 return llvm::createStringError(
3701 std::errc::illegal_byte_sequence,
3702 "duplicate TYPE_OFFSET record in AST file");
3703 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3704 F.LocalNumTypes = Record[0];
3705 F.BaseTypeIndex = getTotalNumTypes();
3706
3707 if (F.LocalNumTypes > 0)
3708 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3709
3710 break;
3711 }
3712
3713 case DECL_OFFSET: {
3714 if (F.LocalNumDecls != 0)
3715 return llvm::createStringError(
3716 std::errc::illegal_byte_sequence,
3717 "duplicate DECL_OFFSET record in AST file");
3718 F.DeclOffsets = (const DeclOffset *)Blob.data();
3719 F.LocalNumDecls = Record[0];
3720 F.BaseDeclIndex = getTotalNumDecls();
3721
3722 if (F.LocalNumDecls > 0)
3723 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3724
3725 break;
3726 }
3727
3728 case TU_UPDATE_LEXICAL: {
3729 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3730 LexicalContents Contents(
3731 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3732 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3733 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3735 break;
3736 }
3737
3738 case UPDATE_VISIBLE: {
3739 unsigned Idx = 0;
3740 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3741 auto *Data = (const unsigned char*)Blob.data();
3742 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3743 // If we've already loaded the decl, perform the updates when we finish
3744 // loading this block.
3745 if (Decl *D = GetExistingDecl(ID))
3746 PendingUpdateRecords.push_back(
3747 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3748 break;
3749 }
3750
3752 unsigned Idx = 0;
3753 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3754 auto *Data = (const unsigned char *)Blob.data();
3755 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3756 // If we've already loaded the decl, perform the updates when we finish
3757 // loading this block.
3758 if (Decl *D = GetExistingDecl(ID))
3759 PendingUpdateRecords.push_back(
3760 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3761 break;
3762 }
3763
3765 if (F.Kind != MK_MainFile)
3766 break;
3767 unsigned Idx = 0;
3768 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3769 auto *Data = (const unsigned char *)Blob.data();
3770 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3771 // If we've already loaded the decl, perform the updates when we finish
3772 // loading this block.
3773 if (Decl *D = GetExistingDecl(ID))
3774 PendingUpdateRecords.push_back(
3775 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3776 break;
3777 }
3778
3780 unsigned Idx = 0;
3781 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3782 auto *Data = (const unsigned char *)Blob.data();
3783 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3784 // If we've already loaded the decl, perform the updates when we finish
3785 // loading this block.
3786 if (Decl *D = GetExistingDecl(ID))
3787 PendingUpdateRecords.push_back(
3788 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3789 break;
3790 }
3791
3793 unsigned Idx = 0;
3794 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3795 auto *Data = (const unsigned char *)Blob.data();
3796 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3797 // If we've already loaded the decl, perform the updates when we finish
3798 // loading this block.
3799 if (Decl *D = GetExistingDecl(ID))
3800 PendingUpdateRecords.push_back(
3801 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3802 break;
3803 }
3804
3805 case IDENTIFIER_TABLE:
3807 reinterpret_cast<const unsigned char *>(Blob.data());
3808 if (Record[0]) {
3809 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3811 F.IdentifierTableData + sizeof(uint32_t),
3813 ASTIdentifierLookupTrait(*this, F));
3814
3815 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3816 }
3817 break;
3818
3819 case IDENTIFIER_OFFSET: {
3820 if (F.LocalNumIdentifiers != 0)
3821 return llvm::createStringError(
3822 std::errc::illegal_byte_sequence,
3823 "duplicate IDENTIFIER_OFFSET record in AST file");
3824 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3826 F.BaseIdentifierID = getTotalNumIdentifiers();
3827
3828 if (F.LocalNumIdentifiers > 0)
3829 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3831 break;
3832 }
3833
3835 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3836 break;
3837
3839 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3840 // about "interesting" decls (for instance, if we're building a module).
3841 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3842 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3843 break;
3844
3846 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3847 // them (ie: if we're not codegenerating this module).
3848 if (F.Kind == MK_MainFile ||
3849 getContext().getLangOpts().BuildingPCHWithObjectFile)
3850 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3851 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3852 break;
3853
3854 case SPECIAL_TYPES:
3855 if (SpecialTypes.empty()) {
3856 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3857 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3858 break;
3859 }
3860
3861 if (Record.empty())
3862 break;
3863
3864 if (SpecialTypes.size() != Record.size())
3865 return llvm::createStringError(std::errc::illegal_byte_sequence,
3866 "invalid special-types record");
3867
3868 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3869 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3870 if (!SpecialTypes[I])
3871 SpecialTypes[I] = ID;
3872 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3873 // merge step?
3874 }
3875 break;
3876
3877 case STATISTICS:
3878 TotalNumStatements += Record[0];
3879 TotalNumMacros += Record[1];
3880 TotalLexicalDeclContexts += Record[2];
3881 TotalVisibleDeclContexts += Record[3];
3882 TotalModuleLocalVisibleDeclContexts += Record[4];
3883 TotalTULocalVisibleDeclContexts += Record[5];
3884 break;
3885
3887 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3888 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3889 break;
3890
3891 case DELEGATING_CTORS:
3892 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3893 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3894 break;
3895
3897 if (Record.size() % 3 != 0)
3898 return llvm::createStringError(std::errc::illegal_byte_sequence,
3899 "invalid weak identifiers record");
3900
3901 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3902 // files. This isn't the way to do it :)
3903 WeakUndeclaredIdentifiers.clear();
3904
3905 // Translate the weak, undeclared identifiers into global IDs.
3906 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3907 WeakUndeclaredIdentifiers.push_back(
3908 getGlobalIdentifierID(F, Record[I++]));
3909 WeakUndeclaredIdentifiers.push_back(
3910 getGlobalIdentifierID(F, Record[I++]));
3911 WeakUndeclaredIdentifiers.push_back(
3912 ReadSourceLocation(F, Record, I).getRawEncoding());
3913 }
3914 break;
3915
3916 case SELECTOR_OFFSETS: {
3917 F.SelectorOffsets = (const uint32_t *)Blob.data();
3919 unsigned LocalBaseSelectorID = Record[1];
3920 F.BaseSelectorID = getTotalNumSelectors();
3921
3922 if (F.LocalNumSelectors > 0) {
3923 // Introduce the global -> local mapping for selectors within this
3924 // module.
3925 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3926
3927 // Introduce the local -> global mapping for selectors within this
3928 // module.
3930 std::make_pair(LocalBaseSelectorID,
3931 F.BaseSelectorID - LocalBaseSelectorID));
3932
3933 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3934 }
3935 break;
3936 }
3937
3938 case METHOD_POOL:
3939 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3940 if (Record[0])
3942 = ASTSelectorLookupTable::Create(
3945 ASTSelectorLookupTrait(*this, F));
3946 TotalNumMethodPoolEntries += Record[1];
3947 break;
3948
3950 if (!Record.empty()) {
3951 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3952 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3953 Record[Idx++]));
3954 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3955 getRawEncoding());
3956 }
3957 }
3958 break;
3959
3960 case PP_ASSUME_NONNULL_LOC: {
3961 unsigned Idx = 0;
3962 if (!Record.empty())
3963 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3964 ReadSourceLocation(F, Record, Idx));
3965 break;
3966 }
3967
3969 if (!Record.empty()) {
3971 unsigned Idx = 0;
3972 while (Idx < Record.size())
3973 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
3974 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3975 }
3976 break;
3977 }
3978
3980 if (!Record.empty()) {
3981 unsigned Idx = 0, End = Record.size() - 1;
3982 bool ReachedEOFWhileSkipping = Record[Idx++];
3983 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3984 if (ReachedEOFWhileSkipping) {
3985 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3986 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3987 bool FoundNonSkipPortion = Record[Idx++];
3988 bool FoundElse = Record[Idx++];
3989 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3990 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3991 FoundElse, ElseLoc);
3992 }
3993 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3994 while (Idx < End) {
3995 auto Loc = ReadSourceLocation(F, Record, Idx);
3996 bool WasSkipping = Record[Idx++];
3997 bool FoundNonSkip = Record[Idx++];
3998 bool FoundElse = Record[Idx++];
3999 ConditionalStack.push_back(
4000 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4001 }
4002 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4003 }
4004 break;
4005
4006 case PP_COUNTER_VALUE:
4007 if (!Record.empty() && Listener)
4008 Listener->ReadCounter(F, Record[0]);
4009 break;
4010
4011 case FILE_SORTED_DECLS:
4012 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4014 break;
4015
4017 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4019 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4021 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4022 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4023 SLocSpaceSize);
4024 if (!F.SLocEntryBaseID) {
4025 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4026 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4027 return llvm::createStringError(std::errc::invalid_argument,
4028 "ran out of source locations");
4029 }
4030 // Make our entry in the range map. BaseID is negative and growing, so
4031 // we invert it. Because we invert it, though, we need the other end of
4032 // the range.
4033 unsigned RangeStart =
4035 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4037
4038 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4039 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4040 GlobalSLocOffsetMap.insert(
4041 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4042 - SLocSpaceSize,&F));
4043
4044 TotalNumSLocEntries += F.LocalNumSLocEntries;
4045 break;
4046 }
4047
4048 case MODULE_OFFSET_MAP:
4049 F.ModuleOffsetMap = Blob;
4050 break;
4051
4053 ParseLineTable(F, Record);
4054 break;
4055
4056 case EXT_VECTOR_DECLS:
4057 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4058 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4059 break;
4060
4061 case VTABLE_USES:
4062 if (Record.size() % 3 != 0)
4063 return llvm::createStringError(std::errc::illegal_byte_sequence,
4064 "Invalid VTABLE_USES record");
4065
4066 // Later tables overwrite earlier ones.
4067 // FIXME: Modules will have some trouble with this. This is clearly not
4068 // the right way to do this.
4069 VTableUses.clear();
4070
4071 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4072 VTableUses.push_back(
4073 {ReadDeclID(F, Record, Idx),
4074 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4075 (bool)Record[Idx++]});
4076 }
4077 break;
4078
4080
4081 if (Record.size() % 2 != 0)
4082 return llvm::createStringError(
4083 std::errc::illegal_byte_sequence,
4084 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4085
4086 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4087 PendingInstantiations.push_back(
4088 {ReadDeclID(F, Record, I),
4089 ReadSourceLocation(F, Record, I).getRawEncoding()});
4090 }
4091 break;
4092
4093 case SEMA_DECL_REFS:
4094 if (Record.size() != 3)
4095 return llvm::createStringError(std::errc::illegal_byte_sequence,
4096 "Invalid SEMA_DECL_REFS block");
4097 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4098 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4099 break;
4100
4101 case PPD_ENTITIES_OFFSETS: {
4102 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4103 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4104 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4105
4106 unsigned LocalBasePreprocessedEntityID = Record[0];
4107
4108 unsigned StartingID;
4109 if (!PP.getPreprocessingRecord())
4110 PP.createPreprocessingRecord();
4111 if (!PP.getPreprocessingRecord()->getExternalSource())
4112 PP.getPreprocessingRecord()->SetExternalSource(*this);
4113 StartingID
4114 = PP.getPreprocessingRecord()
4115 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4116 F.BasePreprocessedEntityID = StartingID;
4117
4118 if (F.NumPreprocessedEntities > 0) {
4119 // Introduce the global -> local mapping for preprocessed entities in
4120 // this module.
4121 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4122
4123 // Introduce the local -> global mapping for preprocessed entities in
4124 // this module.
4126 std::make_pair(LocalBasePreprocessedEntityID,
4127 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
4128 }
4129
4130 break;
4131 }
4132
4133 case PPD_SKIPPED_RANGES: {
4134 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4135 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4136 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4137
4138 if (!PP.getPreprocessingRecord())
4139 PP.createPreprocessingRecord();
4140 if (!PP.getPreprocessingRecord()->getExternalSource())
4141 PP.getPreprocessingRecord()->SetExternalSource(*this);
4142 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4143 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4144
4146 GlobalSkippedRangeMap.insert(
4147 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4148 break;
4149 }
4150
4152 if (Record.size() % 2 != 0)
4153 return llvm::createStringError(
4154 std::errc::illegal_byte_sequence,
4155 "invalid DECL_UPDATE_OFFSETS block in AST file");
4156 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4157 GlobalDeclID ID = ReadDeclID(F, Record, I);
4158 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4159
4160 // If we've already loaded the decl, perform the updates when we finish
4161 // loading this block.
4162 if (Decl *D = GetExistingDecl(ID))
4163 PendingUpdateRecords.push_back(
4164 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4165 }
4166 break;
4167
4169 if (Record.size() % 5 != 0)
4170 return llvm::createStringError(
4171 std::errc::illegal_byte_sequence,
4172 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4173 "file");
4174 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4175 GlobalDeclID ID = ReadDeclID(F, Record, I);
4176
4177 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4178 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4179 uint64_t LocalLexicalOffset = Record[I++];
4180 uint64_t LexicalOffset =
4181 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4182 uint64_t LocalVisibleOffset = Record[I++];
4183 uint64_t VisibleOffset =
4184 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4185 uint64_t LocalModuleLocalOffset = Record[I++];
4186 uint64_t ModuleLocalOffset =
4187 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4188 uint64_t TULocalLocalOffset = Record[I++];
4189 uint64_t TULocalOffset =
4190 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4191
4192 DelayedNamespaceOffsetMap[ID] = {
4193 {VisibleOffset, TULocalOffset, ModuleLocalOffset}, LexicalOffset};
4194
4195 assert(!GetExistingDecl(ID) &&
4196 "We shouldn't load the namespace in the front of delayed "
4197 "namespace lexical and visible block");
4198 }
4199 break;
4200 }
4201
4202 case RELATED_DECLS_MAP:
4203 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4204 GlobalDeclID ID = ReadDeclID(F, Record, I);
4205 auto &RelatedDecls = RelatedDeclsMap[ID];
4206 unsigned NN = Record[I++];
4207 RelatedDecls.reserve(NN);
4208 for (unsigned II = 0; II < NN; II++)
4209 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4210 }
4211 break;
4212
4214 if (F.LocalNumObjCCategoriesInMap != 0)
4215 return llvm::createStringError(
4216 std::errc::illegal_byte_sequence,
4217 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4218
4220 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4221 break;
4222
4223 case OBJC_CATEGORIES:
4224 F.ObjCCategories.swap(Record);
4225 break;
4226
4228 // Later tables overwrite earlier ones.
4229 // FIXME: Modules will have trouble with this.
4230 CUDASpecialDeclRefs.clear();
4231 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4232 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4233 break;
4234
4236 F.HeaderFileInfoTableData = Blob.data();
4238 if (Record[0]) {
4239 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4240 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4241 (const unsigned char *)F.HeaderFileInfoTableData,
4242 HeaderFileInfoTrait(*this, F));
4243
4244 PP.getHeaderSearchInfo().SetExternalSource(this);
4245 if (!PP.getHeaderSearchInfo().getExternalLookup())
4246 PP.getHeaderSearchInfo().SetExternalLookup(this);
4247 }
4248 break;
4249
4250 case FP_PRAGMA_OPTIONS:
4251 // Later tables overwrite earlier ones.
4252 FPPragmaOptions.swap(Record);
4253 break;
4254
4256 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4257 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4258 break;
4259
4260 case OPENCL_EXTENSIONS:
4261 for (unsigned I = 0, E = Record.size(); I != E; ) {
4262 auto Name = ReadString(Record, I);
4263 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4264 OptInfo.Supported = Record[I++] != 0;
4265 OptInfo.Enabled = Record[I++] != 0;
4266 OptInfo.WithPragma = Record[I++] != 0;
4267 OptInfo.Avail = Record[I++];
4268 OptInfo.Core = Record[I++];
4269 OptInfo.Opt = Record[I++];
4270 }
4271 break;
4272
4274 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4275 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4276 break;
4277
4278 case KNOWN_NAMESPACES:
4279 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4280 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4281 break;
4282
4283 case UNDEFINED_BUT_USED:
4284 if (Record.size() % 2 != 0)
4285 return llvm::createStringError(std::errc::illegal_byte_sequence,
4286 "invalid undefined-but-used record");
4287 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4288 UndefinedButUsed.push_back(
4289 {ReadDeclID(F, Record, I),
4290 ReadSourceLocation(F, Record, I).getRawEncoding()});
4291 }
4292 break;
4293
4295 for (unsigned I = 0, N = Record.size(); I != N;) {
4296 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4297 const uint64_t Count = Record[I++];
4298 DelayedDeleteExprs.push_back(Count);
4299 for (uint64_t C = 0; C < Count; ++C) {
4300 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4301 bool IsArrayForm = Record[I++] == 1;
4302 DelayedDeleteExprs.push_back(IsArrayForm);
4303 }
4304 }
4305 break;
4306
4307 case VTABLES_TO_EMIT:
4308 if (F.Kind == MK_MainFile ||
4309 getContext().getLangOpts().BuildingPCHWithObjectFile)
4310 for (unsigned I = 0, N = Record.size(); I != N;)
4311 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4312 break;
4313
4314 case IMPORTED_MODULES:
4315 if (!F.isModule()) {
4316 // If we aren't loading a module (which has its own exports), make
4317 // all of the imported modules visible.
4318 // FIXME: Deal with macros-only imports.
4319 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4320 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4321 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4322 if (GlobalID) {
4323 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4324 if (DeserializationListener)
4325 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4326 }
4327 }
4328 }
4329 break;
4330
4331 case MACRO_OFFSET: {
4332 if (F.LocalNumMacros != 0)
4333 return llvm::createStringError(
4334 std::errc::illegal_byte_sequence,
4335 "duplicate MACRO_OFFSET record in AST file");
4336 F.MacroOffsets = (const uint32_t *)Blob.data();
4337 F.LocalNumMacros = Record[0];
4338 unsigned LocalBaseMacroID = Record[1];
4340 F.BaseMacroID = getTotalNumMacros();
4341
4342 if (F.LocalNumMacros > 0) {
4343 // Introduce the global -> local mapping for macros within this module.
4344 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
4345
4346 // Introduce the local -> global mapping for macros within this module.
4348 std::make_pair(LocalBaseMacroID,
4349 F.BaseMacroID - LocalBaseMacroID));
4350
4351 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4352 }
4353 break;
4354 }
4355
4357 LateParsedTemplates.emplace_back(
4358 std::piecewise_construct, std::forward_as_tuple(&F),
4359 std::forward_as_tuple(Record.begin(), Record.end()));
4360 break;
4361
4363 if (Record.size() != 1)
4364 return llvm::createStringError(std::errc::illegal_byte_sequence,
4365 "invalid pragma optimize record");
4366 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4367 break;
4368
4370 if (Record.size() != 1)
4371 return llvm::createStringError(std::errc::illegal_byte_sequence,
4372 "invalid pragma ms_struct record");
4373 PragmaMSStructState = Record[0];
4374 break;
4375
4377 if (Record.size() != 2)
4378 return llvm::createStringError(
4379 std::errc::illegal_byte_sequence,
4380 "invalid pragma pointers to members record");
4381 PragmaMSPointersToMembersState = Record[0];
4382 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4383 break;
4384
4386 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4387 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4388 break;
4389
4391 if (Record.size() != 1)
4392 return llvm::createStringError(std::errc::illegal_byte_sequence,
4393 "invalid cuda pragma options record");
4394 ForceHostDeviceDepth = Record[0];
4395 break;
4396
4398 if (Record.size() < 3)
4399 return llvm::createStringError(std::errc::illegal_byte_sequence,
4400 "invalid pragma pack record");
4401 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4402 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4403 unsigned NumStackEntries = Record[2];
4404 unsigned Idx = 3;
4405 // Reset the stack when importing a new module.
4406 PragmaAlignPackStack.clear();
4407 for (unsigned I = 0; I < NumStackEntries; ++I) {
4408 PragmaAlignPackStackEntry Entry;
4409 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4410 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4411 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4412 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4413 Entry.SlotLabel = PragmaAlignPackStrings.back();
4414 PragmaAlignPackStack.push_back(Entry);
4415 }
4416 break;
4417 }
4418
4420 if (Record.size() < 3)
4421 return llvm::createStringError(std::errc::illegal_byte_sequence,
4422 "invalid pragma float control record");
4423 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4424 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4425 unsigned NumStackEntries = Record[2];
4426 unsigned Idx = 3;
4427 // Reset the stack when importing a new module.
4428 FpPragmaStack.clear();
4429 for (unsigned I = 0; I < NumStackEntries; ++I) {
4430 FpPragmaStackEntry Entry;
4431 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4432 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4433 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4434 FpPragmaStrings.push_back(ReadString(Record, Idx));
4435 Entry.SlotLabel = FpPragmaStrings.back();
4436 FpPragmaStack.push_back(Entry);
4437 }
4438 break;
4439 }
4440
4442 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4443 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4444 break;
4445 }
4446 }
4447}
4448
4449void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4450 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4451
4452 // Additional remapping information.
4453 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4454 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4455 F.ModuleOffsetMap = StringRef();
4456
4458 RemapBuilder MacroRemap(F.MacroRemap);
4459 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4460 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4461 RemapBuilder SelectorRemap(F.SelectorRemap);
4462
4463 auto &ImportedModuleVector = F.TransitiveImports;
4464 assert(ImportedModuleVector.empty());
4465
4466 while (Data < DataEnd) {
4467 // FIXME: Looking up dependency modules by filename is horrible. Let's
4468 // start fixing this with prebuilt, explicit and implicit modules and see
4469 // how it goes...
4470 using namespace llvm::support;
4471 ModuleKind Kind = static_cast<ModuleKind>(
4472 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4473 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4474 StringRef Name = StringRef((const char*)Data, Len);
4475 Data += Len;
4478 ? ModuleMgr.lookupByModuleName(Name)
4479 : ModuleMgr.lookupByFileName(Name));
4480 if (!OM) {
4481 std::string Msg = "refers to unknown module, cannot find ";
4482 Msg.append(std::string(Name));
4483 Error(Msg);
4484 return;
4485 }
4486
4487 ImportedModuleVector.push_back(OM);
4488
4489 uint32_t MacroIDOffset =
4490 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4491 uint32_t PreprocessedEntityIDOffset =
4492 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4493 uint32_t SubmoduleIDOffset =
4494 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4495 uint32_t SelectorIDOffset =
4496 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4497
4498 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4499 RemapBuilder &Remap) {
4500 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4501 if (Offset != None)
4502 Remap.insert(std::make_pair(Offset,
4503 static_cast<int>(BaseOffset - Offset)));
4504 };
4505
4506 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4507 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4508 PreprocessedEntityRemap);
4509 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4510 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4511 }
4512}
4513
4515ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4516 const ModuleFile *ImportedBy,
4517 unsigned ClientLoadCapabilities) {
4518 unsigned Idx = 0;
4519 F.ModuleMapPath = ReadPath(F, Record, Idx);
4520
4521 // Try to resolve ModuleName in the current header search context and
4522 // verify that it is found in the same module map file as we saved. If the
4523 // top-level AST file is a main file, skip this check because there is no
4524 // usable header search context.
4525 assert(!F.ModuleName.empty() &&
4526 "MODULE_NAME should come before MODULE_MAP_FILE");
4527 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4528 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4529 // An implicitly-loaded module file should have its module listed in some
4530 // module map file that we've already loaded.
4531 Module *M =
4532 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4533 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4534 OptionalFileEntryRef ModMap =
4535 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4536 // Don't emit module relocation error if we have -fno-validate-pch
4537 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4539 !ModMap) {
4540 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4541 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4542 // This module was defined by an imported (explicit) module.
4543 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4544 << ASTFE->getName();
4545 // TODO: Add a note with the module map paths if they differ.
4546 } else {
4547 // This module was built with a different module map.
4548 Diag(diag::err_imported_module_not_found)
4549 << F.ModuleName << F.FileName
4550 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4551 << !ImportedBy;
4552 // In case it was imported by a PCH, there's a chance the user is
4553 // just missing to include the search path to the directory containing
4554 // the modulemap.
4555 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4556 Diag(diag::note_imported_by_pch_module_not_found)
4557 << llvm::sys::path::parent_path(F.ModuleMapPath);
4558 }
4559 }
4560 return OutOfDate;
4561 }
4562
4563 assert(M && M->Name == F.ModuleName && "found module with different name");
4564
4565 // Check the primary module map file.
4566 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4567 if (!StoredModMap || *StoredModMap != ModMap) {
4568 assert(ModMap && "found module is missing module map file");
4569 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4570 "top-level import should be verified");
4571 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4572 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4573 Diag(diag::err_imported_module_modmap_changed)
4574 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4575 << ModMap->getName() << F.ModuleMapPath << NotImported;
4576 return OutOfDate;
4577 }
4578
4579 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4580 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4581 // FIXME: we should use input files rather than storing names.
4582 std::string Filename = ReadPath(F, Record, Idx);
4583 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4584 if (!SF) {
4585 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4586 Error("could not find file '" + Filename +"' referenced by AST file");
4587 return OutOfDate;
4588 }
4589 AdditionalStoredMaps.insert(*SF);
4590 }
4591
4592 // Check any additional module map files (e.g. module.private.modulemap)
4593 // that are not in the pcm.
4594 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4595 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4596 // Remove files that match
4597 // Note: SmallPtrSet::erase is really remove
4598 if (!AdditionalStoredMaps.erase(ModMap)) {
4599 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4600 Diag(diag::err_module_different_modmap)
4601 << F.ModuleName << /*new*/0 << ModMap.getName();
4602 return OutOfDate;
4603 }
4604 }
4605 }
4606
4607 // Check any additional module map files that are in the pcm, but not
4608 // found in header search. Cases that match are already removed.
4609 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4610 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4611 Diag(diag::err_module_different_modmap)
4612 << F.ModuleName << /*not new*/1 << ModMap.getName();
4613 return OutOfDate;
4614 }
4615 }
4616
4617 if (Listener)
4618 Listener->ReadModuleMapFile(F.ModuleMapPath);
4619 return Success;
4620}
4621
4622/// Move the given method to the back of the global list of methods.
4624 // Find the entry for this selector in the method pool.
4625 SemaObjC::GlobalMethodPool::iterator Known =
4626 S.ObjC().MethodPool.find(Method->getSelector());
4627 if (Known == S.ObjC().MethodPool.end())
4628 return;
4629
4630 // Retrieve the appropriate method list.
4631 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4632 : Known->second.second;
4633 bool Found = false;
4634 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4635 if (!Found) {
4636 if (List->getMethod() == Method) {
4637 Found = true;
4638 } else {
4639 // Keep searching.
4640 continue;
4641 }
4642 }
4643
4644 if (List->getNext())
4645 List->setMethod(List->getNext()->getMethod());
4646 else
4647 List->setMethod(Method);
4648 }
4649}
4650
4652 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4653 for (Decl *D : Names) {
4654 bool wasHidden = !D->isUnconditionallyVisible();
4656
4657 if (wasHidden && SemaObj) {
4658 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4660 }
4661 }
4662 }
4663}
4664
4666 Module::NameVisibilityKind NameVisibility,
4667 SourceLocation ImportLoc) {
4670 Stack.push_back(Mod);
4671 while (!Stack.empty()) {
4672 Mod = Stack.pop_back_val();
4673
4674 if (NameVisibility <= Mod->NameVisibility) {
4675 // This module already has this level of visibility (or greater), so
4676 // there is nothing more to do.
4677 continue;
4678 }
4679
4680 if (Mod->isUnimportable()) {
4681 // Modules that aren't importable cannot be made visible.
4682 continue;
4683 }
4684
4685 // Update the module's name visibility.
4686 Mod->NameVisibility = NameVisibility;
4687
4688 // If we've already deserialized any names from this module,
4689 // mark them as visible.
4690 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4691 if (Hidden != HiddenNamesMap.end()) {
4692 auto HiddenNames = std::move(*Hidden);
4693 HiddenNamesMap.erase(Hidden);
4694 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4695 assert(!HiddenNamesMap.contains(Mod) &&
4696 "making names visible added hidden names");
4697 }
4698
4699 // Push any exported modules onto the stack to be marked as visible.
4701 Mod->getExportedModules(Exports);
4703 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4704 Module *Exported = *I;
4705 if (Visited.insert(Exported).second)
4706 Stack.push_back(Exported);
4707 }
4708 }
4709}
4710
4711/// We've merged the definition \p MergedDef into the existing definition
4712/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4713/// visible.
4715 NamedDecl *MergedDef) {
4716 if (!Def->isUnconditionallyVisible()) {
4717 // If MergedDef is visible or becomes visible, make the definition visible.
4718 if (MergedDef->isUnconditionallyVisible())
4720 else {
4721 getContext().mergeDefinitionIntoModule(
4722 Def, MergedDef->getImportedOwningModule(),
4723 /*NotifyListeners*/ false);
4724 PendingMergedDefinitionsToDeduplicate.insert(Def);
4725 }
4726 }
4727}
4728
4730 if (GlobalIndex)
4731 return false;
4732
4733 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4734 !PP.getLangOpts().Modules)
4735 return true;
4736
4737 // Try to load the global index.
4738 TriedLoadingGlobalIndex = true;
4739 StringRef ModuleCachePath
4740 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4741 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4742 GlobalModuleIndex::readIndex(ModuleCachePath);
4743 if (llvm::Error Err = std::move(Result.second)) {
4744 assert(!Result.first);
4745 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4746 return true;
4747 }
4748
4749 GlobalIndex.reset(Result.first);
4750 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4751 return false;
4752}
4753
4755 return PP.getLangOpts().Modules && UseGlobalIndex &&
4756 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4757}
4758
4759/// Given a cursor at the start of an AST file, scan ahead and drop the
4760/// cursor into the start of the given block ID, returning false on success and
4761/// true on failure.
4762static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4763 while (true) {
4764 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4765 if (!MaybeEntry) {
4766 // FIXME this drops errors on the floor.
4767 consumeError(MaybeEntry.takeError());
4768 return true;
4769 }
4770 llvm::BitstreamEntry Entry = MaybeEntry.get();
4771
4772 switch (Entry.Kind) {
4773 case llvm::BitstreamEntry::Error:
4774 case llvm::BitstreamEntry::EndBlock:
4775 return true;
4776
4777 case llvm::BitstreamEntry::Record:
4778 // Ignore top-level records.
4779 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4780 break;
4781 else {
4782 // FIXME this drops errors on the floor.
4783 consumeError(Skipped.takeError());
4784 return true;
4785 }
4786
4787 case llvm::BitstreamEntry::SubBlock:
4788 if (Entry.ID == BlockID) {
4789 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4790 // FIXME this drops the error on the floor.
4791 consumeError(std::move(Err));
4792 return true;
4793 }
4794 // Found it!
4795 return false;
4796 }
4797
4798 if (llvm::Error Err = Cursor.SkipBlock()) {
4799 // FIXME this drops the error on the floor.
4800 consumeError(std::move(Err));
4801 return true;
4802 }
4803 }
4804 }
4805}
4806
4808 SourceLocation ImportLoc,
4809 unsigned ClientLoadCapabilities,
4810 ModuleFile **NewLoadedModuleFile) {
4811 llvm::TimeTraceScope scope("ReadAST", FileName);
4812
4813 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4815 CurrentDeserializingModuleKind, Type);
4816
4817 // Defer any pending actions until we get to the end of reading the AST file.
4818 Deserializing AnASTFile(this);
4819
4820 // Bump the generation number.
4821 unsigned PreviousGeneration = 0;
4822 if (ContextObj)
4823 PreviousGeneration = incrementGeneration(*ContextObj);
4824
4825 unsigned NumModules = ModuleMgr.size();
4827 if (ASTReadResult ReadResult =
4828 ReadASTCore(FileName, Type, ImportLoc,
4829 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4830 ClientLoadCapabilities)) {
4831 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4832
4833 // If we find that any modules are unusable, the global index is going
4834 // to be out-of-date. Just remove it.
4835 GlobalIndex.reset();
4836 ModuleMgr.setGlobalIndex(nullptr);
4837 return ReadResult;
4838 }
4839
4840 if (NewLoadedModuleFile && !Loaded.empty())
4841 *NewLoadedModuleFile = Loaded.back().Mod;
4842
4843 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4844 // remove modules from this point. Various fields are updated during reading
4845 // the AST block and removing the modules would result in dangling pointers.
4846 // They are generally only incidentally dereferenced, ie. a binary search
4847 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4848 // be dereferenced but it wouldn't actually be used.
4849
4850 // Load the AST blocks of all of the modules that we loaded. We can still
4851 // hit errors parsing the ASTs at this point.
4852 for (ImportedModule &M : Loaded) {
4853 ModuleFile &F = *M.Mod;
4854 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4855
4856 // Read the AST block.
4857 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4858 Error(std::move(Err));
4859 return Failure;
4860 }
4861
4862 // The AST block should always have a definition for the main module.
4863 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4864 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4865 return Failure;
4866 }
4867
4868 // Read the extension blocks.
4870 if (llvm::Error Err = ReadExtensionBlock(F)) {
4871 Error(std::move(Err));
4872 return Failure;
4873 }
4874 }
4875
4876 // Once read, set the ModuleFile bit base offset and update the size in
4877 // bits of all files we've seen.
4878 F.GlobalBitOffset = TotalModulesSizeInBits;
4879 TotalModulesSizeInBits += F.SizeInBits;
4880 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4881 }
4882
4883 // Preload source locations and interesting indentifiers.
4884 for (ImportedModule &M : Loaded) {
4885 ModuleFile &F = *M.Mod;
4886
4887 // Map the original source file ID into the ID space of the current
4888 // compilation.
4890 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4891
4892 for (auto Offset : F.PreloadIdentifierOffsets) {
4893 const unsigned char *Data = F.IdentifierTableData + Offset;
4894
4895 ASTIdentifierLookupTrait Trait(*this, F);
4896 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4897 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4898
4899 IdentifierInfo *II;
4900 if (!PP.getLangOpts().CPlusPlus) {
4901 // Identifiers present in both the module file and the importing
4902 // instance are marked out-of-date so that they can be deserialized
4903 // on next use via ASTReader::updateOutOfDateIdentifier().
4904 // Identifiers present in the module file but not in the importing
4905 // instance are ignored for now, preventing growth of the identifier
4906 // table. They will be deserialized on first use via ASTReader::get().
4907 auto It = PP.getIdentifierTable().find(Key);
4908 if (It == PP.getIdentifierTable().end())
4909 continue;
4910 II = It->second;
4911 } else {
4912 // With C++ modules, not many identifiers are considered interesting.
4913 // All identifiers in the module file can be placed into the identifier
4914 // table of the importing instance and marked as out-of-date. This makes
4915 // ASTReader::get() a no-op, and deserialization will take place on
4916 // first/next use via ASTReader::updateOutOfDateIdentifier().
4917 II = &PP.getIdentifierTable().getOwn(Key);
4918 }
4919
4920 II->setOutOfDate(true);
4921
4922 // Mark this identifier as being from an AST file so that we can track
4923 // whether we need to serialize it.
4924 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
4925
4926 // Associate the ID with the identifier so that the writer can reuse it.
4927 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4928 SetIdentifierInfo(ID, II);
4929 }
4930 }
4931
4932 // Builtins and library builtins have already been initialized. Mark all
4933 // identifiers as out-of-date, so that they are deserialized on first use.
4934 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4935 for (auto &Id : PP.getIdentifierTable())
4936 Id.second->setOutOfDate(true);
4937
4938 // Mark selectors as out of date.
4939 for (const auto &Sel : SelectorGeneration)
4940 SelectorOutOfDate[Sel.first] = true;
4941
4942 // Setup the import locations and notify the module manager that we've
4943 // committed to these module files.
4944 for (ImportedModule &M : Loaded) {
4945 ModuleFile &F = *M.Mod;
4946
4947 ModuleMgr.moduleFileAccepted(&F);
4948
4949 // Set the import location.
4950 F.DirectImportLoc = ImportLoc;
4951 // FIXME: We assume that locations from PCH / preamble do not need
4952 // any translation.
4953 if (!M.ImportedBy)
4954 F.ImportLoc = M.ImportLoc;
4955 else
4956 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4957 }
4958
4959 // Resolve any unresolved module exports.
4960 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4961 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4962 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4963 Module *ResolvedMod = getSubmodule(GlobalID);
4964
4965 switch (Unresolved.Kind) {
4966 case UnresolvedModuleRef::Conflict:
4967 if (ResolvedMod) {
4968 Module::Conflict Conflict;
4969 Conflict.Other = ResolvedMod;
4970 Conflict.Message = Unresolved.String.str();
4971 Unresolved.Mod->Conflicts.push_back(Conflict);
4972 }
4973 continue;
4974
4975 case UnresolvedModuleRef::Import:
4976 if (ResolvedMod)
4977 Unresolved.Mod->Imports.insert(ResolvedMod);
4978 continue;
4979
4980 case UnresolvedModuleRef::Affecting:
4981 if (ResolvedMod)
4982 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4983 continue;
4984
4985 case UnresolvedModuleRef::Export:
4986 if (ResolvedMod || Unresolved.IsWildcard)
4987 Unresolved.Mod->Exports.push_back(
4988 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4989 continue;
4990 }
4991 }
4992 UnresolvedModuleRefs.clear();
4993
4994 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4995 // Might be unnecessary as use declarations are only used to build the
4996 // module itself.
4997
4998 if (ContextObj)
4999 InitializeContext();
5000
5001 if (SemaObj)
5002 UpdateSema();
5003
5004 if (DeserializationListener)
5005 DeserializationListener->ReaderInitialized(this);
5006
5007 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5008 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5009 // If this AST file is a precompiled preamble, then set the
5010 // preamble file ID of the source manager to the file source file
5011 // from which the preamble was built.
5012 if (Type == MK_Preamble) {
5013 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5014 } else if (Type == MK_MainFile) {
5015 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5016 }
5017 }
5018
5019 // For any Objective-C class definitions we have already loaded, make sure
5020 // that we load any additional categories.
5021 if (ContextObj) {
5022 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5023 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5024 ObjCClassesLoaded[I], PreviousGeneration);
5025 }
5026 }
5027
5028 const HeaderSearchOptions &HSOpts =
5029 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5031 // Now we are certain that the module and all modules it depends on are
5032 // up-to-date. For implicitly-built module files, ensure the corresponding
5033 // timestamp files are up-to-date in this build session.
5034 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5035 ImportedModule &M = Loaded[I];
5036 if (M.Mod->Kind == MK_ImplicitModule &&
5037 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
5038 getModuleManager().getModuleCache().updateModuleTimestamp(
5039 M.Mod->FileName);
5040 }
5041 }
5042
5043 return Success;
5044}
5045
5046static ASTFileSignature readASTFileSignature(StringRef PCH);
5047
5048/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5049static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5050 // FIXME checking magic headers is done in other places such as
5051 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5052 // always done the same. Unify it all with a helper.
5053 if (!Stream.canSkipToPos(4))
5054 return llvm::createStringError(
5055 std::errc::illegal_byte_sequence,
5056 "file too small to contain precompiled file magic");
5057 for (unsigned C : {'C', 'P', 'C', 'H'})
5058 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5059 if (Res.get() != C)
5060 return llvm::createStringError(
5061 std::errc::illegal_byte_sequence,
5062 "file doesn't start with precompiled file magic");
5063 } else
5064 return Res.takeError();
5065 return llvm::Error::success();
5066}
5067
5069 switch (Kind) {
5070 case MK_PCH:
5071 return 0; // PCH
5072 case MK_ImplicitModule:
5073 case MK_ExplicitModule:
5074 case MK_PrebuiltModule:
5075 return 1; // module
5076 case MK_MainFile:
5077 case MK_Preamble:
5078 return 2; // main source file
5079 }
5080 llvm_unreachable("unknown module kind");
5081}
5082
5084ASTReader::ReadASTCore(StringRef FileName,
5086 SourceLocation ImportLoc,
5087 ModuleFile *ImportedBy,
5089 off_t ExpectedSize, time_t ExpectedModTime,
5090 ASTFileSignature ExpectedSignature,
5091 unsigned ClientLoadCapabilities) {
5092 ModuleFile *M;
5093 std::string ErrorStr;
5095 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
5096 getGeneration(), ExpectedSize, ExpectedModTime,
5097 ExpectedSignature, readASTFileSignature,
5098 M, ErrorStr);
5099
5100 switch (AddResult) {
5102 Diag(diag::remark_module_import)
5103 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5104 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5105 return Success;
5106
5108 // Load module file below.
5109 break;
5110
5112 // The module file was missing; if the client can handle that, return
5113 // it.
5114 if (ClientLoadCapabilities & ARR_Missing)
5115 return Missing;
5116
5117 // Otherwise, return an error.
5118 Diag(diag::err_ast_file_not_found)
5119 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5120 << ErrorStr;
5121 return Failure;
5122
5124 // We couldn't load the module file because it is out-of-date. If the
5125 // client can handle out-of-date, return it.
5126 if (ClientLoadCapabilities & ARR_OutOfDate)
5127 return OutOfDate;
5128
5129 // Otherwise, return an error.
5130 Diag(diag::err_ast_file_out_of_date)
5131 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5132 << ErrorStr;
5133 return Failure;
5134 }
5135
5136 assert(M && "Missing module file");
5137
5138 bool ShouldFinalizePCM = false;
5139 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
5140 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5141 if (ShouldFinalizePCM)
5142 MC.finalizePCM(FileName);
5143 else
5144 MC.tryToDropPCM(FileName);
5145 });
5146 ModuleFile &F = *M;
5147 BitstreamCursor &Stream = F.Stream;
5148 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5149 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5150
5151 // Sniff for the signature.
5152 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5153 Diag(diag::err_ast_file_invalid)
5154 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5155 return Failure;
5156 }
5157
5158 // This is used for compatibility with older PCH formats.
5159 bool HaveReadControlBlock = false;
5160 while (true) {
5161 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5162 if (!MaybeEntry) {
5163 Error(MaybeEntry.takeError());
5164 return Failure;
5165 }
5166 llvm::BitstreamEntry Entry = MaybeEntry.get();
5167
5168 switch (Entry.Kind) {
5169 case llvm::BitstreamEntry::Error:
5170 case llvm::BitstreamEntry::Record:
5171 case llvm::BitstreamEntry::EndBlock:
5172 Error("invalid record at top-level of AST file");
5173 return Failure;
5174
5175 case llvm::BitstreamEntry::SubBlock:
5176 break;
5177 }
5178
5179 switch (Entry.ID) {
5180 case CONTROL_BLOCK_ID:
5181 HaveReadControlBlock = true;
5182 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5183 case Success:
5184 // Check that we didn't try to load a non-module AST file as a module.
5185 //
5186 // FIXME: Should we also perform the converse check? Loading a module as
5187 // a PCH file sort of works, but it's a bit wonky.
5189 Type == MK_PrebuiltModule) &&
5190 F.ModuleName.empty()) {
5191 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
5192 if (Result != OutOfDate ||
5193 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5194 Diag(diag::err_module_file_not_module) << FileName;
5195 return Result;
5196 }
5197 break;
5198
5199 case Failure: return Failure;
5200 case Missing: return Missing;
5201 case OutOfDate: return OutOfDate;
5202 case VersionMismatch: return VersionMismatch;
5203 case ConfigurationMismatch: return ConfigurationMismatch;
5204 case HadErrors: return HadErrors;
5205 }
5206 break;
5207
5208 case AST_BLOCK_ID:
5209 if (!HaveReadControlBlock) {
5210 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5211 Diag(diag::err_ast_file_version_too_old)
5213 return VersionMismatch;
5214 }
5215
5216 // Record that we've loaded this module.
5217 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5218 ShouldFinalizePCM = true;
5219 return Success;
5220
5221 default:
5222 if (llvm::Error Err = Stream.SkipBlock()) {
5223 Error(std::move(Err));
5224 return Failure;
5225 }
5226 break;
5227 }
5228 }
5229
5230 llvm_unreachable("unexpected break; expected return");
5231}
5232
5234ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5235 unsigned ClientLoadCapabilities) {
5236 const HeaderSearchOptions &HSOpts =
5237 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5238 bool AllowCompatibleConfigurationMismatch =
5240 bool DisableValidation = shouldDisableValidationForFile(F);
5241
5242 ASTReadResult Result = readUnhashedControlBlockImpl(
5243 &F, F.Data, F.FileName, ClientLoadCapabilities,
5244 AllowCompatibleConfigurationMismatch, Listener.get(),
5245 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5246
5247 // If F was directly imported by another module, it's implicitly validated by
5248 // the importing module.
5249 if (DisableValidation || WasImportedBy ||
5250 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5251 return Success;
5252
5253 if (Result == Failure) {
5254 Error("malformed block record in AST file");
5255 return Failure;
5256 }
5257
5258 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5259 // If this module has already been finalized in the ModuleCache, we're stuck
5260 // with it; we can only load a single version of each module.
5261 //
5262 // This can happen when a module is imported in two contexts: in one, as a
5263 // user module; in another, as a system module (due to an import from
5264 // another module marked with the [system] flag). It usually indicates a
5265 // bug in the module map: this module should also be marked with [system].
5266 //
5267 // If -Wno-system-headers (the default), and the first import is as a
5268 // system module, then validation will fail during the as-user import,
5269 // since -Werror flags won't have been validated. However, it's reasonable
5270 // to treat this consistently as a system module.
5271 //
5272 // If -Wsystem-headers, the PCM on disk was built with
5273 // -Wno-system-headers, and the first import is as a user module, then
5274 // validation will fail during the as-system import since the PCM on disk
5275 // doesn't guarantee that -Werror was respected. However, the -Werror
5276 // flags were checked during the initial as-user import.
5277 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5278 F.FileName)) {
5279 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5280 return Success;
5281 }
5282 }
5283
5284 return Result;
5285}
5286
5287ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5288 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5289 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5290 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5291 // Initialize a stream.
5292 BitstreamCursor Stream(StreamData);
5293
5294 // Sniff for the signature.
5295 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5296 // FIXME this drops the error on the floor.
5297 consumeError(std::move(Err));
5298 return Failure;
5299 }
5300
5301 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5303 return Failure;
5304
5305 // Read all of the records in the options block.
5306 RecordData Record;
5307 ASTReadResult Result = Success;
5308 while (true) {
5309 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5310 if (!MaybeEntry) {
5311 // FIXME this drops the error on the floor.
5312 consumeError(MaybeEntry.takeError());
5313 return Failure;
5314 }
5315 llvm::BitstreamEntry Entry = MaybeEntry.get();
5316
5317 switch (Entry.Kind) {
5318 case llvm::BitstreamEntry::Error:
5319 case llvm::BitstreamEntry::SubBlock:
5320 return Failure;
5321
5322 case llvm::BitstreamEntry::EndBlock:
5323 return Result;
5324
5325 case llvm::BitstreamEntry::Record:
5326 // The interesting case.
5327 break;
5328 }
5329
5330 // Read and process a record.
5331 Record.clear();
5332 StringRef Blob;
5333 Expected<unsigned> MaybeRecordType =
5334 Stream.readRecord(Entry.ID, Record, &Blob);
5335 if (!MaybeRecordType) {
5336 // FIXME this drops the error.
5337 return Failure;
5338 }
5339 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5340 case SIGNATURE:
5341 if (F) {
5342 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5344 "Dummy AST file signature not backpatched in ASTWriter.");
5345 }
5346 break;
5347 case AST_BLOCK_HASH:
5348 if (F) {
5349 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5351 "Dummy AST block hash not backpatched in ASTWriter.");
5352 }
5353 break;
5354 case DIAGNOSTIC_OPTIONS: {
5355 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5356 if (Listener && ValidateDiagnosticOptions &&
5357 !AllowCompatibleConfigurationMismatch &&
5358 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5359 Result = OutOfDate; // Don't return early. Read the signature.
5360 break;
5361 }
5362 case HEADER_SEARCH_PATHS: {
5363 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5364 if (Listener && !AllowCompatibleConfigurationMismatch &&
5365 ParseHeaderSearchPaths(Record, Complain, *Listener))
5366 Result = ConfigurationMismatch;
5367 break;
5368 }
5370 if (!F)
5371 break;
5372 if (F->PragmaDiagMappings.empty())
5373 F->PragmaDiagMappings.swap(Record);
5374 else
5375 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5376 Record.begin(), Record.end());
5377 break;
5379 if (F)
5380 F->SearchPathUsage = ReadBitVector(Record, Blob);
5381 break;
5382 case VFS_USAGE:
5383 if (F)
5384 F->VFSUsage = ReadBitVector(Record, Blob);
5385 break;
5386 }
5387 }
5388}
5389
5390/// Parse a record and blob containing module file extension metadata.
5393 StringRef Blob,
5394 ModuleFileExtensionMetadata &Metadata) {
5395 if (Record.size() < 4) return true;
5396
5397 Metadata.MajorVersion = Record[0];
5398 Metadata.MinorVersion = Record[1];
5399
5400 unsigned BlockNameLen = Record[2];
5401 unsigned UserInfoLen = Record[3];
5402
5403 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5404
5405 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5406 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5407 Blob.data() + BlockNameLen + UserInfoLen);
5408 return false;
5409}
5410
5411llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5412 BitstreamCursor &Stream = F.Stream;
5413
5414 RecordData Record;
5415 while (true) {
5416 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5417 if (!MaybeEntry)
5418 return MaybeEntry.takeError();
5419 llvm::BitstreamEntry Entry = MaybeEntry.get();
5420
5421 switch (Entry.Kind) {
5422 case llvm::BitstreamEntry::SubBlock:
5423 if (llvm::Error Err = Stream.SkipBlock())
5424 return Err;
5425 continue;
5426 case llvm::BitstreamEntry::EndBlock:
5427 return llvm::Error::success();
5428 case llvm::BitstreamEntry::Error:
5429 return llvm::createStringError(std::errc::illegal_byte_sequence,
5430 "malformed block record in AST file");
5431 case llvm::BitstreamEntry::Record:
5432 break;
5433 }
5434
5435 Record.clear();
5436 StringRef Blob;
5437 Expected<unsigned> MaybeRecCode =
5438 Stream.readRecord(Entry.ID, Record, &Blob);
5439 if (!MaybeRecCode)
5440 return MaybeRecCode.takeError();
5441 switch (MaybeRecCode.get()) {
5442 case EXTENSION_METADATA: {
5444 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5445 return llvm::createStringError(
5446 std::errc::illegal_byte_sequence,
5447 "malformed EXTENSION_METADATA in AST file");
5448
5449 // Find a module file extension with this block name.
5450 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5451 if (Known == ModuleFileExtensions.end()) break;
5452
5453 // Form a reader.
5454 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5455 F, Stream)) {
5456 F.ExtensionReaders.push_back(std::move(Reader));
5457 }
5458
5459 break;
5460 }
5461 }
5462 }
5463
5464 llvm_unreachable("ReadExtensionBlock should return from while loop");
5465}
5466
5468 assert(ContextObj && "no context to initialize");
5469 ASTContext &Context = *ContextObj;
5470
5471 // If there's a listener, notify them that we "read" the translation unit.
5472 if (DeserializationListener)
5473 DeserializationListener->DeclRead(
5475 Context.getTranslationUnitDecl());
5476
5477 // FIXME: Find a better way to deal with collisions between these
5478 // built-in types. Right now, we just ignore the problem.
5479
5480 // Load the special types.
5481 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5482 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5483 if (!Context.CFConstantStringTypeDecl)
5484 Context.setCFConstantStringType(GetType(String));
5485 }
5486
5487 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5488 QualType FileType = GetType(File);
5489 if (FileType.isNull()) {
5490 Error("FILE type is NULL");
5491 return;
5492 }
5493
5494 if (!Context.FILEDecl) {
5495 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5496 Context.setFILEDecl(Typedef->getDecl());
5497 else {
5498 const TagType *Tag = FileType->getAs<TagType>();
5499 if (!Tag) {
5500 Error("Invalid FILE type in AST file");
5501 return;
5502 }
5503 Context.setFILEDecl(Tag->getOriginalDecl());
5504 }
5505 }
5506 }
5507
5508 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5509 QualType Jmp_bufType = GetType(Jmp_buf);
5510 if (Jmp_bufType.isNull()) {
5511 Error("jmp_buf type is NULL");
5512 return;
5513 }
5514
5515 if (!Context.jmp_bufDecl) {
5516 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5517 Context.setjmp_bufDecl(Typedef->getDecl());
5518 else {
5519 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5520 if (!Tag) {
5521 Error("Invalid jmp_buf type in AST file");
5522 return;
5523 }
5524 Context.setjmp_bufDecl(Tag->getOriginalDecl());
5525 }
5526 }
5527 }
5528
5529 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5530 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5531 if (Sigjmp_bufType.isNull()) {
5532 Error("sigjmp_buf type is NULL");
5533 return;
5534 }
5535
5536 if (!Context.sigjmp_bufDecl) {
5537 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5538 Context.setsigjmp_bufDecl(Typedef->getDecl());
5539 else {
5540 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5541 assert(Tag && "Invalid sigjmp_buf type in AST file");
5542 Context.setsigjmp_bufDecl(Tag->getOriginalDecl());
5543 }
5544 }
5545 }
5546
5547 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5548 if (Context.ObjCIdRedefinitionType.isNull())
5549 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5550 }
5551
5552 if (TypeID ObjCClassRedef =
5554 if (Context.ObjCClassRedefinitionType.isNull())
5555 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5556 }
5557
5558 if (TypeID ObjCSelRedef =
5559 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5560 if (Context.ObjCSelRedefinitionType.isNull())
5561 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5562 }
5563
5564 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5565 QualType Ucontext_tType = GetType(Ucontext_t);
5566 if (Ucontext_tType.isNull()) {
5567 Error("ucontext_t type is NULL");
5568 return;
5569 }
5570
5571 if (!Context.ucontext_tDecl) {
5572 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5573 Context.setucontext_tDecl(Typedef->getDecl());
5574 else {
5575 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5576 assert(Tag && "Invalid ucontext_t type in AST file");
5577 Context.setucontext_tDecl(Tag->getOriginalDecl());
5578 }
5579 }
5580 }
5581 }
5582
5583 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5584
5585 // If there were any CUDA special declarations, deserialize them.
5586 if (!CUDASpecialDeclRefs.empty()) {
5587 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5589 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5590 }
5591
5592 // Re-export any modules that were imported by a non-module AST file.
5593 // FIXME: This does not make macro-only imports visible again.
5594 for (auto &Import : PendingImportedModules) {
5595 if (Module *Imported = getSubmodule(Import.ID)) {
5596 makeModuleVisible(Imported, Module::AllVisible,
5597 /*ImportLoc=*/Import.ImportLoc);
5598 if (Import.ImportLoc.isValid())
5599 PP.makeModuleVisible(Imported, Import.ImportLoc);
5600 // This updates visibility for Preprocessor only. For Sema, which can be
5601 // nullptr here, we do the same later, in UpdateSema().
5602 }
5603 }
5604
5605 // Hand off these modules to Sema.
5606 PendingImportedModulesSema.append(PendingImportedModules);
5607 PendingImportedModules.clear();
5608}
5609
5611 // Nothing to do for now.
5612}
5613
5614/// Reads and return the signature record from \p PCH's control block, or
5615/// else returns 0.
5617 BitstreamCursor Stream(PCH);
5618 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5619 // FIXME this drops the error on the floor.
5620 consumeError(std::move(Err));
5621 return ASTFileSignature();
5622 }
5623
5624 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5626 return ASTFileSignature();
5627
5628 // Scan for SIGNATURE inside the diagnostic options block.
5630 while (true) {
5632 Stream.advanceSkippingSubblocks();
5633 if (!MaybeEntry) {
5634 // FIXME this drops the error on the floor.
5635 consumeError(MaybeEntry.takeError());
5636 return ASTFileSignature();
5637 }
5638 llvm::BitstreamEntry Entry = MaybeEntry.get();
5639
5640 if (Entry.Kind != llvm::BitstreamEntry::Record)
5641 return ASTFileSignature();
5642
5643 Record.clear();
5644 StringRef Blob;
5645 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5646 if (!MaybeRecord) {
5647 // FIXME this drops the error on the floor.
5648 consumeError(MaybeRecord.takeError());
5649 return ASTFileSignature();
5650 }
5651 if (SIGNATURE == MaybeRecord.get()) {
5652 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5653 assert(Signature != ASTFileSignature::createDummy() &&
5654 "Dummy AST file signature not backpatched in ASTWriter.");
5655 return Signature;
5656 }
5657 }
5658}
5659
5660/// Retrieve the name of the original source file name
5661/// directly from the AST file, without actually loading the AST
5662/// file.
5664 const std::string &ASTFileName, FileManager &FileMgr,
5665 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5666 // Open the AST file.
5667 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5668 /*RequiresNullTerminator=*/false,
5669 /*MaybeLimit=*/std::nullopt,
5670 /*IsText=*/false);
5671 if (!Buffer) {
5672 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5673 << ASTFileName << Buffer.getError().message();
5674 return std::string();
5675 }
5676
5677 // Initialize the stream
5678 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5679
5680 // Sniff for the signature.
5681 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5682 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5683 return std::string();
5684 }
5685
5686 // Scan for the CONTROL_BLOCK_ID block.
5687 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5688 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5689 return std::string();
5690 }
5691
5692 // Scan for ORIGINAL_FILE inside the control block.
5694 while (true) {
5696 Stream.advanceSkippingSubblocks();
5697 if (!MaybeEntry) {
5698 // FIXME this drops errors on the floor.
5699 consumeError(MaybeEntry.takeError());
5700 return std::string();
5701 }
5702 llvm::BitstreamEntry Entry = MaybeEntry.get();
5703
5704 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5705 return std::string();
5706
5707 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5708 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5709 return std::string();
5710 }
5711
5712 Record.clear();
5713 StringRef Blob;
5714 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5715 if (!MaybeRecord) {
5716 // FIXME this drops the errors on the floor.
5717 consumeError(MaybeRecord.takeError());
5718 return std::string();
5719 }
5720 if (ORIGINAL_FILE == MaybeRecord.get())
5721 return Blob.str();
5722 }
5723}
5724
5725namespace {
5726
5727 class SimplePCHValidator : public ASTReaderListener {
5728 const LangOptions &ExistingLangOpts;
5729 const CodeGenOptions &ExistingCGOpts;
5730 const TargetOptions &ExistingTargetOpts;
5731 const PreprocessorOptions &ExistingPPOpts;
5732 std::string ExistingModuleCachePath;
5733 FileManager &FileMgr;
5734 bool StrictOptionMatches;
5735
5736 public:
5737 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5738 const CodeGenOptions &ExistingCGOpts,
5739 const TargetOptions &ExistingTargetOpts,
5740 const PreprocessorOptions &ExistingPPOpts,
5741 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5742 bool StrictOptionMatches)
5743 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5744 ExistingTargetOpts(ExistingTargetOpts),
5745 ExistingPPOpts(ExistingPPOpts),
5746 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5747 StrictOptionMatches(StrictOptionMatches) {}
5748
5749 bool ReadLanguageOptions(const LangOptions &LangOpts,
5750 StringRef ModuleFilename, bool Complain,
5751 bool AllowCompatibleDifferences) override {
5752 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5753 nullptr, AllowCompatibleDifferences);
5754 }
5755
5756 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5757 StringRef ModuleFilename, bool Complain,
5758 bool AllowCompatibleDifferences) override {
5759 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5760 nullptr, AllowCompatibleDifferences);
5761 }
5762
5763 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5764 StringRef ModuleFilename, bool Complain,
5765 bool AllowCompatibleDifferences) override {
5766 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5767 nullptr, AllowCompatibleDifferences);
5768 }
5769
5770 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5771 StringRef ModuleFilename,
5772 StringRef SpecificModuleCachePath,
5773 bool Complain) override {
5775 SpecificModuleCachePath,
5776 ExistingModuleCachePath, ModuleFilename,
5777 nullptr, ExistingLangOpts, ExistingPPOpts);
5778 }
5779
5780 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5781 StringRef ModuleFilename, bool ReadMacros,
5782 bool Complain,
5783 std::string &SuggestedPredefines) override {
5785 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5786 FileMgr, SuggestedPredefines, ExistingLangOpts,
5787 StrictOptionMatches ? OptionValidateStrictMatches
5789 }
5790 };
5791
5792} // namespace
5793
5795 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5796 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5797 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5798 unsigned ClientLoadCapabilities) {
5799 // Open the AST file.
5800 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5801 llvm::MemoryBuffer *Buffer =
5803 if (!Buffer) {
5804 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5805 // read again later, but we do not have the context here to determine if it
5806 // is safe to change the result of InMemoryModuleCache::getPCMState().
5807
5808 // FIXME: This allows use of the VFS; we do not allow use of the
5809 // VFS when actually loading a module.
5810 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5811 if (!BufferOrErr)
5812 return true;
5813 OwnedBuffer = std::move(*BufferOrErr);
5814 Buffer = OwnedBuffer.get();
5815 }
5816
5817 // Initialize the stream
5818 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5819 BitstreamCursor Stream(Bytes);
5820
5821 // Sniff for the signature.
5822 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5823 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5824 return true;
5825 }
5826
5827 // Scan for the CONTROL_BLOCK_ID block.
5829 return true;
5830
5831 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5832 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5833 bool NeedsImports = Listener.needsImportVisitation();
5834 BitstreamCursor InputFilesCursor;
5835 uint64_t InputFilesOffsetBase = 0;
5836
5838 std::string ModuleDir;
5839 bool DoneWithControlBlock = false;
5840 SmallString<0> PathBuf;
5841 PathBuf.reserve(256);
5842 // Additional path buffer to use when multiple paths need to be resolved.
5843 // For example, when deserializing input files that contains a path that was
5844 // resolved from a vfs overlay and an external location.
5845 SmallString<0> AdditionalPathBuf;
5846 AdditionalPathBuf.reserve(256);
5847 while (!DoneWithControlBlock) {
5848 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5849 if (!MaybeEntry) {
5850 // FIXME this drops the error on the floor.
5851 consumeError(MaybeEntry.takeError());
5852 return true;
5853 }
5854 llvm::BitstreamEntry Entry = MaybeEntry.get();
5855
5856 switch (Entry.Kind) {
5857 case llvm::BitstreamEntry::SubBlock: {
5858 switch (Entry.ID) {
5859 case OPTIONS_BLOCK_ID: {
5860 std::string IgnoredSuggestedPredefines;
5861 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5862 /*AllowCompatibleConfigurationMismatch*/ false,
5863 Listener, IgnoredSuggestedPredefines) != Success)
5864 return true;
5865 break;
5866 }
5867
5869 InputFilesCursor = Stream;
5870 if (llvm::Error Err = Stream.SkipBlock()) {
5871 // FIXME this drops the error on the floor.
5872 consumeError(std::move(Err));
5873 return true;
5874 }
5875 if (NeedsInputFiles &&
5876 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5877 return true;
5878 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5879 break;
5880
5881 default:
5882 if (llvm::Error Err = Stream.SkipBlock()) {
5883 // FIXME this drops the error on the floor.
5884 consumeError(std::move(Err));
5885 return true;
5886 }
5887 break;
5888 }
5889
5890 continue;
5891 }
5892
5893 case llvm::BitstreamEntry::EndBlock:
5894 DoneWithControlBlock = true;
5895 break;
5896
5897 case llvm::BitstreamEntry::Error:
5898 return true;
5899
5900 case llvm::BitstreamEntry::Record:
5901 break;
5902 }
5903
5904 if (DoneWithControlBlock) break;
5905
5906 Record.clear();
5907 StringRef Blob;
5908 Expected<unsigned> MaybeRecCode =
5909 Stream.readRecord(Entry.ID, Record, &Blob);
5910 if (!MaybeRecCode) {
5911 // FIXME this drops the error.
5912 return Failure;
5913 }
5914 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5915 case METADATA:
5916 if (Record[0] != VERSION_MAJOR)
5917 return true;
5918 if (Listener.ReadFullVersionInformation(Blob))
5919 return true;
5920 break;
5921 case MODULE_NAME:
5922 Listener.ReadModuleName(Blob);
5923 break;
5924 case MODULE_DIRECTORY:
5925 ModuleDir = std::string(Blob);
5926 break;
5927 case MODULE_MAP_FILE: {
5928 unsigned Idx = 0;
5929 std::string PathStr = ReadString(Record, Idx);
5930 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
5931 Listener.ReadModuleMapFile(*Path);
5932 break;
5933 }
5934 case INPUT_FILE_OFFSETS: {
5935 if (!NeedsInputFiles)
5936 break;
5937
5938 unsigned NumInputFiles = Record[0];
5939 unsigned NumUserFiles = Record[1];
5940 const llvm::support::unaligned_uint64_t *InputFileOffs =
5941 (const llvm::support::unaligned_uint64_t *)Blob.data();
5942 for (unsigned I = 0; I != NumInputFiles; ++I) {
5943 // Go find this input file.
5944 bool isSystemFile = I >= NumUserFiles;
5945
5946 if (isSystemFile && !NeedsSystemInputFiles)
5947 break; // the rest are system input files
5948
5949 BitstreamCursor &Cursor = InputFilesCursor;
5950 SavedStreamPosition SavedPosition(Cursor);
5951 if (llvm::Error Err =
5952 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5953 // FIXME this drops errors on the floor.
5954 consumeError(std::move(Err));
5955 }
5956
5957 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5958 if (!MaybeCode) {
5959 // FIXME this drops errors on the floor.
5960 consumeError(MaybeCode.takeError());
5961 }
5962 unsigned Code = MaybeCode.get();
5963
5965 StringRef Blob;
5966 bool shouldContinue = false;
5967 Expected<unsigned> MaybeRecordType =
5968 Cursor.readRecord(Code, Record, &Blob);
5969 if (!MaybeRecordType) {
5970 // FIXME this drops errors on the floor.
5971 consumeError(MaybeRecordType.takeError());
5972 }
5973 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5974 case INPUT_FILE_HASH:
5975 break;
5976 case INPUT_FILE:
5977 bool Overridden = static_cast<bool>(Record[3]);
5978 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
5980 auto FilenameAsRequestedBuf = ResolveImportedPath(
5981 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
5982 StringRef Filename;
5983 if (UnresolvedFilename.empty())
5984 Filename = *FilenameAsRequestedBuf;
5985 else {
5986 auto FilenameBuf = ResolveImportedPath(
5987 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
5988 Filename = *FilenameBuf;
5989 }
5990 shouldContinue = Listener.visitInputFile(
5991 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
5992 /*IsExplicitModule=*/false);
5993 break;
5994 }
5995 if (!shouldContinue)
5996 break;
5997 }
5998 break;
5999 }
6000
6001 case IMPORT: {
6002 if (!NeedsImports)
6003 break;
6004
6005 unsigned Idx = 0;
6006 // Read information about the AST file.
6007
6008 // Skip Kind
6009 Idx++;
6010
6011 // Skip ImportLoc
6012 Idx++;
6013
6014 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6015
6016 bool IsStandardCXXModule = Record[Idx++];
6017
6018 // In C++20 Modules, we don't record the path to imported
6019 // modules in the BMI files.
6020 if (IsStandardCXXModule) {
6021 Listener.visitImport(ModuleName, /*Filename=*/"");
6022 continue;
6023 }
6024
6025 // Skip Size and ModTime.
6026 Idx += 1 + 1;
6027 // Skip signature.
6028 Blob = Blob.substr(ASTFileSignature::size);
6029
6030 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6031 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6032 Listener.visitImport(ModuleName, *Filename);
6033 break;
6034 }
6035
6036 default:
6037 // No other validation to perform.
6038 break;
6039 }
6040 }
6041
6042 // Look for module file extension blocks, if requested.
6043 if (FindModuleFileExtensions) {
6044 BitstreamCursor SavedStream = Stream;
6045 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6046 bool DoneWithExtensionBlock = false;
6047 while (!DoneWithExtensionBlock) {
6048 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6049 if (!MaybeEntry) {
6050 // FIXME this drops the error.
6051 return true;
6052 }
6053 llvm::BitstreamEntry Entry = MaybeEntry.get();
6054
6055 switch (Entry.Kind) {
6056 case llvm::BitstreamEntry::SubBlock:
6057 if (llvm::Error Err = Stream.SkipBlock()) {
6058 // FIXME this drops the error on the floor.
6059 consumeError(std::move(Err));
6060 return true;
6061 }
6062 continue;
6063
6064 case llvm::BitstreamEntry::EndBlock:
6065 DoneWithExtensionBlock = true;
6066 continue;
6067
6068 case llvm::BitstreamEntry::Error:
6069 return true;
6070
6071 case llvm::BitstreamEntry::Record:
6072 break;
6073 }
6074
6075 Record.clear();
6076 StringRef Blob;
6077 Expected<unsigned> MaybeRecCode =
6078 Stream.readRecord(Entry.ID, Record, &Blob);
6079 if (!MaybeRecCode) {
6080 // FIXME this drops the error.
6081 return true;
6082 }
6083 switch (MaybeRecCode.get()) {
6084 case EXTENSION_METADATA: {
6086 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6087 return true;
6088
6089 Listener.readModuleFileExtension(Metadata);
6090 break;
6091 }
6092 }
6093 }
6094 }
6095 Stream = std::move(SavedStream);
6096 }
6097
6098 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6099 if (readUnhashedControlBlockImpl(
6100 nullptr, Bytes, Filename, ClientLoadCapabilities,
6101 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6102 ValidateDiagnosticOptions) != Success)
6103 return true;
6104
6105 return false;
6106}
6107
6109 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6110 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6111 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6112 const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath,
6113 bool RequireStrictOptionMatches) {
6114 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts,
6115 ExistingModuleCachePath, FileMgr,
6116 RequireStrictOptionMatches);
6117 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6118 /*FindModuleFileExtensions=*/false, validator,
6119 /*ValidateDiagnosticOptions=*/true);
6120}
6121
6122llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6123 unsigned ClientLoadCapabilities) {
6124 // Enter the submodule block.
6125 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6126 return Err;
6127
6128 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6129 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6130 // If we don't know the top-level module, there's no point in doing qualified
6131 // lookup of its submodules; it won't find anything anywhere within this tree.
6132 // Let's skip that and avoid some string lookups.
6133 auto CreateModule = !KnowsTopLevelModule
6136
6137 bool First = true;
6138 Module *CurrentModule = nullptr;
6139 RecordData Record;
6140 while (true) {
6142 F.Stream.advanceSkippingSubblocks();
6143 if (!MaybeEntry)
6144 return MaybeEntry.takeError();
6145 llvm::BitstreamEntry Entry = MaybeEntry.get();
6146
6147 switch (Entry.Kind) {
6148 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6149 case llvm::BitstreamEntry::Error:
6150 return llvm::createStringError(std::errc::illegal_byte_sequence,
6151 "malformed block record in AST file");
6152 case llvm::BitstreamEntry::EndBlock:
6153 return llvm::Error::success();
6154 case llvm::BitstreamEntry::Record:
6155 // The interesting case.
6156 break;
6157 }
6158
6159 // Read a record.
6160 StringRef Blob;
6161 Record.clear();
6162 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6163 if (!MaybeKind)
6164 return MaybeKind.takeError();
6165 unsigned Kind = MaybeKind.get();
6166
6167 if ((Kind == SUBMODULE_METADATA) != First)
6168 return llvm::createStringError(
6169 std::errc::illegal_byte_sequence,
6170 "submodule metadata record should be at beginning of block");
6171 First = false;
6172
6173 // Submodule information is only valid if we have a current module.
6174 // FIXME: Should we error on these cases?
6175 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6176 Kind != SUBMODULE_DEFINITION)
6177 continue;
6178
6179 switch (Kind) {
6180 default: // Default behavior: ignore.
6181 break;
6182
6183 case SUBMODULE_DEFINITION: {
6184 if (Record.size() < 13)
6185 return llvm::createStringError(std::errc::illegal_byte_sequence,
6186 "malformed module definition");
6187
6188 StringRef Name = Blob;
6189 unsigned Idx = 0;
6190 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6191 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6193 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6194 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6195 bool IsFramework = Record[Idx++];
6196 bool IsExplicit = Record[Idx++];
6197 bool IsSystem = Record[Idx++];
6198 bool IsExternC = Record[Idx++];
6199 bool InferSubmodules = Record[Idx++];
6200 bool InferExplicitSubmodules = Record[Idx++];
6201 bool InferExportWildcard = Record[Idx++];
6202 bool ConfigMacrosExhaustive = Record[Idx++];
6203 bool ModuleMapIsPrivate = Record[Idx++];
6204 bool NamedModuleHasInit = Record[Idx++];
6205
6206 Module *ParentModule = nullptr;
6207 if (Parent)
6208 ParentModule = getSubmodule(Parent);
6209
6210 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6211 IsFramework, IsExplicit);
6212
6213 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6214 if (GlobalIndex >= SubmodulesLoaded.size() ||
6215 SubmodulesLoaded[GlobalIndex])
6216 return llvm::createStringError(std::errc::invalid_argument,
6217 "too many submodules");
6218
6219 if (!ParentModule) {
6220 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
6221 // Don't emit module relocation error if we have -fno-validate-pch
6222 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6224 assert(CurFile != F.File && "ModuleManager did not de-duplicate");
6225
6226 Diag(diag::err_module_file_conflict)
6227 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
6228 << F.File.getName();
6229
6230 auto CurModMapFile =
6231 ModMap.getContainingModuleMapFile(CurrentModule);
6232 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6233 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6234 Diag(diag::note_module_file_conflict)
6235 << CurModMapFile->getName() << ModMapFile->getName();
6236
6237 return llvm::make_error<AlreadyReportedDiagnosticError>();
6238 }
6239 }
6240
6241 F.DidReadTopLevelSubmodule = true;
6242 CurrentModule->setASTFile(F.File);
6243 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6244 }
6245
6246 CurrentModule->Kind = Kind;
6247 // Note that we may be rewriting an existing location and it is important
6248 // to keep doing that. In particular, we would like to prefer a
6249 // `DefinitionLoc` loaded from the module file instead of the location
6250 // created in the current source manager, because it allows the new
6251 // location to be marked as "unaffecting" when writing and avoid creating
6252 // duplicate locations for the same module map file.
6253 CurrentModule->DefinitionLoc = DefinitionLoc;
6254 CurrentModule->Signature = F.Signature;
6255 CurrentModule->IsFromModuleFile = true;
6256 if (InferredAllowedBy.isValid())
6257 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6258 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6259 CurrentModule->IsExternC = IsExternC;
6260 CurrentModule->InferSubmodules = InferSubmodules;
6261 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6262 CurrentModule->InferExportWildcard = InferExportWildcard;
6263 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6264 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6265 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6266 if (DeserializationListener)
6267 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6268
6269 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6270
6271 // Clear out data that will be replaced by what is in the module file.
6272 CurrentModule->LinkLibraries.clear();
6273 CurrentModule->ConfigMacros.clear();
6274 CurrentModule->UnresolvedConflicts.clear();
6275 CurrentModule->Conflicts.clear();
6276
6277 // The module is available unless it's missing a requirement; relevant
6278 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6279 // Missing headers that were present when the module was built do not
6280 // make it unavailable -- if we got this far, this must be an explicitly
6281 // imported module file.
6282 CurrentModule->Requirements.clear();
6283 CurrentModule->MissingHeaders.clear();
6284 CurrentModule->IsUnimportable =
6285 ParentModule && ParentModule->IsUnimportable;
6286 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6287 break;
6288 }
6289
6291 // FIXME: This doesn't work for framework modules as `Filename` is the
6292 // name as written in the module file and does not include
6293 // `Headers/`, so this path will never exist.
6294 auto Filename = ResolveImportedPath(PathBuf, Blob, F);
6295 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(*Filename)) {
6296 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6297 // FIXME: NameAsWritten
6298 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
6299 }
6300 // Note that it's too late at this point to return out of date if the
6301 // name from the PCM doesn't match up with the one in the module map,
6302 // but also quite unlikely since we will have already checked the
6303 // modification time and size of the module map file itself.
6304 }
6305 break;
6306 }
6307
6308 case SUBMODULE_HEADER:
6311 // We lazily associate headers with their modules via the HeaderInfo table.
6312 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6313 // of complete filenames or remove it entirely.
6314 break;
6315
6318 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6319 // them here.
6320 break;
6321
6322 case SUBMODULE_TOPHEADER: {
6323 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6324 CurrentModule->addTopHeaderFilename(*HeaderName);
6325 break;
6326 }
6327
6329 // See comments in SUBMODULE_UMBRELLA_HEADER
6330 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6331 if (auto Umbrella =
6332 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6333 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6334 // FIXME: NameAsWritten
6335 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6336 }
6337 }
6338 break;
6339 }
6340
6341 case SUBMODULE_METADATA: {
6342 F.BaseSubmoduleID = getTotalNumSubmodules();
6344 unsigned LocalBaseSubmoduleID = Record[1];
6345 if (F.LocalNumSubmodules > 0) {
6346 // Introduce the global -> local mapping for submodules within this
6347 // module.
6348 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6349
6350 // Introduce the local -> global mapping for submodules within this
6351 // module.
6353 std::make_pair(LocalBaseSubmoduleID,
6354 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6355
6356 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6357 }
6358 break;
6359 }
6360
6361 case SUBMODULE_IMPORTS:
6362 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6363 UnresolvedModuleRef Unresolved;
6364 Unresolved.File = &F;
6365 Unresolved.Mod = CurrentModule;
6366 Unresolved.ID = Record[Idx];
6367 Unresolved.Kind = UnresolvedModuleRef::Import;
6368 Unresolved.IsWildcard = false;
6369 UnresolvedModuleRefs.push_back(Unresolved);
6370 }
6371 break;
6372
6374 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6375 UnresolvedModuleRef Unresolved;
6376 Unresolved.File = &F;
6377 Unresolved.Mod = CurrentModule;
6378 Unresolved.ID = Record[Idx];
6379 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6380 Unresolved.IsWildcard = false;
6381 UnresolvedModuleRefs.push_back(Unresolved);
6382 }
6383 break;
6384
6385 case SUBMODULE_EXPORTS:
6386 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6387 UnresolvedModuleRef Unresolved;
6388 Unresolved.File = &F;
6389 Unresolved.Mod = CurrentModule;
6390 Unresolved.ID = Record[Idx];
6391 Unresolved.Kind = UnresolvedModuleRef::Export;
6392 Unresolved.IsWildcard = Record[Idx + 1];
6393 UnresolvedModuleRefs.push_back(Unresolved);
6394 }
6395
6396 // Once we've loaded the set of exports, there's no reason to keep
6397 // the parsed, unresolved exports around.
6398 CurrentModule->UnresolvedExports.clear();
6399 break;
6400
6401 case SUBMODULE_REQUIRES:
6402 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6403 PP.getTargetInfo());
6404 break;
6405
6407 ModMap.resolveLinkAsDependencies(CurrentModule);
6408 CurrentModule->LinkLibraries.push_back(
6409 Module::LinkLibrary(std::string(Blob), Record[0]));
6410 break;
6411
6413 CurrentModule->ConfigMacros.push_back(Blob.str());
6414 break;
6415
6416 case SUBMODULE_CONFLICT: {
6417 UnresolvedModuleRef Unresolved;
6418 Unresolved.File = &F;
6419 Unresolved.Mod = CurrentModule;
6420 Unresolved.ID = Record[0];
6421 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6422 Unresolved.IsWildcard = false;
6423 Unresolved.String = Blob;
6424 UnresolvedModuleRefs.push_back(Unresolved);
6425 break;
6426 }
6427
6429 if (!ContextObj)
6430 break;
6432 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6433 Inits.push_back(ReadDeclID(F, Record, I));
6434 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6435 break;
6436 }
6437
6439 CurrentModule->ExportAsModule = Blob.str();
6440 ModMap.addLinkAsDependency(CurrentModule);
6441 break;
6442 }
6443 }
6444}
6445
6446/// Parse the record that corresponds to a LangOptions data
6447/// structure.
6448///
6449/// This routine parses the language options from the AST file and then gives
6450/// them to the AST listener if one is set.
6451///
6452/// \returns true if the listener deems the file unacceptable, false otherwise.
6453bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6454 StringRef ModuleFilename, bool Complain,
6455 ASTReaderListener &Listener,
6456 bool AllowCompatibleDifferences) {
6457 LangOptions LangOpts;
6458 unsigned Idx = 0;
6459#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6460 LangOpts.Name = Record[Idx++];
6461#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6462 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6463#include "clang/Basic/LangOptions.def"
6464#define SANITIZER(NAME, ID) \
6465 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6466#include "clang/Basic/Sanitizers.def"
6467
6468 for (unsigned N = Record[Idx++]; N; --N)
6469 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6470
6471 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6472 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6473 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6474
6475 LangOpts.CurrentModule = ReadString(Record, Idx);
6476
6477 // Comment options.
6478 for (unsigned N = Record[Idx++]; N; --N) {
6479 LangOpts.CommentOpts.BlockCommandNames.push_back(
6480 ReadString(Record, Idx));
6481 }
6482 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6483
6484 // OpenMP offloading options.
6485 for (unsigned N = Record[Idx++]; N; --N) {
6486 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6487 }
6488
6489 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6490
6491 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6492 AllowCompatibleDifferences);
6493}
6494
6495bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6496 StringRef ModuleFilename, bool Complain,
6497 ASTReaderListener &Listener,
6498 bool AllowCompatibleDifferences) {
6499 unsigned Idx = 0;
6500 CodeGenOptions CGOpts;
6502#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6503 if constexpr (CK::Compatibility != CK::Benign) \
6504 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6505#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6506 if constexpr (CK::Compatibility != CK::Benign) \
6507 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6508#define DEBUGOPT(Name, Bits, Default, Compatibility)
6509#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6510#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6511#include "clang/Basic/CodeGenOptions.def"
6512
6513 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6514 AllowCompatibleDifferences);
6515}
6516
6517bool ASTReader::ParseTargetOptions(const RecordData &Record,
6518 StringRef ModuleFilename, bool Complain,
6519 ASTReaderListener &Listener,
6520 bool AllowCompatibleDifferences) {
6521 unsigned Idx = 0;
6522 TargetOptions TargetOpts;
6523 TargetOpts.Triple = ReadString(Record, Idx);
6524 TargetOpts.CPU = ReadString(Record, Idx);
6525 TargetOpts.TuneCPU = ReadString(Record, Idx);
6526 TargetOpts.ABI = ReadString(Record, Idx);
6527 for (unsigned N = Record[Idx++]; N; --N) {
6528 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6529 }
6530 for (unsigned N = Record[Idx++]; N; --N) {
6531 TargetOpts.Features.push_back(ReadString(Record, Idx));
6532 }
6533
6534 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6535 AllowCompatibleDifferences);
6536}
6537
6538bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6539 StringRef ModuleFilename, bool Complain,
6540 ASTReaderListener &Listener) {
6541 DiagnosticOptions DiagOpts;
6542 unsigned Idx = 0;
6543#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6544#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6545 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6546#include "clang/Basic/DiagnosticOptions.def"
6547
6548 for (unsigned N = Record[Idx++]; N; --N)
6549 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6550 for (unsigned N = Record[Idx++]; N; --N)
6551 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6552
6553 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6554}
6555
6556bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6557 ASTReaderListener &Listener) {
6558 FileSystemOptions FSOpts;
6559 unsigned Idx = 0;
6560 FSOpts.WorkingDir = ReadString(Record, Idx);
6561 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6562}
6563
6564bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6565 StringRef ModuleFilename,
6566 bool Complain,
6567 ASTReaderListener &Listener) {
6568 HeaderSearchOptions HSOpts;
6569 unsigned Idx = 0;
6570 HSOpts.Sysroot = ReadString(Record, Idx);
6571
6572 HSOpts.ResourceDir = ReadString(Record, Idx);
6573 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6574 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6575 HSOpts.DisableModuleHash = Record[Idx++];
6576 HSOpts.ImplicitModuleMaps = Record[Idx++];
6577 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6578 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6579 HSOpts.UseBuiltinIncludes = Record[Idx++];
6580 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6581 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6582 HSOpts.UseLibcxx = Record[Idx++];
6583 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6584
6585 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6586 SpecificModuleCachePath, Complain);
6587}
6588
6589bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6590 ASTReaderListener &Listener) {
6591 HeaderSearchOptions HSOpts;
6592 unsigned Idx = 0;
6593
6594 // Include entries.
6595 for (unsigned N = Record[Idx++]; N; --N) {
6596 std::string Path = ReadString(Record, Idx);
6598 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6599 bool IsFramework = Record[Idx++];
6600 bool IgnoreSysRoot = Record[Idx++];
6601 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6602 IgnoreSysRoot);
6603 }
6604
6605 // System header prefixes.
6606 for (unsigned N = Record[Idx++]; N; --N) {
6607 std::string Prefix = ReadString(Record, Idx);
6608 bool IsSystemHeader = Record[Idx++];
6609 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6610 }
6611
6612 // VFS overlay files.
6613 for (unsigned N = Record[Idx++]; N; --N) {
6614 std::string VFSOverlayFile = ReadString(Record, Idx);
6615 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6616 }
6617
6618 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6619}
6620
6621bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6622 StringRef ModuleFilename,
6623 bool Complain,
6624 ASTReaderListener &Listener,
6625 std::string &SuggestedPredefines) {
6626 PreprocessorOptions PPOpts;
6627 unsigned Idx = 0;
6628
6629 // Macro definitions/undefs
6630 bool ReadMacros = Record[Idx++];
6631 if (ReadMacros) {
6632 for (unsigned N = Record[Idx++]; N; --N) {
6633 std::string Macro = ReadString(Record, Idx);
6634 bool IsUndef = Record[Idx++];
6635 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6636 }
6637 }
6638
6639 // Includes
6640 for (unsigned N = Record[Idx++]; N; --N) {
6641 PPOpts.Includes.push_back(ReadString(Record, Idx));
6642 }
6643
6644 // Macro Includes
6645 for (unsigned N = Record[Idx++]; N; --N) {
6646 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6647 }
6648
6649 PPOpts.UsePredefines = Record[Idx++];
6650 PPOpts.DetailedRecord = Record[Idx++];
6651 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6653 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6654 SuggestedPredefines.clear();
6655 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6656 Complain, SuggestedPredefines);
6657}
6658
6659std::pair<ModuleFile *, unsigned>
6660ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6661 GlobalPreprocessedEntityMapType::iterator
6662 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6663 assert(I != GlobalPreprocessedEntityMap.end() &&
6664 "Corrupted global preprocessed entity map");
6665 ModuleFile *M = I->second;
6666 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6667 return std::make_pair(M, LocalIndex);
6668}
6669
6670llvm::iterator_range<PreprocessingRecord::iterator>
6671ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6672 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6673 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6675
6676 return llvm::make_range(PreprocessingRecord::iterator(),
6678}
6679
6680bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6681 unsigned int ClientLoadCapabilities) {
6682 return ClientLoadCapabilities & ARR_OutOfDate &&
6683 !getModuleManager()
6684 .getModuleCache()
6685 .getInMemoryModuleCache()
6686 .isPCMFinal(ModuleFileName);
6687}
6688
6689llvm::iterator_range<ASTReader::ModuleDeclIterator>
6691 return llvm::make_range(
6692 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6693 ModuleDeclIterator(this, &Mod,
6695}
6696
6698 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6699 assert(I != GlobalSkippedRangeMap.end() &&
6700 "Corrupted global skipped range map");
6701 ModuleFile *M = I->second;
6702 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6703 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6704 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6705 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6706 ReadSourceLocation(*M, RawRange.getEnd()));
6707 assert(Range.isValid());
6708 return Range;
6709}
6710
6712 PreprocessedEntityID PPID = Index+1;
6713 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6714 ModuleFile &M = *PPInfo.first;
6715 unsigned LocalIndex = PPInfo.second;
6716 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6717
6718 if (!PP.getPreprocessingRecord()) {
6719 Error("no preprocessing record");
6720 return nullptr;
6721 }
6722
6724 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6725 M.MacroOffsetsBase + PPOffs.getOffset())) {
6726 Error(std::move(Err));
6727 return nullptr;
6728 }
6729
6731 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6732 if (!MaybeEntry) {
6733 Error(MaybeEntry.takeError());
6734 return nullptr;
6735 }
6736 llvm::BitstreamEntry Entry = MaybeEntry.get();
6737
6738 if (Entry.Kind != llvm::BitstreamEntry::Record)
6739 return nullptr;
6740
6741 // Read the record.
6742 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6743 ReadSourceLocation(M, PPOffs.getEnd()));
6744 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6745 StringRef Blob;
6747 Expected<unsigned> MaybeRecType =
6748 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6749 if (!MaybeRecType) {
6750 Error(MaybeRecType.takeError());
6751 return nullptr;
6752 }
6753 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6754 case PPD_MACRO_EXPANSION: {
6755 bool isBuiltin = Record[0];
6756 IdentifierInfo *Name = nullptr;
6757 MacroDefinitionRecord *Def = nullptr;
6758 if (isBuiltin)
6759 Name = getLocalIdentifier(M, Record[1]);
6760 else {
6761 PreprocessedEntityID GlobalID =
6762 getGlobalPreprocessedEntityID(M, Record[1]);
6763 Def = cast<MacroDefinitionRecord>(
6764 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6765 }
6766
6767 MacroExpansion *ME;
6768 if (isBuiltin)
6769 ME = new (PPRec) MacroExpansion(Name, Range);
6770 else
6771 ME = new (PPRec) MacroExpansion(Def, Range);
6772
6773 return ME;
6774 }
6775
6776 case PPD_MACRO_DEFINITION: {
6777 // Decode the identifier info and then check again; if the macro is
6778 // still defined and associated with the identifier,
6779 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6780 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6781
6782 if (DeserializationListener)
6783 DeserializationListener->MacroDefinitionRead(PPID, MD);
6784
6785 return MD;
6786 }
6787
6789 const char *FullFileNameStart = Blob.data() + Record[0];
6790 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6792 if (!FullFileName.empty())
6793 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6794
6795 // FIXME: Stable encoding
6797 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6799 = new (PPRec) InclusionDirective(PPRec, Kind,
6800 StringRef(Blob.data(), Record[0]),
6801 Record[1], Record[3],
6802 File,
6803 Range);
6804 return ID;
6805 }
6806 }
6807
6808 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6809}
6810
6811/// Find the next module that contains entities and return the ID
6812/// of the first entry.
6813///
6814/// \param SLocMapI points at a chunk of a module that contains no
6815/// preprocessed entities or the entities it contains are not the ones we are
6816/// looking for.
6817PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6818 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6819 ++SLocMapI;
6820 for (GlobalSLocOffsetMapType::const_iterator
6821 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6822 ModuleFile &M = *SLocMapI->second;
6824 return M.BasePreprocessedEntityID;
6825 }
6826
6827 return getTotalNumPreprocessedEntities();
6828}
6829
6830namespace {
6831
6832struct PPEntityComp {
6833 const ASTReader &Reader;
6834 ModuleFile &M;
6835
6836 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6837
6838 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6839 SourceLocation LHS = getLoc(L);
6840 SourceLocation RHS = getLoc(R);
6841 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6842 }
6843
6844 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6845 SourceLocation LHS = getLoc(L);
6846 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6847 }
6848
6849 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6850 SourceLocation RHS = getLoc(R);
6851 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6852 }
6853
6854 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6855 return Reader.ReadSourceLocation(M, PPE.getBegin());
6856 }
6857};
6858
6859} // namespace
6860
6861PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6862 bool EndsAfter) const {
6863 if (SourceMgr.isLocalSourceLocation(Loc))
6864 return getTotalNumPreprocessedEntities();
6865
6866 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6867 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6868 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6869 "Corrupted global sloc offset map");
6870
6871 if (SLocMapI->second->NumPreprocessedEntities == 0)
6872 return findNextPreprocessedEntity(SLocMapI);
6873
6874 ModuleFile &M = *SLocMapI->second;
6875
6876 using pp_iterator = const PPEntityOffset *;
6877
6878 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6879 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6880
6881 size_t Count = M.NumPreprocessedEntities;
6882 size_t Half;
6883 pp_iterator First = pp_begin;
6884 pp_iterator PPI;
6885
6886 if (EndsAfter) {
6887 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6888 PPEntityComp(*this, M));
6889 } else {
6890 // Do a binary search manually instead of using std::lower_bound because
6891 // The end locations of entities may be unordered (when a macro expansion
6892 // is inside another macro argument), but for this case it is not important
6893 // whether we get the first macro expansion or its containing macro.
6894 while (Count > 0) {
6895 Half = Count / 2;
6896 PPI = First;
6897 std::advance(PPI, Half);
6898 if (SourceMgr.isBeforeInTranslationUnit(
6899 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6900 First = PPI;
6901 ++First;
6902 Count = Count - Half - 1;
6903 } else
6904 Count = Half;
6905 }
6906 }
6907
6908 if (PPI == pp_end)
6909 return findNextPreprocessedEntity(SLocMapI);
6910
6911 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6912}
6913
6914/// Returns a pair of [Begin, End) indices of preallocated
6915/// preprocessed entities that \arg Range encompasses.
6916std::pair<unsigned, unsigned>
6918 if (Range.isInvalid())
6919 return std::make_pair(0,0);
6920 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6921
6922 PreprocessedEntityID BeginID =
6923 findPreprocessedEntity(Range.getBegin(), false);
6924 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6925 return std::make_pair(BeginID, EndID);
6926}
6927
6928/// Optionally returns true or false if the preallocated preprocessed
6929/// entity with index \arg Index came from file \arg FID.
6930std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6931 FileID FID) {
6932 if (FID.isInvalid())
6933 return false;
6934
6935 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6936 ModuleFile &M = *PPInfo.first;
6937 unsigned LocalIndex = PPInfo.second;
6938 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6939
6940 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6941 if (Loc.isInvalid())
6942 return false;
6943
6944 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6945 return true;
6946 else
6947 return false;
6948}
6949
6950namespace {
6951
6952 /// Visitor used to search for information about a header file.
6953 class HeaderFileInfoVisitor {
6954 FileEntryRef FE;
6955 std::optional<HeaderFileInfo> HFI;
6956
6957 public:
6958 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6959
6960 bool operator()(ModuleFile &M) {
6963 if (!Table)
6964 return false;
6965
6966 // Look in the on-disk hash table for an entry for this file name.
6967 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6968 if (Pos == Table->end())
6969 return false;
6970
6971 HFI = *Pos;
6972 return true;
6973 }
6974
6975 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6976 };
6977
6978} // namespace
6979
6981 HeaderFileInfoVisitor Visitor(FE);
6982 ModuleMgr.visit(Visitor);
6983 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6984 return *HFI;
6985
6986 return HeaderFileInfo();
6987}
6988
6990 using DiagState = DiagnosticsEngine::DiagState;
6992
6993 for (ModuleFile &F : ModuleMgr) {
6994 unsigned Idx = 0;
6995 auto &Record = F.PragmaDiagMappings;
6996 if (Record.empty())
6997 continue;
6998
6999 DiagStates.clear();
7000
7001 auto ReadDiagState = [&](const DiagState &BasedOn,
7002 bool IncludeNonPragmaStates) {
7003 unsigned BackrefID = Record[Idx++];
7004 if (BackrefID != 0)
7005 return DiagStates[BackrefID - 1];
7006
7007 // A new DiagState was created here.
7008 Diag.DiagStates.push_back(BasedOn);
7009 DiagState *NewState = &Diag.DiagStates.back();
7010 DiagStates.push_back(NewState);
7011 unsigned Size = Record[Idx++];
7012 assert(Idx + Size * 2 <= Record.size() &&
7013 "Invalid data, not enough diag/map pairs");
7014 while (Size--) {
7015 unsigned DiagID = Record[Idx++];
7016 DiagnosticMapping NewMapping =
7018 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7019 continue;
7020
7021 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7022
7023 // If this mapping was specified as a warning but the severity was
7024 // upgraded due to diagnostic settings, simulate the current diagnostic
7025 // settings (and use a warning).
7026 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7028 NewMapping.setUpgradedFromWarning(false);
7029 }
7030
7031 Mapping = NewMapping;
7032 }
7033 return NewState;
7034 };
7035
7036 // Read the first state.
7037 DiagState *FirstState;
7038 if (F.Kind == MK_ImplicitModule) {
7039 // Implicitly-built modules are reused with different diagnostic
7040 // settings. Use the initial diagnostic state from Diag to simulate this
7041 // compilation's diagnostic settings.
7042 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7043 DiagStates.push_back(FirstState);
7044
7045 // Skip the initial diagnostic state from the serialized module.
7046 assert(Record[1] == 0 &&
7047 "Invalid data, unexpected backref in initial state");
7048 Idx = 3 + Record[2] * 2;
7049 assert(Idx < Record.size() &&
7050 "Invalid data, not enough state change pairs in initial state");
7051 } else if (F.isModule()) {
7052 // For an explicit module, preserve the flags from the module build
7053 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7054 // -Wblah flags.
7055 unsigned Flags = Record[Idx++];
7056 DiagState Initial(*Diag.getDiagnosticIDs());
7057 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7058 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7059 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7060 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7061 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7062 Initial.ExtBehavior = (diag::Severity)Flags;
7063 FirstState = ReadDiagState(Initial, true);
7064
7065 assert(F.OriginalSourceFileID.isValid());
7066
7067 // Set up the root buffer of the module to start with the initial
7068 // diagnostic state of the module itself, to cover files that contain no
7069 // explicit transitions (for which we did not serialize anything).
7070 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7071 .StateTransitions.push_back({FirstState, 0});
7072 } else {
7073 // For prefix ASTs, start with whatever the user configured on the
7074 // command line.
7075 Idx++; // Skip flags.
7076 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7077 }
7078
7079 // Read the state transitions.
7080 unsigned NumLocations = Record[Idx++];
7081 while (NumLocations--) {
7082 assert(Idx < Record.size() &&
7083 "Invalid data, missing pragma diagnostic states");
7084 FileID FID = ReadFileID(F, Record, Idx);
7085 assert(FID.isValid() && "invalid FileID for transition");
7086 unsigned Transitions = Record[Idx++];
7087
7088 // Note that we don't need to set up Parent/ParentOffset here, because
7089 // we won't be changing the diagnostic state within imported FileIDs
7090 // (other than perhaps appending to the main source file, which has no
7091 // parent).
7092 auto &F = Diag.DiagStatesByLoc.Files[FID];
7093 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7094 for (unsigned I = 0; I != Transitions; ++I) {
7095 unsigned Offset = Record[Idx++];
7096 auto *State = ReadDiagState(*FirstState, false);
7097 F.StateTransitions.push_back({State, Offset});
7098 }
7099 }
7100
7101 // Read the final state.
7102 assert(Idx < Record.size() &&
7103 "Invalid data, missing final pragma diagnostic state");
7104 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7105 auto *CurState = ReadDiagState(*FirstState, false);
7106
7107 if (!F.isModule()) {
7108 Diag.DiagStatesByLoc.CurDiagState = CurState;
7109 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7110
7111 // Preserve the property that the imaginary root file describes the
7112 // current state.
7113 FileID NullFile;
7114 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7115 if (T.empty())
7116 T.push_back({CurState, 0});
7117 else
7118 T[0].State = CurState;
7119 }
7120
7121 // Don't try to read these mappings again.
7122 Record.clear();
7123 }
7124}
7125
7126/// Get the correct cursor and offset for loading a type.
7127ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7128 auto [M, Index] = translateTypeIDToIndex(ID);
7129 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7131}
7132
7133static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7134 switch (code) {
7135#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7136 case TYPE_##CODE_ID: return Type::CLASS_ID;
7137#include "clang/Serialization/TypeBitCodes.def"
7138 default:
7139 return std::nullopt;
7140 }
7141}
7142
7143/// Read and return the type with the given index..
7144///
7145/// The index is the type ID, shifted and minus the number of predefs. This
7146/// routine actually reads the record corresponding to the type at the given
7147/// location. It is a helper routine for GetType, which deals with reading type
7148/// IDs.
7149QualType ASTReader::readTypeRecord(TypeID ID) {
7150 assert(ContextObj && "reading type with no AST context");
7151 ASTContext &Context = *ContextObj;
7152 RecordLocation Loc = TypeCursorForIndex(ID);
7153 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7154
7155 // Keep track of where we are in the stream, then jump back there
7156 // after reading this type.
7157 SavedStreamPosition SavedPosition(DeclsCursor);
7158
7159 ReadingKindTracker ReadingKind(Read_Type, *this);
7160
7161 // Note that we are loading a type record.
7162 Deserializing AType(this);
7163
7164 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7165 Error(std::move(Err));
7166 return QualType();
7167 }
7168 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7169 if (!RawCode) {
7170 Error(RawCode.takeError());
7171 return QualType();
7172 }
7173
7174 ASTRecordReader Record(*this, *Loc.F);
7175 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7176 if (!Code) {
7177 Error(Code.takeError());
7178 return QualType();
7179 }
7180 if (Code.get() == TYPE_EXT_QUAL) {
7181 QualType baseType = Record.readQualType();
7182 Qualifiers quals = Record.readQualifiers();
7183 return Context.getQualifiedType(baseType, quals);
7184 }
7185
7186 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7187 if (!maybeClass) {
7188 Error("Unexpected code for type");
7189 return QualType();
7190 }
7191
7193 return TypeReader.read(*maybeClass);
7194}
7195
7196namespace clang {
7197
7198class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7199 ASTRecordReader &Reader;
7200
7201 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7202 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7203
7204 TypeSourceInfo *GetTypeSourceInfo() {
7205 return Reader.readTypeSourceInfo();
7206 }
7207
7208 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7209 return Reader.readNestedNameSpecifierLoc();
7210 }
7211
7212 Attr *ReadAttr() {
7213 return Reader.readAttr();
7214 }
7215
7216public:
7217 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7218
7219 // We want compile-time assurance that we've enumerated all of
7220 // these, so unfortunately we have to declare them first, then
7221 // define them out-of-line.
7222#define ABSTRACT_TYPELOC(CLASS, PARENT)
7223#define TYPELOC(CLASS, PARENT) \
7224 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7225#include "clang/AST/TypeLocNodes.def"
7226
7227 void VisitFunctionTypeLoc(FunctionTypeLoc);
7228 void VisitArrayTypeLoc(ArrayTypeLoc);
7229 void VisitTagTypeLoc(TagTypeLoc TL);
7230};
7231
7232} // namespace clang
7233
7234void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7235 // nothing to do
7236}
7237
7238void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7239 TL.setBuiltinLoc(readSourceLocation());
7240 if (TL.needsExtraLocalData()) {
7241 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7242 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7243 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7244 TL.setModeAttr(Reader.readInt());
7245 }
7246}
7247
7248void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7249 TL.setNameLoc(readSourceLocation());
7250}
7251
7252void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7253 TL.setStarLoc(readSourceLocation());
7254}
7255
7256void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7257 // nothing to do
7258}
7259
7260void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7261 // nothing to do
7262}
7263
7264void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7265 // nothing to do
7266}
7267
7268void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7269 TL.setExpansionLoc(readSourceLocation());
7270}
7271
7272void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7273 TL.setCaretLoc(readSourceLocation());
7274}
7275
7276void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7277 TL.setAmpLoc(readSourceLocation());
7278}
7279
7280void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7281 TL.setAmpAmpLoc(readSourceLocation());
7282}
7283
7284void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7285 TL.setStarLoc(readSourceLocation());
7286 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7287}
7288
7290 TL.setLBracketLoc(readSourceLocation());
7291 TL.setRBracketLoc(readSourceLocation());
7292 if (Reader.readBool())
7293 TL.setSizeExpr(Reader.readExpr());
7294 else
7295 TL.setSizeExpr(nullptr);
7296}
7297
7298void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7299 VisitArrayTypeLoc(TL);
7300}
7301
7302void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7303 VisitArrayTypeLoc(TL);
7304}
7305
7306void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7307 VisitArrayTypeLoc(TL);
7308}
7309
7310void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7312 VisitArrayTypeLoc(TL);
7313}
7314
7315void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7317
7318 TL.setAttrNameLoc(readSourceLocation());
7319 TL.setAttrOperandParensRange(readSourceRange());
7320 TL.setAttrExprOperand(Reader.readExpr());
7321}
7322
7323void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7325 TL.setNameLoc(readSourceLocation());
7326}
7327
7328void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7329 TL.setNameLoc(readSourceLocation());
7330}
7331
7332void TypeLocReader::VisitDependentVectorTypeLoc(
7334 TL.setNameLoc(readSourceLocation());
7335}
7336
7337void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7338 TL.setNameLoc(readSourceLocation());
7339}
7340
7341void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7342 TL.setAttrNameLoc(readSourceLocation());
7343 TL.setAttrOperandParensRange(readSourceRange());
7344 TL.setAttrRowOperand(Reader.readExpr());
7345 TL.setAttrColumnOperand(Reader.readExpr());
7346}
7347
7348void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7350 TL.setAttrNameLoc(readSourceLocation());
7351 TL.setAttrOperandParensRange(readSourceRange());
7352 TL.setAttrRowOperand(Reader.readExpr());
7353 TL.setAttrColumnOperand(Reader.readExpr());
7354}
7355
7357 TL.setLocalRangeBegin(readSourceLocation());
7358 TL.setLParenLoc(readSourceLocation());
7359 TL.setRParenLoc(readSourceLocation());
7360 TL.setExceptionSpecRange(readSourceRange());
7361 TL.setLocalRangeEnd(readSourceLocation());
7362 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7363 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7364 }
7365}
7366
7367void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7368 VisitFunctionTypeLoc(TL);
7369}
7370
7371void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7372 VisitFunctionTypeLoc(TL);
7373}
7374
7375void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7376 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7377 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7378 SourceLocation NameLoc = readSourceLocation();
7379 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7380}
7381
7382void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7383 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7384 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7385 SourceLocation NameLoc = readSourceLocation();
7386 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7387}
7388
7389void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7390 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7391 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7392 SourceLocation NameLoc = readSourceLocation();
7393 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7394}
7395
7396void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7397 TL.setTypeofLoc(readSourceLocation());
7398 TL.setLParenLoc(readSourceLocation());
7399 TL.setRParenLoc(readSourceLocation());
7400}
7401
7402void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7403 TL.setTypeofLoc(readSourceLocation());
7404 TL.setLParenLoc(readSourceLocation());
7405 TL.setRParenLoc(readSourceLocation());
7406 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7407}
7408
7409void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7410 TL.setDecltypeLoc(readSourceLocation());
7411 TL.setRParenLoc(readSourceLocation());
7412}
7413
7414void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7415 TL.setEllipsisLoc(readSourceLocation());
7416}
7417
7418void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7419 TL.setKWLoc(readSourceLocation());
7420 TL.setLParenLoc(readSourceLocation());
7421 TL.setRParenLoc(readSourceLocation());
7422 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7423}
7424
7426 auto NNS = readNestedNameSpecifierLoc();
7427 auto TemplateKWLoc = readSourceLocation();
7428 auto ConceptNameLoc = readDeclarationNameInfo();
7429 auto FoundDecl = readDeclAs<NamedDecl>();
7430 auto NamedConcept = readDeclAs<ConceptDecl>();
7431 auto *CR = ConceptReference::Create(
7432 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7433 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7434 return CR;
7435}
7436
7437void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7438 TL.setNameLoc(readSourceLocation());
7439 if (Reader.readBool())
7440 TL.setConceptReference(Reader.readConceptReference());
7441 if (Reader.readBool())
7442 TL.setRParenLoc(readSourceLocation());
7443}
7444
7445void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7447 TL.setElaboratedKeywordLoc(readSourceLocation());
7448 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7449 TL.setTemplateNameLoc(readSourceLocation());
7450}
7451
7453 TL.setElaboratedKeywordLoc(readSourceLocation());
7454 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7455 TL.setNameLoc(readSourceLocation());
7456}
7457
7458void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7459 VisitTagTypeLoc(TL);
7460}
7461
7462void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7463 VisitTagTypeLoc(TL);
7464}
7465
7466void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7467
7468void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7469 TL.setAttr(ReadAttr());
7470}
7471
7472void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7473 // Nothing to do
7474}
7475
7476void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7477 // Nothing to do.
7478}
7479
7480void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7482 // Nothing to do.
7483}
7484
7485void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7486 // Nothing to do.
7487}
7488
7489void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7490 TL.setNameLoc(readSourceLocation());
7491}
7492
7493void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7495 TL.setNameLoc(readSourceLocation());
7496}
7497
7498void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7500 TL.setNameLoc(readSourceLocation());
7501}
7502
7503void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7505 TL.setNameLoc(readSourceLocation());
7506}
7507
7508void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7510 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7511 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7512 SourceLocation TemplateKeywordLoc = readSourceLocation();
7513 SourceLocation NameLoc = readSourceLocation();
7514 SourceLocation LAngleLoc = readSourceLocation();
7515 SourceLocation RAngleLoc = readSourceLocation();
7516 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7517 LAngleLoc, RAngleLoc);
7519 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7520 Args[I] = Reader.readTemplateArgumentLocInfo(
7521 TL.getTypePtr()->template_arguments()[I].getKind());
7522}
7523
7524void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7525 TL.setLParenLoc(readSourceLocation());
7526 TL.setRParenLoc(readSourceLocation());
7527}
7528
7529void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7530 TL.setElaboratedKeywordLoc(readSourceLocation());
7531 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7532 TL.setNameLoc(readSourceLocation());
7533}
7534
7535void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7537 TL.setElaboratedKeywordLoc(readSourceLocation());
7538 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7539 TL.setTemplateKeywordLoc(readSourceLocation());
7540 TL.setTemplateNameLoc(readSourceLocation());
7541 TL.setLAngleLoc(readSourceLocation());
7542 TL.setRAngleLoc(readSourceLocation());
7543 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7544 TL.setArgLocInfo(I,
7545 Reader.readTemplateArgumentLocInfo(
7546 TL.getTypePtr()->template_arguments()[I].getKind()));
7547}
7548
7549void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7550 TL.setEllipsisLoc(readSourceLocation());
7551}
7552
7553void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7554 TL.setNameLoc(readSourceLocation());
7555 TL.setNameEndLoc(readSourceLocation());
7556}
7557
7558void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7559 if (TL.getNumProtocols()) {
7560 TL.setProtocolLAngleLoc(readSourceLocation());
7561 TL.setProtocolRAngleLoc(readSourceLocation());
7562 }
7563 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7564 TL.setProtocolLoc(i, readSourceLocation());
7565}
7566
7567void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7568 TL.setHasBaseTypeAsWritten(Reader.readBool());
7569 TL.setTypeArgsLAngleLoc(readSourceLocation());
7570 TL.setTypeArgsRAngleLoc(readSourceLocation());
7571 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7572 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7573 TL.setProtocolLAngleLoc(readSourceLocation());
7574 TL.setProtocolRAngleLoc(readSourceLocation());
7575 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7576 TL.setProtocolLoc(i, readSourceLocation());
7577}
7578
7579void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7580 TL.setStarLoc(readSourceLocation());
7581}
7582
7583void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7584 TL.setKWLoc(readSourceLocation());
7585 TL.setLParenLoc(readSourceLocation());
7586 TL.setRParenLoc(readSourceLocation());
7587}
7588
7589void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7590 TL.setKWLoc(readSourceLocation());
7591}
7592
7593void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7594 TL.setNameLoc(readSourceLocation());
7595}
7596
7597void TypeLocReader::VisitDependentBitIntTypeLoc(
7599 TL.setNameLoc(readSourceLocation());
7600}
7601
7602void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7603 // Nothing to do.
7604}
7605
7607 TypeLocReader TLR(*this);
7608 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7609 TLR.Visit(TL);
7610}
7611
7613 QualType InfoTy = readType();
7614 if (InfoTy.isNull())
7615 return nullptr;
7616
7617 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7618 readTypeLoc(TInfo->getTypeLoc());
7619 return TInfo;
7620}
7621
7623 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7624}
7625
7627 return ID >> 32;
7628}
7629
7631 // We don't need to erase the higher bits since if these bits are not 0,
7632 // it must be larger than NUM_PREDEF_TYPE_IDS.
7634}
7635
7636std::pair<ModuleFile *, unsigned>
7637ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7638 assert(!isPredefinedType(ID) &&
7639 "Predefined type shouldn't be in TypesLoaded");
7640 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7641 assert(ModuleFileIndex && "Untranslated Local Decl?");
7642
7643 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7644 assert(OwningModuleFile &&
7645 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7646
7647 return {OwningModuleFile,
7648 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7649}
7650
7652 assert(ContextObj && "reading type with no AST context");
7653 ASTContext &Context = *ContextObj;
7654
7655 unsigned FastQuals = ID & Qualifiers::FastMask;
7656
7657 if (isPredefinedType(ID)) {
7658 QualType T;
7659 unsigned Index = getIndexForTypeID(ID);
7660 switch ((PredefinedTypeIDs)Index) {
7662 // We should never use this one.
7663 llvm_unreachable("Invalid predefined type");
7664 break;
7666 return QualType();
7668 T = Context.VoidTy;
7669 break;
7671 T = Context.BoolTy;
7672 break;
7675 // FIXME: Check that the signedness of CharTy is correct!
7676 T = Context.CharTy;
7677 break;
7679 T = Context.UnsignedCharTy;
7680 break;
7682 T = Context.UnsignedShortTy;
7683 break;
7685 T = Context.UnsignedIntTy;
7686 break;
7688 T = Context.UnsignedLongTy;
7689 break;
7691 T = Context.UnsignedLongLongTy;
7692 break;
7694 T = Context.UnsignedInt128Ty;
7695 break;
7697 T = Context.SignedCharTy;
7698 break;
7700 T = Context.WCharTy;
7701 break;
7703 T = Context.ShortTy;
7704 break;
7705 case PREDEF_TYPE_INT_ID:
7706 T = Context.IntTy;
7707 break;
7709 T = Context.LongTy;
7710 break;
7712 T = Context.LongLongTy;
7713 break;
7715 T = Context.Int128Ty;
7716 break;
7718 T = Context.BFloat16Ty;
7719 break;
7721 T = Context.HalfTy;
7722 break;
7724 T = Context.FloatTy;
7725 break;
7727 T = Context.DoubleTy;
7728 break;
7730 T = Context.LongDoubleTy;
7731 break;
7733 T = Context.ShortAccumTy;
7734 break;
7736 T = Context.AccumTy;
7737 break;
7739 T = Context.LongAccumTy;
7740 break;
7742 T = Context.UnsignedShortAccumTy;
7743 break;
7745 T = Context.UnsignedAccumTy;
7746 break;
7748 T = Context.UnsignedLongAccumTy;
7749 break;
7751 T = Context.ShortFractTy;
7752 break;
7754 T = Context.FractTy;
7755 break;
7757 T = Context.LongFractTy;
7758 break;
7760 T = Context.UnsignedShortFractTy;
7761 break;
7763 T = Context.UnsignedFractTy;
7764 break;
7766 T = Context.UnsignedLongFractTy;
7767 break;
7769 T = Context.SatShortAccumTy;
7770 break;
7772 T = Context.SatAccumTy;
7773 break;
7775 T = Context.SatLongAccumTy;
7776 break;
7778 T = Context.SatUnsignedShortAccumTy;
7779 break;
7781 T = Context.SatUnsignedAccumTy;
7782 break;
7784 T = Context.SatUnsignedLongAccumTy;
7785 break;
7787 T = Context.SatShortFractTy;
7788 break;
7790 T = Context.SatFractTy;
7791 break;
7793 T = Context.SatLongFractTy;
7794 break;
7796 T = Context.SatUnsignedShortFractTy;
7797 break;
7799 T = Context.SatUnsignedFractTy;
7800 break;
7802 T = Context.SatUnsignedLongFractTy;
7803 break;
7805 T = Context.Float16Ty;
7806 break;
7808 T = Context.Float128Ty;
7809 break;
7811 T = Context.Ibm128Ty;
7812 break;
7814 T = Context.OverloadTy;
7815 break;
7817 T = Context.UnresolvedTemplateTy;
7818 break;
7820 T = Context.BoundMemberTy;
7821 break;
7823 T = Context.PseudoObjectTy;
7824 break;
7826 T = Context.DependentTy;
7827 break;
7829 T = Context.UnknownAnyTy;
7830 break;
7832 T = Context.NullPtrTy;
7833 break;
7835 T = Context.Char8Ty;
7836 break;
7838 T = Context.Char16Ty;
7839 break;
7841 T = Context.Char32Ty;
7842 break;
7844 T = Context.ObjCBuiltinIdTy;
7845 break;
7847 T = Context.ObjCBuiltinClassTy;
7848 break;
7850 T = Context.ObjCBuiltinSelTy;
7851 break;
7852#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7853 case PREDEF_TYPE_##Id##_ID: \
7854 T = Context.SingletonId; \
7855 break;
7856#include "clang/Basic/OpenCLImageTypes.def"
7857#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7858 case PREDEF_TYPE_##Id##_ID: \
7859 T = Context.Id##Ty; \
7860 break;
7861#include "clang/Basic/OpenCLExtensionTypes.def"
7863 T = Context.OCLSamplerTy;
7864 break;
7866 T = Context.OCLEventTy;
7867 break;
7869 T = Context.OCLClkEventTy;
7870 break;
7872 T = Context.OCLQueueTy;
7873 break;
7875 T = Context.OCLReserveIDTy;
7876 break;
7878 T = Context.getAutoDeductType();
7879 break;
7881 T = Context.getAutoRRefDeductType();
7882 break;
7884 T = Context.ARCUnbridgedCastTy;
7885 break;
7887 T = Context.BuiltinFnTy;
7888 break;
7890 T = Context.IncompleteMatrixIdxTy;
7891 break;
7893 T = Context.ArraySectionTy;
7894 break;
7896 T = Context.OMPArrayShapingTy;
7897 break;
7899 T = Context.OMPIteratorTy;
7900 break;
7901#define SVE_TYPE(Name, Id, SingletonId) \
7902 case PREDEF_TYPE_##Id##_ID: \
7903 T = Context.SingletonId; \
7904 break;
7905#include "clang/Basic/AArch64ACLETypes.def"
7906#define PPC_VECTOR_TYPE(Name, Id, Size) \
7907 case PREDEF_TYPE_##Id##_ID: \
7908 T = Context.Id##Ty; \
7909 break;
7910#include "clang/Basic/PPCTypes.def"
7911#define RVV_TYPE(Name, Id, SingletonId) \
7912 case PREDEF_TYPE_##Id##_ID: \
7913 T = Context.SingletonId; \
7914 break;
7915#include "clang/Basic/RISCVVTypes.def"
7916#define WASM_TYPE(Name, Id, SingletonId) \
7917 case PREDEF_TYPE_##Id##_ID: \
7918 T = Context.SingletonId; \
7919 break;
7920#include "clang/Basic/WebAssemblyReferenceTypes.def"
7921#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
7922 case PREDEF_TYPE_##Id##_ID: \
7923 T = Context.SingletonId; \
7924 break;
7925#include "clang/Basic/AMDGPUTypes.def"
7926#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
7927 case PREDEF_TYPE_##Id##_ID: \
7928 T = Context.SingletonId; \
7929 break;
7930#include "clang/Basic/HLSLIntangibleTypes.def"
7931 }
7932
7933 assert(!T.isNull() && "Unknown predefined type");
7934 return T.withFastQualifiers(FastQuals);
7935 }
7936
7937 unsigned Index = translateTypeIDToIndex(ID).second;
7938
7939 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7940 if (TypesLoaded[Index].isNull()) {
7941 TypesLoaded[Index] = readTypeRecord(ID);
7942 if (TypesLoaded[Index].isNull())
7943 return QualType();
7944
7945 TypesLoaded[Index]->setFromAST();
7946 if (DeserializationListener)
7947 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7948 TypesLoaded[Index]);
7949 }
7950
7951 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7952}
7953
7955 return GetType(getGlobalTypeID(F, LocalID));
7956}
7957
7959 LocalTypeID LocalID) const {
7960 if (isPredefinedType(LocalID))
7961 return LocalID;
7962
7963 if (!F.ModuleOffsetMap.empty())
7964 ReadModuleOffsetMap(F);
7965
7966 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
7967 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
7968
7969 if (ModuleFileIndex == 0)
7971
7972 ModuleFile &MF =
7973 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
7974 ModuleFileIndex = MF.Index + 1;
7975 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
7976}
7977
7980 switch (Kind) {
7982 return readExpr();
7984 return readTypeSourceInfo();
7987 SourceLocation TemplateKWLoc = readSourceLocation();
7988 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7989 SourceLocation TemplateNameLoc = readSourceLocation();
7991 ? readSourceLocation()
7992 : SourceLocation();
7993 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
7994 TemplateNameLoc, EllipsisLoc);
7995 }
8002 // FIXME: Is this right?
8003 return TemplateArgumentLocInfo();
8004 }
8005 llvm_unreachable("unexpected template argument loc");
8006}
8007
8009 TemplateArgument Arg = readTemplateArgument();
8010
8012 if (readBool()) // bool InfoHasSameExpr.
8014 }
8015 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
8016}
8017
8020 Result.setLAngleLoc(readSourceLocation());
8021 Result.setRAngleLoc(readSourceLocation());
8022 unsigned NumArgsAsWritten = readInt();
8023 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8024 Result.addArgument(readTemplateArgumentLoc());
8025}
8026
8030 readTemplateArgumentListInfo(Result);
8031 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
8032}
8033
8035
8037 if (NumCurrentElementsDeserializing) {
8038 // We arrange to not care about the complete redeclaration chain while we're
8039 // deserializing. Just remember that the AST has marked this one as complete
8040 // but that it's not actually complete yet, so we know we still need to
8041 // complete it later.
8042 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8043 return;
8044 }
8045
8046 if (!D->getDeclContext()) {
8047 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8048 return;
8049 }
8050
8051 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8052
8053 // If this is a named declaration, complete it by looking it up
8054 // within its context.
8055 //
8056 // FIXME: Merging a function definition should merge
8057 // all mergeable entities within it.
8058 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
8059 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8060 if (!getContext().getLangOpts().CPlusPlus &&
8061 isa<TranslationUnitDecl>(DC)) {
8062 // Outside of C++, we don't have a lookup table for the TU, so update
8063 // the identifier instead. (For C++ modules, we don't store decls
8064 // in the serialized identifier table, so we do the lookup in the TU.)
8065 auto *II = Name.getAsIdentifierInfo();
8066 assert(II && "non-identifier name in C?");
8067 if (II->isOutOfDate())
8068 updateOutOfDateIdentifier(*II);
8069 } else
8070 DC->lookup(Name);
8071 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
8072 // Find all declarations of this kind from the relevant context.
8073 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8074 auto *DC = cast<DeclContext>(DCDecl);
8076 FindExternalLexicalDecls(
8077 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8078 }
8079 }
8080 }
8081
8084 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8085 Template = CTSD->getSpecializedTemplate();
8086 Args = CTSD->getTemplateArgs().asArray();
8087 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8088 Template = VTSD->getSpecializedTemplate();
8089 Args = VTSD->getTemplateArgs().asArray();
8090 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8091 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8092 Template = Tmplt;
8093 Args = FD->getTemplateSpecializationArgs()->asArray();
8094 }
8095 }
8096
8097 if (Template) {
8098 // For partitial specialization, load all the specializations for safety.
8101 Template->loadLazySpecializationsImpl();
8102 else
8103 Template->loadLazySpecializationsImpl(Args);
8104 }
8105}
8106
8109 RecordLocation Loc = getLocalBitOffset(Offset);
8110 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8111 SavedStreamPosition SavedPosition(Cursor);
8112 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8113 Error(std::move(Err));
8114 return nullptr;
8115 }
8116 ReadingKindTracker ReadingKind(Read_Decl, *this);
8117 Deserializing D(this);
8118
8119 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8120 if (!MaybeCode) {
8121 Error(MaybeCode.takeError());
8122 return nullptr;
8123 }
8124 unsigned Code = MaybeCode.get();
8125
8126 ASTRecordReader Record(*this, *Loc.F);
8127 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8128 if (!MaybeRecCode) {
8129 Error(MaybeRecCode.takeError());
8130 return nullptr;
8131 }
8132 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8133 Error("malformed AST file: missing C++ ctor initializers");
8134 return nullptr;
8135 }
8136
8137 return Record.readCXXCtorInitializers();
8138}
8139
8141 assert(ContextObj && "reading base specifiers with no AST context");
8142 ASTContext &Context = *ContextObj;
8143
8144 RecordLocation Loc = getLocalBitOffset(Offset);
8145 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8146 SavedStreamPosition SavedPosition(Cursor);
8147 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8148 Error(std::move(Err));
8149 return nullptr;
8150 }
8151 ReadingKindTracker ReadingKind(Read_Decl, *this);
8152 Deserializing D(this);
8153
8154 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8155 if (!MaybeCode) {
8156 Error(MaybeCode.takeError());
8157 return nullptr;
8158 }
8159 unsigned Code = MaybeCode.get();
8160
8161 ASTRecordReader Record(*this, *Loc.F);
8162 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8163 if (!MaybeRecCode) {
8164 Error(MaybeCode.takeError());
8165 return nullptr;
8166 }
8167 unsigned RecCode = MaybeRecCode.get();
8168
8169 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8170 Error("malformed AST file: missing C++ base specifiers");
8171 return nullptr;
8172 }
8173
8174 unsigned NumBases = Record.readInt();
8175 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8176 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8177 for (unsigned I = 0; I != NumBases; ++I)
8178 Bases[I] = Record.readCXXBaseSpecifier();
8179 return Bases;
8180}
8181
8183 LocalDeclID LocalID) const {
8184 if (LocalID < NUM_PREDEF_DECL_IDS)
8185 return GlobalDeclID(LocalID.getRawValue());
8186
8187 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8188 DeclID ID = LocalID.getLocalDeclIndex();
8189
8190 if (!F.ModuleOffsetMap.empty())
8191 ReadModuleOffsetMap(F);
8192
8193 ModuleFile *OwningModuleFile =
8194 OwningModuleFileIndex == 0
8195 ? &F
8196 : F.TransitiveImports[OwningModuleFileIndex - 1];
8197
8198 if (OwningModuleFileIndex == 0)
8199 ID -= NUM_PREDEF_DECL_IDS;
8200
8201 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8202 return GlobalDeclID(NewModuleFileIndex, ID);
8203}
8204
8206 // Predefined decls aren't from any module.
8207 if (ID < NUM_PREDEF_DECL_IDS)
8208 return false;
8209
8210 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8211 return M.Index == ModuleFileIndex - 1;
8212}
8213
8215 // Predefined decls aren't from any module.
8216 if (ID < NUM_PREDEF_DECL_IDS)
8217 return nullptr;
8218
8219 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8220 assert(ModuleFileIndex && "Untranslated Local Decl?");
8221
8222 return &getModuleManager()[ModuleFileIndex - 1];
8223}
8224
8226 if (!D->isFromASTFile())
8227 return nullptr;
8228
8229 return getOwningModuleFile(D->getGlobalID());
8230}
8231
8233 if (ID < NUM_PREDEF_DECL_IDS)
8234 return SourceLocation();
8235
8236 if (Decl *D = GetExistingDecl(ID))
8237 return D->getLocation();
8238
8240 DeclCursorForID(ID, Loc);
8241 return Loc;
8242}
8243
8244Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8245 assert(ContextObj && "reading predefined decl without AST context");
8246 ASTContext &Context = *ContextObj;
8247 Decl *NewLoaded = nullptr;
8248 switch (ID) {
8250 return nullptr;
8251
8253 return Context.getTranslationUnitDecl();
8254
8256 if (Context.ObjCIdDecl)
8257 return Context.ObjCIdDecl;
8258 NewLoaded = Context.getObjCIdDecl();
8259 break;
8260
8262 if (Context.ObjCSelDecl)
8263 return Context.ObjCSelDecl;
8264 NewLoaded = Context.getObjCSelDecl();
8265 break;
8266
8268 if (Context.ObjCClassDecl)
8269 return Context.ObjCClassDecl;
8270 NewLoaded = Context.getObjCClassDecl();
8271 break;
8272
8274 if (Context.ObjCProtocolClassDecl)
8275 return Context.ObjCProtocolClassDecl;
8276 NewLoaded = Context.getObjCProtocolDecl();
8277 break;
8278
8280 if (Context.Int128Decl)
8281 return Context.Int128Decl;
8282 NewLoaded = Context.getInt128Decl();
8283 break;
8284
8286 if (Context.UInt128Decl)
8287 return Context.UInt128Decl;
8288 NewLoaded = Context.getUInt128Decl();
8289 break;
8290
8292 if (Context.ObjCInstanceTypeDecl)
8293 return Context.ObjCInstanceTypeDecl;
8294 NewLoaded = Context.getObjCInstanceTypeDecl();
8295 break;
8296
8298 if (Context.BuiltinVaListDecl)
8299 return Context.BuiltinVaListDecl;
8300 NewLoaded = Context.getBuiltinVaListDecl();
8301 break;
8302
8304 if (Context.VaListTagDecl)
8305 return Context.VaListTagDecl;
8306 NewLoaded = Context.getVaListTagDecl();
8307 break;
8308
8310 if (Context.BuiltinMSVaListDecl)
8311 return Context.BuiltinMSVaListDecl;
8312 NewLoaded = Context.getBuiltinMSVaListDecl();
8313 break;
8314
8316 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8317 return Context.getMSGuidTagDecl();
8318
8320 if (Context.ExternCContext)
8321 return Context.ExternCContext;
8322 NewLoaded = Context.getExternCContextDecl();
8323 break;
8324
8326 if (Context.CFConstantStringTypeDecl)
8327 return Context.CFConstantStringTypeDecl;
8328 NewLoaded = Context.getCFConstantStringDecl();
8329 break;
8330
8332 if (Context.CFConstantStringTagDecl)
8333 return Context.CFConstantStringTagDecl;
8334 NewLoaded = Context.getCFConstantStringTagDecl();
8335 break;
8336
8338 return Context.getMSTypeInfoTagDecl();
8339
8340#define BuiltinTemplate(BTName) \
8341 case PREDEF_DECL##BTName##_ID: \
8342 if (Context.Decl##BTName) \
8343 return Context.Decl##BTName; \
8344 NewLoaded = Context.get##BTName##Decl(); \
8345 break;
8346#include "clang/Basic/BuiltinTemplates.inc"
8347
8349 llvm_unreachable("Invalid decl ID");
8350 break;
8351 }
8352
8353 assert(NewLoaded && "Failed to load predefined decl?");
8354
8355 if (DeserializationListener)
8356 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8357
8358 return NewLoaded;
8359}
8360
8361unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8362 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8363 if (!OwningModuleFile) {
8364 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8365 return GlobalID.getRawValue();
8366 }
8367
8368 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8369}
8370
8372 assert(ContextObj && "reading decl with no AST context");
8373
8374 if (ID < NUM_PREDEF_DECL_IDS) {
8375 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8376 if (D) {
8377 // Track that we have merged the declaration with ID \p ID into the
8378 // pre-existing predefined declaration \p D.
8379 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8380 if (Merged.empty())
8381 Merged.push_back(ID);
8382 }
8383 return D;
8384 }
8385
8386 unsigned Index = translateGlobalDeclIDToIndex(ID);
8387
8388 if (Index >= DeclsLoaded.size()) {
8389 assert(0 && "declaration ID out-of-range for AST file");
8390 Error("declaration ID out-of-range for AST file");
8391 return nullptr;
8392 }
8393
8394 return DeclsLoaded[Index];
8395}
8396
8398 if (ID < NUM_PREDEF_DECL_IDS)
8399 return GetExistingDecl(ID);
8400
8401 unsigned Index = translateGlobalDeclIDToIndex(ID);
8402
8403 if (Index >= DeclsLoaded.size()) {
8404 assert(0 && "declaration ID out-of-range for AST file");
8405 Error("declaration ID out-of-range for AST file");
8406 return nullptr;
8407 }
8408
8409 if (!DeclsLoaded[Index]) {
8410 ReadDeclRecord(ID);
8411 if (DeserializationListener)
8412 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8413 }
8414
8415 return DeclsLoaded[Index];
8416}
8417
8419 GlobalDeclID GlobalID) {
8420 if (GlobalID < NUM_PREDEF_DECL_IDS)
8421 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8422
8423 if (!M.ModuleOffsetMap.empty())
8424 ReadModuleOffsetMap(M);
8425
8426 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8427 DeclID ID = GlobalID.getLocalDeclIndex();
8428
8429 if (Owner == &M) {
8430 ID += NUM_PREDEF_DECL_IDS;
8431 return LocalDeclID::get(*this, M, ID);
8432 }
8433
8434 uint64_t OrignalModuleFileIndex = 0;
8435 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8436 if (M.TransitiveImports[I] == Owner) {
8437 OrignalModuleFileIndex = I + 1;
8438 break;
8439 }
8440
8441 if (!OrignalModuleFileIndex)
8442 return LocalDeclID();
8443
8444 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8445}
8446
8448 unsigned &Idx) {
8449 if (Idx >= Record.size()) {
8450 Error("Corrupted AST file");
8451 return GlobalDeclID(0);
8452 }
8453
8454 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8455}
8456
8457/// Resolve the offset of a statement into a statement.
8458///
8459/// This operation will read a new statement from the external
8460/// source each time it is called, and is meant to be used via a
8461/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8463 // Switch case IDs are per Decl.
8464 ClearSwitchCaseIDs();
8465
8466 // Offset here is a global offset across the entire chain.
8467 RecordLocation Loc = getLocalBitOffset(Offset);
8468 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8469 Error(std::move(Err));
8470 return nullptr;
8471 }
8472 assert(NumCurrentElementsDeserializing == 0 &&
8473 "should not be called while already deserializing");
8474 Deserializing D(this);
8475 return ReadStmtFromStream(*Loc.F);
8476}
8477
8478bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8479 const Decl *D) {
8480 assert(D);
8481
8482 auto It = SpecLookups.find(D);
8483 if (It == SpecLookups.end())
8484 return false;
8485
8486 // Get Decl may violate the iterator from SpecializationsLookups so we store
8487 // the DeclIDs in ahead.
8489 It->second.Table.findAll();
8490
8491 // Since we've loaded all the specializations, we can erase it from
8492 // the lookup table.
8493 SpecLookups.erase(It);
8494
8495 bool NewSpecsFound = false;
8496 Deserializing LookupResults(this);
8497 for (auto &Info : Infos) {
8498 if (GetExistingDecl(Info))
8499 continue;
8500 NewSpecsFound = true;
8501 GetDecl(Info);
8502 }
8503
8504 return NewSpecsFound;
8505}
8506
8507bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) {
8508 assert(D);
8509
8510 CompleteRedeclChain(D);
8511 bool NewSpecsFound =
8512 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8513 if (OnlyPartial)
8514 return NewSpecsFound;
8515
8516 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8517 return NewSpecsFound;
8518}
8519
8520bool ASTReader::LoadExternalSpecializationsImpl(
8521 SpecLookupTableTy &SpecLookups, const Decl *D,
8522 ArrayRef<TemplateArgument> TemplateArgs) {
8523 assert(D);
8524
8525 auto It = SpecLookups.find(D);
8526 if (It == SpecLookups.end())
8527 return false;
8528
8529 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8530 std::string Name;
8531 llvm::raw_string_ostream OS(Name);
8532 auto *ND = cast<NamedDecl>(D);
8533 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(),
8534 /*Qualified=*/true);
8535 return Name;
8536 });
8537
8538 Deserializing LookupResults(this);
8539 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8540
8541 // Get Decl may violate the iterator from SpecLookups
8543 It->second.Table.find(HashValue);
8544
8545 bool NewSpecsFound = false;
8546 for (auto &Info : Infos) {
8547 if (GetExistingDecl(Info))
8548 continue;
8549 NewSpecsFound = true;
8550 GetDecl(Info);
8551 }
8552
8553 return NewSpecsFound;
8554}
8555
8557 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8558 assert(D);
8559
8560 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8561 PartialSpecializationsLookups, D, TemplateArgs);
8562 NewDeclsFound |=
8563 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8564
8565 return NewDeclsFound;
8566}
8567
8569 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8570 SmallVectorImpl<Decl *> &Decls) {
8571 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8572
8573 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8574 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8575 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8576 auto K = (Decl::Kind)+LexicalDecls[I];
8577 if (!IsKindWeWant(K))
8578 continue;
8579
8580 auto ID = (DeclID) + LexicalDecls[I + 1];
8581
8582 // Don't add predefined declarations to the lexical context more
8583 // than once.
8584 if (ID < NUM_PREDEF_DECL_IDS) {
8585 if (PredefsVisited[ID])
8586 continue;
8587
8588 PredefsVisited[ID] = true;
8589 }
8590
8591 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8592 assert(D->getKind() == K && "wrong kind for lexical decl");
8593 if (!DC->isDeclInLexicalTraversal(D))
8594 Decls.push_back(D);
8595 }
8596 }
8597 };
8598
8599 if (isa<TranslationUnitDecl>(DC)) {
8600 for (const auto &Lexical : TULexicalDecls)
8601 Visit(Lexical.first, Lexical.second);
8602 } else {
8603 auto I = LexicalDecls.find(DC);
8604 if (I != LexicalDecls.end())
8605 Visit(I->second.first, I->second.second);
8606 }
8607
8608 ++NumLexicalDeclContextsRead;
8609}
8610
8611namespace {
8612
8613class UnalignedDeclIDComp {
8614 ASTReader &Reader;
8615 ModuleFile &Mod;
8616
8617public:
8618 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8619 : Reader(Reader), Mod(M) {}
8620
8621 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8622 SourceLocation LHS = getLocation(L);
8623 SourceLocation RHS = getLocation(R);
8624 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8625 }
8626
8627 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8628 SourceLocation RHS = getLocation(R);
8629 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8630 }
8631
8632 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8633 SourceLocation LHS = getLocation(L);
8634 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8635 }
8636
8637 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8638 return Reader.getSourceManager().getFileLoc(
8640 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8641 }
8642};
8643
8644} // namespace
8645
8647 unsigned Offset, unsigned Length,
8648 SmallVectorImpl<Decl *> &Decls) {
8649 SourceManager &SM = getSourceManager();
8650
8651 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8652 if (I == FileDeclIDs.end())
8653 return;
8654
8655 FileDeclsInfo &DInfo = I->second;
8656 if (DInfo.Decls.empty())
8657 return;
8658
8660 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8661 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8662
8663 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8665 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8666 if (BeginIt != DInfo.Decls.begin())
8667 --BeginIt;
8668
8669 // If we are pointing at a top-level decl inside an objc container, we need
8670 // to backtrack until we find it otherwise we will fail to report that the
8671 // region overlaps with an objc container.
8672 while (BeginIt != DInfo.Decls.begin() &&
8673 GetDecl(getGlobalDeclID(*DInfo.Mod,
8674 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8675 ->isTopLevelDeclInObjCContainer())
8676 --BeginIt;
8677
8679 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8680 if (EndIt != DInfo.Decls.end())
8681 ++EndIt;
8682
8683 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8684 ++DIt)
8685 Decls.push_back(GetDecl(getGlobalDeclID(
8686 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8687}
8688
8690 DeclarationName Name,
8691 const DeclContext *OriginalDC) {
8692 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8693 "DeclContext has no visible decls in storage");
8694 if (!Name)
8695 return false;
8696
8697 // Load the list of declarations.
8700
8701 auto Find = [&, this](auto &&Table, auto &&Key) {
8702 for (GlobalDeclID ID : Table.find(Key)) {
8703 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8704 if (ND->getDeclName() == Name && Found.insert(ND).second)
8705 Decls.push_back(ND);
8706 }
8707 };
8708
8709 Deserializing LookupResults(this);
8710
8711 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8712 // available.
8713 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8714 ++NumVisibleDeclContextsRead;
8715 Find(It->second.Table, Name);
8716 }
8717
8718 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8719 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8720 ++NumModuleLocalVisibleDeclContexts;
8721 Find(It->second.Table, std::make_pair(Name, NamedModule));
8722 }
8723 };
8724 if (auto *NamedModule =
8725 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8726 : nullptr)
8727 FindModuleLocalLookup(NamedModule);
8728 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8729 // We're going to find a decl but the decl context of the lookup is
8730 // unspecified. In this case, the OriginalDC may be the decl context in other
8731 // module.
8732 if (ContextObj && ContextObj->getCurrentNamedModule())
8733 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8734
8735 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8736 ++NumTULocalVisibleDeclContexts;
8737 Find(It->second.Table, Name);
8738 }
8739
8740 SetExternalVisibleDeclsForName(DC, Name, Decls);
8741 return !Decls.empty();
8742}
8743
8745 if (!DC->hasExternalVisibleStorage())
8746 return;
8747
8748 DeclsMap Decls;
8749
8750 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8751 auto It = LookupTables.find(DC);
8752 if (It == LookupTables.end())
8753 return;
8754
8755 NumRead++;
8756
8757 for (GlobalDeclID ID : It->second.Table.findAll()) {
8758 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8759 Decls[ND->getDeclName()].push_back(ND);
8760 }
8761
8762 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8763 };
8764
8765 findAll(Lookups, NumVisibleDeclContextsRead);
8766 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8767 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8768
8769 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8770 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8771 }
8772 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8773}
8774
8777 auto I = Lookups.find(Primary);
8778 return I == Lookups.end() ? nullptr : &I->second;
8779}
8780
8783 auto I = ModuleLocalLookups.find(Primary);
8784 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8785}
8786
8789 auto I = TULocalLookups.find(Primary);
8790 return I == TULocalLookups.end() ? nullptr : &I->second;
8791}
8792
8795 assert(D->isCanonicalDecl());
8796 auto &LookupTable =
8797 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8798 auto I = LookupTable.find(D);
8799 return I == LookupTable.end() ? nullptr : &I->second;
8800}
8801
8803 assert(D->isCanonicalDecl());
8804 return PartialSpecializationsLookups.contains(D) ||
8805 SpecializationsLookups.contains(D);
8806}
8807
8808/// Under non-PCH compilation the consumer receives the objc methods
8809/// before receiving the implementation, and codegen depends on this.
8810/// We simulate this by deserializing and passing to consumer the methods of the
8811/// implementation before passing the deserialized implementation decl.
8813 ASTConsumer *Consumer) {
8814 assert(ImplD && Consumer);
8815
8816 for (auto *I : ImplD->methods())
8817 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8818
8819 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8820}
8821
8822void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8823 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8824 PassObjCImplDeclToConsumer(ImplD, Consumer);
8825 else
8826 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8827}
8828
8829void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8830 Consumer->HandleVTable(RD);
8831}
8832
8834 this->Consumer = Consumer;
8835
8836 if (Consumer)
8837 PassInterestingDeclsToConsumer();
8838
8839 if (DeserializationListener)
8840 DeserializationListener->ReaderInitialized(this);
8841}
8842
8844 std::fprintf(stderr, "*** AST File Statistics:\n");
8845
8846 unsigned NumTypesLoaded =
8847 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8848 unsigned NumDeclsLoaded =
8849 DeclsLoaded.size() -
8850 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8851 unsigned NumIdentifiersLoaded =
8852 IdentifiersLoaded.size() -
8853 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8854 unsigned NumMacrosLoaded =
8855 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8856 unsigned NumSelectorsLoaded =
8857 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8858
8859 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8860 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8861 NumSLocEntriesRead, TotalNumSLocEntries,
8862 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8863 if (!TypesLoaded.empty())
8864 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8865 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8866 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8867 if (!DeclsLoaded.empty())
8868 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8869 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8870 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8871 if (!IdentifiersLoaded.empty())
8872 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8873 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8874 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8875 if (!MacrosLoaded.empty())
8876 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8877 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8878 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8879 if (!SelectorsLoaded.empty())
8880 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8881 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8882 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8883 if (TotalNumStatements)
8884 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8885 NumStatementsRead, TotalNumStatements,
8886 ((float)NumStatementsRead/TotalNumStatements * 100));
8887 if (TotalNumMacros)
8888 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8889 NumMacrosRead, TotalNumMacros,
8890 ((float)NumMacrosRead/TotalNumMacros * 100));
8891 if (TotalLexicalDeclContexts)
8892 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8893 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8894 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8895 * 100));
8896 if (TotalVisibleDeclContexts)
8897 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8898 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8899 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8900 * 100));
8901 if (TotalModuleLocalVisibleDeclContexts)
8902 std::fprintf(
8903 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
8904 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
8905 ((float)NumModuleLocalVisibleDeclContexts /
8906 TotalModuleLocalVisibleDeclContexts * 100));
8907 if (TotalTULocalVisibleDeclContexts)
8908 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
8909 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
8910 ((float)NumTULocalVisibleDeclContexts /
8911 TotalTULocalVisibleDeclContexts * 100));
8912 if (TotalNumMethodPoolEntries)
8913 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8914 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8915 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8916 * 100));
8917 if (NumMethodPoolLookups)
8918 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8919 NumMethodPoolHits, NumMethodPoolLookups,
8920 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8921 if (NumMethodPoolTableLookups)
8922 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8923 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8924 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8925 * 100.0));
8926 if (NumIdentifierLookupHits)
8927 std::fprintf(stderr,
8928 " %u / %u identifier table lookups succeeded (%f%%)\n",
8929 NumIdentifierLookupHits, NumIdentifierLookups,
8930 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8931
8932 if (GlobalIndex) {
8933 std::fprintf(stderr, "\n");
8934 GlobalIndex->printStats();
8935 }
8936
8937 std::fprintf(stderr, "\n");
8938 dump();
8939 std::fprintf(stderr, "\n");
8940}
8941
8942template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8943LLVM_DUMP_METHOD static void
8944dumpModuleIDMap(StringRef Name,
8945 const ContinuousRangeMap<Key, ModuleFile *,
8946 InitialCapacity> &Map) {
8947 if (Map.begin() == Map.end())
8948 return;
8949
8951
8952 llvm::errs() << Name << ":\n";
8953 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8954 I != IEnd; ++I)
8955 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
8956 << "\n";
8957}
8958
8959LLVM_DUMP_METHOD void ASTReader::dump() {
8960 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8961 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8962 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8963 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8964 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8965 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8966 dumpModuleIDMap("Global preprocessed entity map",
8967 GlobalPreprocessedEntityMap);
8968
8969 llvm::errs() << "\n*** PCH/Modules Loaded:";
8970 for (ModuleFile &M : ModuleMgr)
8971 M.dump();
8972}
8973
8974/// Return the amount of memory used by memory buffers, breaking down
8975/// by heap-backed versus mmap'ed memory.
8977 for (ModuleFile &I : ModuleMgr) {
8978 if (llvm::MemoryBuffer *buf = I.Buffer) {
8979 size_t bytes = buf->getBufferSize();
8980 switch (buf->getBufferKind()) {
8981 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8982 sizes.malloc_bytes += bytes;
8983 break;
8984 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8985 sizes.mmap_bytes += bytes;
8986 break;
8987 }
8988 }
8989 }
8990}
8991
8993 SemaObj = &S;
8994 S.addExternalSource(this);
8995
8996 // Makes sure any declarations that were deserialized "too early"
8997 // still get added to the identifier's declaration chains.
8998 for (GlobalDeclID ID : PreloadedDeclIDs) {
8999 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
9000 pushExternalDeclIntoScope(D, D->getDeclName());
9001 }
9002 PreloadedDeclIDs.clear();
9003
9004 // FIXME: What happens if these are changed by a module import?
9005 if (!FPPragmaOptions.empty()) {
9006 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9007 FPOptionsOverride NewOverrides =
9008 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9009 SemaObj->CurFPFeatures =
9010 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9011 }
9012
9013 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9014 Decl *D = GetDecl(ID);
9015 if (auto *FD = dyn_cast<FunctionDecl>(D))
9016 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9017 else if (auto *BD = dyn_cast<BlockDecl>(D))
9018 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9019 else
9020 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9021 }
9022 DeclsWithEffectsToVerify.clear();
9023
9024 SemaObj->OpenCLFeatures = OpenCLExtensions;
9025
9026 UpdateSema();
9027}
9028
9030 assert(SemaObj && "no Sema to update");
9031
9032 // Load the offsets of the declarations that Sema references.
9033 // They will be lazily deserialized when needed.
9034 if (!SemaDeclRefs.empty()) {
9035 assert(SemaDeclRefs.size() % 3 == 0);
9036 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9037 if (!SemaObj->StdNamespace)
9038 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9039 if (!SemaObj->StdBadAlloc)
9040 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9041 if (!SemaObj->StdAlignValT)
9042 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9043 }
9044 SemaDeclRefs.clear();
9045 }
9046
9047 // Update the state of pragmas. Use the same API as if we had encountered the
9048 // pragma in the source.
9049 if(OptimizeOffPragmaLocation.isValid())
9050 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9051 if (PragmaMSStructState != -1)
9052 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9053 if (PointersToMembersPragmaLocation.isValid()) {
9054 SemaObj->ActOnPragmaMSPointersToMembers(
9056 PragmaMSPointersToMembersState,
9057 PointersToMembersPragmaLocation);
9058 }
9059 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9060
9061 if (PragmaAlignPackCurrentValue) {
9062 // The bottom of the stack might have a default value. It must be adjusted
9063 // to the current value to ensure that the packing state is preserved after
9064 // popping entries that were included/imported from a PCH/module.
9065 bool DropFirst = false;
9066 if (!PragmaAlignPackStack.empty() &&
9067 PragmaAlignPackStack.front().Location.isInvalid()) {
9068 assert(PragmaAlignPackStack.front().Value ==
9069 SemaObj->AlignPackStack.DefaultValue &&
9070 "Expected a default alignment value");
9071 SemaObj->AlignPackStack.Stack.emplace_back(
9072 PragmaAlignPackStack.front().SlotLabel,
9073 SemaObj->AlignPackStack.CurrentValue,
9074 SemaObj->AlignPackStack.CurrentPragmaLocation,
9075 PragmaAlignPackStack.front().PushLocation);
9076 DropFirst = true;
9077 }
9078 for (const auto &Entry :
9079 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9080 SemaObj->AlignPackStack.Stack.emplace_back(
9081 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9082 }
9083 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9084 assert(*PragmaAlignPackCurrentValue ==
9085 SemaObj->AlignPackStack.DefaultValue &&
9086 "Expected a default align and pack value");
9087 // Keep the current values.
9088 } else {
9089 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9090 SemaObj->AlignPackStack.CurrentPragmaLocation =
9091 PragmaAlignPackCurrentLocation;
9092 }
9093 }
9094 if (FpPragmaCurrentValue) {
9095 // The bottom of the stack might have a default value. It must be adjusted
9096 // to the current value to ensure that fp-pragma state is preserved after
9097 // popping entries that were included/imported from a PCH/module.
9098 bool DropFirst = false;
9099 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9100 assert(FpPragmaStack.front().Value ==
9101 SemaObj->FpPragmaStack.DefaultValue &&
9102 "Expected a default pragma float_control value");
9103 SemaObj->FpPragmaStack.Stack.emplace_back(
9104 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9105 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9106 FpPragmaStack.front().PushLocation);
9107 DropFirst = true;
9108 }
9109 for (const auto &Entry :
9110 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9111 SemaObj->FpPragmaStack.Stack.emplace_back(
9112 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9113 if (FpPragmaCurrentLocation.isInvalid()) {
9114 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9115 "Expected a default pragma float_control value");
9116 // Keep the current values.
9117 } else {
9118 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9119 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9120 }
9121 }
9122
9123 // For non-modular AST files, restore visiblity of modules.
9124 for (auto &Import : PendingImportedModulesSema) {
9125 if (Import.ImportLoc.isInvalid())
9126 continue;
9127 if (Module *Imported = getSubmodule(Import.ID)) {
9128 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9129 }
9130 }
9131 PendingImportedModulesSema.clear();
9132}
9133
9135 // Note that we are loading an identifier.
9136 Deserializing AnIdentifier(this);
9137
9138 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9139 NumIdentifierLookups,
9140 NumIdentifierLookupHits);
9141
9142 // We don't need to do identifier table lookups in C++ modules (we preload
9143 // all interesting declarations, and don't need to use the scope for name
9144 // lookups). Perform the lookup in PCH files, though, since we don't build
9145 // a complete initial identifier table if we're carrying on from a PCH.
9146 if (PP.getLangOpts().CPlusPlus) {
9147 for (auto *F : ModuleMgr.pch_modules())
9148 if (Visitor(*F))
9149 break;
9150 } else {
9151 // If there is a global index, look there first to determine which modules
9152 // provably do not have any results for this identifier.
9154 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9155 if (!loadGlobalIndex()) {
9156 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9157 HitsPtr = &Hits;
9158 }
9159 }
9160
9161 ModuleMgr.visit(Visitor, HitsPtr);
9162 }
9163
9164 IdentifierInfo *II = Visitor.getIdentifierInfo();
9165 markIdentifierUpToDate(II);
9166 return II;
9167}
9168
9169namespace clang {
9170
9171 /// An identifier-lookup iterator that enumerates all of the
9172 /// identifiers stored within a set of AST files.
9174 /// The AST reader whose identifiers are being enumerated.
9175 const ASTReader &Reader;
9176
9177 /// The current index into the chain of AST files stored in
9178 /// the AST reader.
9179 unsigned Index;
9180
9181 /// The current position within the identifier lookup table
9182 /// of the current AST file.
9183 ASTIdentifierLookupTable::key_iterator Current;
9184
9185 /// The end position within the identifier lookup table of
9186 /// the current AST file.
9187 ASTIdentifierLookupTable::key_iterator End;
9188
9189 /// Whether to skip any modules in the ASTReader.
9190 bool SkipModules;
9191
9192 public:
9193 explicit ASTIdentifierIterator(const ASTReader &Reader,
9194 bool SkipModules = false);
9195
9196 StringRef Next() override;
9197 };
9198
9199} // namespace clang
9200
9202 bool SkipModules)
9203 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9204}
9205
9207 while (Current == End) {
9208 // If we have exhausted all of our AST files, we're done.
9209 if (Index == 0)
9210 return StringRef();
9211
9212 --Index;
9213 ModuleFile &F = Reader.ModuleMgr[Index];
9214 if (SkipModules && F.isModule())
9215 continue;
9216
9217 ASTIdentifierLookupTable *IdTable =
9219 Current = IdTable->key_begin();
9220 End = IdTable->key_end();
9221 }
9222
9223 // We have any identifiers remaining in the current AST file; return
9224 // the next one.
9225 StringRef Result = *Current;
9226 ++Current;
9227 return Result;
9228}
9229
9230namespace {
9231
9232/// A utility for appending two IdentifierIterators.
9233class ChainedIdentifierIterator : public IdentifierIterator {
9234 std::unique_ptr<IdentifierIterator> Current;
9235 std::unique_ptr<IdentifierIterator> Queued;
9236
9237public:
9238 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9239 std::unique_ptr<IdentifierIterator> Second)
9240 : Current(std::move(First)), Queued(std::move(Second)) {}
9241
9242 StringRef Next() override {
9243 if (!Current)
9244 return StringRef();
9245
9246 StringRef result = Current->Next();
9247 if (!result.empty())
9248 return result;
9249
9250 // Try the queued iterator, which may itself be empty.
9251 Current.reset();
9252 std::swap(Current, Queued);
9253 return Next();
9254 }
9255};
9256
9257} // namespace
9258
9260 if (!loadGlobalIndex()) {
9261 std::unique_ptr<IdentifierIterator> ReaderIter(
9262 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9263 std::unique_ptr<IdentifierIterator> ModulesIter(
9264 GlobalIndex->createIdentifierIterator());
9265 return new ChainedIdentifierIterator(std::move(ReaderIter),
9266 std::move(ModulesIter));
9267 }
9268
9269 return new ASTIdentifierIterator(*this);
9270}
9271
9272namespace clang {
9273namespace serialization {
9274
9276 ASTReader &Reader;
9277 Selector Sel;
9278 unsigned PriorGeneration;
9279 unsigned InstanceBits = 0;
9280 unsigned FactoryBits = 0;
9281 bool InstanceHasMoreThanOneDecl = false;
9282 bool FactoryHasMoreThanOneDecl = false;
9283 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9284 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9285
9286 public:
9288 unsigned PriorGeneration)
9289 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9290
9292 if (!M.SelectorLookupTable)
9293 return false;
9294
9295 // If we've already searched this module file, skip it now.
9296 if (M.Generation <= PriorGeneration)
9297 return true;
9298
9299 ++Reader.NumMethodPoolTableLookups;
9300 ASTSelectorLookupTable *PoolTable
9302 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9303 if (Pos == PoolTable->end())
9304 return false;
9305
9306 ++Reader.NumMethodPoolTableHits;
9307 ++Reader.NumSelectorsRead;
9308 // FIXME: Not quite happy with the statistics here. We probably should
9309 // disable this tracking when called via LoadSelector.
9310 // Also, should entries without methods count as misses?
9311 ++Reader.NumMethodPoolEntriesRead;
9313 if (Reader.DeserializationListener)
9314 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9315
9316 // Append methods in the reverse order, so that later we can process them
9317 // in the order they appear in the source code by iterating through
9318 // the vector in the reverse order.
9319 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9320 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9321 InstanceBits = Data.InstanceBits;
9322 FactoryBits = Data.FactoryBits;
9323 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9324 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9325 return false;
9326 }
9327
9328 /// Retrieve the instance methods found by this visitor.
9330 return InstanceMethods;
9331 }
9332
9333 /// Retrieve the instance methods found by this visitor.
9335 return FactoryMethods;
9336 }
9337
9338 unsigned getInstanceBits() const { return InstanceBits; }
9339 unsigned getFactoryBits() const { return FactoryBits; }
9340
9342 return InstanceHasMoreThanOneDecl;
9343 }
9344
9345 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9346 };
9347
9348} // namespace serialization
9349} // namespace clang
9350
9351/// Add the given set of methods to the method list.
9353 ObjCMethodList &List) {
9354 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9355 S.ObjC().addMethodToGlobalList(&List, M);
9356}
9357
9359 // Get the selector generation and update it to the current generation.
9360 unsigned &Generation = SelectorGeneration[Sel];
9361 unsigned PriorGeneration = Generation;
9362 Generation = getGeneration();
9363 SelectorOutOfDate[Sel] = false;
9364
9365 // Search for methods defined with this selector.
9366 ++NumMethodPoolLookups;
9367 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9368 ModuleMgr.visit(Visitor);
9369
9370 if (Visitor.getInstanceMethods().empty() &&
9371 Visitor.getFactoryMethods().empty())
9372 return;
9373
9374 ++NumMethodPoolHits;
9375
9376 if (!getSema())
9377 return;
9378
9379 Sema &S = *getSema();
9380 auto &Methods = S.ObjC().MethodPool[Sel];
9381
9382 Methods.first.setBits(Visitor.getInstanceBits());
9383 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9384 Methods.second.setBits(Visitor.getFactoryBits());
9385 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9386
9387 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9388 // when building a module we keep every method individually and may need to
9389 // update hasMoreThanOneDecl as we add the methods.
9390 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9391 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9392}
9393
9395 if (SelectorOutOfDate[Sel])
9396 ReadMethodPool(Sel);
9397}
9398
9401 Namespaces.clear();
9402
9403 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9404 if (NamespaceDecl *Namespace
9405 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9406 Namespaces.push_back(Namespace);
9407 }
9408}
9409
9411 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9412 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9413 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9414 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
9416 Undefined.insert(std::make_pair(D, Loc));
9417 }
9418 UndefinedButUsed.clear();
9419}
9420
9422 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9423 Exprs) {
9424 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9425 FieldDecl *FD =
9426 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9427 uint64_t Count = DelayedDeleteExprs[Idx++];
9428 for (uint64_t C = 0; C < Count; ++C) {
9429 SourceLocation DeleteLoc =
9430 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9431 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9432 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9433 }
9434 }
9435}
9436
9438 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9439 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9440 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9441 if (Var)
9442 TentativeDefs.push_back(Var);
9443 }
9444 TentativeDefinitions.clear();
9445}
9446
9449 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9451 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9452 if (D)
9453 Decls.push_back(D);
9454 }
9455 UnusedFileScopedDecls.clear();
9456}
9457
9460 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9462 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9463 if (D)
9464 Decls.push_back(D);
9465 }
9466 DelegatingCtorDecls.clear();
9467}
9468
9470 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9472 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9473 if (D)
9474 Decls.push_back(D);
9475 }
9476 ExtVectorDecls.clear();
9477}
9478
9481 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9482 ++I) {
9483 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9484 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9485 if (D)
9486 Decls.insert(D);
9487 }
9488 UnusedLocalTypedefNameCandidates.clear();
9489}
9490
9493 for (auto I : DeclsToCheckForDeferredDiags) {
9494 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9495 if (D)
9496 Decls.insert(D);
9497 }
9498 DeclsToCheckForDeferredDiags.clear();
9499}
9500
9502 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9503 if (ReferencedSelectorsData.empty())
9504 return;
9505
9506 // If there are @selector references added them to its pool. This is for
9507 // implementation of -Wselector.
9508 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9509 unsigned I = 0;
9510 while (I < DataSize) {
9511 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9512 SourceLocation SelLoc
9513 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9514 Sels.push_back(std::make_pair(Sel, SelLoc));
9515 }
9516 ReferencedSelectorsData.clear();
9517}
9518
9520 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9521 if (WeakUndeclaredIdentifiers.empty())
9522 return;
9523
9524 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9525 IdentifierInfo *WeakId
9526 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9527 IdentifierInfo *AliasId
9528 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9530 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9531 WeakInfo WI(AliasId, Loc);
9532 WeakIDs.push_back(std::make_pair(WeakId, WI));
9533 }
9534 WeakUndeclaredIdentifiers.clear();
9535}
9536
9538 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9540 VTableUse &TableInfo = VTableUses[Idx++];
9541 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9542 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9543 VT.DefinitionRequired = TableInfo.Used;
9544 VTables.push_back(VT);
9545 }
9546
9547 VTableUses.clear();
9548}
9549
9551 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9552 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9553 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9554 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9556
9557 Pending.push_back(std::make_pair(D, Loc));
9558 }
9559 PendingInstantiations.clear();
9560}
9561
9563 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9564 &LPTMap) {
9565 for (auto &LPT : LateParsedTemplates) {
9566 ModuleFile *FMod = LPT.first;
9567 RecordDataImpl &LateParsed = LPT.second;
9568 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9569 /* In loop */) {
9570 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9571
9572 auto LT = std::make_unique<LateParsedTemplate>();
9573 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9574 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9575
9577 assert(F && "No module");
9578
9579 unsigned TokN = LateParsed[Idx++];
9580 LT->Toks.reserve(TokN);
9581 for (unsigned T = 0; T < TokN; ++T)
9582 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9583
9584 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9585 }
9586 }
9587
9588 LateParsedTemplates.clear();
9589}
9590
9592 if (!Lambda->getLambdaContextDecl())
9593 return;
9594
9595 auto LambdaInfo =
9596 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9597 Lambda->getLambdaIndexInContext());
9598
9599 // Handle the import and then include case for lambdas.
9600 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9601 Iter != LambdaDeclarationsForMerging.end() &&
9602 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9604 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9605 Lambda->setPreviousDecl(Previous);
9606 return;
9607 }
9608
9609 // Keep track of this lambda so it can be merged with another lambda that
9610 // is loaded later.
9611 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9612}
9613
9615 // It would be complicated to avoid reading the methods anyway. So don't.
9616 ReadMethodPool(Sel);
9617}
9618
9620 assert(ID && "Non-zero identifier ID required");
9621 unsigned Index = translateIdentifierIDToIndex(ID).second;
9622 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9623 IdentifiersLoaded[Index] = II;
9624 if (DeserializationListener)
9625 DeserializationListener->IdentifierRead(ID, II);
9626}
9627
9628/// Set the globally-visible declarations associated with the given
9629/// identifier.
9630///
9631/// If the AST reader is currently in a state where the given declaration IDs
9632/// cannot safely be resolved, they are queued until it is safe to resolve
9633/// them.
9634///
9635/// \param II an IdentifierInfo that refers to one or more globally-visible
9636/// declarations.
9637///
9638/// \param DeclIDs the set of declaration IDs with the name @p II that are
9639/// visible at global scope.
9640///
9641/// \param Decls if non-null, this vector will be populated with the set of
9642/// deserialized declarations. These declarations will not be pushed into
9643/// scope.
9646 SmallVectorImpl<Decl *> *Decls) {
9647 if (NumCurrentElementsDeserializing && !Decls) {
9648 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9649 return;
9650 }
9651
9652 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9653 if (!SemaObj) {
9654 // Queue this declaration so that it will be added to the
9655 // translation unit scope and identifier's declaration chain
9656 // once a Sema object is known.
9657 PreloadedDeclIDs.push_back(DeclIDs[I]);
9658 continue;
9659 }
9660
9661 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9662
9663 // If we're simply supposed to record the declarations, do so now.
9664 if (Decls) {
9665 Decls->push_back(D);
9666 continue;
9667 }
9668
9669 // Introduce this declaration into the translation-unit scope
9670 // and add it to the declaration chain for this identifier, so
9671 // that (unqualified) name lookup will find it.
9672 pushExternalDeclIntoScope(D, II);
9673 }
9674}
9675
9676std::pair<ModuleFile *, unsigned>
9677ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9678 if (ID == 0)
9679 return {nullptr, 0};
9680
9681 unsigned ModuleFileIndex = ID >> 32;
9682 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9683
9684 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9685 assert(getModuleManager().size() > ModuleFileIndex - 1);
9686
9687 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9688 assert(LocalID < MF.LocalNumIdentifiers);
9689 return {&MF, MF.BaseIdentifierID + LocalID};
9690}
9691
9693 if (ID == 0)
9694 return nullptr;
9695
9696 if (IdentifiersLoaded.empty()) {
9697 Error("no identifier table in AST file");
9698 return nullptr;
9699 }
9700
9701 auto [M, Index] = translateIdentifierIDToIndex(ID);
9702 if (!IdentifiersLoaded[Index]) {
9703 assert(M != nullptr && "Untranslated Identifier ID?");
9704 assert(Index >= M->BaseIdentifierID);
9705 unsigned LocalIndex = Index - M->BaseIdentifierID;
9706 const unsigned char *Data =
9707 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9708
9709 ASTIdentifierLookupTrait Trait(*this, *M);
9710 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9711 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9712 auto &II = PP.getIdentifierTable().get(Key);
9713 IdentifiersLoaded[Index] = &II;
9714 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9715 markIdentifierFromAST(*this, II, IsModule);
9716 if (DeserializationListener)
9717 DeserializationListener->IdentifierRead(ID, &II);
9718 }
9719
9720 return IdentifiersLoaded[Index];
9721}
9722
9724 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
9725}
9726
9728 if (LocalID < NUM_PREDEF_IDENT_IDS)
9729 return LocalID;
9730
9731 if (!M.ModuleOffsetMap.empty())
9732 ReadModuleOffsetMap(M);
9733
9734 unsigned ModuleFileIndex = LocalID >> 32;
9735 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9736 ModuleFile *MF =
9737 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9738 assert(MF && "malformed identifier ID encoding?");
9739
9740 if (!ModuleFileIndex)
9741 LocalID -= NUM_PREDEF_IDENT_IDS;
9742
9743 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9744}
9745
9747 if (ID == 0)
9748 return nullptr;
9749
9750 if (MacrosLoaded.empty()) {
9751 Error("no macro table in AST file");
9752 return nullptr;
9753 }
9754
9756 if (!MacrosLoaded[ID]) {
9758 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
9759 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
9760 ModuleFile *M = I->second;
9761 unsigned Index = ID - M->BaseMacroID;
9762 MacrosLoaded[ID] =
9763 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
9764
9765 if (DeserializationListener)
9766 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
9767 MacrosLoaded[ID]);
9768 }
9769
9770 return MacrosLoaded[ID];
9771}
9772
9774 if (LocalID < NUM_PREDEF_MACRO_IDS)
9775 return LocalID;
9776
9777 if (!M.ModuleOffsetMap.empty())
9778 ReadModuleOffsetMap(M);
9779
9781 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
9782 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
9783
9784 return LocalID + I->second;
9785}
9786
9788ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9789 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9790 return LocalID;
9791
9792 if (!M.ModuleOffsetMap.empty())
9793 ReadModuleOffsetMap(M);
9794
9797 assert(I != M.SubmoduleRemap.end()
9798 && "Invalid index into submodule index remap");
9799
9800 return LocalID + I->second;
9801}
9802
9804 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9805 assert(GlobalID == 0 && "Unhandled global submodule ID");
9806 return nullptr;
9807 }
9808
9809 if (GlobalID > SubmodulesLoaded.size()) {
9810 Error("submodule ID out of range in AST file");
9811 return nullptr;
9812 }
9813
9814 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9815}
9816
9818 return getSubmodule(ID);
9819}
9820
9822 if (ID & 1) {
9823 // It's a module, look it up by submodule ID.
9824 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9825 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9826 } else {
9827 // It's a prefix (preamble, PCH, ...). Look it up by index.
9828 int IndexFromEnd = static_cast<int>(ID >> 1);
9829 assert(IndexFromEnd && "got reference to unknown module file");
9830 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9831 }
9832}
9833
9835 if (!M)
9836 return 1;
9837
9838 // For a file representing a module, use the submodule ID of the top-level
9839 // module as the file ID. For any other kind of file, the number of such
9840 // files loaded beforehand will be the same on reload.
9841 // FIXME: Is this true even if we have an explicit module file and a PCH?
9842 if (M->isModule())
9843 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9844
9845 auto PCHModules = getModuleManager().pch_modules();
9846 auto I = llvm::find(PCHModules, M);
9847 assert(I != PCHModules.end() && "emitting reference to unknown file");
9848 return std::distance(I, PCHModules.end()) << 1;
9849}
9850
9851std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9852 if (Module *M = getSubmodule(ID))
9853 return ASTSourceDescriptor(*M);
9854
9855 // If there is only a single PCH, return it instead.
9856 // Chained PCH are not supported.
9857 const auto &PCHChain = ModuleMgr.pch_modules();
9858 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9859 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9860 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9861 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9862 return ASTSourceDescriptor(ModuleName,
9863 llvm::sys::path::parent_path(MF.FileName),
9864 FileName, MF.Signature);
9865 }
9866 return std::nullopt;
9867}
9868
9870 auto I = DefinitionSource.find(FD);
9871 if (I == DefinitionSource.end())
9872 return EK_ReplyHazy;
9873 return I->second ? EK_Never : EK_Always;
9874}
9875
9877 return ThisDeclarationWasADefinitionSet.contains(FD);
9878}
9879
9881 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9882}
9883
9885 if (ID == 0)
9886 return Selector();
9887
9888 if (ID > SelectorsLoaded.size()) {
9889 Error("selector ID out of range in AST file");
9890 return Selector();
9891 }
9892
9893 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9894 // Load this selector from the selector table.
9895 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9896 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9897 ModuleFile &M = *I->second;
9898 ASTSelectorLookupTrait Trait(*this, M);
9899 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9900 SelectorsLoaded[ID - 1] =
9901 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9902 if (DeserializationListener)
9903 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9904 }
9905
9906 return SelectorsLoaded[ID - 1];
9907}
9908
9910 return DecodeSelector(ID);
9911}
9912
9914 // ID 0 (the null selector) is considered an external selector.
9915 return getTotalNumSelectors() + 1;
9916}
9917
9919ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9920 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9921 return LocalID;
9922
9923 if (!M.ModuleOffsetMap.empty())
9924 ReadModuleOffsetMap(M);
9925
9928 assert(I != M.SelectorRemap.end()
9929 && "Invalid index into selector index remap");
9930
9931 return LocalID + I->second;
9932}
9933
9936 switch (Name.getNameKind()) {
9941
9944
9948
9955 break;
9956 }
9957 return DeclarationNameLoc();
9958}
9959
9961 DeclarationNameInfo NameInfo;
9962 NameInfo.setName(readDeclarationName());
9963 NameInfo.setLoc(readSourceLocation());
9964 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9965 return NameInfo;
9966}
9967
9969 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9970}
9971
9973 auto Kind = readInt();
9974 auto ResultType = readQualType();
9975 auto Value = readAPInt();
9976 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
9977 assert(Op.isValid());
9978 return Op;
9979}
9980
9983 unsigned NumTPLists = readInt();
9984 Info.NumTemplParamLists = NumTPLists;
9985 if (NumTPLists) {
9986 Info.TemplParamLists =
9987 new (getContext()) TemplateParameterList *[NumTPLists];
9988 for (unsigned i = 0; i != NumTPLists; ++i)
9990 }
9991}
9992
9995 SourceLocation TemplateLoc = readSourceLocation();
9996 SourceLocation LAngleLoc = readSourceLocation();
9997 SourceLocation RAngleLoc = readSourceLocation();
9998
9999 unsigned NumParams = readInt();
10001 Params.reserve(NumParams);
10002 while (NumParams--)
10003 Params.push_back(readDeclAs<NamedDecl>());
10004
10005 bool HasRequiresClause = readBool();
10006 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10007
10009 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10010 return TemplateParams;
10011}
10012
10015 bool Canonicalize) {
10016 unsigned NumTemplateArgs = readInt();
10017 TemplArgs.reserve(NumTemplateArgs);
10018 while (NumTemplateArgs--)
10019 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10020}
10021
10022/// Read a UnresolvedSet structure.
10024 unsigned NumDecls = readInt();
10025 Set.reserve(getContext(), NumDecls);
10026 while (NumDecls--) {
10027 GlobalDeclID ID = readDeclID();
10029 Set.addLazyDecl(getContext(), ID, AS);
10030 }
10031}
10032
10035 bool isVirtual = readBool();
10036 bool isBaseOfClass = readBool();
10037 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10038 bool inheritConstructors = readBool();
10041 SourceLocation EllipsisLoc = readSourceLocation();
10042 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10043 EllipsisLoc);
10044 Result.setInheritConstructors(inheritConstructors);
10045 return Result;
10046}
10047
10050 ASTContext &Context = getContext();
10051 unsigned NumInitializers = readInt();
10052 assert(NumInitializers && "wrote ctor initializers but have no inits");
10053 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10054 for (unsigned i = 0; i != NumInitializers; ++i) {
10055 TypeSourceInfo *TInfo = nullptr;
10056 bool IsBaseVirtual = false;
10057 FieldDecl *Member = nullptr;
10058 IndirectFieldDecl *IndirectMember = nullptr;
10059
10061 switch (Type) {
10063 TInfo = readTypeSourceInfo();
10064 IsBaseVirtual = readBool();
10065 break;
10066
10068 TInfo = readTypeSourceInfo();
10069 break;
10070
10072 Member = readDeclAs<FieldDecl>();
10073 break;
10074
10076 IndirectMember = readDeclAs<IndirectFieldDecl>();
10077 break;
10078 }
10079
10080 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10081 Expr *Init = readExpr();
10082 SourceLocation LParenLoc = readSourceLocation();
10083 SourceLocation RParenLoc = readSourceLocation();
10084
10085 CXXCtorInitializer *BOMInit;
10087 BOMInit = new (Context)
10088 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10089 RParenLoc, MemberOrEllipsisLoc);
10091 BOMInit = new (Context)
10092 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10093 else if (Member)
10094 BOMInit = new (Context)
10095 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10096 Init, RParenLoc);
10097 else
10098 BOMInit = new (Context)
10099 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10100 LParenLoc, Init, RParenLoc);
10101
10102 if (/*IsWritten*/readBool()) {
10103 unsigned SourceOrder = readInt();
10104 BOMInit->setSourceOrder(SourceOrder);
10105 }
10106
10107 CtorInitializers[i] = BOMInit;
10108 }
10109
10110 return CtorInitializers;
10111}
10112
10115 ASTContext &Context = getContext();
10116 unsigned N = readInt();
10118 for (unsigned I = 0; I != N; ++I) {
10119 auto Kind = readNestedNameSpecifierKind();
10120 switch (Kind) {
10122 auto *NS = readDeclAs<NamespaceBaseDecl>();
10124 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10125 break;
10126 }
10127
10130 if (!T)
10131 return NestedNameSpecifierLoc();
10132 SourceLocation ColonColonLoc = readSourceLocation();
10133 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10134 break;
10135 }
10136
10138 SourceLocation ColonColonLoc = readSourceLocation();
10139 Builder.MakeGlobal(Context, ColonColonLoc);
10140 break;
10141 }
10142
10144 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
10146 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10147 break;
10148 }
10149
10151 llvm_unreachable("unexpected null nested name specifier");
10152 }
10153 }
10154
10155 return Builder.getWithLocInContext(Context);
10156}
10157
10159 unsigned &Idx) {
10162 return SourceRange(beg, end);
10163}
10164
10166 const StringRef Blob) {
10167 unsigned Count = Record[0];
10168 const char *Byte = Blob.data();
10169 llvm::BitVector Ret = llvm::BitVector(Count, false);
10170 for (unsigned I = 0; I < Count; ++Byte)
10171 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10172 if (*Byte & (1 << Bit))
10173 Ret[I] = true;
10174 return Ret;
10175}
10176
10177/// Read a floating-point value
10178llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10179 return llvm::APFloat(Sem, readAPInt());
10180}
10181
10182// Read a string
10183std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10184 unsigned Len = Record[Idx++];
10185 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10186 Idx += Len;
10187 return Result;
10188}
10189
10190StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10191 StringRef &Blob) {
10192 unsigned Len = Record[Idx++];
10193 StringRef Result = Blob.substr(0, Len);
10194 Blob = Blob.substr(Len);
10195 return Result;
10196}
10197
10199 unsigned &Idx) {
10200 return ReadPath(F.BaseDirectory, Record, Idx);
10201}
10202
10203std::string ASTReader::ReadPath(StringRef BaseDirectory,
10204 const RecordData &Record, unsigned &Idx) {
10205 std::string Filename = ReadString(Record, Idx);
10206 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10207}
10208
10209std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10210 const RecordData &Record, unsigned &Idx,
10211 StringRef &Blob) {
10212 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10213 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10214}
10215
10217 unsigned &Idx) {
10218 unsigned Major = Record[Idx++];
10219 unsigned Minor = Record[Idx++];
10220 unsigned Subminor = Record[Idx++];
10221 if (Minor == 0)
10222 return VersionTuple(Major);
10223 if (Subminor == 0)
10224 return VersionTuple(Major, Minor - 1);
10225 return VersionTuple(Major, Minor - 1, Subminor - 1);
10226}
10227
10229 const RecordData &Record,
10230 unsigned &Idx) {
10231 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
10233}
10234
10235DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10236 return Diag(CurrentImportLoc, DiagID);
10237}
10238
10240 return Diags.Report(Loc, DiagID);
10241}
10242
10244 llvm::function_ref<void()> Fn) {
10245 // When Sema is available, avoid duplicate errors.
10246 if (SemaObj) {
10247 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10248 return;
10249 }
10250
10251 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10252}
10253
10254/// Retrieve the identifier table associated with the
10255/// preprocessor.
10257 return PP.getIdentifierTable();
10258}
10259
10260/// Record that the given ID maps to the given switch-case
10261/// statement.
10263 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10264 "Already have a SwitchCase with this ID");
10265 (*CurrSwitchCaseStmts)[ID] = SC;
10266}
10267
10268/// Retrieve the switch-case statement with the given ID.
10270 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10271 return (*CurrSwitchCaseStmts)[ID];
10272}
10273
10275 CurrSwitchCaseStmts->clear();
10276}
10277
10279 ASTContext &Context = getContext();
10280 std::vector<RawComment *> Comments;
10281 for (SmallVectorImpl<std::pair<BitstreamCursor,
10282 serialization::ModuleFile *>>::iterator
10283 I = CommentsCursors.begin(),
10284 E = CommentsCursors.end();
10285 I != E; ++I) {
10286 Comments.clear();
10287 BitstreamCursor &Cursor = I->first;
10288 serialization::ModuleFile &F = *I->second;
10289 SavedStreamPosition SavedPosition(Cursor);
10290
10292 while (true) {
10294 Cursor.advanceSkippingSubblocks(
10295 BitstreamCursor::AF_DontPopBlockAtEnd);
10296 if (!MaybeEntry) {
10297 Error(MaybeEntry.takeError());
10298 return;
10299 }
10300 llvm::BitstreamEntry Entry = MaybeEntry.get();
10301
10302 switch (Entry.Kind) {
10303 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10304 case llvm::BitstreamEntry::Error:
10305 Error("malformed block record in AST file");
10306 return;
10307 case llvm::BitstreamEntry::EndBlock:
10308 goto NextCursor;
10309 case llvm::BitstreamEntry::Record:
10310 // The interesting case.
10311 break;
10312 }
10313
10314 // Read a record.
10315 Record.clear();
10316 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10317 if (!MaybeComment) {
10318 Error(MaybeComment.takeError());
10319 return;
10320 }
10321 switch ((CommentRecordTypes)MaybeComment.get()) {
10322 case COMMENTS_RAW_COMMENT: {
10323 unsigned Idx = 0;
10324 SourceRange SR = ReadSourceRange(F, Record, Idx);
10327 bool IsTrailingComment = Record[Idx++];
10328 bool IsAlmostTrailingComment = Record[Idx++];
10329 Comments.push_back(new (Context) RawComment(
10330 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10331 break;
10332 }
10333 }
10334 }
10335 NextCursor:
10336 for (RawComment *C : Comments) {
10337 SourceLocation CommentLoc = C->getBeginLoc();
10338 if (CommentLoc.isValid()) {
10339 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10340 if (Loc.first.isValid())
10341 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10342 }
10343 }
10344 }
10345}
10346
10348 serialization::ModuleFile &MF, bool IncludeSystem,
10349 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10350 bool IsSystem)>
10351 Visitor) {
10352 unsigned NumUserInputs = MF.NumUserInputFiles;
10353 unsigned NumInputs = MF.InputFilesLoaded.size();
10354 assert(NumUserInputs <= NumInputs);
10355 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10356 for (unsigned I = 0; I < N; ++I) {
10357 bool IsSystem = I >= NumUserInputs;
10358 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10359 Visitor(IFI, IsSystem);
10360 }
10361}
10362
10364 bool IncludeSystem, bool Complain,
10365 llvm::function_ref<void(const serialization::InputFile &IF,
10366 bool isSystem)> Visitor) {
10367 unsigned NumUserInputs = MF.NumUserInputFiles;
10368 unsigned NumInputs = MF.InputFilesLoaded.size();
10369 assert(NumUserInputs <= NumInputs);
10370 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10371 for (unsigned I = 0; I < N; ++I) {
10372 bool IsSystem = I >= NumUserInputs;
10373 InputFile IF = getInputFile(MF, I+1, Complain);
10374 Visitor(IF, IsSystem);
10375 }
10376}
10377
10380 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10381 unsigned NumInputs = MF.InputFilesLoaded.size();
10382 for (unsigned I = 0; I < NumInputs; ++I) {
10383 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10384 if (IFI.TopLevel && IFI.ModuleMap)
10385 if (auto FE = getInputFile(MF, I + 1).getFile())
10386 Visitor(*FE);
10387 }
10388}
10389
10390void ASTReader::finishPendingActions() {
10391 while (!PendingIdentifierInfos.empty() ||
10392 !PendingDeducedFunctionTypes.empty() ||
10393 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10394 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10395 !PendingUpdateRecords.empty() ||
10396 !PendingObjCExtensionIvarRedeclarations.empty()) {
10397 // If any identifiers with corresponding top-level declarations have
10398 // been loaded, load those declarations now.
10399 using TopLevelDeclsMap =
10400 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10401 TopLevelDeclsMap TopLevelDecls;
10402
10403 while (!PendingIdentifierInfos.empty()) {
10404 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10406 std::move(PendingIdentifierInfos.back().second);
10407 PendingIdentifierInfos.pop_back();
10408
10409 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10410 }
10411
10412 // Load each function type that we deferred loading because it was a
10413 // deduced type that might refer to a local type declared within itself.
10414 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10415 auto *FD = PendingDeducedFunctionTypes[I].first;
10416 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10417
10418 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10419 // If we gave a function a deduced return type, remember that we need to
10420 // propagate that along the redeclaration chain.
10421 if (DT->isDeduced()) {
10422 PendingDeducedTypeUpdates.insert(
10423 {FD->getCanonicalDecl(), FD->getReturnType()});
10424 continue;
10425 }
10426
10427 // The function has undeduced DeduceType return type. We hope we can
10428 // find the deduced type by iterating the redecls in other modules
10429 // later.
10430 PendingUndeducedFunctionDecls.push_back(FD);
10431 continue;
10432 }
10433 }
10434 PendingDeducedFunctionTypes.clear();
10435
10436 // Load each variable type that we deferred loading because it was a
10437 // deduced type that might refer to a local type declared within itself.
10438 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10439 auto *VD = PendingDeducedVarTypes[I].first;
10440 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10441 }
10442 PendingDeducedVarTypes.clear();
10443
10444 // Load pending declaration chains.
10445 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10446 loadPendingDeclChain(PendingDeclChains[I].first,
10447 PendingDeclChains[I].second);
10448 PendingDeclChains.clear();
10449
10450 // Make the most recent of the top-level declarations visible.
10451 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10452 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10453 IdentifierInfo *II = TLD->first;
10454 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10455 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10456 }
10457 }
10458
10459 // Load any pending macro definitions.
10460 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10461 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10463 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10464 // Initialize the macro history from chained-PCHs ahead of module imports.
10465 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10466 ++IDIdx) {
10467 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10468 if (!Info.M->isModule())
10469 resolvePendingMacro(II, Info);
10470 }
10471 // Handle module imports.
10472 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10473 ++IDIdx) {
10474 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10475 if (Info.M->isModule())
10476 resolvePendingMacro(II, Info);
10477 }
10478 }
10479 PendingMacroIDs.clear();
10480
10481 // Wire up the DeclContexts for Decls that we delayed setting until
10482 // recursive loading is completed.
10483 while (!PendingDeclContextInfos.empty()) {
10484 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10485 PendingDeclContextInfos.pop_front();
10486 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10487 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10488 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10489 }
10490
10491 // Perform any pending declaration updates.
10492 while (!PendingUpdateRecords.empty()) {
10493 auto Update = PendingUpdateRecords.pop_back_val();
10494 ReadingKindTracker ReadingKind(Read_Decl, *this);
10495 loadDeclUpdateRecords(Update);
10496 }
10497
10498 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10499 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10500 auto DuplicateIvars =
10501 PendingObjCExtensionIvarRedeclarations.back().second;
10504 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10505 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10506 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10507 /*Complain =*/false,
10508 /*ErrorOnTagTypeMismatch =*/true);
10509 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10510 // Merge redeclared ivars with their predecessors.
10511 for (auto IvarPair : DuplicateIvars) {
10512 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10513 // Change semantic DeclContext but keep the lexical one.
10514 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10515 Ivar->getLexicalDeclContext(),
10516 getContext());
10517 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10518 }
10519 // Invalidate duplicate extension and the cached ivar list.
10520 ExtensionsPair.first->setInvalidDecl();
10521 ExtensionsPair.second->getClassInterface()
10522 ->getDefinition()
10523 ->setIvarList(nullptr);
10524 } else {
10525 for (auto IvarPair : DuplicateIvars) {
10526 Diag(IvarPair.first->getLocation(),
10527 diag::err_duplicate_ivar_declaration)
10528 << IvarPair.first->getIdentifier();
10529 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10530 }
10531 }
10532 PendingObjCExtensionIvarRedeclarations.pop_back();
10533 }
10534 }
10535
10536 // At this point, all update records for loaded decls are in place, so any
10537 // fake class definitions should have become real.
10538 assert(PendingFakeDefinitionData.empty() &&
10539 "faked up a class definition but never saw the real one");
10540
10541 // If we deserialized any C++ or Objective-C class definitions, any
10542 // Objective-C protocol definitions, or any redeclarable templates, make sure
10543 // that all redeclarations point to the definitions. Note that this can only
10544 // happen now, after the redeclaration chains have been fully wired.
10545 for (Decl *D : PendingDefinitions) {
10546 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10547 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10548 for (auto *R = getMostRecentExistingDecl(RD); R;
10549 R = R->getPreviousDecl()) {
10550 assert((R == D) ==
10551 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10552 "declaration thinks it's the definition but it isn't");
10553 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10554 }
10555 }
10556
10557 continue;
10558 }
10559
10560 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10561 // Make sure that the ObjCInterfaceType points at the definition.
10562 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10563 ->Decl = ID;
10564
10565 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10566 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10567
10568 continue;
10569 }
10570
10571 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10572 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10573 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10574
10575 continue;
10576 }
10577
10578 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10579 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10580 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10581 }
10582 PendingDefinitions.clear();
10583
10584 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10585 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10586 if (auto *VD = dyn_cast<VarDecl>(D))
10587 return VD->isThisDeclarationADefinition() ||
10588 VD->isThisDeclarationADemotedDefinition();
10589
10590 if (auto *TD = dyn_cast<TagDecl>(D))
10591 return TD->isThisDeclarationADefinition() ||
10592 TD->isThisDeclarationADemotedDefinition();
10593
10594 if (auto *FD = dyn_cast<FunctionDecl>(D))
10595 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10596
10597 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10598 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10599
10600 // Conservatively return false here.
10601 return false;
10602 };
10603
10604 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10605 return hasDefinitionImpl(D, hasDefinitionImpl);
10606 };
10607
10608 // It is not good to prevent multiple declarations since the forward
10609 // declaration is common. Let's try to avoid duplicated definitions
10610 // only.
10612 continue;
10613
10614 Module *PM = Previous->getOwningModule();
10615 Module *DM = D->getOwningModule();
10616 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10617 << cast<NamedDecl>(Previous) << PM->getTopLevelModuleName()
10618 << (DM ? DM->getTopLevelModuleName() : "global module");
10619 Diag(Previous->getLocation(), diag::note_also_found);
10620 }
10621 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10622
10623 // Load the bodies of any functions or methods we've encountered. We do
10624 // this now (delayed) so that we can be sure that the declaration chains
10625 // have been fully wired up (hasBody relies on this).
10626 // FIXME: We shouldn't require complete redeclaration chains here.
10627 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10628 PBEnd = PendingBodies.end();
10629 PB != PBEnd; ++PB) {
10630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10631 // FIXME: Check for =delete/=default?
10632 const FunctionDecl *Defn = nullptr;
10633 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10634 FD->setLazyBody(PB->second);
10635 } else {
10636 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10637 mergeDefinitionVisibility(NonConstDefn, FD);
10638
10639 if (!FD->isLateTemplateParsed() &&
10640 !NonConstDefn->isLateTemplateParsed() &&
10641 // We only perform ODR checks for decls not in the explicit
10642 // global module fragment.
10643 !shouldSkipCheckingODR(FD) &&
10644 !shouldSkipCheckingODR(NonConstDefn) &&
10645 FD->getODRHash() != NonConstDefn->getODRHash()) {
10646 if (!isa<CXXMethodDecl>(FD)) {
10647 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10648 } else if (FD->getLexicalParent()->isFileContext() &&
10649 NonConstDefn->getLexicalParent()->isFileContext()) {
10650 // Only diagnose out-of-line method definitions. If they are
10651 // in class definitions, then an error will be generated when
10652 // processing the class bodies.
10653 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10654 }
10655 }
10656 }
10657 continue;
10658 }
10659
10660 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10661 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10662 MD->setLazyBody(PB->second);
10663 }
10664 PendingBodies.clear();
10665
10666 // Inform any classes that had members added that they now have more members.
10667 for (auto [RD, MD] : PendingAddedClassMembers) {
10668 RD->addedMember(MD);
10669 }
10670 PendingAddedClassMembers.clear();
10671
10672 // Do some cleanup.
10673 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10675 PendingMergedDefinitionsToDeduplicate.clear();
10676
10677 // For each decl chain that we wanted to complete while deserializing, mark
10678 // it as "still needs to be completed".
10679 for (Decl *D : PendingIncompleteDeclChains)
10680 markIncompleteDeclChain(D);
10681 PendingIncompleteDeclChains.clear();
10682
10683 assert(PendingIdentifierInfos.empty() &&
10684 "Should be empty at the end of finishPendingActions");
10685 assert(PendingDeducedFunctionTypes.empty() &&
10686 "Should be empty at the end of finishPendingActions");
10687 assert(PendingDeducedVarTypes.empty() &&
10688 "Should be empty at the end of finishPendingActions");
10689 assert(PendingDeclChains.empty() &&
10690 "Should be empty at the end of finishPendingActions");
10691 assert(PendingMacroIDs.empty() &&
10692 "Should be empty at the end of finishPendingActions");
10693 assert(PendingDeclContextInfos.empty() &&
10694 "Should be empty at the end of finishPendingActions");
10695 assert(PendingUpdateRecords.empty() &&
10696 "Should be empty at the end of finishPendingActions");
10697 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10698 "Should be empty at the end of finishPendingActions");
10699 assert(PendingFakeDefinitionData.empty() &&
10700 "Should be empty at the end of finishPendingActions");
10701 assert(PendingDefinitions.empty() &&
10702 "Should be empty at the end of finishPendingActions");
10703 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10704 "Should be empty at the end of finishPendingActions");
10705 assert(PendingBodies.empty() &&
10706 "Should be empty at the end of finishPendingActions");
10707 assert(PendingAddedClassMembers.empty() &&
10708 "Should be empty at the end of finishPendingActions");
10709 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10710 "Should be empty at the end of finishPendingActions");
10711 assert(PendingIncompleteDeclChains.empty() &&
10712 "Should be empty at the end of finishPendingActions");
10713}
10714
10715void ASTReader::diagnoseOdrViolations() {
10716 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10717 PendingRecordOdrMergeFailures.empty() &&
10718 PendingFunctionOdrMergeFailures.empty() &&
10719 PendingEnumOdrMergeFailures.empty() &&
10720 PendingObjCInterfaceOdrMergeFailures.empty() &&
10721 PendingObjCProtocolOdrMergeFailures.empty())
10722 return;
10723
10724 // Trigger the import of the full definition of each class that had any
10725 // odr-merging problems, so we can produce better diagnostics for them.
10726 // These updates may in turn find and diagnose some ODR failures, so take
10727 // ownership of the set first.
10728 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10729 PendingOdrMergeFailures.clear();
10730 for (auto &Merge : OdrMergeFailures) {
10731 Merge.first->buildLookup();
10732 Merge.first->decls_begin();
10733 Merge.first->bases_begin();
10734 Merge.first->vbases_begin();
10735 for (auto &RecordPair : Merge.second) {
10736 auto *RD = RecordPair.first;
10737 RD->decls_begin();
10738 RD->bases_begin();
10739 RD->vbases_begin();
10740 }
10741 }
10742
10743 // Trigger the import of the full definition of each record in C/ObjC.
10744 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10745 PendingRecordOdrMergeFailures.clear();
10746 for (auto &Merge : RecordOdrMergeFailures) {
10747 Merge.first->decls_begin();
10748 for (auto &D : Merge.second)
10749 D->decls_begin();
10750 }
10751
10752 // Trigger the import of the full interface definition.
10753 auto ObjCInterfaceOdrMergeFailures =
10754 std::move(PendingObjCInterfaceOdrMergeFailures);
10755 PendingObjCInterfaceOdrMergeFailures.clear();
10756 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10757 Merge.first->decls_begin();
10758 for (auto &InterfacePair : Merge.second)
10759 InterfacePair.first->decls_begin();
10760 }
10761
10762 // Trigger the import of functions.
10763 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10764 PendingFunctionOdrMergeFailures.clear();
10765 for (auto &Merge : FunctionOdrMergeFailures) {
10766 Merge.first->buildLookup();
10767 Merge.first->decls_begin();
10768 Merge.first->getBody();
10769 for (auto &FD : Merge.second) {
10770 FD->buildLookup();
10771 FD->decls_begin();
10772 FD->getBody();
10773 }
10774 }
10775
10776 // Trigger the import of enums.
10777 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10778 PendingEnumOdrMergeFailures.clear();
10779 for (auto &Merge : EnumOdrMergeFailures) {
10780 Merge.first->decls_begin();
10781 for (auto &Enum : Merge.second) {
10782 Enum->decls_begin();
10783 }
10784 }
10785
10786 // Trigger the import of the full protocol definition.
10787 auto ObjCProtocolOdrMergeFailures =
10788 std::move(PendingObjCProtocolOdrMergeFailures);
10789 PendingObjCProtocolOdrMergeFailures.clear();
10790 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10791 Merge.first->decls_begin();
10792 for (auto &ProtocolPair : Merge.second)
10793 ProtocolPair.first->decls_begin();
10794 }
10795
10796 // For each declaration from a merged context, check that the canonical
10797 // definition of that context also contains a declaration of the same
10798 // entity.
10799 //
10800 // Caution: this loop does things that might invalidate iterators into
10801 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10802 while (!PendingOdrMergeChecks.empty()) {
10803 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10804
10805 // FIXME: Skip over implicit declarations for now. This matters for things
10806 // like implicitly-declared special member functions. This isn't entirely
10807 // correct; we can end up with multiple unmerged declarations of the same
10808 // implicit entity.
10809 if (D->isImplicit())
10810 continue;
10811
10812 DeclContext *CanonDef = D->getDeclContext();
10813
10814 bool Found = false;
10815 const Decl *DCanon = D->getCanonicalDecl();
10816
10817 for (auto *RI : D->redecls()) {
10818 if (RI->getLexicalDeclContext() == CanonDef) {
10819 Found = true;
10820 break;
10821 }
10822 }
10823 if (Found)
10824 continue;
10825
10826 // Quick check failed, time to do the slow thing. Note, we can't just
10827 // look up the name of D in CanonDef here, because the member that is
10828 // in CanonDef might not be found by name lookup (it might have been
10829 // replaced by a more recent declaration in the lookup table), and we
10830 // can't necessarily find it in the redeclaration chain because it might
10831 // be merely mergeable, not redeclarable.
10833 for (auto *CanonMember : CanonDef->decls()) {
10834 if (CanonMember->getCanonicalDecl() == DCanon) {
10835 // This can happen if the declaration is merely mergeable and not
10836 // actually redeclarable (we looked for redeclarations earlier).
10837 //
10838 // FIXME: We should be able to detect this more efficiently, without
10839 // pulling in all of the members of CanonDef.
10840 Found = true;
10841 break;
10842 }
10843 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10844 if (ND->getDeclName() == D->getDeclName())
10845 Candidates.push_back(ND);
10846 }
10847
10848 if (!Found) {
10849 // The AST doesn't like TagDecls becoming invalid after they've been
10850 // completed. We only really need to mark FieldDecls as invalid here.
10851 if (!isa<TagDecl>(D))
10852 D->setInvalidDecl();
10853
10854 // Ensure we don't accidentally recursively enter deserialization while
10855 // we're producing our diagnostic.
10856 Deserializing RecursionGuard(this);
10857
10858 std::string CanonDefModule =
10860 cast<Decl>(CanonDef));
10861 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10863 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10864
10865 if (Candidates.empty())
10866 Diag(cast<Decl>(CanonDef)->getLocation(),
10867 diag::note_module_odr_violation_no_possible_decls) << D;
10868 else {
10869 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10870 Diag(Candidates[I]->getLocation(),
10871 diag::note_module_odr_violation_possible_decl)
10872 << Candidates[I];
10873 }
10874
10875 DiagnosedOdrMergeFailures.insert(CanonDef);
10876 }
10877 }
10878
10879 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10880 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10881 ObjCInterfaceOdrMergeFailures.empty() &&
10882 ObjCProtocolOdrMergeFailures.empty())
10883 return;
10884
10885 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10886 getPreprocessor().getLangOpts());
10887
10888 // Issue any pending ODR-failure diagnostics.
10889 for (auto &Merge : OdrMergeFailures) {
10890 // If we've already pointed out a specific problem with this class, don't
10891 // bother issuing a general "something's different" diagnostic.
10892 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10893 continue;
10894
10895 bool Diagnosed = false;
10896 CXXRecordDecl *FirstRecord = Merge.first;
10897 for (auto &RecordPair : Merge.second) {
10898 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10899 RecordPair.second)) {
10900 Diagnosed = true;
10901 break;
10902 }
10903 }
10904
10905 if (!Diagnosed) {
10906 // All definitions are updates to the same declaration. This happens if a
10907 // module instantiates the declaration of a class template specialization
10908 // and two or more other modules instantiate its definition.
10909 //
10910 // FIXME: Indicate which modules had instantiations of this definition.
10911 // FIXME: How can this even happen?
10912 Diag(Merge.first->getLocation(),
10913 diag::err_module_odr_violation_different_instantiations)
10914 << Merge.first;
10915 }
10916 }
10917
10918 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10919 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10920 for (auto &Merge : RecordOdrMergeFailures) {
10921 // If we've already pointed out a specific problem with this class, don't
10922 // bother issuing a general "something's different" diagnostic.
10923 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10924 continue;
10925
10926 RecordDecl *FirstRecord = Merge.first;
10927 bool Diagnosed = false;
10928 for (auto *SecondRecord : Merge.second) {
10929 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10930 Diagnosed = true;
10931 break;
10932 }
10933 }
10934 (void)Diagnosed;
10935 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10936 }
10937
10938 // Issue ODR failures diagnostics for functions.
10939 for (auto &Merge : FunctionOdrMergeFailures) {
10940 FunctionDecl *FirstFunction = Merge.first;
10941 bool Diagnosed = false;
10942 for (auto &SecondFunction : Merge.second) {
10943 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10944 Diagnosed = true;
10945 break;
10946 }
10947 }
10948 (void)Diagnosed;
10949 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10950 }
10951
10952 // Issue ODR failures diagnostics for enums.
10953 for (auto &Merge : EnumOdrMergeFailures) {
10954 // If we've already pointed out a specific problem with this enum, don't
10955 // bother issuing a general "something's different" diagnostic.
10956 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10957 continue;
10958
10959 EnumDecl *FirstEnum = Merge.first;
10960 bool Diagnosed = false;
10961 for (auto &SecondEnum : Merge.second) {
10962 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10963 Diagnosed = true;
10964 break;
10965 }
10966 }
10967 (void)Diagnosed;
10968 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10969 }
10970
10971 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10972 // If we've already pointed out a specific problem with this interface,
10973 // don't bother issuing a general "something's different" diagnostic.
10974 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10975 continue;
10976
10977 bool Diagnosed = false;
10978 ObjCInterfaceDecl *FirstID = Merge.first;
10979 for (auto &InterfacePair : Merge.second) {
10980 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10981 InterfacePair.second)) {
10982 Diagnosed = true;
10983 break;
10984 }
10985 }
10986 (void)Diagnosed;
10987 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10988 }
10989
10990 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10991 // If we've already pointed out a specific problem with this protocol,
10992 // don't bother issuing a general "something's different" diagnostic.
10993 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10994 continue;
10995
10996 ObjCProtocolDecl *FirstProtocol = Merge.first;
10997 bool Diagnosed = false;
10998 for (auto &ProtocolPair : Merge.second) {
10999 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11000 ProtocolPair.second)) {
11001 Diagnosed = true;
11002 break;
11003 }
11004 }
11005 (void)Diagnosed;
11006 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11007 }
11008}
11009
11011 if (llvm::Timer *T = ReadTimer.get();
11012 ++NumCurrentElementsDeserializing == 1 && T)
11013 ReadTimeRegion.emplace(T);
11014}
11015
11017 assert(NumCurrentElementsDeserializing &&
11018 "FinishedDeserializing not paired with StartedDeserializing");
11019 if (NumCurrentElementsDeserializing == 1) {
11020 // We decrease NumCurrentElementsDeserializing only after pending actions
11021 // are finished, to avoid recursively re-calling finishPendingActions().
11022 finishPendingActions();
11023 }
11024 --NumCurrentElementsDeserializing;
11025
11026 if (NumCurrentElementsDeserializing == 0) {
11027 {
11028 // Guard variable to avoid recursively entering the process of passing
11029 // decls to consumer.
11030 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11031 /*NewValue=*/false);
11032
11033 // Propagate exception specification and deduced type updates along
11034 // redeclaration chains.
11035 //
11036 // We do this now rather than in finishPendingActions because we want to
11037 // be able to walk the complete redeclaration chains of the updated decls.
11038 while (!PendingExceptionSpecUpdates.empty() ||
11039 !PendingDeducedTypeUpdates.empty() ||
11040 !PendingUndeducedFunctionDecls.empty()) {
11041 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11042 PendingExceptionSpecUpdates.clear();
11043 for (auto Update : ESUpdates) {
11044 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11045 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11046 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11047 if (auto *Listener = getContext().getASTMutationListener())
11048 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11049 for (auto *Redecl : Update.second->redecls())
11050 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
11051 }
11052
11053 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11054 PendingDeducedTypeUpdates.clear();
11055 for (auto Update : DTUpdates) {
11056 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11057 // FIXME: If the return type is already deduced, check that it
11058 // matches.
11060 Update.second);
11061 }
11062
11063 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11064 PendingUndeducedFunctionDecls.clear();
11065 // We hope we can find the deduced type for the functions by iterating
11066 // redeclarations in other modules.
11067 for (FunctionDecl *UndeducedFD : UDTUpdates)
11068 (void)UndeducedFD->getMostRecentDecl();
11069 }
11070
11071 ReadTimeRegion.reset();
11072
11073 diagnoseOdrViolations();
11074 }
11075
11076 // We are not in recursive loading, so it's safe to pass the "interesting"
11077 // decls to the consumer.
11078 if (Consumer)
11079 PassInterestingDeclsToConsumer();
11080 }
11081}
11082
11083void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11084 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11085 // Remove any fake results before adding any real ones.
11086 auto It = PendingFakeLookupResults.find(II);
11087 if (It != PendingFakeLookupResults.end()) {
11088 for (auto *ND : It->second)
11089 SemaObj->IdResolver.RemoveDecl(ND);
11090 // FIXME: this works around module+PCH performance issue.
11091 // Rather than erase the result from the map, which is O(n), just clear
11092 // the vector of NamedDecls.
11093 It->second.clear();
11094 }
11095 }
11096
11097 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11098 SemaObj->TUScope->AddDecl(D);
11099 } else if (SemaObj->TUScope) {
11100 // Adding the decl to IdResolver may have failed because it was already in
11101 // (even though it was not added in scope). If it is already in, make sure
11102 // it gets in the scope as well.
11103 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11104 SemaObj->TUScope->AddDecl(D);
11105 }
11106}
11107
11109 ASTContext *Context,
11110 const PCHContainerReader &PCHContainerRdr,
11111 const CodeGenOptions &CodeGenOpts,
11112 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11113 StringRef isysroot,
11114 DisableValidationForModuleKind DisableValidationKind,
11115 bool AllowASTWithCompilerErrors,
11116 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11117 bool ForceValidateUserInputs,
11118 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11119 std::unique_ptr<llvm::Timer> ReadTimer)
11120 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11122 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11123 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11124 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11125 StackHandler(Diags), PP(PP), ContextObj(Context),
11126 CodeGenOpts(CodeGenOpts),
11127 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11128 PP.getHeaderSearchInfo()),
11129 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11130 DisableValidationKind(DisableValidationKind),
11131 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11132 AllowConfigurationMismatch(AllowConfigurationMismatch),
11133 ValidateSystemInputs(ValidateSystemInputs),
11134 ForceValidateUserInputs(ForceValidateUserInputs),
11135 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11136 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11137 SourceMgr.setExternalSLocEntrySource(this);
11138
11139 PathBuf.reserve(256);
11140
11141 for (const auto &Ext : Extensions) {
11142 auto BlockName = Ext->getExtensionMetadata().BlockName;
11143 auto Known = ModuleFileExtensions.find(BlockName);
11144 if (Known != ModuleFileExtensions.end()) {
11145 Diags.Report(diag::warn_duplicate_module_file_extension)
11146 << BlockName;
11147 continue;
11148 }
11149
11150 ModuleFileExtensions.insert({BlockName, Ext});
11151 }
11152}
11153
11155 if (OwnsDeserializationListener)
11156 delete DeserializationListener;
11157}
11158
11160 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11161}
11162
11164 unsigned AbbrevID) {
11165 Idx = 0;
11166 Record.clear();
11167 return Cursor.readRecord(AbbrevID, Record);
11168}
11169//===----------------------------------------------------------------------===//
11170//// OMPClauseReader implementation
11171////===----------------------------------------------------------------------===//
11172
11173// This has to be in namespace clang because it's friended by all
11174// of the OMP clauses.
11175namespace clang {
11176
11177class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11179 ASTContext &Context;
11180
11181public:
11183 : Record(Record), Context(Record.getContext()) {}
11184#define GEN_CLANG_CLAUSE_CLASS
11185#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11186#include "llvm/Frontend/OpenMP/OMP.inc"
11190};
11191
11192} // end namespace clang
11193
11195 return OMPClauseReader(*this).readClause();
11196}
11197
11199 OMPClause *C = nullptr;
11200 switch (llvm::omp::Clause(Record.readInt())) {
11201 case llvm::omp::OMPC_if:
11202 C = new (Context) OMPIfClause();
11203 break;
11204 case llvm::omp::OMPC_final:
11205 C = new (Context) OMPFinalClause();
11206 break;
11207 case llvm::omp::OMPC_num_threads:
11208 C = new (Context) OMPNumThreadsClause();
11209 break;
11210 case llvm::omp::OMPC_safelen:
11211 C = new (Context) OMPSafelenClause();
11212 break;
11213 case llvm::omp::OMPC_simdlen:
11214 C = new (Context) OMPSimdlenClause();
11215 break;
11216 case llvm::omp::OMPC_sizes: {
11217 unsigned NumSizes = Record.readInt();
11218 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11219 break;
11220 }
11221 case llvm::omp::OMPC_permutation: {
11222 unsigned NumLoops = Record.readInt();
11223 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11224 break;
11225 }
11226 case llvm::omp::OMPC_full:
11227 C = OMPFullClause::CreateEmpty(Context);
11228 break;
11229 case llvm::omp::OMPC_partial:
11231 break;
11232 case llvm::omp::OMPC_allocator:
11233 C = new (Context) OMPAllocatorClause();
11234 break;
11235 case llvm::omp::OMPC_collapse:
11236 C = new (Context) OMPCollapseClause();
11237 break;
11238 case llvm::omp::OMPC_default:
11239 C = new (Context) OMPDefaultClause();
11240 break;
11241 case llvm::omp::OMPC_proc_bind:
11242 C = new (Context) OMPProcBindClause();
11243 break;
11244 case llvm::omp::OMPC_schedule:
11245 C = new (Context) OMPScheduleClause();
11246 break;
11247 case llvm::omp::OMPC_ordered:
11248 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11249 break;
11250 case llvm::omp::OMPC_nowait:
11251 C = new (Context) OMPNowaitClause();
11252 break;
11253 case llvm::omp::OMPC_untied:
11254 C = new (Context) OMPUntiedClause();
11255 break;
11256 case llvm::omp::OMPC_mergeable:
11257 C = new (Context) OMPMergeableClause();
11258 break;
11259 case llvm::omp::OMPC_read:
11260 C = new (Context) OMPReadClause();
11261 break;
11262 case llvm::omp::OMPC_write:
11263 C = new (Context) OMPWriteClause();
11264 break;
11265 case llvm::omp::OMPC_update:
11266 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11267 break;
11268 case llvm::omp::OMPC_capture:
11269 C = new (Context) OMPCaptureClause();
11270 break;
11271 case llvm::omp::OMPC_compare:
11272 C = new (Context) OMPCompareClause();
11273 break;
11274 case llvm::omp::OMPC_fail:
11275 C = new (Context) OMPFailClause();
11276 break;
11277 case llvm::omp::OMPC_seq_cst:
11278 C = new (Context) OMPSeqCstClause();
11279 break;
11280 case llvm::omp::OMPC_acq_rel:
11281 C = new (Context) OMPAcqRelClause();
11282 break;
11283 case llvm::omp::OMPC_absent: {
11284 unsigned NumKinds = Record.readInt();
11285 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11286 break;
11287 }
11288 case llvm::omp::OMPC_holds:
11289 C = new (Context) OMPHoldsClause();
11290 break;
11291 case llvm::omp::OMPC_contains: {
11292 unsigned NumKinds = Record.readInt();
11293 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11294 break;
11295 }
11296 case llvm::omp::OMPC_no_openmp:
11297 C = new (Context) OMPNoOpenMPClause();
11298 break;
11299 case llvm::omp::OMPC_no_openmp_routines:
11300 C = new (Context) OMPNoOpenMPRoutinesClause();
11301 break;
11302 case llvm::omp::OMPC_no_openmp_constructs:
11303 C = new (Context) OMPNoOpenMPConstructsClause();
11304 break;
11305 case llvm::omp::OMPC_no_parallelism:
11306 C = new (Context) OMPNoParallelismClause();
11307 break;
11308 case llvm::omp::OMPC_acquire:
11309 C = new (Context) OMPAcquireClause();
11310 break;
11311 case llvm::omp::OMPC_release:
11312 C = new (Context) OMPReleaseClause();
11313 break;
11314 case llvm::omp::OMPC_relaxed:
11315 C = new (Context) OMPRelaxedClause();
11316 break;
11317 case llvm::omp::OMPC_weak:
11318 C = new (Context) OMPWeakClause();
11319 break;
11320 case llvm::omp::OMPC_threads:
11321 C = new (Context) OMPThreadsClause();
11322 break;
11323 case llvm::omp::OMPC_simd:
11324 C = new (Context) OMPSIMDClause();
11325 break;
11326 case llvm::omp::OMPC_nogroup:
11327 C = new (Context) OMPNogroupClause();
11328 break;
11329 case llvm::omp::OMPC_unified_address:
11330 C = new (Context) OMPUnifiedAddressClause();
11331 break;
11332 case llvm::omp::OMPC_unified_shared_memory:
11333 C = new (Context) OMPUnifiedSharedMemoryClause();
11334 break;
11335 case llvm::omp::OMPC_reverse_offload:
11336 C = new (Context) OMPReverseOffloadClause();
11337 break;
11338 case llvm::omp::OMPC_dynamic_allocators:
11339 C = new (Context) OMPDynamicAllocatorsClause();
11340 break;
11341 case llvm::omp::OMPC_atomic_default_mem_order:
11342 C = new (Context) OMPAtomicDefaultMemOrderClause();
11343 break;
11344 case llvm::omp::OMPC_self_maps:
11345 C = new (Context) OMPSelfMapsClause();
11346 break;
11347 case llvm::omp::OMPC_at:
11348 C = new (Context) OMPAtClause();
11349 break;
11350 case llvm::omp::OMPC_severity:
11351 C = new (Context) OMPSeverityClause();
11352 break;
11353 case llvm::omp::OMPC_message:
11354 C = new (Context) OMPMessageClause();
11355 break;
11356 case llvm::omp::OMPC_private:
11357 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11358 break;
11359 case llvm::omp::OMPC_firstprivate:
11360 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11361 break;
11362 case llvm::omp::OMPC_lastprivate:
11363 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11364 break;
11365 case llvm::omp::OMPC_shared:
11366 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11367 break;
11368 case llvm::omp::OMPC_reduction: {
11369 unsigned N = Record.readInt();
11370 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11371 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11372 break;
11373 }
11374 case llvm::omp::OMPC_task_reduction:
11375 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11376 break;
11377 case llvm::omp::OMPC_in_reduction:
11378 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11379 break;
11380 case llvm::omp::OMPC_linear:
11381 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11382 break;
11383 case llvm::omp::OMPC_aligned:
11384 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11385 break;
11386 case llvm::omp::OMPC_copyin:
11387 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11388 break;
11389 case llvm::omp::OMPC_copyprivate:
11390 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11391 break;
11392 case llvm::omp::OMPC_flush:
11393 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11394 break;
11395 case llvm::omp::OMPC_depobj:
11397 break;
11398 case llvm::omp::OMPC_depend: {
11399 unsigned NumVars = Record.readInt();
11400 unsigned NumLoops = Record.readInt();
11401 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11402 break;
11403 }
11404 case llvm::omp::OMPC_device:
11405 C = new (Context) OMPDeviceClause();
11406 break;
11407 case llvm::omp::OMPC_map: {
11409 Sizes.NumVars = Record.readInt();
11410 Sizes.NumUniqueDeclarations = Record.readInt();
11411 Sizes.NumComponentLists = Record.readInt();
11412 Sizes.NumComponents = Record.readInt();
11413 C = OMPMapClause::CreateEmpty(Context, Sizes);
11414 break;
11415 }
11416 case llvm::omp::OMPC_num_teams:
11417 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11418 break;
11419 case llvm::omp::OMPC_thread_limit:
11420 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11421 break;
11422 case llvm::omp::OMPC_priority:
11423 C = new (Context) OMPPriorityClause();
11424 break;
11425 case llvm::omp::OMPC_grainsize:
11426 C = new (Context) OMPGrainsizeClause();
11427 break;
11428 case llvm::omp::OMPC_num_tasks:
11429 C = new (Context) OMPNumTasksClause();
11430 break;
11431 case llvm::omp::OMPC_hint:
11432 C = new (Context) OMPHintClause();
11433 break;
11434 case llvm::omp::OMPC_dist_schedule:
11435 C = new (Context) OMPDistScheduleClause();
11436 break;
11437 case llvm::omp::OMPC_defaultmap:
11438 C = new (Context) OMPDefaultmapClause();
11439 break;
11440 case llvm::omp::OMPC_to: {
11442 Sizes.NumVars = Record.readInt();
11443 Sizes.NumUniqueDeclarations = Record.readInt();
11444 Sizes.NumComponentLists = Record.readInt();
11445 Sizes.NumComponents = Record.readInt();
11446 C = OMPToClause::CreateEmpty(Context, Sizes);
11447 break;
11448 }
11449 case llvm::omp::OMPC_from: {
11451 Sizes.NumVars = Record.readInt();
11452 Sizes.NumUniqueDeclarations = Record.readInt();
11453 Sizes.NumComponentLists = Record.readInt();
11454 Sizes.NumComponents = Record.readInt();
11455 C = OMPFromClause::CreateEmpty(Context, Sizes);
11456 break;
11457 }
11458 case llvm::omp::OMPC_use_device_ptr: {
11460 Sizes.NumVars = Record.readInt();
11461 Sizes.NumUniqueDeclarations = Record.readInt();
11462 Sizes.NumComponentLists = Record.readInt();
11463 Sizes.NumComponents = Record.readInt();
11464 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11465 break;
11466 }
11467 case llvm::omp::OMPC_use_device_addr: {
11469 Sizes.NumVars = Record.readInt();
11470 Sizes.NumUniqueDeclarations = Record.readInt();
11471 Sizes.NumComponentLists = Record.readInt();
11472 Sizes.NumComponents = Record.readInt();
11473 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11474 break;
11475 }
11476 case llvm::omp::OMPC_is_device_ptr: {
11478 Sizes.NumVars = Record.readInt();
11479 Sizes.NumUniqueDeclarations = Record.readInt();
11480 Sizes.NumComponentLists = Record.readInt();
11481 Sizes.NumComponents = Record.readInt();
11482 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11483 break;
11484 }
11485 case llvm::omp::OMPC_has_device_addr: {
11487 Sizes.NumVars = Record.readInt();
11488 Sizes.NumUniqueDeclarations = Record.readInt();
11489 Sizes.NumComponentLists = Record.readInt();
11490 Sizes.NumComponents = Record.readInt();
11491 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11492 break;
11493 }
11494 case llvm::omp::OMPC_allocate:
11495 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11496 break;
11497 case llvm::omp::OMPC_nontemporal:
11498 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11499 break;
11500 case llvm::omp::OMPC_inclusive:
11501 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11502 break;
11503 case llvm::omp::OMPC_exclusive:
11504 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11505 break;
11506 case llvm::omp::OMPC_order:
11507 C = new (Context) OMPOrderClause();
11508 break;
11509 case llvm::omp::OMPC_init:
11510 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11511 break;
11512 case llvm::omp::OMPC_use:
11513 C = new (Context) OMPUseClause();
11514 break;
11515 case llvm::omp::OMPC_destroy:
11516 C = new (Context) OMPDestroyClause();
11517 break;
11518 case llvm::omp::OMPC_novariants:
11519 C = new (Context) OMPNovariantsClause();
11520 break;
11521 case llvm::omp::OMPC_nocontext:
11522 C = new (Context) OMPNocontextClause();
11523 break;
11524 case llvm::omp::OMPC_detach:
11525 C = new (Context) OMPDetachClause();
11526 break;
11527 case llvm::omp::OMPC_uses_allocators:
11528 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11529 break;
11530 case llvm::omp::OMPC_affinity:
11531 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11532 break;
11533 case llvm::omp::OMPC_filter:
11534 C = new (Context) OMPFilterClause();
11535 break;
11536 case llvm::omp::OMPC_bind:
11537 C = OMPBindClause::CreateEmpty(Context);
11538 break;
11539 case llvm::omp::OMPC_align:
11540 C = new (Context) OMPAlignClause();
11541 break;
11542 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11543 C = new (Context) OMPXDynCGroupMemClause();
11544 break;
11545 case llvm::omp::OMPC_doacross: {
11546 unsigned NumVars = Record.readInt();
11547 unsigned NumLoops = Record.readInt();
11548 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11549 break;
11550 }
11551 case llvm::omp::OMPC_ompx_attribute:
11552 C = new (Context) OMPXAttributeClause();
11553 break;
11554 case llvm::omp::OMPC_ompx_bare:
11555 C = new (Context) OMPXBareClause();
11556 break;
11557#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11558 case llvm::omp::Enum: \
11559 break;
11560#include "llvm/Frontend/OpenMP/OMPKinds.def"
11561 default:
11562 break;
11563 }
11564 assert(C && "Unknown OMPClause type");
11565
11566 Visit(C);
11567 C->setLocStart(Record.readSourceLocation());
11568 C->setLocEnd(Record.readSourceLocation());
11569
11570 return C;
11571}
11572
11574 C->setPreInitStmt(Record.readSubStmt(),
11575 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11576}
11577
11580 C->setPostUpdateExpr(Record.readSubExpr());
11581}
11582
11583void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11585 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11586 C->setNameModifierLoc(Record.readSourceLocation());
11587 C->setColonLoc(Record.readSourceLocation());
11588 C->setCondition(Record.readSubExpr());
11589 C->setLParenLoc(Record.readSourceLocation());
11590}
11591
11592void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11594 C->setCondition(Record.readSubExpr());
11595 C->setLParenLoc(Record.readSourceLocation());
11596}
11597
11598void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11600 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11601 C->setNumThreads(Record.readSubExpr());
11602 C->setModifierLoc(Record.readSourceLocation());
11603 C->setLParenLoc(Record.readSourceLocation());
11604}
11605
11606void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11607 C->setSafelen(Record.readSubExpr());
11608 C->setLParenLoc(Record.readSourceLocation());
11609}
11610
11611void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11612 C->setSimdlen(Record.readSubExpr());
11613 C->setLParenLoc(Record.readSourceLocation());
11614}
11615
11616void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11617 for (Expr *&E : C->getSizesRefs())
11618 E = Record.readSubExpr();
11619 C->setLParenLoc(Record.readSourceLocation());
11620}
11621
11622void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11623 for (Expr *&E : C->getArgsRefs())
11624 E = Record.readSubExpr();
11625 C->setLParenLoc(Record.readSourceLocation());
11626}
11627
11628void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11629
11630void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11631 C->setFactor(Record.readSubExpr());
11632 C->setLParenLoc(Record.readSourceLocation());
11633}
11634
11635void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11636 C->setAllocator(Record.readExpr());
11637 C->setLParenLoc(Record.readSourceLocation());
11638}
11639
11640void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11641 C->setNumForLoops(Record.readSubExpr());
11642 C->setLParenLoc(Record.readSourceLocation());
11643}
11644
11645void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11646 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11647 C->setLParenLoc(Record.readSourceLocation());
11648 C->setDefaultKindKwLoc(Record.readSourceLocation());
11649}
11650
11651void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11652 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11653 C->setLParenLoc(Record.readSourceLocation());
11654 C->setProcBindKindKwLoc(Record.readSourceLocation());
11655}
11656
11657void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11659 C->setScheduleKind(
11660 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11661 C->setFirstScheduleModifier(
11662 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11663 C->setSecondScheduleModifier(
11664 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11665 C->setChunkSize(Record.readSubExpr());
11666 C->setLParenLoc(Record.readSourceLocation());
11667 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11668 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11669 C->setScheduleKindLoc(Record.readSourceLocation());
11670 C->setCommaLoc(Record.readSourceLocation());
11671}
11672
11673void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11674 C->setNumForLoops(Record.readSubExpr());
11675 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11676 C->setLoopNumIterations(I, Record.readSubExpr());
11677 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11678 C->setLoopCounter(I, Record.readSubExpr());
11679 C->setLParenLoc(Record.readSourceLocation());
11680}
11681
11682void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11683 C->setEventHandler(Record.readSubExpr());
11684 C->setLParenLoc(Record.readSourceLocation());
11685}
11686
11687void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11688
11689void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11690
11691void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11692
11693void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11694
11695void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11696
11697void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11698 if (C->isExtended()) {
11699 C->setLParenLoc(Record.readSourceLocation());
11700 C->setArgumentLoc(Record.readSourceLocation());
11701 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11702 }
11703}
11704
11705void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11706
11707void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11708
11709// Read the parameter of fail clause. This will have been saved when
11710// OMPClauseWriter is called.
11711void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11712 C->setLParenLoc(Record.readSourceLocation());
11713 SourceLocation FailParameterLoc = Record.readSourceLocation();
11714 C->setFailParameterLoc(FailParameterLoc);
11715 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11716 C->setFailParameter(CKind);
11717}
11718
11719void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11720 unsigned Count = C->getDirectiveKinds().size();
11721 C->setLParenLoc(Record.readSourceLocation());
11723 DKVec.reserve(Count);
11724 for (unsigned I = 0; I < Count; I++) {
11725 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11726 }
11727 C->setDirectiveKinds(DKVec);
11728}
11729
11730void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11731 C->setExpr(Record.readExpr());
11732 C->setLParenLoc(Record.readSourceLocation());
11733}
11734
11735void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11736 unsigned Count = C->getDirectiveKinds().size();
11737 C->setLParenLoc(Record.readSourceLocation());
11739 DKVec.reserve(Count);
11740 for (unsigned I = 0; I < Count; I++) {
11741 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11742 }
11743 C->setDirectiveKinds(DKVec);
11744}
11745
11746void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11747
11748void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11750
11751void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
11753
11754void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11755
11756void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11757
11758void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11759
11760void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11761
11762void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11763
11764void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11765
11766void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11767
11768void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11769
11770void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11771
11772void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11773
11774void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11775 unsigned NumVars = C->varlist_size();
11777 Vars.reserve(NumVars);
11778 for (unsigned I = 0; I != NumVars; ++I)
11779 Vars.push_back(Record.readSubExpr());
11780 C->setVarRefs(Vars);
11781 C->setIsTarget(Record.readBool());
11782 C->setIsTargetSync(Record.readBool());
11783 C->setLParenLoc(Record.readSourceLocation());
11784 C->setVarLoc(Record.readSourceLocation());
11785}
11786
11787void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11788 C->setInteropVar(Record.readSubExpr());
11789 C->setLParenLoc(Record.readSourceLocation());
11790 C->setVarLoc(Record.readSourceLocation());
11791}
11792
11793void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11794 C->setInteropVar(Record.readSubExpr());
11795 C->setLParenLoc(Record.readSourceLocation());
11796 C->setVarLoc(Record.readSourceLocation());
11797}
11798
11799void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11801 C->setCondition(Record.readSubExpr());
11802 C->setLParenLoc(Record.readSourceLocation());
11803}
11804
11805void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11807 C->setCondition(Record.readSubExpr());
11808 C->setLParenLoc(Record.readSourceLocation());
11809}
11810
11811void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11812
11813void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11815
11816void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11817
11818void
11819OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11820}
11821
11822void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11824 C->setAtomicDefaultMemOrderKind(
11825 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11826 C->setLParenLoc(Record.readSourceLocation());
11827 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11828}
11829
11830void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
11831
11832void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
11833 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
11834 C->setLParenLoc(Record.readSourceLocation());
11835 C->setAtKindKwLoc(Record.readSourceLocation());
11836}
11837
11838void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
11839 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
11840 C->setLParenLoc(Record.readSourceLocation());
11841 C->setSeverityKindKwLoc(Record.readSourceLocation());
11842}
11843
11844void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
11846 C->setMessageString(Record.readSubExpr());
11847 C->setLParenLoc(Record.readSourceLocation());
11848}
11849
11850void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11851 C->setLParenLoc(Record.readSourceLocation());
11852 unsigned NumVars = C->varlist_size();
11854 Vars.reserve(NumVars);
11855 for (unsigned i = 0; i != NumVars; ++i)
11856 Vars.push_back(Record.readSubExpr());
11857 C->setVarRefs(Vars);
11858 Vars.clear();
11859 for (unsigned i = 0; i != NumVars; ++i)
11860 Vars.push_back(Record.readSubExpr());
11861 C->setPrivateCopies(Vars);
11862}
11863
11864void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11866 C->setLParenLoc(Record.readSourceLocation());
11867 unsigned NumVars = C->varlist_size();
11869 Vars.reserve(NumVars);
11870 for (unsigned i = 0; i != NumVars; ++i)
11871 Vars.push_back(Record.readSubExpr());
11872 C->setVarRefs(Vars);
11873 Vars.clear();
11874 for (unsigned i = 0; i != NumVars; ++i)
11875 Vars.push_back(Record.readSubExpr());
11876 C->setPrivateCopies(Vars);
11877 Vars.clear();
11878 for (unsigned i = 0; i != NumVars; ++i)
11879 Vars.push_back(Record.readSubExpr());
11880 C->setInits(Vars);
11881}
11882
11883void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11885 C->setLParenLoc(Record.readSourceLocation());
11886 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11887 C->setKindLoc(Record.readSourceLocation());
11888 C->setColonLoc(Record.readSourceLocation());
11889 unsigned NumVars = C->varlist_size();
11891 Vars.reserve(NumVars);
11892 for (unsigned i = 0; i != NumVars; ++i)
11893 Vars.push_back(Record.readSubExpr());
11894 C->setVarRefs(Vars);
11895 Vars.clear();
11896 for (unsigned i = 0; i != NumVars; ++i)
11897 Vars.push_back(Record.readSubExpr());
11898 C->setPrivateCopies(Vars);
11899 Vars.clear();
11900 for (unsigned i = 0; i != NumVars; ++i)
11901 Vars.push_back(Record.readSubExpr());
11902 C->setSourceExprs(Vars);
11903 Vars.clear();
11904 for (unsigned i = 0; i != NumVars; ++i)
11905 Vars.push_back(Record.readSubExpr());
11906 C->setDestinationExprs(Vars);
11907 Vars.clear();
11908 for (unsigned i = 0; i != NumVars; ++i)
11909 Vars.push_back(Record.readSubExpr());
11910 C->setAssignmentOps(Vars);
11911}
11912
11913void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11914 C->setLParenLoc(Record.readSourceLocation());
11915 unsigned NumVars = C->varlist_size();
11917 Vars.reserve(NumVars);
11918 for (unsigned i = 0; i != NumVars; ++i)
11919 Vars.push_back(Record.readSubExpr());
11920 C->setVarRefs(Vars);
11921}
11922
11923void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11925 C->setLParenLoc(Record.readSourceLocation());
11926 C->setModifierLoc(Record.readSourceLocation());
11927 C->setColonLoc(Record.readSourceLocation());
11928 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11929 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11930 C->setQualifierLoc(NNSL);
11931 C->setNameInfo(DNI);
11932
11933 unsigned NumVars = C->varlist_size();
11935 Vars.reserve(NumVars);
11936 for (unsigned i = 0; i != NumVars; ++i)
11937 Vars.push_back(Record.readSubExpr());
11938 C->setVarRefs(Vars);
11939 Vars.clear();
11940 for (unsigned i = 0; i != NumVars; ++i)
11941 Vars.push_back(Record.readSubExpr());
11942 C->setPrivates(Vars);
11943 Vars.clear();
11944 for (unsigned i = 0; i != NumVars; ++i)
11945 Vars.push_back(Record.readSubExpr());
11946 C->setLHSExprs(Vars);
11947 Vars.clear();
11948 for (unsigned i = 0; i != NumVars; ++i)
11949 Vars.push_back(Record.readSubExpr());
11950 C->setRHSExprs(Vars);
11951 Vars.clear();
11952 for (unsigned i = 0; i != NumVars; ++i)
11953 Vars.push_back(Record.readSubExpr());
11954 C->setReductionOps(Vars);
11955 if (C->getModifier() == OMPC_REDUCTION_inscan) {
11956 Vars.clear();
11957 for (unsigned i = 0; i != NumVars; ++i)
11958 Vars.push_back(Record.readSubExpr());
11959 C->setInscanCopyOps(Vars);
11960 Vars.clear();
11961 for (unsigned i = 0; i != NumVars; ++i)
11962 Vars.push_back(Record.readSubExpr());
11963 C->setInscanCopyArrayTemps(Vars);
11964 Vars.clear();
11965 for (unsigned i = 0; i != NumVars; ++i)
11966 Vars.push_back(Record.readSubExpr());
11967 C->setInscanCopyArrayElems(Vars);
11968 }
11969 unsigned NumFlags = Record.readInt();
11971 Flags.reserve(NumFlags);
11972 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
11973 Flags.push_back(Record.readInt());
11974 C->setPrivateVariableReductionFlags(Flags);
11975}
11976
11977void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11979 C->setLParenLoc(Record.readSourceLocation());
11980 C->setColonLoc(Record.readSourceLocation());
11981 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11982 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11983 C->setQualifierLoc(NNSL);
11984 C->setNameInfo(DNI);
11985
11986 unsigned NumVars = C->varlist_size();
11988 Vars.reserve(NumVars);
11989 for (unsigned I = 0; I != NumVars; ++I)
11990 Vars.push_back(Record.readSubExpr());
11991 C->setVarRefs(Vars);
11992 Vars.clear();
11993 for (unsigned I = 0; I != NumVars; ++I)
11994 Vars.push_back(Record.readSubExpr());
11995 C->setPrivates(Vars);
11996 Vars.clear();
11997 for (unsigned I = 0; I != NumVars; ++I)
11998 Vars.push_back(Record.readSubExpr());
11999 C->setLHSExprs(Vars);
12000 Vars.clear();
12001 for (unsigned I = 0; I != NumVars; ++I)
12002 Vars.push_back(Record.readSubExpr());
12003 C->setRHSExprs(Vars);
12004 Vars.clear();
12005 for (unsigned I = 0; I != NumVars; ++I)
12006 Vars.push_back(Record.readSubExpr());
12007 C->setReductionOps(Vars);
12008}
12009
12010void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12012 C->setLParenLoc(Record.readSourceLocation());
12013 C->setColonLoc(Record.readSourceLocation());
12014 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12015 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12016 C->setQualifierLoc(NNSL);
12017 C->setNameInfo(DNI);
12018
12019 unsigned NumVars = C->varlist_size();
12021 Vars.reserve(NumVars);
12022 for (unsigned I = 0; I != NumVars; ++I)
12023 Vars.push_back(Record.readSubExpr());
12024 C->setVarRefs(Vars);
12025 Vars.clear();
12026 for (unsigned I = 0; I != NumVars; ++I)
12027 Vars.push_back(Record.readSubExpr());
12028 C->setPrivates(Vars);
12029 Vars.clear();
12030 for (unsigned I = 0; I != NumVars; ++I)
12031 Vars.push_back(Record.readSubExpr());
12032 C->setLHSExprs(Vars);
12033 Vars.clear();
12034 for (unsigned I = 0; I != NumVars; ++I)
12035 Vars.push_back(Record.readSubExpr());
12036 C->setRHSExprs(Vars);
12037 Vars.clear();
12038 for (unsigned I = 0; I != NumVars; ++I)
12039 Vars.push_back(Record.readSubExpr());
12040 C->setReductionOps(Vars);
12041 Vars.clear();
12042 for (unsigned I = 0; I != NumVars; ++I)
12043 Vars.push_back(Record.readSubExpr());
12044 C->setTaskgroupDescriptors(Vars);
12045}
12046
12047void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12049 C->setLParenLoc(Record.readSourceLocation());
12050 C->setColonLoc(Record.readSourceLocation());
12051 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12052 C->setModifierLoc(Record.readSourceLocation());
12053 unsigned NumVars = C->varlist_size();
12055 Vars.reserve(NumVars);
12056 for (unsigned i = 0; i != NumVars; ++i)
12057 Vars.push_back(Record.readSubExpr());
12058 C->setVarRefs(Vars);
12059 Vars.clear();
12060 for (unsigned i = 0; i != NumVars; ++i)
12061 Vars.push_back(Record.readSubExpr());
12062 C->setPrivates(Vars);
12063 Vars.clear();
12064 for (unsigned i = 0; i != NumVars; ++i)
12065 Vars.push_back(Record.readSubExpr());
12066 C->setInits(Vars);
12067 Vars.clear();
12068 for (unsigned i = 0; i != NumVars; ++i)
12069 Vars.push_back(Record.readSubExpr());
12070 C->setUpdates(Vars);
12071 Vars.clear();
12072 for (unsigned i = 0; i != NumVars; ++i)
12073 Vars.push_back(Record.readSubExpr());
12074 C->setFinals(Vars);
12075 C->setStep(Record.readSubExpr());
12076 C->setCalcStep(Record.readSubExpr());
12077 Vars.clear();
12078 for (unsigned I = 0; I != NumVars + 1; ++I)
12079 Vars.push_back(Record.readSubExpr());
12080 C->setUsedExprs(Vars);
12081}
12082
12083void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12084 C->setLParenLoc(Record.readSourceLocation());
12085 C->setColonLoc(Record.readSourceLocation());
12086 unsigned NumVars = C->varlist_size();
12088 Vars.reserve(NumVars);
12089 for (unsigned i = 0; i != NumVars; ++i)
12090 Vars.push_back(Record.readSubExpr());
12091 C->setVarRefs(Vars);
12092 C->setAlignment(Record.readSubExpr());
12093}
12094
12095void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12096 C->setLParenLoc(Record.readSourceLocation());
12097 unsigned NumVars = C->varlist_size();
12099 Exprs.reserve(NumVars);
12100 for (unsigned i = 0; i != NumVars; ++i)
12101 Exprs.push_back(Record.readSubExpr());
12102 C->setVarRefs(Exprs);
12103 Exprs.clear();
12104 for (unsigned i = 0; i != NumVars; ++i)
12105 Exprs.push_back(Record.readSubExpr());
12106 C->setSourceExprs(Exprs);
12107 Exprs.clear();
12108 for (unsigned i = 0; i != NumVars; ++i)
12109 Exprs.push_back(Record.readSubExpr());
12110 C->setDestinationExprs(Exprs);
12111 Exprs.clear();
12112 for (unsigned i = 0; i != NumVars; ++i)
12113 Exprs.push_back(Record.readSubExpr());
12114 C->setAssignmentOps(Exprs);
12115}
12116
12117void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12118 C->setLParenLoc(Record.readSourceLocation());
12119 unsigned NumVars = C->varlist_size();
12121 Exprs.reserve(NumVars);
12122 for (unsigned i = 0; i != NumVars; ++i)
12123 Exprs.push_back(Record.readSubExpr());
12124 C->setVarRefs(Exprs);
12125 Exprs.clear();
12126 for (unsigned i = 0; i != NumVars; ++i)
12127 Exprs.push_back(Record.readSubExpr());
12128 C->setSourceExprs(Exprs);
12129 Exprs.clear();
12130 for (unsigned i = 0; i != NumVars; ++i)
12131 Exprs.push_back(Record.readSubExpr());
12132 C->setDestinationExprs(Exprs);
12133 Exprs.clear();
12134 for (unsigned i = 0; i != NumVars; ++i)
12135 Exprs.push_back(Record.readSubExpr());
12136 C->setAssignmentOps(Exprs);
12137}
12138
12139void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12140 C->setLParenLoc(Record.readSourceLocation());
12141 unsigned NumVars = C->varlist_size();
12143 Vars.reserve(NumVars);
12144 for (unsigned i = 0; i != NumVars; ++i)
12145 Vars.push_back(Record.readSubExpr());
12146 C->setVarRefs(Vars);
12147}
12148
12149void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12150 C->setDepobj(Record.readSubExpr());
12151 C->setLParenLoc(Record.readSourceLocation());
12152}
12153
12154void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12155 C->setLParenLoc(Record.readSourceLocation());
12156 C->setModifier(Record.readSubExpr());
12157 C->setDependencyKind(
12158 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12159 C->setDependencyLoc(Record.readSourceLocation());
12160 C->setColonLoc(Record.readSourceLocation());
12161 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12162 unsigned NumVars = C->varlist_size();
12164 Vars.reserve(NumVars);
12165 for (unsigned I = 0; I != NumVars; ++I)
12166 Vars.push_back(Record.readSubExpr());
12167 C->setVarRefs(Vars);
12168 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12169 C->setLoopData(I, Record.readSubExpr());
12170}
12171
12172void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12174 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12175 C->setDevice(Record.readSubExpr());
12176 C->setModifierLoc(Record.readSourceLocation());
12177 C->setLParenLoc(Record.readSourceLocation());
12178}
12179
12180void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12181 C->setLParenLoc(Record.readSourceLocation());
12182 bool HasIteratorModifier = false;
12183 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12184 C->setMapTypeModifier(
12185 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12186 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12187 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12188 HasIteratorModifier = true;
12189 }
12190 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12191 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12192 C->setMapType(
12193 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12194 C->setMapLoc(Record.readSourceLocation());
12195 C->setColonLoc(Record.readSourceLocation());
12196 auto NumVars = C->varlist_size();
12197 auto UniqueDecls = C->getUniqueDeclarationsNum();
12198 auto TotalLists = C->getTotalComponentListNum();
12199 auto TotalComponents = C->getTotalComponentsNum();
12200
12202 Vars.reserve(NumVars);
12203 for (unsigned i = 0; i != NumVars; ++i)
12204 Vars.push_back(Record.readExpr());
12205 C->setVarRefs(Vars);
12206
12207 SmallVector<Expr *, 16> UDMappers;
12208 UDMappers.reserve(NumVars);
12209 for (unsigned I = 0; I < NumVars; ++I)
12210 UDMappers.push_back(Record.readExpr());
12211 C->setUDMapperRefs(UDMappers);
12212
12213 if (HasIteratorModifier)
12214 C->setIteratorModifier(Record.readExpr());
12215
12217 Decls.reserve(UniqueDecls);
12218 for (unsigned i = 0; i < UniqueDecls; ++i)
12219 Decls.push_back(Record.readDeclAs<ValueDecl>());
12220 C->setUniqueDecls(Decls);
12221
12222 SmallVector<unsigned, 16> ListsPerDecl;
12223 ListsPerDecl.reserve(UniqueDecls);
12224 for (unsigned i = 0; i < UniqueDecls; ++i)
12225 ListsPerDecl.push_back(Record.readInt());
12226 C->setDeclNumLists(ListsPerDecl);
12227
12228 SmallVector<unsigned, 32> ListSizes;
12229 ListSizes.reserve(TotalLists);
12230 for (unsigned i = 0; i < TotalLists; ++i)
12231 ListSizes.push_back(Record.readInt());
12232 C->setComponentListSizes(ListSizes);
12233
12235 Components.reserve(TotalComponents);
12236 for (unsigned i = 0; i < TotalComponents; ++i) {
12237 Expr *AssociatedExprPr = Record.readExpr();
12238 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12239 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12240 /*IsNonContiguous=*/false);
12241 }
12242 C->setComponents(Components, ListSizes);
12243}
12244
12245void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12246 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12247 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12248 C->setLParenLoc(Record.readSourceLocation());
12249 C->setColonLoc(Record.readSourceLocation());
12250 C->setAllocator(Record.readSubExpr());
12251 C->setAlignment(Record.readSubExpr());
12252 unsigned NumVars = C->varlist_size();
12254 Vars.reserve(NumVars);
12255 for (unsigned i = 0; i != NumVars; ++i)
12256 Vars.push_back(Record.readSubExpr());
12257 C->setVarRefs(Vars);
12258}
12259
12260void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12262 C->setLParenLoc(Record.readSourceLocation());
12263 unsigned NumVars = C->varlist_size();
12265 Vars.reserve(NumVars);
12266 for (unsigned I = 0; I != NumVars; ++I)
12267 Vars.push_back(Record.readSubExpr());
12268 C->setVarRefs(Vars);
12269}
12270
12271void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12273 C->setLParenLoc(Record.readSourceLocation());
12274 unsigned NumVars = C->varlist_size();
12276 Vars.reserve(NumVars);
12277 for (unsigned I = 0; I != NumVars; ++I)
12278 Vars.push_back(Record.readSubExpr());
12279 C->setVarRefs(Vars);
12280}
12281
12282void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12284 C->setPriority(Record.readSubExpr());
12285 C->setLParenLoc(Record.readSourceLocation());
12286}
12287
12288void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12290 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12291 C->setGrainsize(Record.readSubExpr());
12292 C->setModifierLoc(Record.readSourceLocation());
12293 C->setLParenLoc(Record.readSourceLocation());
12294}
12295
12296void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12298 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12299 C->setNumTasks(Record.readSubExpr());
12300 C->setModifierLoc(Record.readSourceLocation());
12301 C->setLParenLoc(Record.readSourceLocation());
12302}
12303
12304void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12305 C->setHint(Record.readSubExpr());
12306 C->setLParenLoc(Record.readSourceLocation());
12307}
12308
12309void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12311 C->setDistScheduleKind(
12312 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12313 C->setChunkSize(Record.readSubExpr());
12314 C->setLParenLoc(Record.readSourceLocation());
12315 C->setDistScheduleKindLoc(Record.readSourceLocation());
12316 C->setCommaLoc(Record.readSourceLocation());
12317}
12318
12319void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12320 C->setDefaultmapKind(
12321 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12322 C->setDefaultmapModifier(
12323 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12324 C->setLParenLoc(Record.readSourceLocation());
12325 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12326 C->setDefaultmapKindLoc(Record.readSourceLocation());
12327}
12328
12329void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12330 C->setLParenLoc(Record.readSourceLocation());
12331 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12332 C->setMotionModifier(
12333 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12334 C->setMotionModifierLoc(I, Record.readSourceLocation());
12335 }
12336 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12337 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12338 C->setColonLoc(Record.readSourceLocation());
12339 auto NumVars = C->varlist_size();
12340 auto UniqueDecls = C->getUniqueDeclarationsNum();
12341 auto TotalLists = C->getTotalComponentListNum();
12342 auto TotalComponents = C->getTotalComponentsNum();
12343
12345 Vars.reserve(NumVars);
12346 for (unsigned i = 0; i != NumVars; ++i)
12347 Vars.push_back(Record.readSubExpr());
12348 C->setVarRefs(Vars);
12349
12350 SmallVector<Expr *, 16> UDMappers;
12351 UDMappers.reserve(NumVars);
12352 for (unsigned I = 0; I < NumVars; ++I)
12353 UDMappers.push_back(Record.readSubExpr());
12354 C->setUDMapperRefs(UDMappers);
12355
12357 Decls.reserve(UniqueDecls);
12358 for (unsigned i = 0; i < UniqueDecls; ++i)
12359 Decls.push_back(Record.readDeclAs<ValueDecl>());
12360 C->setUniqueDecls(Decls);
12361
12362 SmallVector<unsigned, 16> ListsPerDecl;
12363 ListsPerDecl.reserve(UniqueDecls);
12364 for (unsigned i = 0; i < UniqueDecls; ++i)
12365 ListsPerDecl.push_back(Record.readInt());
12366 C->setDeclNumLists(ListsPerDecl);
12367
12368 SmallVector<unsigned, 32> ListSizes;
12369 ListSizes.reserve(TotalLists);
12370 for (unsigned i = 0; i < TotalLists; ++i)
12371 ListSizes.push_back(Record.readInt());
12372 C->setComponentListSizes(ListSizes);
12373
12375 Components.reserve(TotalComponents);
12376 for (unsigned i = 0; i < TotalComponents; ++i) {
12377 Expr *AssociatedExprPr = Record.readSubExpr();
12378 bool IsNonContiguous = Record.readBool();
12379 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12380 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12381 }
12382 C->setComponents(Components, ListSizes);
12383}
12384
12385void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12386 C->setLParenLoc(Record.readSourceLocation());
12387 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12388 C->setMotionModifier(
12389 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12390 C->setMotionModifierLoc(I, Record.readSourceLocation());
12391 }
12392 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12393 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12394 C->setColonLoc(Record.readSourceLocation());
12395 auto NumVars = C->varlist_size();
12396 auto UniqueDecls = C->getUniqueDeclarationsNum();
12397 auto TotalLists = C->getTotalComponentListNum();
12398 auto TotalComponents = C->getTotalComponentsNum();
12399
12401 Vars.reserve(NumVars);
12402 for (unsigned i = 0; i != NumVars; ++i)
12403 Vars.push_back(Record.readSubExpr());
12404 C->setVarRefs(Vars);
12405
12406 SmallVector<Expr *, 16> UDMappers;
12407 UDMappers.reserve(NumVars);
12408 for (unsigned I = 0; I < NumVars; ++I)
12409 UDMappers.push_back(Record.readSubExpr());
12410 C->setUDMapperRefs(UDMappers);
12411
12413 Decls.reserve(UniqueDecls);
12414 for (unsigned i = 0; i < UniqueDecls; ++i)
12415 Decls.push_back(Record.readDeclAs<ValueDecl>());
12416 C->setUniqueDecls(Decls);
12417
12418 SmallVector<unsigned, 16> ListsPerDecl;
12419 ListsPerDecl.reserve(UniqueDecls);
12420 for (unsigned i = 0; i < UniqueDecls; ++i)
12421 ListsPerDecl.push_back(Record.readInt());
12422 C->setDeclNumLists(ListsPerDecl);
12423
12424 SmallVector<unsigned, 32> ListSizes;
12425 ListSizes.reserve(TotalLists);
12426 for (unsigned i = 0; i < TotalLists; ++i)
12427 ListSizes.push_back(Record.readInt());
12428 C->setComponentListSizes(ListSizes);
12429
12431 Components.reserve(TotalComponents);
12432 for (unsigned i = 0; i < TotalComponents; ++i) {
12433 Expr *AssociatedExprPr = Record.readSubExpr();
12434 bool IsNonContiguous = Record.readBool();
12435 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12436 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12437 }
12438 C->setComponents(Components, ListSizes);
12439}
12440
12441void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12442 C->setLParenLoc(Record.readSourceLocation());
12443 auto NumVars = C->varlist_size();
12444 auto UniqueDecls = C->getUniqueDeclarationsNum();
12445 auto TotalLists = C->getTotalComponentListNum();
12446 auto TotalComponents = C->getTotalComponentsNum();
12447
12449 Vars.reserve(NumVars);
12450 for (unsigned i = 0; i != NumVars; ++i)
12451 Vars.push_back(Record.readSubExpr());
12452 C->setVarRefs(Vars);
12453 Vars.clear();
12454 for (unsigned i = 0; i != NumVars; ++i)
12455 Vars.push_back(Record.readSubExpr());
12456 C->setPrivateCopies(Vars);
12457 Vars.clear();
12458 for (unsigned i = 0; i != NumVars; ++i)
12459 Vars.push_back(Record.readSubExpr());
12460 C->setInits(Vars);
12461
12463 Decls.reserve(UniqueDecls);
12464 for (unsigned i = 0; i < UniqueDecls; ++i)
12465 Decls.push_back(Record.readDeclAs<ValueDecl>());
12466 C->setUniqueDecls(Decls);
12467
12468 SmallVector<unsigned, 16> ListsPerDecl;
12469 ListsPerDecl.reserve(UniqueDecls);
12470 for (unsigned i = 0; i < UniqueDecls; ++i)
12471 ListsPerDecl.push_back(Record.readInt());
12472 C->setDeclNumLists(ListsPerDecl);
12473
12474 SmallVector<unsigned, 32> ListSizes;
12475 ListSizes.reserve(TotalLists);
12476 for (unsigned i = 0; i < TotalLists; ++i)
12477 ListSizes.push_back(Record.readInt());
12478 C->setComponentListSizes(ListSizes);
12479
12481 Components.reserve(TotalComponents);
12482 for (unsigned i = 0; i < TotalComponents; ++i) {
12483 auto *AssociatedExprPr = Record.readSubExpr();
12484 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12485 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12486 /*IsNonContiguous=*/false);
12487 }
12488 C->setComponents(Components, ListSizes);
12489}
12490
12491void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12492 C->setLParenLoc(Record.readSourceLocation());
12493 auto NumVars = C->varlist_size();
12494 auto UniqueDecls = C->getUniqueDeclarationsNum();
12495 auto TotalLists = C->getTotalComponentListNum();
12496 auto TotalComponents = C->getTotalComponentsNum();
12497
12499 Vars.reserve(NumVars);
12500 for (unsigned i = 0; i != NumVars; ++i)
12501 Vars.push_back(Record.readSubExpr());
12502 C->setVarRefs(Vars);
12503
12505 Decls.reserve(UniqueDecls);
12506 for (unsigned i = 0; i < UniqueDecls; ++i)
12507 Decls.push_back(Record.readDeclAs<ValueDecl>());
12508 C->setUniqueDecls(Decls);
12509
12510 SmallVector<unsigned, 16> ListsPerDecl;
12511 ListsPerDecl.reserve(UniqueDecls);
12512 for (unsigned i = 0; i < UniqueDecls; ++i)
12513 ListsPerDecl.push_back(Record.readInt());
12514 C->setDeclNumLists(ListsPerDecl);
12515
12516 SmallVector<unsigned, 32> ListSizes;
12517 ListSizes.reserve(TotalLists);
12518 for (unsigned i = 0; i < TotalLists; ++i)
12519 ListSizes.push_back(Record.readInt());
12520 C->setComponentListSizes(ListSizes);
12521
12523 Components.reserve(TotalComponents);
12524 for (unsigned i = 0; i < TotalComponents; ++i) {
12525 Expr *AssociatedExpr = Record.readSubExpr();
12526 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12527 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12528 /*IsNonContiguous*/ false);
12529 }
12530 C->setComponents(Components, ListSizes);
12531}
12532
12533void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12534 C->setLParenLoc(Record.readSourceLocation());
12535 auto NumVars = C->varlist_size();
12536 auto UniqueDecls = C->getUniqueDeclarationsNum();
12537 auto TotalLists = C->getTotalComponentListNum();
12538 auto TotalComponents = C->getTotalComponentsNum();
12539
12541 Vars.reserve(NumVars);
12542 for (unsigned i = 0; i != NumVars; ++i)
12543 Vars.push_back(Record.readSubExpr());
12544 C->setVarRefs(Vars);
12545 Vars.clear();
12546
12548 Decls.reserve(UniqueDecls);
12549 for (unsigned i = 0; i < UniqueDecls; ++i)
12550 Decls.push_back(Record.readDeclAs<ValueDecl>());
12551 C->setUniqueDecls(Decls);
12552
12553 SmallVector<unsigned, 16> ListsPerDecl;
12554 ListsPerDecl.reserve(UniqueDecls);
12555 for (unsigned i = 0; i < UniqueDecls; ++i)
12556 ListsPerDecl.push_back(Record.readInt());
12557 C->setDeclNumLists(ListsPerDecl);
12558
12559 SmallVector<unsigned, 32> ListSizes;
12560 ListSizes.reserve(TotalLists);
12561 for (unsigned i = 0; i < TotalLists; ++i)
12562 ListSizes.push_back(Record.readInt());
12563 C->setComponentListSizes(ListSizes);
12564
12566 Components.reserve(TotalComponents);
12567 for (unsigned i = 0; i < TotalComponents; ++i) {
12568 Expr *AssociatedExpr = Record.readSubExpr();
12569 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12570 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12571 /*IsNonContiguous=*/false);
12572 }
12573 C->setComponents(Components, ListSizes);
12574}
12575
12576void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12577 C->setLParenLoc(Record.readSourceLocation());
12578 auto NumVars = C->varlist_size();
12579 auto UniqueDecls = C->getUniqueDeclarationsNum();
12580 auto TotalLists = C->getTotalComponentListNum();
12581 auto TotalComponents = C->getTotalComponentsNum();
12582
12584 Vars.reserve(NumVars);
12585 for (unsigned I = 0; I != NumVars; ++I)
12586 Vars.push_back(Record.readSubExpr());
12587 C->setVarRefs(Vars);
12588 Vars.clear();
12589
12591 Decls.reserve(UniqueDecls);
12592 for (unsigned I = 0; I < UniqueDecls; ++I)
12593 Decls.push_back(Record.readDeclAs<ValueDecl>());
12594 C->setUniqueDecls(Decls);
12595
12596 SmallVector<unsigned, 16> ListsPerDecl;
12597 ListsPerDecl.reserve(UniqueDecls);
12598 for (unsigned I = 0; I < UniqueDecls; ++I)
12599 ListsPerDecl.push_back(Record.readInt());
12600 C->setDeclNumLists(ListsPerDecl);
12601
12602 SmallVector<unsigned, 32> ListSizes;
12603 ListSizes.reserve(TotalLists);
12604 for (unsigned i = 0; i < TotalLists; ++i)
12605 ListSizes.push_back(Record.readInt());
12606 C->setComponentListSizes(ListSizes);
12607
12609 Components.reserve(TotalComponents);
12610 for (unsigned I = 0; I < TotalComponents; ++I) {
12611 Expr *AssociatedExpr = Record.readSubExpr();
12612 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12613 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12614 /*IsNonContiguous=*/false);
12615 }
12616 C->setComponents(Components, ListSizes);
12617}
12618
12619void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12620 C->setLParenLoc(Record.readSourceLocation());
12621 unsigned NumVars = C->varlist_size();
12623 Vars.reserve(NumVars);
12624 for (unsigned i = 0; i != NumVars; ++i)
12625 Vars.push_back(Record.readSubExpr());
12626 C->setVarRefs(Vars);
12627 Vars.clear();
12628 Vars.reserve(NumVars);
12629 for (unsigned i = 0; i != NumVars; ++i)
12630 Vars.push_back(Record.readSubExpr());
12631 C->setPrivateRefs(Vars);
12632}
12633
12634void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12635 C->setLParenLoc(Record.readSourceLocation());
12636 unsigned NumVars = C->varlist_size();
12638 Vars.reserve(NumVars);
12639 for (unsigned i = 0; i != NumVars; ++i)
12640 Vars.push_back(Record.readSubExpr());
12641 C->setVarRefs(Vars);
12642}
12643
12644void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12645 C->setLParenLoc(Record.readSourceLocation());
12646 unsigned NumVars = C->varlist_size();
12648 Vars.reserve(NumVars);
12649 for (unsigned i = 0; i != NumVars; ++i)
12650 Vars.push_back(Record.readSubExpr());
12651 C->setVarRefs(Vars);
12652}
12653
12654void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12655 C->setLParenLoc(Record.readSourceLocation());
12656 unsigned NumOfAllocators = C->getNumberOfAllocators();
12658 Data.reserve(NumOfAllocators);
12659 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12660 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12661 D.Allocator = Record.readSubExpr();
12662 D.AllocatorTraits = Record.readSubExpr();
12663 D.LParenLoc = Record.readSourceLocation();
12664 D.RParenLoc = Record.readSourceLocation();
12665 }
12666 C->setAllocatorsData(Data);
12667}
12668
12669void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12670 C->setLParenLoc(Record.readSourceLocation());
12671 C->setModifier(Record.readSubExpr());
12672 C->setColonLoc(Record.readSourceLocation());
12673 unsigned NumOfLocators = C->varlist_size();
12674 SmallVector<Expr *, 4> Locators;
12675 Locators.reserve(NumOfLocators);
12676 for (unsigned I = 0; I != NumOfLocators; ++I)
12677 Locators.push_back(Record.readSubExpr());
12678 C->setVarRefs(Locators);
12679}
12680
12681void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12682 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12683 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12684 C->setLParenLoc(Record.readSourceLocation());
12685 C->setKindKwLoc(Record.readSourceLocation());
12686 C->setModifierKwLoc(Record.readSourceLocation());
12687}
12688
12689void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12691 C->setThreadID(Record.readSubExpr());
12692 C->setLParenLoc(Record.readSourceLocation());
12693}
12694
12695void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12696 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12697 C->setLParenLoc(Record.readSourceLocation());
12698 C->setBindKindLoc(Record.readSourceLocation());
12699}
12700
12701void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12702 C->setAlignment(Record.readExpr());
12703 C->setLParenLoc(Record.readSourceLocation());
12704}
12705
12706void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12708 C->setSize(Record.readSubExpr());
12709 C->setLParenLoc(Record.readSourceLocation());
12710}
12711
12712void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12713 C->setLParenLoc(Record.readSourceLocation());
12714 C->setDependenceType(
12715 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12716 C->setDependenceLoc(Record.readSourceLocation());
12717 C->setColonLoc(Record.readSourceLocation());
12718 unsigned NumVars = C->varlist_size();
12720 Vars.reserve(NumVars);
12721 for (unsigned I = 0; I != NumVars; ++I)
12722 Vars.push_back(Record.readSubExpr());
12723 C->setVarRefs(Vars);
12724 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12725 C->setLoopData(I, Record.readSubExpr());
12726}
12727
12728void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12729 AttrVec Attrs;
12730 Record.readAttributes(Attrs);
12731 C->setAttrs(Attrs);
12732 C->setLocStart(Record.readSourceLocation());
12733 C->setLParenLoc(Record.readSourceLocation());
12734 C->setLocEnd(Record.readSourceLocation());
12735}
12736
12737void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12738
12741 TI.Sets.resize(readUInt32());
12742 for (auto &Set : TI.Sets) {
12743 Set.Kind = readEnum<llvm::omp::TraitSet>();
12744 Set.Selectors.resize(readUInt32());
12745 for (auto &Selector : Set.Selectors) {
12746 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12747 Selector.ScoreOrCondition = nullptr;
12748 if (readBool())
12749 Selector.ScoreOrCondition = readExprRef();
12750 Selector.Properties.resize(readUInt32());
12751 for (auto &Property : Selector.Properties)
12752 Property.Kind = readEnum<llvm::omp::TraitProperty>();
12753 }
12754 }
12755 return &TI;
12756}
12757
12759 if (!Data)
12760 return;
12761 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12762 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12763 skipInts(3);
12764 }
12765 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12766 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12767 Clauses[I] = readOMPClause();
12768 Data->setClauses(Clauses);
12769 if (Data->hasAssociatedStmt())
12770 Data->setAssociatedStmt(readStmt());
12771 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12772 Data->getChildren()[I] = readStmt();
12773}
12774
12776 unsigned NumVars = readInt();
12778 for (unsigned I = 0; I < NumVars; ++I)
12779 VarList.push_back(readExpr());
12780 return VarList;
12781}
12782
12784 unsigned NumExprs = readInt();
12786 for (unsigned I = 0; I < NumExprs; ++I)
12787 ExprList.push_back(readSubExpr());
12788 return ExprList;
12789}
12790
12792 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
12795
12796 switch (ClauseKind) {
12798 SourceLocation LParenLoc = readSourceLocation();
12799 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
12800 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
12801 EndLoc);
12802 }
12803 case OpenACCClauseKind::If: {
12804 SourceLocation LParenLoc = readSourceLocation();
12805 Expr *CondExpr = readSubExpr();
12806 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
12807 EndLoc);
12808 }
12810 SourceLocation LParenLoc = readSourceLocation();
12811 bool isConditionExprClause = readBool();
12812 if (isConditionExprClause) {
12813 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
12814 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
12815 CondExpr, EndLoc);
12816 }
12817 unsigned NumVars = readInt();
12819 for (unsigned I = 0; I < NumVars; ++I)
12820 VarList.push_back(readSubExpr());
12821 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12822 EndLoc);
12823 }
12825 SourceLocation LParenLoc = readSourceLocation();
12826 unsigned NumClauses = readInt();
12828 for (unsigned I = 0; I < NumClauses; ++I)
12829 IntExprs.push_back(readSubExpr());
12830 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
12831 IntExprs, EndLoc);
12832 }
12834 SourceLocation LParenLoc = readSourceLocation();
12835 Expr *IntExpr = readSubExpr();
12836 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
12837 IntExpr, EndLoc);
12838 }
12840 SourceLocation LParenLoc = readSourceLocation();
12841 Expr *IntExpr = readSubExpr();
12842 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
12843 IntExpr, EndLoc);
12844 }
12846 SourceLocation LParenLoc = readSourceLocation();
12847 Expr *IntExpr = readSubExpr();
12848 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12849 IntExpr, EndLoc);
12850 }
12852 SourceLocation LParenLoc = readSourceLocation();
12853 Expr *IntExpr = readSubExpr();
12854 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
12855 IntExpr, EndLoc);
12856 }
12858 SourceLocation LParenLoc = readSourceLocation();
12860
12862 for (unsigned I = 0; I < VarList.size(); ++I)
12863 RecipeList.push_back(readDeclAs<VarDecl>());
12864
12865 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12866 VarList, RecipeList, EndLoc);
12867 }
12869 SourceLocation LParenLoc = readSourceLocation();
12871 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12872 EndLoc);
12873 }
12875 SourceLocation LParenLoc = readSourceLocation();
12877 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
12878 VarList, EndLoc);
12879 }
12881 SourceLocation LParenLoc = readSourceLocation();
12884 for (unsigned I = 0; I < VarList.size(); ++I) {
12885 VarDecl *Recipe = readDeclAs<VarDecl>();
12886 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
12887 RecipeList.push_back({Recipe, RecipeTemp});
12888 }
12889
12890 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12891 VarList, RecipeList, EndLoc);
12892 }
12894 SourceLocation LParenLoc = readSourceLocation();
12896 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
12897 VarList, EndLoc);
12898 }
12900 SourceLocation LParenLoc = readSourceLocation();
12902 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
12903 VarList, EndLoc);
12904 }
12906 SourceLocation LParenLoc = readSourceLocation();
12908 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
12909 VarList, EndLoc);
12910 }
12912 SourceLocation LParenLoc = readSourceLocation();
12914 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
12915 VarList, EndLoc);
12916 }
12918 SourceLocation LParenLoc = readSourceLocation();
12920 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
12921 VarList, EndLoc);
12922 }
12924 SourceLocation LParenLoc = readSourceLocation();
12926 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
12927 VarList, EndLoc);
12928 }
12930 SourceLocation LParenLoc = readSourceLocation();
12932 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
12933 VarList, EndLoc);
12934 }
12938 SourceLocation LParenLoc = readSourceLocation();
12939 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
12941 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
12942 LParenLoc, ModList, VarList, EndLoc);
12943 }
12947 SourceLocation LParenLoc = readSourceLocation();
12948 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
12950 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
12951 LParenLoc, ModList, VarList, EndLoc);
12952 }
12956 SourceLocation LParenLoc = readSourceLocation();
12957 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
12959 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
12960 LParenLoc, ModList, VarList, EndLoc);
12961 }
12965 SourceLocation LParenLoc = readSourceLocation();
12966 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
12968 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
12969 LParenLoc, ModList, VarList, EndLoc);
12970 }
12972 SourceLocation LParenLoc = readSourceLocation();
12973 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
12974 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12975 AsyncExpr, EndLoc);
12976 }
12978 SourceLocation LParenLoc = readSourceLocation();
12979 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
12980 SourceLocation QueuesLoc = readSourceLocation();
12982 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
12983 DevNumExpr, QueuesLoc, QueueIdExprs,
12984 EndLoc);
12985 }
12988 SourceLocation LParenLoc = readSourceLocation();
12990 unsigned NumArchs = readInt();
12991
12992 for (unsigned I = 0; I < NumArchs; ++I) {
12993 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
12995 Archs.emplace_back(Loc, Ident);
12996 }
12997
12998 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
12999 LParenLoc, Archs, EndLoc);
13000 }
13002 SourceLocation LParenLoc = readSourceLocation();
13003 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();
13006
13007 for (unsigned I = 0; I < VarList.size(); ++I) {
13008 VarDecl *Recipe = readDeclAs<VarDecl>();
13009 static_assert(sizeof(OpenACCReductionRecipe) == sizeof(int *));
13010 RecipeList.push_back({Recipe});
13011 }
13012
13013 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13014 VarList, RecipeList, EndLoc);
13015 }
13017 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13019 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13021 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13023 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13025 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13027 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13029 SourceLocation LParenLoc = readSourceLocation();
13030 bool HasForce = readBool();
13031 Expr *LoopCount = readSubExpr();
13032 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13033 HasForce, LoopCount, EndLoc);
13034 }
13036 SourceLocation LParenLoc = readSourceLocation();
13037 unsigned NumClauses = readInt();
13038 llvm::SmallVector<Expr *> SizeExprs;
13039 for (unsigned I = 0; I < NumClauses; ++I)
13040 SizeExprs.push_back(readSubExpr());
13041 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13042 SizeExprs, EndLoc);
13043 }
13045 SourceLocation LParenLoc = readSourceLocation();
13046 unsigned NumExprs = readInt();
13049 for (unsigned I = 0; I < NumExprs; ++I) {
13050 GangKinds.push_back(readEnum<OpenACCGangKind>());
13051 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13052 Exprs.push_back(readExpr());
13053 }
13054 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13055 GangKinds, Exprs, EndLoc);
13056 }
13058 SourceLocation LParenLoc = readSourceLocation();
13059 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13060 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13061 WorkerExpr, EndLoc);
13062 }
13064 SourceLocation LParenLoc = readSourceLocation();
13065 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13066 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13067 VectorExpr, EndLoc);
13068 }
13070 SourceLocation LParenLoc = readSourceLocation();
13072 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13073 EndLoc);
13074 }
13076 SourceLocation LParenLoc = readSourceLocation();
13079 LParenLoc, VarList, EndLoc);
13080 }
13081
13083 SourceLocation LParenLoc = readSourceLocation();
13084 bool IsString = readBool();
13085 if (IsString)
13086 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13087 cast<StringLiteral>(readExpr()), EndLoc);
13088 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13089 readIdentifier(), EndLoc);
13090 }
13093 llvm_unreachable("Clause serialization not yet implemented");
13094 }
13095 llvm_unreachable("Invalid Clause Kind");
13096}
13097
13100 for (unsigned I = 0; I < Clauses.size(); ++I)
13101 Clauses[I] = readOpenACCClause();
13102}
13103
13104void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13105 unsigned NumVars = readInt();
13106 A->Clauses.resize(NumVars);
13107 readOpenACCClauseList(A->Clauses);
13108}
13109
13110static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13111 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13112 // module name?
13113 llvm::FoldingSetNodeID ID;
13114 ID.AddString(PrimaryModuleName);
13115 return ID.computeStableHash();
13116}
13117
13119 if (!M)
13120 return std::nullopt;
13121
13122 if (M->isHeaderLikeModule())
13123 return std::nullopt;
13124
13125 if (M->isGlobalModule())
13126 return std::nullopt;
13127
13128 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13129 return getStableHashForModuleName(PrimaryModuleName);
13130}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:5068
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8812
static bool checkCodegenOptions(const CodeGenOptions &CGOpts, const CodeGenOptions &ExistingCGOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Definition: ASTReader.cpp:395
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST file magic number 'CPCH'.
Definition: ASTReader.cpp:5049
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:596
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.
Definition: ASTReader.cpp:945
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7626
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
Definition: ASTReader.cpp:711
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
Definition: ASTReader.cpp:1162
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4623
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:3008
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:1136
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
Definition: ASTReader.cpp:5391
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:651
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...
Definition: ASTReader.cpp:764
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:9352
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:603
static bool isPredefinedType(serialization::TypeID ID)
Definition: ASTReader.cpp:7630
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1148
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
Definition: ASTReader.cpp:562
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:7133
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:997
static unsigned getStableHashForModuleName(StringRef PrimaryModuleName)
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8944
OptionValidation
Definition: ASTReader.cpp:748
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:751
@ OptionValidateNone
Definition: ASTReader.cpp:749
@ OptionValidateContradictions
Definition: ASTReader.cpp:750
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.
Definition: ASTReader.cpp:463
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.
Definition: ASTReader.cpp:285
static std::pair< StringRef, StringRef > getUnresolvedInputFilenames(const ASTReader::RecordData &Record, const StringRef InputBlob)
Definition: ASTReader.cpp:2698
#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.
Definition: ASTReader.cpp:5616
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...
Definition: ASTReader.cpp:4762
static unsigned getIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7622
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:984
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:126
static char ID
Definition: Arena.cpp:183
Defines the Diagnostic-related interfaces.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
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.
StringRef Filename
Definition: Format.cpp:3177
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:145
unsigned Iter
Definition: HTMLLogger.cpp:153
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::FileType FileType
Definition: MachO.h:46
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)
Definition: OffloadArch.cpp:16
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.
uint32_t Id
Definition: SemaARM.cpp:1179
This file declares semantic analysis for CUDA constructs.
@ None
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
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.
const char * Data
Defines the clang::TargetOptions class.
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
StateNode * Previous
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.
Definition: ASTConsumer.cpp:22
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType AccumTy
Definition: ASTContext.h:1235
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1254
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1253
CanQualType LongTy
Definition: ASTContext.h:1231
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1231
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1244
ExternCContextDecl * getExternCContextDecl() const
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1237
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CanQualType SatAccumTy
Definition: ASTContext.h:1240
CanQualType ShortAccumTy
Definition: ASTContext.h:1235
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1360
CanQualType FloatTy
Definition: ASTContext.h:1234
CanQualType DoubleTy
Definition: ASTContext.h:1234
CanQualType SatLongAccumTy
Definition: ASTContext.h:1240
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2243
CanQualType LongDoubleTy
Definition: ASTContext.h:1234
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1263
CanQualType Char16Ty
Definition: ASTContext.h:1229
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2219
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1239
CanQualType DependentTy
Definition: ASTContext.h:1250
CanQualType NullPtrTy
Definition: ASTContext.h:1249
CanQualType OMPIteratorTy
Definition: ASTContext.h:1263
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:927
CanQualType SatShortFractTy
Definition: ASTContext.h:1243
CanQualType Ibm128Ty
Definition: ASTContext.h:1234
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1241
CanQualType ArraySectionTy
Definition: ASTContext.h:1262
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1254
CanQualType BoolTy
Definition: ASTContext.h:1223
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1239
CanQualType Float128Ty
Definition: ASTContext.h:1234
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1254
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1250
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2256
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1237
CanQualType ShortFractTy
Definition: ASTContext.h:1238
CanQualType BoundMemberTy
Definition: ASTContext.h:1250
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1244
CanQualType CharTy
Definition: ASTContext.h:1224
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1231
CanQualType PseudoObjectTy
Definition: ASTContext.h:1253
CanQualType Float16Ty
Definition: ASTContext.h:1248
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
CanQualType SignedCharTy
Definition: ASTContext.h:1231
CanQualType OverloadTy
Definition: ASTContext.h:1250
CanQualType OCLClkEventTy
Definition: ASTContext.h:1259
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1241
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1233
CanQualType BuiltinFnTy
Definition: ASTContext.h:1252
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1259
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1222
CanQualType UnsignedCharTy
Definition: ASTContext.h:1232
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1239
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:814
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
TagDecl * getMSTypeInfoTagDecl() const
Retrieve the implicitly-predeclared 'struct type_info' declaration.
Definition: ASTContext.h:2424
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2415
CanQualType UnknownAnyTy
Definition: ASTContext.h:1251
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1233
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1260
CanQualType UnsignedShortTy
Definition: ASTContext.h:1232
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1245
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1604
CanQualType ShortTy
Definition: ASTContext.h:1231
CanQualType FractTy
Definition: ASTContext.h:1238
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1236
CanQualType Char32Ty
Definition: ASTContext.h:1230
CanQualType SatFractTy
Definition: ASTContext.h:1243
CanQualType SatLongFractTy
Definition: ASTContext.h:1243
CanQualType OCLQueueTy
Definition: ASTContext.h:1260
CanQualType LongFractTy
Definition: ASTContext.h:1238
CanQualType SatShortAccumTy
Definition: ASTContext.h:1240
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1247
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1261
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2230
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1242
CanQualType LongLongTy
Definition: ASTContext.h:1231
CanQualType WCharTy
Definition: ASTContext.h:1225
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1161
CanQualType Char8Ty
Definition: ASTContext.h:1228
CanQualType HalfTy
Definition: ASTContext.h:1246
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1237
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1259
virtual void MacroRead(serialization::MacroID ID, MacroInfo *MI)
A macro was read from the AST file.
virtual void SelectorRead(serialization::SelectorID iD, Selector Sel)
A selector was read from the AST file.
virtual void IdentifierRead(serialization::IdentifierID ID, IdentifierInfo *II)
An identifier was deserialized from the AST file.
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:9173
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:9201
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:9206
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 void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:270
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:135
virtual void visitImport(StringRef ModuleName, StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file.
Definition: ASTReader.h:267
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:227
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:263
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:125
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:223
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:129
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:429
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...
Definition: ASTReader.cpp:6930
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6711
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2539
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.
Definition: ASTReader.cpp:1009
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:9788
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9869
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1990
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:8205
friend class ASTIdentifierIterator
Definition: ASTReader.h:434
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1833
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2599
Decl * ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:2174
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.
Definition: ASTReader.cpp:9491
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8992
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1832
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1845
@ 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:1836
@ 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:1840
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:9421
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.
Definition: ASTReader.cpp:8646
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.
Definition: ASTReader.cpp:6697
serialization::TypeID getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7958
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8959
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:2132
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2633
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9880
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.
Definition: ASTReader.cpp:8568
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...
Definition: ASTReader.cpp:8225
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9851
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8776
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7954
void ClearSwitchCaseIDs()
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:9644
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4729
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition: ASTReader.h:1816
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
Definition: ASTReader.cpp:8782
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:8232
const CodeGenOptions & getCodeGenOpts() const
Definition: ASTReader.h:1819
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...
Definition: ASTReader.cpp:4665
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.
Definition: ASTReader.cpp:8507
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5610
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2611
static std::string ResolveImportedPathAndAllocate(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
Definition: ASTReader.cpp:2995
static StringRef ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx, StringRef &Blob)
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:8108
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.
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
Definition: ASTReader.cpp:8833
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:8418
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2550
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:9437
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:8034
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:8447
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.
Definition: ASTReader.cpp:1761
~ASTReader() override
bool haveUnloadedSpecializations(const Decl *D) const
If we have any unloaded specialization for D.
Definition: ASTReader.cpp:8802
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
Definition: ASTReader.cpp:8036
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.
Definition: ASTReader.cpp:2052
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
Definition: ASTReader.cpp:9619
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
Definition: ASTReader.cpp:2263
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
Definition: ASTReader.cpp:6917
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:9134
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:9723
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.
Definition: ASTReader.cpp:9817
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...
Definition: ASTReader.cpp:6108
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6690
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:8462
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9909
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:2088
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:9746
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
Definition: ASTReader.cpp:9410
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:9458
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7651
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2386
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:8182
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WeakIDs) override
Read the set of weak, undeclared identifiers known to the external Sema source.
Definition: ASTReader.cpp:9519
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8744
void AssignedLambdaNumbering(CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:9591
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:9479
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.
Definition: ASTReader.cpp:5794
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:9469
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2606
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
Definition: ASTReader.cpp:2015
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:9447
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:9501
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9884
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
Definition: ASTReader.cpp:4807
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1998
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9834
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:8689
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:9692
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:449
@ Success
The control block was read successfully.
Definition: ASTReader.h:452
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:469
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:462
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:455
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:465
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:472
@ Missing
The AST file was missing.
Definition: ASTReader.h:458
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.
Definition: ASTReader.cpp:2079
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:9727
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > &LPTMap) override
Read the set of late parsed template functions for this source.
Definition: ASTReader.cpp:9562
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:9259
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:9537
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
Definition: ASTReader.cpp:4754
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9913
static TemporarilyOwnedStringRef ResolveImportedPath(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
Definition: ASTReader.cpp:2975
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:9394
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:8371
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.
Definition: ASTReader.cpp:9821
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.
Definition: ASTReader.cpp:9614
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6989
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4651
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:9029
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:8397
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
Definition: ASTReader.cpp:1796
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw) const
Read a source location from raw form.
Definition: ASTReader.h:2469
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:9550
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1994
serialization::reader::LazySpecializationInfoLookupTable * getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial)
Get the loaded specializations lookup tables for D, if any.
Definition: ASTReader.cpp:8794
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...
Definition: ASTReader.cpp:9399
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:9803
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8843
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
Definition: ASTReader.cpp:4714
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.
Definition: ASTReader.cpp:9919
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
Definition: ASTReader.cpp:9358
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5467
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.
Definition: ASTReader.cpp:8140
const serialization::reader::DeclContextLookupTable * getTULocalLookupTables(DeclContext *Primary) const
Definition: ASTReader.cpp:8788
FileManager & getFileManager() const
Definition: ASTReader.h:1817
bool wasThisDeclarationADefinition(const FunctionDecl *FD) override
True if this function declaration was a definition before in its own module.
Definition: ASTReader.cpp:9876
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.
Definition: ASTReader.cpp:2514
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2392
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6980
serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
Definition: ASTReader.cpp:9773
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.
Definition: ASTReader.cpp:8008
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)
Definition: ASTReader.cpp:9981
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9935
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Expected< unsigned > readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID)
Reads a record with id AbbrevID from Cursor, resetting the internal state.
DeclarationNameInfo readDeclarationNameInfo()
Definition: ASTReader.cpp:9960
void readTypeLoc(TypeLoc TL)
Reads the location information for a type.
Definition: ASTReader.cpp:7606
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7979
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.
Definition: ASTReader.cpp:7612
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:8018
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9968
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()
Definition: ASTReader.cpp:7425
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.
Definition: ASTReader.cpp:9994
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()
Definition: ASTReader.cpp:9972
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:8028
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Attr * readAttr()
Reads one attribute from the current stream position, advancing Idx.
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 array parameter types.
Definition: TypeLoc.h:1813
Wrapper for source info for arrays.
Definition: TypeLoc.h:1757
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1763
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1771
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1783
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2797
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2789
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2781
Attr - This represents one attribute.
Definition: Attr.h:44
Type source information for an attributed type.
Definition: TypeLoc.h:1017
void setAttr(const Attr *A)
Definition: TypeLoc.h:1043
void setConceptReference(ConceptReference *CR)
Definition: TypeLoc.h:2385
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2379
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:1067
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1506
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1512
Wrapper for source info for builtin types.
Definition: TypeLoc.h:582
void setWrittenTypeSpec(TypeSpecifierType written)
Definition: TypeLoc.h:668
bool needsExtraLocalData() const
Definition: TypeLoc.h:611
void setModeAttr(bool written)
Definition: TypeLoc.h:680
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:588
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition: TypeLoc.h:657
void setWrittenSignSpec(TypeSpecifierSign written)
Definition: TypeLoc.h:641
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
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...
Definition: ASTReader.cpp:249
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
Definition: ASTReader.cpp:178
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:154
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:209
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:203
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:227
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:164
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:169
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:187
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:159
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:233
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:218
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:265
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:243
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:238
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:196
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:126
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:87
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:438
An object that helps properly build a continuous range map from a set of values.
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
typename Representation::const_iterator const_iterator
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1454
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.
Definition: DeclBase.cpp:1879
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 ...
Definition: DeclBase.cpp:2022
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...
Definition: DeclBase.cpp:1459
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
Definition: DeclBase.cpp:1649
unsigned getModuleFileIndex() const
Definition: DeclID.h:125
DeclID getRawValue() const
Definition: DeclID.h:115
unsigned getLocalDeclIndex() const
Definition: DeclBase.cpp:2251
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: DeclID.h:108
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
static void add(Kind k)
Definition: DeclBase.cpp:226
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:156
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:107
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.
NameKind
The kind of the name stored in this DeclarationName.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:779
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2271
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2268
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2511
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2493
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2499
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1957
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1978
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2570
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2076
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2631
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2651
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2618
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2675
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2667
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2683
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2659
ArrayRef< TemplateArgument > template_arguments() const
Definition: TypeBase.h:7480
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2048
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1233
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:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:596
bool getEnableAllWarnings() const
Definition: Diagnostic.h:696
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:236
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:965
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:722
bool getWarningsAsErrors() const
Definition: Diagnostic.h:704
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:809
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:591
StringRef getName() const
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition: TypeLoc.h:749
Represents an enum.
Definition: Decl.h:4004
Wrapper for source info for enum types.
Definition: TypeLoc.h:870
This represents one expression.
Definition: Expr.h:112
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
uint32_t getGeneration() const
Get the current generation of this AST source.
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:982
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:989
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:880
Represents a member of a struct/union/class.
Definition: Decl.h:3157
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:358
off_t getSize() const
Definition: FileEntry.h:350
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
Definition: FileManager.h:219
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.
Definition: FileManager.h:208
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:1999
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2331
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
Wrapper for source info for functions.
Definition: TypeLoc.h:1624
unsigned getNumParams() const
Definition: TypeLoc.h:1696
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1644
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1660
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1703
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1668
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1652
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1682
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
Type source information for HLSL attributed resource type.
Definition: TypeLoc.h:1094
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.
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:448
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.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn't alre...
llvm::iterator_range< iterator > decls(DeclarationName Name)
Returns a range of decls with the name 'Name'.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
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:3464
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:879
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1594
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
Definition: LangOptions.h:82
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:469
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:440
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:498
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:512
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:508
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:489
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:495
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
Used to hold and unique data used to represent #line information.
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)
Definition: ASTReader.cpp:1019
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:1363
void setAttrRowOperand(Expr *e)
Definition: TypeLoc.h:2111
void setAttrColumnOperand(Expr *e)
Definition: TypeLoc.h:2117
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:2126
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:2105
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1524
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1530
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1539
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.
Definition: ModuleMap.cpp:1215
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Definition: ModuleMap.cpp:1409
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:812
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
Definition: ModuleMap.cpp:1426
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:1200
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.
Definition: ModuleMap.cpp:866
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.
Definition: ModuleMap.cpp:1296
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:273
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
Represent a C++ namespace.
Definition: Decl.h:591
Class that aids in the construction of nested-name-specifiers along with source-location information ...
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.
@ Type
A type, stored as a Type*.
@ 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.
Definition: OpenMPClause.h:442
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.
Definition: OpenMPClause.h:487
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.
Definition: OpenMPClause.h:408
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)
OMPClause * readClause()
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
RetTy Visit(PTR(OMPClause) S)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Definition: OpenMPClause.h:233
Class that handles pre-initialization statement for some clauses, like 'schedule',...
Definition: OpenMPClause.h:195
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
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' d...
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 '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.
Definition: OpenMPClause.h:779
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.
Definition: OpenMPClause.h:676
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 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' direct...
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.
Definition: OpenMPClause.h:825
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.
Definition: OpenMPClause.h:891
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' direc...
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.
Definition: OpenMPClause.h:926
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:958
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 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
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1283
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1293
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1305
Interfaces are the core concept in Objective-C for object oriented design.
Definition: TypeBase.h:7905
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
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
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1566
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1572
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1176
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:1180
unsigned getNumProtocols() const
Definition: TypeLoc.h:1210
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1168
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition: TypeLoc.h:1189
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1198
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1206
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:1238
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:1219
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2084
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
Kind
The basic Objective-C runtimes that we know about.
Definition: ObjCRuntime.h:31
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition: TypeLoc.h:904
unsigned getNumProtocols() const
Definition: TypeLoc.h:941
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:950
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:927
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:937
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.
Definition: OpenACCClause.h:27
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< VarDecl * > InitRecipes, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, ArrayRef< OpenACCReductionRecipe > 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...
virtual llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const =0
Returns the serialized AST inside the PCH container Buffer.
ASTReaderListener implementation to validate the information of the PCH file against an initialized P...
Definition: ASTReader.h:327
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:675
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:527
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:965
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:976
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:920
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
Definition: ASTReader.cpp:536
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:545
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2741
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2296
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1395
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1391
Represents a parameter to a function.
Definition: Decl.h:1789
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2833
Wrapper for source info for pointers.
Definition: TypeLoc.h:1493
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1499
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
Iteration over the preprocessed entities.
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 ...
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.
Definition: Preprocessor.h:145
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
const TargetInfo & getTargetInfo() const
FileManager & getFileManager() const
HeaderSearch & getHeaderSearchInfo() const
IdentifierTable & getIdentifierTable()
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
const LangOptions & getLangOpts() const
void setCounterValue(unsigned V)
DiagnosticsEngine & getDiagnostics() 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
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:305
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
@ 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:1608
Represents a struct/union/class.
Definition: Decl.h:4309
Wrapper for source info for record types.
Definition: TypeLoc.h:860
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
Declaration of a redeclarable template.
Definition: DeclTemplate.h:715
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:213
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5292
void AddDecl(Decl *D)
Definition: Scope.h:362
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 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:850
SemaObjC & ObjC()
Definition: Sema.h:1483
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition: Sema.cpp:657
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1239
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:627
IdentifierResolver IdResolver
Definition: Sema.h:3461
PragmaMsStackAction
Definition: Sema.h:1814
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:361
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:932
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.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
void setExternalSLocEntrySource(ExternalSLocEntrySource *Source)
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.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Instances of this class represent operands to a SPIR-V type instruction.
Definition: TypeBase.h:6782
bool isValid() const
Definition: TypeBase.h:6820
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.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Stmt - This represents one statement.
Definition: Stmt.h:85
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:1007
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:1001
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:989
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3714
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:821
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:829
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:810
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:323
Options for controlling the target.
Definition: TargetOptions.h:26
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
Definition: TargetOptions.h:54
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:411
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:64
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
MutableArrayRef< TemplateArgumentLocInfo > getArgLocInfos()
Definition: TypeLoc.h:1893
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition: TypeLoc.cpp:707
ArrayRef< TemplateArgument > template_arguments() const
Definition: TypeBase.h:7357
Wrapper for template type parameters.
Definition: TypeLoc.h:890
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:152
void setLength(unsigned Len)
Definition: Token.h:143
void setKind(tok::TokenKind K)
Definition: Token.h:98
tok::TokenKind getKind() const
Definition: Token.h:97
void setLocation(SourceLocation L)
Definition: Token.h:142
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:123
void setAnnotationValue(void *val)
Definition: Token.h:240
void startToken()
Reset all flags to cleared.
Definition: Token.h:179
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:198
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:246
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: TypeBase.h:3374
TypeLocReader(ASTRecordReader &Reader)
Definition: ASTReader.cpp:7217
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:7289
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:7356
void VisitTagTypeLoc(TagTypeLoc TL)
Definition: ASTReader.cpp:7452
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:2245
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:556
The base class of the type hierarchy.
Definition: TypeBase.h:1833
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3559
Wrapper for source info for typedefs.
Definition: TypeLoc.h:782
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2188
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:2180
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2196
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2330
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2324
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:2336
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2327
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:787
Wrapper for source info for types used via transparent aliases.
Definition: TypeLoc.h:790
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
Represents a variable declaration or definition.
Definition: Decl.h:925
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2025
Captures information about a #pragma weak directive.
Definition: Weak.h:25
Source location and bit offset of a declaration.
Definition: ASTBitCodes.h:252
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2139
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1290
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:378
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:441
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:469
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Definition: ModuleFile.h:376
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:373
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:489
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition: ModuleFile.h:472
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:448
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:426
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition: ModuleFile.h:497
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition: ModuleFile.h:397
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:464
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:369
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:406
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:515
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:423
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition: ModuleFile.h:461
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:401
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:409
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:485
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:481
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:250
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition: ModuleFile.h:384
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:366
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:458
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition: ModuleFile.h:360
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:434
void dump()
Dump debugging output for this module.
Definition: ModuleFile.cpp:47
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition: ModuleFile.h:454
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition: ModuleFile.h:390
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:429
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
Definition: ModuleFile.h:357
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:412
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:451
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition: ModuleFile.h:494
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition: ModuleFile.h:382
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:419
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:476
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:508
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:46
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
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.
void visit(llvm::function_ref< bool(ModuleFile &M)> Visitor, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:211
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:227
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:228
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:234
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:246
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:247
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:9287
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:9329
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:9334
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:121
32 aligned uint64_t in the AST file.
Definition: ASTBitCodes.h:194
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:1125
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:1120
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:1130
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1154
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1171
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)
Definition: ASTReader.cpp:1058
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1080
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:1053
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:1015
Trait class used to search the on-disk hash table containing all of the header search information.
Class that performs lookup to specialized decls.
std::pair< DeclarationName, const Module * > external_key_type
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
Definition: ASTReader.cpp:1417
std::pair< DeclarationNameKey, unsigned > internal_key_type
internal_key_type ReadKey(const unsigned char *d, unsigned)
Definition: ASTReader.cpp:1410
static hash_value_type ComputeHash(const internal_key_type &Key)
Definition: ASTReader.cpp:1391
static internal_key_type GetInternalKey(const external_key_type &Key)
Definition: ASTReader.cpp:1399
#define bool
Definition: gpuintrin.h:32
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:900
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:2084
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1163
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1218
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1177
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1076
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1124
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1109
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:908
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1082
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1100
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1094
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:911
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:1025
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1079
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1121
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:914
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:929
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:971
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1073
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:920
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:974
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:926
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1106
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:917
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:938
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1112
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:905
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1103
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1097
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:902
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1070
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1118
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
Definition: ASTBitCodes.h:1153
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1085
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:944
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1091
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1115
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:923
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1088
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:995
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1464
@ DECL_CONTEXT_TU_LOCAL_VISIBLE
A record that stores the set of declarations that are only visible to the TU.
Definition: ASTBitCodes.h:1353
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1336
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1467
@ DECL_CONTEXT_MODULE_LOCAL_VISIBLE
A record containing the set of declarations that are only visible from DeclContext in the same module...
Definition: ASTBitCodes.h:1349
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1345
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1183
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1211
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1214
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1199
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1196
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1202
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1208
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1193
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1205
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
Definition: ASTMatchers.h:3675
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:82
@ 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...
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.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:88
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:434
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
Definition: ASTBitCodes.h:286
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:849
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:831
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:869
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:828
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:877
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:834
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:825
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:817
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:845
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:861
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:838
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:858
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:873
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:821
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:852
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:855
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:842
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:865
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:880
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition: ASTBitCodes.h:94
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:66
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:185
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:382
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:395
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:392
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:401
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:398
@ CODEGEN_OPTIONS
Record code for the codegen options table.
Definition: ASTBitCodes.h:404
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:389
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:167
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:289
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:182
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:188
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:314
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:311
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:296
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:300
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:322
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:308
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:304
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:317
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:344
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:338
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:335
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:328
unsigned StableHashForTemplateArguments(llvm::ArrayRef< TemplateArgument > Args)
Calculate a stable hash value for template arguments.
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:884
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:754
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:768
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:758
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:764
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:772
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:170
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:474
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:47
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:70
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:776
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:791
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:787
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:782
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:794
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:798
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:348
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:374
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:377
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:363
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:370
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:359
@ IMPORT
Record code for another AST file imported by this AST file.
Definition: ASTBitCodes.h:354
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:367
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:351
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:408
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:416
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:425
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:413
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:422
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:410
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:419
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:428
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:442
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:447
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:444
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:802
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:811
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:804
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:807
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
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:63
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:164
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:451
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:592
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:526
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:712
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:618
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:522
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:581
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:464
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:614
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:718
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:551
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:611
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:608
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
Definition: ASTBitCodes.h:725
@ CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
Definition: ASTBitCodes.h:743
@ DECLS_WITH_EFFECTS_TO_VERIFY
Record code for Sema's vector of functions/blocks with effects to be verified.
Definition: ASTBitCodes.h:736
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:561
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:668
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:709
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:476
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:628
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:542
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:679
@ RELATED_DECLS_MAP
Record code for related declarations that have to be deserialized together from the same module.
Definition: ASTBitCodes.h:732
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:588
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:689
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:656
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:558
@ VTABLES_TO_EMIT
Record code for vtables to emit.
Definition: ASTBitCodes.h:728
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:484
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:649
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:538
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:722
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:703
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:566
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:546
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:578
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:665
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:635
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:682
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:529
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:554
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:700
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:639
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:535
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:674
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:513
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:661
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:605
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:632
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:602
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:570
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:706
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:503
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:575
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:671
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:624
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:685
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:154
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:294
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
OpenACCReductionOperator
Definition: OpenACCKinds.h:547
bool isa(CodeGen::Address addr)
Definition: Address.h:330
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:230
@ CPlusPlus
Definition: LangStandard.h:55
std::pair< FileID, unsigned > FileIDAndOffset
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
OpenACCModifierKind
Definition: OpenACCKinds.h:641
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:25
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
Definition: OpenMPKinds.h:119
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
Definition: OpenMPKinds.h:172
@ Success
Annotation was successful.
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
Definition: OpenMPKinds.h:136
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
Definition: OpenMPKinds.h:187
OpenACCClauseKind
Represents the kind of an OpenACC clause.
Definition: OpenACCKinds.h:207
@ 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
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:28
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
Definition: OpenMPKinds.h:104
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
Definition: OpenMPKinds.h:233
OpenACCDefaultClauseKind
Definition: OpenACCKinds.h:514
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition: OpenMPKinds.h:88
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.
@ Result
The result type of a method or function.
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
Definition: OpenMPKinds.h:208
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
Definition: OpenMPKinds.h:158
@ Template
We are parsing a template declaration.
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition: OpenMPKinds.h:55
OpenMPGrainsizeClauseModifier
Definition: OpenMPKinds.h:214
OpenMPNumTasksClauseModifier
Definition: OpenMPKinds.h:220
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
Definition: OpenMPKinds.h:143
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.
Definition: OpenMPKinds.h:100
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.
Definition: OpenMPKinds.h:111
OpenMPAllocateClauseModifier
OpenMP modifiers for 'allocate' clause.
Definition: OpenMPKinds.h:240
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition: OpenMPKinds.h:63
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition: Specifiers.h:50
const FunctionProtoType * T
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ PCH
Disable validation for a precompiled header and the modules it depends on.
@ Module
Disable validation for module files.
bool shouldSkipCheckingODR(const Decl *D)
Definition: ASTReader.h:2703
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
OpenMPNumThreadsClauseModifier
Definition: OpenMPKinds.h:226
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
Definition: OpenMPKinds.h:128
U cast(CodeGen::Address addr)
Definition: Address.h:327
@ None
The alignment was not explicit in code.
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.
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
Definition: OpenMPKinds.h:165
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition: OpenMPKinds.h:31
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
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>".
Definition: TemplateBase.h:678
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.
Definition: HeaderSearch.h:59
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,...
Definition: HeaderSearch.h:123
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:81
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:74
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:113
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:70
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:86
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
A library or framework to link against when an entity from this module is used.
Definition: Module.h:503
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.
Data for list of allocators.
a linked list of methods with the same selector name but different signatures.
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition: Decl.h:752
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:766
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:753
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:759
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:1825
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
Location information for a TemplateArgument.
Definition: TemplateBase.h:480
The input file info that has been loaded from an AST file.
Definition: ModuleFile.h:64
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:2095
#define log(__x)
Definition: tgmath.h:460