clang 20.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"
55#include "clang/Basic/LLVM.h"
57#include "clang/Basic/Module.h"
68#include "clang/Basic/Stack.h"
72#include "clang/Basic/Version.h"
75#include "clang/Lex/MacroInfo.h"
76#include "clang/Lex/ModuleMap.h"
80#include "clang/Lex/Token.h"
82#include "clang/Sema/Scope.h"
83#include "clang/Sema/Sema.h"
84#include "clang/Sema/SemaCUDA.h"
85#include "clang/Sema/SemaObjC.h"
86#include "clang/Sema/Weak.h"
98#include "llvm/ADT/APFloat.h"
99#include "llvm/ADT/APInt.h"
100#include "llvm/ADT/APSInt.h"
101#include "llvm/ADT/ArrayRef.h"
102#include "llvm/ADT/DenseMap.h"
103#include "llvm/ADT/FloatingPointMode.h"
104#include "llvm/ADT/FoldingSet.h"
105#include "llvm/ADT/Hashing.h"
106#include "llvm/ADT/IntrusiveRefCntPtr.h"
107#include "llvm/ADT/STLExtras.h"
108#include "llvm/ADT/ScopeExit.h"
109#include "llvm/ADT/Sequence.h"
110#include "llvm/ADT/SmallPtrSet.h"
111#include "llvm/ADT/SmallString.h"
112#include "llvm/ADT/SmallVector.h"
113#include "llvm/ADT/StringExtras.h"
114#include "llvm/ADT/StringMap.h"
115#include "llvm/ADT/StringRef.h"
116#include "llvm/ADT/iterator_range.h"
117#include "llvm/Bitstream/BitstreamReader.h"
118#include "llvm/Support/Casting.h"
119#include "llvm/Support/Compiler.h"
120#include "llvm/Support/Compression.h"
121#include "llvm/Support/DJB.h"
122#include "llvm/Support/Endian.h"
123#include "llvm/Support/Error.h"
124#include "llvm/Support/ErrorHandling.h"
125#include "llvm/Support/FileSystem.h"
126#include "llvm/Support/LEB128.h"
127#include "llvm/Support/MemoryBuffer.h"
128#include "llvm/Support/Path.h"
129#include "llvm/Support/SaveAndRestore.h"
130#include "llvm/Support/TimeProfiler.h"
131#include "llvm/Support/Timer.h"
132#include "llvm/Support/VersionTuple.h"
133#include "llvm/Support/raw_ostream.h"
134#include "llvm/TargetParser/Triple.h"
135#include <algorithm>
136#include <cassert>
137#include <cstddef>
138#include <cstdint>
139#include <cstdio>
140#include <ctime>
141#include <iterator>
142#include <limits>
143#include <map>
144#include <memory>
145#include <optional>
146#include <string>
147#include <system_error>
148#include <tuple>
149#include <utility>
150#include <vector>
151
152using namespace clang;
153using namespace clang::serialization;
154using namespace clang::serialization::reader;
155using llvm::BitstreamCursor;
156
157//===----------------------------------------------------------------------===//
158// ChainedASTReaderListener implementation
159//===----------------------------------------------------------------------===//
160
161bool
163 return First->ReadFullVersionInformation(FullVersion) ||
164 Second->ReadFullVersionInformation(FullVersion);
165}
166
168 First->ReadModuleName(ModuleName);
169 Second->ReadModuleName(ModuleName);
170}
171
172void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
173 First->ReadModuleMapFile(ModuleMapPath);
174 Second->ReadModuleMapFile(ModuleMapPath);
175}
176
178 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
179 bool AllowCompatibleDifferences) {
180 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
181 AllowCompatibleDifferences) ||
182 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
183 AllowCompatibleDifferences);
184}
185
187 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
188 bool AllowCompatibleDifferences) {
189 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
190 AllowCompatibleDifferences) ||
191 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
192 AllowCompatibleDifferences);
193}
194
196 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, StringRef ModuleFilename,
197 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#define LANGOPT(Name, Bits, Default, Description) \
291 if (ExistingLangOpts.Name != LangOpts.Name) { \
292 if (Diags) { \
293 if (Bits == 1) \
294 Diags->Report(diag::err_ast_file_langopt_mismatch) \
295 << Description << LangOpts.Name << ExistingLangOpts.Name \
296 << ModuleFilename; \
297 else \
298 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
299 << Description << ModuleFilename; \
300 } \
301 return true; \
302 }
303
304#define VALUE_LANGOPT(Name, Bits, Default, Description) \
305 if (ExistingLangOpts.Name != LangOpts.Name) { \
306 if (Diags) \
307 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
308 << Description << ModuleFilename; \
309 return true; \
310 }
311
312#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
313 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
314 if (Diags) \
315 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
316 << Description << ModuleFilename; \
317 return true; \
318 }
319
320#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
321 if (!AllowCompatibleDifferences) \
322 LANGOPT(Name, Bits, Default, Description)
323
324#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
325 if (!AllowCompatibleDifferences) \
326 ENUM_LANGOPT(Name, Bits, Default, Description)
327
328#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
329 if (!AllowCompatibleDifferences) \
330 VALUE_LANGOPT(Name, Bits, Default, Description)
331
332#define BENIGN_LANGOPT(Name, Bits, Default, Description)
333#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
334#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
335#include "clang/Basic/LangOptions.def"
336
337 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
338 if (Diags)
339 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
340 << "module features" << ModuleFilename;
341 return true;
342 }
343
344 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
345 if (Diags)
346 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
347 << "target Objective-C runtime" << ModuleFilename;
348 return true;
349 }
350
351 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
353 if (Diags)
354 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
355 << "block command names" << ModuleFilename;
356 return true;
357 }
358
359 // Sanitizer feature mismatches are treated as compatible differences. If
360 // compatible differences aren't allowed, we still only want to check for
361 // mismatches of non-modular sanitizers (the only ones which can affect AST
362 // generation).
363 if (!AllowCompatibleDifferences) {
364 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
365 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
366 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
367 ExistingSanitizers.clear(ModularSanitizers);
368 ImportedSanitizers.clear(ModularSanitizers);
369 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
370 const std::string Flag = "-fsanitize=";
371 if (Diags) {
372#define SANITIZER(NAME, ID) \
373 { \
374 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
375 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
376 if (InExistingModule != InImportedModule) \
377 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
378 << InExistingModule << ModuleFilename << (Flag + NAME); \
379 }
380#include "clang/Basic/Sanitizers.def"
381 }
382 return true;
383 }
384 }
385
386 return false;
387}
388
389/// Compare the given set of target options against an existing set of
390/// target options.
391///
392/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
393///
394/// \returns true if the target options mis-match, false otherwise.
395static bool checkTargetOptions(const TargetOptions &TargetOpts,
396 const TargetOptions &ExistingTargetOpts,
397 StringRef ModuleFilename,
398 DiagnosticsEngine *Diags,
399 bool AllowCompatibleDifferences = true) {
400#define CHECK_TARGET_OPT(Field, Name) \
401 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
402 if (Diags) \
403 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
404 << ModuleFilename << Name << TargetOpts.Field \
405 << ExistingTargetOpts.Field; \
406 return true; \
407 }
408
409 // The triple and ABI must match exactly.
410 CHECK_TARGET_OPT(Triple, "target");
411 CHECK_TARGET_OPT(ABI, "target ABI");
412
413 // We can tolerate different CPUs in many cases, notably when one CPU
414 // supports a strict superset of another. When allowing compatible
415 // differences skip this check.
416 if (!AllowCompatibleDifferences) {
417 CHECK_TARGET_OPT(CPU, "target CPU");
418 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
419 }
420
421#undef CHECK_TARGET_OPT
422
423 // Compare feature sets.
424 SmallVector<StringRef, 4> ExistingFeatures(
425 ExistingTargetOpts.FeaturesAsWritten.begin(),
426 ExistingTargetOpts.FeaturesAsWritten.end());
427 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
428 TargetOpts.FeaturesAsWritten.end());
429 llvm::sort(ExistingFeatures);
430 llvm::sort(ReadFeatures);
431
432 // We compute the set difference in both directions explicitly so that we can
433 // diagnose the differences differently.
434 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
435 std::set_difference(
436 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
437 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
438 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
439 ExistingFeatures.begin(), ExistingFeatures.end(),
440 std::back_inserter(UnmatchedReadFeatures));
441
442 // If we are allowing compatible differences and the read feature set is
443 // a strict subset of the existing feature set, there is nothing to diagnose.
444 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
445 return false;
446
447 if (Diags) {
448 for (StringRef Feature : UnmatchedReadFeatures)
449 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
450 << /* is-existing-feature */ false << ModuleFilename << Feature;
451 for (StringRef Feature : UnmatchedExistingFeatures)
452 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
453 << /* is-existing-feature */ true << ModuleFilename << Feature;
454 }
455
456 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
457}
458
460 StringRef ModuleFilename, bool Complain,
461 bool AllowCompatibleDifferences) {
462 const LangOptions &ExistingLangOpts = PP.getLangOpts();
463 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
464 Complain ? &Reader.Diags : nullptr,
465 AllowCompatibleDifferences);
466}
467
469 StringRef ModuleFilename, bool Complain,
470 bool AllowCompatibleDifferences) {
471 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
472 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
473 Complain ? &Reader.Diags : nullptr,
474 AllowCompatibleDifferences);
475}
476
477namespace {
478
479using MacroDefinitionsMap =
480 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
481using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
482
483} // namespace
484
486 DiagnosticsEngine &Diags,
487 StringRef ModuleFilename,
488 bool Complain) {
489 using Level = DiagnosticsEngine::Level;
490
491 // Check current mappings for new -Werror mappings, and the stored mappings
492 // for cases that were explicitly mapped to *not* be errors that are now
493 // errors because of options like -Werror.
494 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
495
496 for (DiagnosticsEngine *MappingSource : MappingSources) {
497 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
498 diag::kind DiagID = DiagIDMappingPair.first;
499 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
500 if (CurLevel < DiagnosticsEngine::Error)
501 continue; // not significant
502 Level StoredLevel =
503 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
504 if (StoredLevel < DiagnosticsEngine::Error) {
505 if (Complain)
506 Diags.Report(diag::err_ast_file_diagopt_mismatch)
507 << "-Werror=" + Diags.getDiagnosticIDs()
508 ->getWarningOptionForDiag(DiagID)
509 .str()
510 << ModuleFilename;
511 return true;
512 }
513 }
514 }
515
516 return false;
517}
518
521 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
522 return true;
523 return Ext >= diag::Severity::Error;
524}
525
527 DiagnosticsEngine &Diags,
528 StringRef ModuleFilename, bool IsSystem,
529 bool SystemHeaderWarningsInModule,
530 bool Complain) {
531 // Top-level options
532 if (IsSystem) {
533 if (Diags.getSuppressSystemWarnings())
534 return false;
535 // If -Wsystem-headers was not enabled before, and it was not explicit,
536 // be conservative
537 if (StoredDiags.getSuppressSystemWarnings() &&
538 !SystemHeaderWarningsInModule) {
539 if (Complain)
540 Diags.Report(diag::err_ast_file_diagopt_mismatch)
541 << "-Wsystem-headers" << ModuleFilename;
542 return true;
543 }
544 }
545
546 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
547 if (Complain)
548 Diags.Report(diag::err_ast_file_diagopt_mismatch)
549 << "-Werror" << ModuleFilename;
550 return true;
551 }
552
553 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
554 !StoredDiags.getEnableAllWarnings()) {
555 if (Complain)
556 Diags.Report(diag::err_ast_file_diagopt_mismatch)
557 << "-Weverything -Werror" << ModuleFilename;
558 return true;
559 }
560
561 if (isExtHandlingFromDiagsError(Diags) &&
562 !isExtHandlingFromDiagsError(StoredDiags)) {
563 if (Complain)
564 Diags.Report(diag::err_ast_file_diagopt_mismatch)
565 << "-pedantic-errors" << ModuleFilename;
566 return true;
567 }
568
569 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
570 Complain);
571}
572
573/// Return the top import module if it is implicit, nullptr otherwise.
575 Preprocessor &PP) {
576 // If the original import came from a file explicitly generated by the user,
577 // don't check the diagnostic mappings.
578 // FIXME: currently this is approximated by checking whether this is not a
579 // module import of an implicitly-loaded module file.
580 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
581 // the transitive closure of its imports, since unrelated modules cannot be
582 // imported until after this module finishes validation.
583 ModuleFile *TopImport = &*ModuleMgr.rbegin();
584 while (!TopImport->ImportedBy.empty())
585 TopImport = TopImport->ImportedBy[0];
586 if (TopImport->Kind != MK_ImplicitModule)
587 return nullptr;
588
589 StringRef ModuleName = TopImport->ModuleName;
590 assert(!ModuleName.empty() && "diagnostic options read before module name");
591
592 Module *M =
593 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
594 assert(M && "missing module");
595 return M;
596}
597
599 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, StringRef ModuleFilename,
600 bool Complain) {
601 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
604 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
605 // This should never fail, because we would have processed these options
606 // before writing them to an ASTFile.
607 ProcessWarningOptions(*Diags, *DiagOpts,
609 /*Report*/ false);
610
611 ModuleManager &ModuleMgr = Reader.getModuleManager();
612 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
613
614 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
615 if (!TopM)
616 return false;
617
618 Module *Importer = PP.getCurrentModule();
619
620 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
621 bool SystemHeaderWarningsInModule =
622 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
623 Importer->Name);
624
625 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
626 // contains the union of their flags.
627 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
628 TopM->IsSystem, SystemHeaderWarningsInModule,
629 Complain);
630}
631
632/// Collect the macro definitions provided by the given preprocessor
633/// options.
634static void
636 MacroDefinitionsMap &Macros,
637 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
638 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
639 StringRef Macro = PPOpts.Macros[I].first;
640 bool IsUndef = PPOpts.Macros[I].second;
641
642 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
643 StringRef MacroName = MacroPair.first;
644 StringRef MacroBody = MacroPair.second;
645
646 // For an #undef'd macro, we only care about the name.
647 if (IsUndef) {
648 if (MacroNames && !Macros.count(MacroName))
649 MacroNames->push_back(MacroName);
650
651 Macros[MacroName] = std::make_pair("", true);
652 continue;
653 }
654
655 // For a #define'd macro, figure out the actual definition.
656 if (MacroName.size() == Macro.size())
657 MacroBody = "1";
658 else {
659 // Note: GCC drops anything following an end-of-line character.
660 StringRef::size_type End = MacroBody.find_first_of("\n\r");
661 MacroBody = MacroBody.substr(0, End);
662 }
663
664 if (MacroNames && !Macros.count(MacroName))
665 MacroNames->push_back(MacroName);
666 Macros[MacroName] = std::make_pair(MacroBody, false);
667 }
668}
669
674};
675
676/// Check the preprocessor options deserialized from the control block
677/// against the preprocessor options in an existing preprocessor.
678///
679/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
680/// \param Validation If set to OptionValidateNone, ignore differences in
681/// preprocessor options. If set to OptionValidateContradictions,
682/// require that options passed both in the AST file and on the command
683/// line (-D or -U) match, but tolerate options missing in one or the
684/// other. If set to OptionValidateContradictions, require that there
685/// are no differences in the options between the two.
687 const PreprocessorOptions &PPOpts,
688 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
689 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
690 std::string &SuggestedPredefines, const LangOptions &LangOpts,
692 if (ReadMacros) {
693 // Check macro definitions.
694 MacroDefinitionsMap ASTFileMacros;
695 collectMacroDefinitions(PPOpts, ASTFileMacros);
696 MacroDefinitionsMap ExistingMacros;
697 SmallVector<StringRef, 4> ExistingMacroNames;
698 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
699 &ExistingMacroNames);
700
701 // Use a line marker to enter the <command line> file, as the defines and
702 // undefines here will have come from the command line.
703 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
704
705 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
706 // Dig out the macro definition in the existing preprocessor options.
707 StringRef MacroName = ExistingMacroNames[I];
708 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
709
710 // Check whether we know anything about this macro name or not.
711 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
712 ASTFileMacros.find(MacroName);
713 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
714 if (Validation == OptionValidateStrictMatches) {
715 // If strict matches are requested, don't tolerate any extra defines
716 // on the command line that are missing in the AST file.
717 if (Diags) {
718 Diags->Report(diag::err_ast_file_macro_def_undef)
719 << MacroName << true << ModuleFilename;
720 }
721 return true;
722 }
723 // FIXME: Check whether this identifier was referenced anywhere in the
724 // AST file. If so, we should reject the AST file. Unfortunately, this
725 // information isn't in the control block. What shall we do about it?
726
727 if (Existing.second) {
728 SuggestedPredefines += "#undef ";
729 SuggestedPredefines += MacroName.str();
730 SuggestedPredefines += '\n';
731 } else {
732 SuggestedPredefines += "#define ";
733 SuggestedPredefines += MacroName.str();
734 SuggestedPredefines += ' ';
735 SuggestedPredefines += Existing.first.str();
736 SuggestedPredefines += '\n';
737 }
738 continue;
739 }
740
741 // If the macro was defined in one but undef'd in the other, we have a
742 // conflict.
743 if (Existing.second != Known->second.second) {
744 if (Diags) {
745 Diags->Report(diag::err_ast_file_macro_def_undef)
746 << MacroName << Known->second.second << ModuleFilename;
747 }
748 return true;
749 }
750
751 // If the macro was #undef'd in both, or if the macro bodies are
752 // identical, it's fine.
753 if (Existing.second || Existing.first == Known->second.first) {
754 ASTFileMacros.erase(Known);
755 continue;
756 }
757
758 // The macro bodies differ; complain.
759 if (Diags) {
760 Diags->Report(diag::err_ast_file_macro_def_conflict)
761 << MacroName << Known->second.first << Existing.first
762 << ModuleFilename;
763 }
764 return true;
765 }
766
767 // Leave the <command line> file and return to <built-in>.
768 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
769
770 if (Validation == OptionValidateStrictMatches) {
771 // If strict matches are requested, don't tolerate any extra defines in
772 // the AST file that are missing on the command line.
773 for (const auto &MacroName : ASTFileMacros.keys()) {
774 if (Diags) {
775 Diags->Report(diag::err_ast_file_macro_def_undef)
776 << MacroName << false << ModuleFilename;
777 }
778 return true;
779 }
780 }
781 }
782
783 // Check whether we're using predefines.
784 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
785 Validation != OptionValidateNone) {
786 if (Diags) {
787 Diags->Report(diag::err_ast_file_undef)
788 << ExistingPPOpts.UsePredefines << ModuleFilename;
789 }
790 return true;
791 }
792
793 // Detailed record is important since it is used for the module cache hash.
794 if (LangOpts.Modules &&
795 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
796 Validation != OptionValidateNone) {
797 if (Diags) {
798 Diags->Report(diag::err_ast_file_pp_detailed_record)
799 << PPOpts.DetailedRecord << ModuleFilename;
800 }
801 return true;
802 }
803
804 // Compute the #include and #include_macros lines we need.
805 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
806 StringRef File = ExistingPPOpts.Includes[I];
807
808 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
809 !ExistingPPOpts.PCHThroughHeader.empty()) {
810 // In case the through header is an include, we must add all the includes
811 // to the predefines so the start point can be determined.
812 SuggestedPredefines += "#include \"";
813 SuggestedPredefines += File;
814 SuggestedPredefines += "\"\n";
815 continue;
816 }
817
818 if (File == ExistingPPOpts.ImplicitPCHInclude)
819 continue;
820
821 if (llvm::is_contained(PPOpts.Includes, File))
822 continue;
823
824 SuggestedPredefines += "#include \"";
825 SuggestedPredefines += File;
826 SuggestedPredefines += "\"\n";
827 }
828
829 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
830 StringRef File = ExistingPPOpts.MacroIncludes[I];
831 if (llvm::is_contained(PPOpts.MacroIncludes, File))
832 continue;
833
834 SuggestedPredefines += "#__include_macros \"";
835 SuggestedPredefines += File;
836 SuggestedPredefines += "\"\n##\n";
837 }
838
839 return false;
840}
841
843 StringRef ModuleFilename,
844 bool ReadMacros, bool Complain,
845 std::string &SuggestedPredefines) {
846 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
847
849 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
850 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
851 SuggestedPredefines, PP.getLangOpts());
852}
853
855 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
856 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
858 ModuleFilename, ReadMacros, nullptr,
859 PP.getFileManager(), SuggestedPredefines,
861}
862
863/// Check that the specified and the existing module cache paths are equivalent.
864///
865/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
866/// \returns true when the module cache paths differ.
867static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
868 StringRef SpecificModuleCachePath,
869 StringRef ExistingModuleCachePath,
870 StringRef ModuleFilename,
871 DiagnosticsEngine *Diags,
872 const LangOptions &LangOpts,
873 const PreprocessorOptions &PPOpts) {
874 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
875 SpecificModuleCachePath == ExistingModuleCachePath)
876 return false;
877 auto EqualOrErr =
878 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
879 if (EqualOrErr && *EqualOrErr)
880 return false;
881 if (Diags)
882 Diags->Report(diag::err_ast_file_modulecache_mismatch)
883 << SpecificModuleCachePath << ExistingModuleCachePath << ModuleFilename;
884 return true;
885}
886
888 StringRef ModuleFilename,
889 StringRef SpecificModuleCachePath,
890 bool Complain) {
892 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath,
893 PP.getHeaderSearchInfo().getModuleCachePath(), ModuleFilename,
894 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(),
896}
897
900}
901
902//===----------------------------------------------------------------------===//
903// AST reader implementation
904//===----------------------------------------------------------------------===//
905
906static uint64_t readULEB(const unsigned char *&P) {
907 unsigned Length = 0;
908 const char *Error = nullptr;
909
910 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
911 if (Error)
912 llvm::report_fatal_error(Error);
913 P += Length;
914 return Val;
915}
916
917/// Read ULEB-encoded key length and data length.
918static std::pair<unsigned, unsigned>
919readULEBKeyDataLength(const unsigned char *&P) {
920 unsigned KeyLen = readULEB(P);
921 if ((unsigned)KeyLen != KeyLen)
922 llvm::report_fatal_error("key too large");
923
924 unsigned DataLen = readULEB(P);
925 if ((unsigned)DataLen != DataLen)
926 llvm::report_fatal_error("data too large");
927
928 return std::make_pair(KeyLen, DataLen);
929}
930
932 bool TakeOwnership) {
933 DeserializationListener = Listener;
934 OwnsDeserializationListener = TakeOwnership;
935}
936
938 return serialization::ComputeHash(Sel);
939}
940
943#ifndef NDEBUG
944 if (!MF.ModuleOffsetMap.empty())
945 Reader.ReadModuleOffsetMap(MF);
946
947 unsigned ModuleFileIndex = ID.getModuleFileIndex();
948 unsigned LocalDeclID = ID.getLocalDeclIndex();
949
950 assert(ModuleFileIndex <= MF.TransitiveImports.size());
951
952 ModuleFile *OwningModuleFile =
953 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
954 assert(OwningModuleFile);
955
956 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
957
958 if (!ModuleFileIndex)
959 LocalNumDecls += NUM_PREDEF_DECL_IDS;
960
961 assert(LocalDeclID < LocalNumDecls);
962#endif
963 (void)Reader;
964 (void)MF;
965 return ID;
966}
967
969 unsigned ModuleFileIndex, unsigned LocalDeclID) {
970 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
971 return LocalDeclID::get(Reader, MF, Value);
972}
973
974std::pair<unsigned, unsigned>
976 return readULEBKeyDataLength(d);
977}
978
980ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
981 using namespace llvm::support;
982
983 SelectorTable &SelTable = Reader.getContext().Selectors;
984 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
985 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
986 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
987 if (N == 0)
988 return SelTable.getNullarySelector(FirstII);
989 else if (N == 1)
990 return SelTable.getUnarySelector(FirstII);
991
993 Args.push_back(FirstII);
994 for (unsigned I = 1; I != N; ++I)
995 Args.push_back(Reader.getLocalIdentifier(
996 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
997
998 return SelTable.getSelector(N, Args.data());
999}
1000
1003 unsigned DataLen) {
1004 using namespace llvm::support;
1005
1007
1008 Result.ID = Reader.getGlobalSelectorID(
1009 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1010 unsigned FullInstanceBits =
1011 endian::readNext<uint16_t, llvm::endianness::little>(d);
1012 unsigned FullFactoryBits =
1013 endian::readNext<uint16_t, llvm::endianness::little>(d);
1014 Result.InstanceBits = FullInstanceBits & 0x3;
1015 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1016 Result.FactoryBits = FullFactoryBits & 0x3;
1017 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1018 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1019 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1020
1021 // Load instance methods
1022 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1023 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1025 Reader, F,
1026 endian::readNext<DeclID, llvm::endianness::little>(d))))
1027 Result.Instance.push_back(Method);
1028 }
1029
1030 // Load factory methods
1031 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1032 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1034 Reader, F,
1035 endian::readNext<DeclID, llvm::endianness::little>(d))))
1036 Result.Factory.push_back(Method);
1037 }
1038
1039 return Result;
1040}
1041
1043 return llvm::djbHash(a);
1044}
1045
1046std::pair<unsigned, unsigned>
1048 return readULEBKeyDataLength(d);
1049}
1050
1052ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1053 assert(n >= 2 && d[n-1] == '\0');
1054 return StringRef((const char*) d, n-1);
1055}
1056
1057/// Whether the given identifier is "interesting".
1058static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1059 bool IsModule) {
1060 bool IsInteresting =
1061 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1063 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1064 return II.hadMacroDefinition() || II.isPoisoned() ||
1065 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1066 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1067 II.getFETokenInfo());
1068}
1069
1070static bool readBit(unsigned &Bits) {
1071 bool Value = Bits & 0x1;
1072 Bits >>= 1;
1073 return Value;
1074}
1075
1077 using namespace llvm::support;
1078
1079 IdentifierID RawID =
1080 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1081 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1082}
1083
1085 bool IsModule) {
1086 if (!II.isFromAST()) {
1087 II.setIsFromAST();
1088 if (isInterestingIdentifier(Reader, II, IsModule))
1090 }
1091}
1092
1094 const unsigned char* d,
1095 unsigned DataLen) {
1096 using namespace llvm::support;
1097
1098 IdentifierID RawID =
1099 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1100 bool IsInteresting = RawID & 0x01;
1101
1102 DataLen -= sizeof(IdentifierID);
1103
1104 // Wipe out the "is interesting" bit.
1105 RawID = RawID >> 1;
1106
1107 // Build the IdentifierInfo and link the identifier ID with it.
1108 IdentifierInfo *II = KnownII;
1109 if (!II) {
1110 II = &Reader.getIdentifierTable().getOwn(k);
1111 KnownII = II;
1112 }
1113 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1114 markIdentifierFromAST(Reader, *II, IsModule);
1115 Reader.markIdentifierUpToDate(II);
1116
1117 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1118 if (!IsInteresting) {
1119 // For uninteresting identifiers, there's nothing else to do. Just notify
1120 // the reader that we've finished loading this identifier.
1121 Reader.SetIdentifierInfo(ID, II);
1122 return II;
1123 }
1124
1125 unsigned ObjCOrBuiltinID =
1126 endian::readNext<uint16_t, llvm::endianness::little>(d);
1127 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1128 bool CPlusPlusOperatorKeyword = readBit(Bits);
1129 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1130 bool Poisoned = readBit(Bits);
1131 bool ExtensionToken = readBit(Bits);
1132 bool HadMacroDefinition = readBit(Bits);
1133
1134 assert(Bits == 0 && "Extra bits in the identifier?");
1135 DataLen -= sizeof(uint16_t) * 2;
1136
1137 // Set or check the various bits in the IdentifierInfo structure.
1138 // Token IDs are read-only.
1139 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1141 if (!F.isModule())
1142 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1143 assert(II->isExtensionToken() == ExtensionToken &&
1144 "Incorrect extension token flag");
1145 (void)ExtensionToken;
1146 if (Poisoned)
1147 II->setIsPoisoned(true);
1148 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1149 "Incorrect C++ operator keyword flag");
1150 (void)CPlusPlusOperatorKeyword;
1151
1152 // If this identifier is a macro, deserialize the macro
1153 // definition.
1154 if (HadMacroDefinition) {
1155 uint32_t MacroDirectivesOffset =
1156 endian::readNext<uint32_t, llvm::endianness::little>(d);
1157 DataLen -= 4;
1158
1159 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1160 }
1161
1162 Reader.SetIdentifierInfo(ID, II);
1163
1164 // Read all of the declarations visible at global scope with this
1165 // name.
1166 if (DataLen > 0) {
1168 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1169 DeclIDs.push_back(Reader.getGlobalDeclID(
1171 Reader, F,
1172 endian::readNext<DeclID, llvm::endianness::little>(d))));
1173 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1174 }
1175
1176 return II;
1177}
1178
1180 : Kind(Name.getNameKind()) {
1181 switch (Kind) {
1183 Data = (uint64_t)Name.getAsIdentifierInfo();
1184 break;
1188 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1189 break;
1191 Data = Name.getCXXOverloadedOperator();
1192 break;
1194 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1195 break;
1197 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1198 ->getDeclName().getAsIdentifierInfo();
1199 break;
1204 Data = 0;
1205 break;
1206 }
1207}
1208
1210 llvm::FoldingSetNodeID ID;
1211 ID.AddInteger(Kind);
1212
1213 switch (Kind) {
1217 ID.AddString(((IdentifierInfo*)Data)->getName());
1218 break;
1222 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1223 break;
1225 ID.AddInteger((OverloadedOperatorKind)Data);
1226 break;
1231 break;
1232 }
1233
1234 return ID.computeStableHash();
1235}
1236
1237ModuleFile *
1238ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1239 using namespace llvm::support;
1240
1241 uint32_t ModuleFileID =
1242 endian::readNext<uint32_t, llvm::endianness::little>(d);
1243 return Reader.getLocalModuleFile(F, ModuleFileID);
1244}
1245
1246std::pair<unsigned, unsigned>
1247ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1248 return readULEBKeyDataLength(d);
1249}
1250
1252ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1253 using namespace llvm::support;
1254
1255 auto Kind = (DeclarationName::NameKind)*d++;
1256 uint64_t Data;
1257 switch (Kind) {
1261 Data = (uint64_t)Reader.getLocalIdentifier(
1262 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1263 break;
1267 Data = (uint64_t)Reader
1268 .getLocalSelector(
1269 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1270 .getAsOpaquePtr();
1271 break;
1273 Data = *d++; // OverloadedOperatorKind
1274 break;
1279 Data = 0;
1280 break;
1281 }
1282
1283 return DeclarationNameKey(Kind, Data);
1284}
1285
1286void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1287 const unsigned char *d,
1288 unsigned DataLen,
1289 data_type_builder &Val) {
1290 using namespace llvm::support;
1291
1292 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1294 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1295 Val.insert(Reader.getGlobalDeclID(F, ID));
1296 }
1297}
1298
1299ModuleFile *
1300LazySpecializationInfoLookupTrait::ReadFileRef(const unsigned char *&d) {
1301 using namespace llvm::support;
1302
1303 uint32_t ModuleFileID =
1304 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1305 return Reader.getLocalModuleFile(F, ModuleFileID);
1306}
1307
1309LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1310 using namespace llvm::support;
1311 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1312}
1313
1314std::pair<unsigned, unsigned>
1315LazySpecializationInfoLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1316 return readULEBKeyDataLength(d);
1317}
1318
1319void LazySpecializationInfoLookupTrait::ReadDataInto(internal_key_type,
1320 const unsigned char *d,
1321 unsigned DataLen,
1322 data_type_builder &Val) {
1323 using namespace llvm::support;
1324
1325 for (unsigned NumDecls =
1327 NumDecls; --NumDecls) {
1328 LocalDeclID LocalID = LocalDeclID::get(
1329 Reader, F,
1330 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1331 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1332 }
1333}
1334
1335bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1336 BitstreamCursor &Cursor,
1337 uint64_t Offset,
1338 DeclContext *DC) {
1339 assert(Offset != 0);
1340
1341 SavedStreamPosition SavedPosition(Cursor);
1342 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1343 Error(std::move(Err));
1344 return true;
1345 }
1346
1347 RecordData Record;
1348 StringRef Blob;
1349 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1350 if (!MaybeCode) {
1351 Error(MaybeCode.takeError());
1352 return true;
1353 }
1354 unsigned Code = MaybeCode.get();
1355
1356 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1357 if (!MaybeRecCode) {
1358 Error(MaybeRecCode.takeError());
1359 return true;
1360 }
1361 unsigned RecCode = MaybeRecCode.get();
1362 if (RecCode != DECL_CONTEXT_LEXICAL) {
1363 Error("Expected lexical block");
1364 return true;
1365 }
1366
1367 assert(!isa<TranslationUnitDecl>(DC) &&
1368 "expected a TU_UPDATE_LEXICAL record for TU");
1369 // If we are handling a C++ class template instantiation, we can see multiple
1370 // lexical updates for the same record. It's important that we select only one
1371 // of them, so that field numbering works properly. Just pick the first one we
1372 // see.
1373 auto &Lex = LexicalDecls[DC];
1374 if (!Lex.first) {
1375 Lex = std::make_pair(
1376 &M, llvm::ArrayRef(
1377 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1378 Blob.size() / sizeof(DeclID)));
1379 }
1381 return false;
1382}
1383
1384bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1385 BitstreamCursor &Cursor,
1386 uint64_t Offset,
1387 GlobalDeclID ID) {
1388 assert(Offset != 0);
1389
1390 SavedStreamPosition SavedPosition(Cursor);
1391 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1392 Error(std::move(Err));
1393 return true;
1394 }
1395
1396 RecordData Record;
1397 StringRef Blob;
1398 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1399 if (!MaybeCode) {
1400 Error(MaybeCode.takeError());
1401 return true;
1402 }
1403 unsigned Code = MaybeCode.get();
1404
1405 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1406 if (!MaybeRecCode) {
1407 Error(MaybeRecCode.takeError());
1408 return true;
1409 }
1410 unsigned RecCode = MaybeRecCode.get();
1411 if (RecCode != DECL_CONTEXT_VISIBLE) {
1412 Error("Expected visible lookup table block");
1413 return true;
1414 }
1415
1416 // We can't safely determine the primary context yet, so delay attaching the
1417 // lookup table until we're done with recursive deserialization.
1418 auto *Data = (const unsigned char*)Blob.data();
1419 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1420 return false;
1421}
1422
1423void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1424 ModuleFile &M, bool IsPartial) {
1425 D = D->getCanonicalDecl();
1426 auto &SpecLookups =
1427 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1428 SpecLookups[D].Table.add(&M, Data,
1430}
1431
1432bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1433 uint64_t Offset, Decl *D, bool IsPartial) {
1434 assert(Offset != 0);
1435
1436 SavedStreamPosition SavedPosition(Cursor);
1437 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1438 Error(std::move(Err));
1439 return true;
1440 }
1441
1442 RecordData Record;
1443 StringRef Blob;
1444 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1445 if (!MaybeCode) {
1446 Error(MaybeCode.takeError());
1447 return true;
1448 }
1449 unsigned Code = MaybeCode.get();
1450
1451 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1452 if (!MaybeRecCode) {
1453 Error(MaybeRecCode.takeError());
1454 return true;
1455 }
1456 unsigned RecCode = MaybeRecCode.get();
1457 if (RecCode != DECL_SPECIALIZATIONS &&
1458 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1459 Error("Expected decl specs block");
1460 return true;
1461 }
1462
1463 auto *Data = (const unsigned char *)Blob.data();
1464 AddSpecializations(D, Data, M, IsPartial);
1465 return false;
1466}
1467
1468void ASTReader::Error(StringRef Msg) const {
1469 Error(diag::err_fe_pch_malformed, Msg);
1470 if (PP.getLangOpts().Modules &&
1471 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1472 Diag(diag::note_module_cache_path)
1473 << PP.getHeaderSearchInfo().getModuleCachePath();
1474 }
1475}
1476
1477void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1478 StringRef Arg3) const {
1479 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1480}
1481
1482void ASTReader::Error(llvm::Error &&Err) const {
1483 llvm::Error RemainingErr =
1484 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1485 auto Diag = E.getDiagnostic().second;
1486
1487 // Ideally we'd just emit it, but have to handle a possible in-flight
1488 // diagnostic. Note that the location is currently ignored as well.
1489 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1490 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1491 StringRef Arg1, Arg2, Arg3;
1492 switch (NumArgs) {
1493 case 3:
1494 Arg3 = Diag.getStringArg(2);
1495 [[fallthrough]];
1496 case 2:
1497 Arg2 = Diag.getStringArg(1);
1498 [[fallthrough]];
1499 case 1:
1500 Arg1 = Diag.getStringArg(0);
1501 }
1502 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1503 });
1504 if (RemainingErr)
1505 Error(toString(std::move(RemainingErr)));
1506}
1507
1508//===----------------------------------------------------------------------===//
1509// Source Manager Deserialization
1510//===----------------------------------------------------------------------===//
1511
1512/// Read the line table in the source manager block.
1513void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1514 unsigned Idx = 0;
1515 LineTableInfo &LineTable = SourceMgr.getLineTable();
1516
1517 // Parse the file names
1518 std::map<int, int> FileIDs;
1519 FileIDs[-1] = -1; // For unspecified filenames.
1520 for (unsigned I = 0; Record[Idx]; ++I) {
1521 // Extract the file name
1522 auto Filename = ReadPath(F, Record, Idx);
1523 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1524 }
1525 ++Idx;
1526
1527 // Parse the line entries
1528 std::vector<LineEntry> Entries;
1529 while (Idx < Record.size()) {
1530 FileID FID = ReadFileID(F, Record, Idx);
1531
1532 // Extract the line entries
1533 unsigned NumEntries = Record[Idx++];
1534 assert(NumEntries && "no line entries for file ID");
1535 Entries.clear();
1536 Entries.reserve(NumEntries);
1537 for (unsigned I = 0; I != NumEntries; ++I) {
1538 unsigned FileOffset = Record[Idx++];
1539 unsigned LineNo = Record[Idx++];
1540 int FilenameID = FileIDs[Record[Idx++]];
1543 unsigned IncludeOffset = Record[Idx++];
1544 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1545 FileKind, IncludeOffset));
1546 }
1547 LineTable.AddEntry(FID, Entries);
1548 }
1549}
1550
1551/// Read a source manager block
1552llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1553 using namespace SrcMgr;
1554
1555 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1556
1557 // Set the source-location entry cursor to the current position in
1558 // the stream. This cursor will be used to read the contents of the
1559 // source manager block initially, and then lazily read
1560 // source-location entries as needed.
1561 SLocEntryCursor = F.Stream;
1562
1563 // The stream itself is going to skip over the source manager block.
1564 if (llvm::Error Err = F.Stream.SkipBlock())
1565 return Err;
1566
1567 // Enter the source manager block.
1568 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1569 return Err;
1570 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1571
1572 RecordData Record;
1573 while (true) {
1575 SLocEntryCursor.advanceSkippingSubblocks();
1576 if (!MaybeE)
1577 return MaybeE.takeError();
1578 llvm::BitstreamEntry E = MaybeE.get();
1579
1580 switch (E.Kind) {
1581 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1582 case llvm::BitstreamEntry::Error:
1583 return llvm::createStringError(std::errc::illegal_byte_sequence,
1584 "malformed block record in AST file");
1585 case llvm::BitstreamEntry::EndBlock:
1586 return llvm::Error::success();
1587 case llvm::BitstreamEntry::Record:
1588 // The interesting case.
1589 break;
1590 }
1591
1592 // Read a record.
1593 Record.clear();
1594 StringRef Blob;
1595 Expected<unsigned> MaybeRecord =
1596 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1597 if (!MaybeRecord)
1598 return MaybeRecord.takeError();
1599 switch (MaybeRecord.get()) {
1600 default: // Default behavior: ignore.
1601 break;
1602
1603 case SM_SLOC_FILE_ENTRY:
1606 // Once we hit one of the source location entries, we're done.
1607 return llvm::Error::success();
1608 }
1609 }
1610}
1611
1614 BitstreamCursor &Cursor = F->SLocEntryCursor;
1615 SavedStreamPosition SavedPosition(Cursor);
1616 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1617 F->SLocEntryOffsets[Index]))
1618 return std::move(Err);
1619
1620 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1621 if (!MaybeEntry)
1622 return MaybeEntry.takeError();
1623
1624 llvm::BitstreamEntry Entry = MaybeEntry.get();
1625 if (Entry.Kind != llvm::BitstreamEntry::Record)
1626 return llvm::createStringError(
1627 std::errc::illegal_byte_sequence,
1628 "incorrectly-formatted source location entry in AST file");
1629
1631 StringRef Blob;
1632 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1633 if (!MaybeSLOC)
1634 return MaybeSLOC.takeError();
1635
1636 switch (MaybeSLOC.get()) {
1637 default:
1638 return llvm::createStringError(
1639 std::errc::illegal_byte_sequence,
1640 "incorrectly-formatted source location entry in AST file");
1641 case SM_SLOC_FILE_ENTRY:
1644 return F->SLocEntryBaseOffset + Record[0];
1645 }
1646}
1647
1649 auto SLocMapI =
1650 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1651 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1652 "Corrupted global sloc offset map");
1653 ModuleFile *F = SLocMapI->second;
1654
1655 bool Invalid = false;
1656
1657 auto It = llvm::upper_bound(
1658 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1659 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1660 int ID = F->SLocEntryBaseID + LocalIndex;
1661 std::size_t Index = -ID - 2;
1662 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1663 assert(!SourceMgr.SLocEntryLoaded[Index]);
1664 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1665 if (!MaybeEntryOffset) {
1666 Error(MaybeEntryOffset.takeError());
1667 Invalid = true;
1668 return true;
1669 }
1670 SourceMgr.LoadedSLocEntryTable[Index] =
1671 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1672 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1673 }
1674 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1675 });
1676
1677 if (Invalid)
1678 return 0;
1679
1680 // The iterator points to the first entry with start offset greater than the
1681 // offset of interest. The previous entry must contain the offset of interest.
1682 return F->SLocEntryBaseID + *std::prev(It);
1683}
1684
1686 if (ID == 0)
1687 return false;
1688
1689 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1690 Error("source location entry ID out-of-range for AST file");
1691 return true;
1692 }
1693
1694 // Local helper to read the (possibly-compressed) buffer data following the
1695 // entry record.
1696 auto ReadBuffer = [this](
1697 BitstreamCursor &SLocEntryCursor,
1698 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1700 StringRef Blob;
1701 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1702 if (!MaybeCode) {
1703 Error(MaybeCode.takeError());
1704 return nullptr;
1705 }
1706 unsigned Code = MaybeCode.get();
1707
1708 Expected<unsigned> MaybeRecCode =
1709 SLocEntryCursor.readRecord(Code, Record, &Blob);
1710 if (!MaybeRecCode) {
1711 Error(MaybeRecCode.takeError());
1712 return nullptr;
1713 }
1714 unsigned RecCode = MaybeRecCode.get();
1715
1716 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1717 // Inspect the first byte to differentiate zlib (\x78) and zstd
1718 // (little-endian 0xFD2FB528).
1719 const llvm::compression::Format F =
1720 Blob.size() > 0 && Blob.data()[0] == 0x78
1721 ? llvm::compression::Format::Zlib
1722 : llvm::compression::Format::Zstd;
1723 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1724 Error(Reason);
1725 return nullptr;
1726 }
1727 SmallVector<uint8_t, 0> Decompressed;
1728 if (llvm::Error E = llvm::compression::decompress(
1729 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1730 Error("could not decompress embedded file contents: " +
1731 llvm::toString(std::move(E)));
1732 return nullptr;
1733 }
1734 return llvm::MemoryBuffer::getMemBufferCopy(
1735 llvm::toStringRef(Decompressed), Name);
1736 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1737 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1738 } else {
1739 Error("AST record has invalid code");
1740 return nullptr;
1741 }
1742 };
1743
1744 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1745 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1747 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1748 Error(std::move(Err));
1749 return true;
1750 }
1751
1752 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1754
1755 ++NumSLocEntriesRead;
1756 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1757 if (!MaybeEntry) {
1758 Error(MaybeEntry.takeError());
1759 return true;
1760 }
1761 llvm::BitstreamEntry Entry = MaybeEntry.get();
1762
1763 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1764 Error("incorrectly-formatted source location entry in AST file");
1765 return true;
1766 }
1767
1769 StringRef Blob;
1770 Expected<unsigned> MaybeSLOC =
1771 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1772 if (!MaybeSLOC) {
1773 Error(MaybeSLOC.takeError());
1774 return true;
1775 }
1776 switch (MaybeSLOC.get()) {
1777 default:
1778 Error("incorrectly-formatted source location entry in AST file");
1779 return true;
1780
1781 case SM_SLOC_FILE_ENTRY: {
1782 // We will detect whether a file changed and return 'Failure' for it, but
1783 // we will also try to fail gracefully by setting up the SLocEntry.
1784 unsigned InputID = Record[4];
1785 InputFile IF = getInputFile(*F, InputID);
1787 bool OverriddenBuffer = IF.isOverridden();
1788
1789 // Note that we only check if a File was returned. If it was out-of-date
1790 // we have complained but we will continue creating a FileID to recover
1791 // gracefully.
1792 if (!File)
1793 return true;
1794
1795 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1796 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1797 // This is the module's main file.
1798 IncludeLoc = getImportLocation(F);
1799 }
1801 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1802 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1803 BaseOffset + Record[0]);
1804 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1805 FileInfo.NumCreatedFIDs = Record[5];
1806 if (Record[3])
1807 FileInfo.setHasLineDirectives();
1808
1809 unsigned NumFileDecls = Record[7];
1810 if (NumFileDecls && ContextObj) {
1811 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1812 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1813 FileDeclIDs[FID] =
1814 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1815 }
1816
1817 const SrcMgr::ContentCache &ContentCache =
1818 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1819 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1820 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1821 !ContentCache.getBufferIfLoaded()) {
1822 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1823 if (!Buffer)
1824 return true;
1825 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1826 }
1827
1828 break;
1829 }
1830
1831 case SM_SLOC_BUFFER_ENTRY: {
1832 const char *Name = Blob.data();
1833 unsigned Offset = Record[0];
1835 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1836 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1837 if (IncludeLoc.isInvalid() && F->isModule()) {
1838 IncludeLoc = getImportLocation(F);
1839 }
1840
1841 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1842 if (!Buffer)
1843 return true;
1844 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1845 BaseOffset + Offset, IncludeLoc);
1846 if (Record[3]) {
1847 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1848 FileInfo.setHasLineDirectives();
1849 }
1850 break;
1851 }
1852
1855 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1856 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1857 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1858 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1859 Record[5], Record[4], ID,
1860 BaseOffset + Record[0]);
1861 break;
1862 }
1863 }
1864
1865 return false;
1866}
1867
1868std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1869 if (ID == 0)
1870 return std::make_pair(SourceLocation(), "");
1871
1872 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1873 Error("source location entry ID out-of-range for AST file");
1874 return std::make_pair(SourceLocation(), "");
1875 }
1876
1877 // Find which module file this entry lands in.
1878 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1879 if (!M->isModule())
1880 return std::make_pair(SourceLocation(), "");
1881
1882 // FIXME: Can we map this down to a particular submodule? That would be
1883 // ideal.
1884 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1885}
1886
1887/// Find the location where the module F is imported.
1888SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1889 if (F->ImportLoc.isValid())
1890 return F->ImportLoc;
1891
1892 // Otherwise we have a PCH. It's considered to be "imported" at the first
1893 // location of its includer.
1894 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1895 // Main file is the importer.
1896 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1897 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1898 }
1899 return F->ImportedBy[0]->FirstLoc;
1900}
1901
1902/// Enter a subblock of the specified BlockID with the specified cursor. Read
1903/// the abbreviations that are at the top of the block and then leave the cursor
1904/// pointing into the block.
1905llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1906 unsigned BlockID,
1907 uint64_t *StartOfBlockOffset) {
1908 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1909 return Err;
1910
1911 if (StartOfBlockOffset)
1912 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1913
1914 while (true) {
1915 uint64_t Offset = Cursor.GetCurrentBitNo();
1916 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1917 if (!MaybeCode)
1918 return MaybeCode.takeError();
1919 unsigned Code = MaybeCode.get();
1920
1921 // We expect all abbrevs to be at the start of the block.
1922 if (Code != llvm::bitc::DEFINE_ABBREV) {
1923 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1924 return Err;
1925 return llvm::Error::success();
1926 }
1927 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1928 return Err;
1929 }
1930}
1931
1933 unsigned &Idx) {
1934 Token Tok;
1935 Tok.startToken();
1936 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1937 Tok.setKind((tok::TokenKind)Record[Idx++]);
1938 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1939
1940 if (Tok.isAnnotation()) {
1941 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1942 switch (Tok.getKind()) {
1943 case tok::annot_pragma_loop_hint: {
1944 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1945 Info->PragmaName = ReadToken(M, Record, Idx);
1946 Info->Option = ReadToken(M, Record, Idx);
1947 unsigned NumTokens = Record[Idx++];
1949 Toks.reserve(NumTokens);
1950 for (unsigned I = 0; I < NumTokens; ++I)
1951 Toks.push_back(ReadToken(M, Record, Idx));
1952 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1953 Tok.setAnnotationValue(static_cast<void *>(Info));
1954 break;
1955 }
1956 case tok::annot_pragma_pack: {
1957 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1958 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1959 auto SlotLabel = ReadString(Record, Idx);
1960 Info->SlotLabel =
1961 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1962 Info->Alignment = ReadToken(M, Record, Idx);
1963 Tok.setAnnotationValue(static_cast<void *>(Info));
1964 break;
1965 }
1966 // Some annotation tokens do not use the PtrData field.
1967 case tok::annot_pragma_openmp:
1968 case tok::annot_pragma_openmp_end:
1969 case tok::annot_pragma_unused:
1970 case tok::annot_pragma_openacc:
1971 case tok::annot_pragma_openacc_end:
1972 case tok::annot_repl_input_end:
1973 break;
1974 default:
1975 llvm_unreachable("missing deserialization code for annotation token");
1976 }
1977 } else {
1978 Tok.setLength(Record[Idx++]);
1979 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1980 Tok.setIdentifierInfo(II);
1981 }
1982 return Tok;
1983}
1984
1986 BitstreamCursor &Stream = F.MacroCursor;
1987
1988 // Keep track of where we are in the stream, then jump back there
1989 // after reading this macro.
1990 SavedStreamPosition SavedPosition(Stream);
1991
1992 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1993 // FIXME this drops errors on the floor.
1994 consumeError(std::move(Err));
1995 return nullptr;
1996 }
1999 MacroInfo *Macro = nullptr;
2000 llvm::MutableArrayRef<Token> MacroTokens;
2001
2002 while (true) {
2003 // Advance to the next record, but if we get to the end of the block, don't
2004 // pop it (removing all the abbreviations from the cursor) since we want to
2005 // be able to reseek within the block and read entries.
2006 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2008 Stream.advanceSkippingSubblocks(Flags);
2009 if (!MaybeEntry) {
2010 Error(MaybeEntry.takeError());
2011 return Macro;
2012 }
2013 llvm::BitstreamEntry Entry = MaybeEntry.get();
2014
2015 switch (Entry.Kind) {
2016 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2017 case llvm::BitstreamEntry::Error:
2018 Error("malformed block record in AST file");
2019 return Macro;
2020 case llvm::BitstreamEntry::EndBlock:
2021 return Macro;
2022 case llvm::BitstreamEntry::Record:
2023 // The interesting case.
2024 break;
2025 }
2026
2027 // Read a record.
2028 Record.clear();
2030 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2031 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2032 else {
2033 Error(MaybeRecType.takeError());
2034 return Macro;
2035 }
2036 switch (RecType) {
2037 case PP_MODULE_MACRO:
2039 return Macro;
2040
2043 // If we already have a macro, that means that we've hit the end
2044 // of the definition of the macro we were looking for. We're
2045 // done.
2046 if (Macro)
2047 return Macro;
2048
2049 unsigned NextIndex = 1; // Skip identifier ID.
2050 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2051 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2052 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2053 MI->setIsUsed(Record[NextIndex++]);
2054 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2055 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2056 PP.getPreprocessorAllocator());
2057 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2058 // Decode function-like macro info.
2059 bool isC99VarArgs = Record[NextIndex++];
2060 bool isGNUVarArgs = Record[NextIndex++];
2061 bool hasCommaPasting = Record[NextIndex++];
2062 MacroParams.clear();
2063 unsigned NumArgs = Record[NextIndex++];
2064 for (unsigned i = 0; i != NumArgs; ++i)
2065 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2066
2067 // Install function-like macro info.
2068 MI->setIsFunctionLike();
2069 if (isC99VarArgs) MI->setIsC99Varargs();
2070 if (isGNUVarArgs) MI->setIsGNUVarargs();
2071 if (hasCommaPasting) MI->setHasCommaPasting();
2072 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2073 }
2074
2075 // Remember that we saw this macro last so that we add the tokens that
2076 // form its body to it.
2077 Macro = MI;
2078
2079 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2080 Record[NextIndex]) {
2081 // We have a macro definition. Register the association
2083 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2084 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2085 PreprocessingRecord::PPEntityID PPID =
2086 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
2087 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2088 PPRec.getPreprocessedEntity(PPID));
2089 if (PPDef)
2090 PPRec.RegisterMacroDefinition(Macro, PPDef);
2091 }
2092
2093 ++NumMacrosRead;
2094 break;
2095 }
2096
2097 case PP_TOKEN: {
2098 // If we see a TOKEN before a PP_MACRO_*, then the file is
2099 // erroneous, just pretend we didn't see this.
2100 if (!Macro) break;
2101 if (MacroTokens.empty()) {
2102 Error("unexpected number of macro tokens for a macro in AST file");
2103 return Macro;
2104 }
2105
2106 unsigned Idx = 0;
2107 MacroTokens[0] = ReadToken(F, Record, Idx);
2108 MacroTokens = MacroTokens.drop_front();
2109 break;
2110 }
2111 }
2112 }
2113}
2114
2117 unsigned LocalID) const {
2118 if (!M.ModuleOffsetMap.empty())
2119 ReadModuleOffsetMap(M);
2120
2123 assert(I != M.PreprocessedEntityRemap.end()
2124 && "Invalid index into preprocessed entity index remap");
2125
2126 return LocalID + I->second;
2127}
2128
2130HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2131 FileManager &FileMgr = Reader.getFileManager();
2132 if (!Key.Imported)
2133 return FileMgr.getOptionalFileRef(Key.Filename);
2134
2135 auto Resolved =
2136 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2137 return FileMgr.getOptionalFileRef(*Resolved);
2138}
2139
2140unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
2141 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2142 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2143 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2144 return llvm::xxh3_64bits(buf);
2145}
2146
2148HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
2149 internal_key_type ikey = {ekey.getSize(),
2150 M.HasTimestamps ? ekey.getModificationTime() : 0,
2151 ekey.getName(), /*Imported*/ false};
2152 return ikey;
2153}
2154
2155bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2156 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2157 return false;
2158
2159 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2160 return true;
2161
2162 // Determine whether the actual files are equivalent.
2163 OptionalFileEntryRef FEA = getFile(a);
2164 OptionalFileEntryRef FEB = getFile(b);
2165 return FEA && FEA == FEB;
2166}
2167
2168std::pair<unsigned, unsigned>
2169HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2170 return readULEBKeyDataLength(d);
2171}
2172
2174HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2175 using namespace llvm::support;
2176
2177 internal_key_type ikey;
2178 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2179 ikey.ModTime =
2180 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2181 ikey.Filename = (const char *)d;
2182 ikey.Imported = true;
2183 return ikey;
2184}
2185
2187HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2188 unsigned DataLen) {
2189 using namespace llvm::support;
2190
2191 const unsigned char *End = d + DataLen;
2192 HeaderFileInfo HFI;
2193 unsigned Flags = *d++;
2194
2196 bool Included = (Flags >> 6) & 0x01;
2197 if (Included)
2198 if ((FE = getFile(key)))
2199 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2200 // deserialize this header file info again.
2201 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2202
2203 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2204 HFI.isImport |= (Flags >> 5) & 0x01;
2205 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2206 HFI.DirInfo = (Flags >> 1) & 0x07;
2207 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2208 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2209
2210 assert((End - d) % 4 == 0 &&
2211 "Wrong data length in HeaderFileInfo deserialization");
2212 while (d != End) {
2213 uint32_t LocalSMID =
2214 endian::readNext<uint32_t, llvm::endianness::little>(d);
2215 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2216 LocalSMID >>= 3;
2217
2218 // This header is part of a module. Associate it with the module to enable
2219 // implicit module import.
2220 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2221 Module *Mod = Reader.getSubmodule(GlobalSMID);
2222 ModuleMap &ModMap =
2223 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2224
2225 if (FE || (FE = getFile(key))) {
2226 // FIXME: NameAsWritten
2227 Module::Header H = {std::string(key.Filename), "", *FE};
2228 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2229 }
2230 HFI.mergeModuleMembership(HeaderRole);
2231 }
2232
2233 // This HeaderFileInfo was externally loaded.
2234 HFI.External = true;
2235 HFI.IsValid = true;
2236 return HFI;
2237}
2238
2240 uint32_t MacroDirectivesOffset) {
2241 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2242 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2243}
2244
2246 // Note that we are loading defined macros.
2247 Deserializing Macros(this);
2248
2249 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2250 BitstreamCursor &MacroCursor = I.MacroCursor;
2251
2252 // If there was no preprocessor block, skip this file.
2253 if (MacroCursor.getBitcodeBytes().empty())
2254 continue;
2255
2256 BitstreamCursor Cursor = MacroCursor;
2257 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2258 Error(std::move(Err));
2259 return;
2260 }
2261
2263 while (true) {
2264 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2265 if (!MaybeE) {
2266 Error(MaybeE.takeError());
2267 return;
2268 }
2269 llvm::BitstreamEntry E = MaybeE.get();
2270
2271 switch (E.Kind) {
2272 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2273 case llvm::BitstreamEntry::Error:
2274 Error("malformed block record in AST file");
2275 return;
2276 case llvm::BitstreamEntry::EndBlock:
2277 goto NextCursor;
2278
2279 case llvm::BitstreamEntry::Record: {
2280 Record.clear();
2281 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2282 if (!MaybeRecord) {
2283 Error(MaybeRecord.takeError());
2284 return;
2285 }
2286 switch (MaybeRecord.get()) {
2287 default: // Default behavior: ignore.
2288 break;
2289
2292 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2293 if (II->isOutOfDate())
2294 updateOutOfDateIdentifier(*II);
2295 break;
2296 }
2297
2298 case PP_TOKEN:
2299 // Ignore tokens.
2300 break;
2301 }
2302 break;
2303 }
2304 }
2305 }
2306 NextCursor: ;
2307 }
2308}
2309
2310namespace {
2311
2312 /// Visitor class used to look up identifirs in an AST file.
2313 class IdentifierLookupVisitor {
2314 StringRef Name;
2315 unsigned NameHash;
2316 unsigned PriorGeneration;
2317 unsigned &NumIdentifierLookups;
2318 unsigned &NumIdentifierLookupHits;
2319 IdentifierInfo *Found = nullptr;
2320
2321 public:
2322 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2323 unsigned &NumIdentifierLookups,
2324 unsigned &NumIdentifierLookupHits)
2325 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2326 PriorGeneration(PriorGeneration),
2327 NumIdentifierLookups(NumIdentifierLookups),
2328 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2329
2330 bool operator()(ModuleFile &M) {
2331 // If we've already searched this module file, skip it now.
2332 if (M.Generation <= PriorGeneration)
2333 return true;
2334
2337 if (!IdTable)
2338 return false;
2339
2340 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2341 Found);
2342 ++NumIdentifierLookups;
2343 ASTIdentifierLookupTable::iterator Pos =
2344 IdTable->find_hashed(Name, NameHash, &Trait);
2345 if (Pos == IdTable->end())
2346 return false;
2347
2348 // Dereferencing the iterator has the effect of building the
2349 // IdentifierInfo node and populating it with the various
2350 // declarations it needs.
2351 ++NumIdentifierLookupHits;
2352 Found = *Pos;
2353 return true;
2354 }
2355
2356 // Retrieve the identifier info found within the module
2357 // files.
2358 IdentifierInfo *getIdentifierInfo() const { return Found; }
2359 };
2360
2361} // namespace
2362
2364 // Note that we are loading an identifier.
2365 Deserializing AnIdentifier(this);
2366
2367 unsigned PriorGeneration = 0;
2368 if (getContext().getLangOpts().Modules)
2369 PriorGeneration = IdentifierGeneration[&II];
2370
2371 // If there is a global index, look there first to determine which modules
2372 // provably do not have any results for this identifier.
2374 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2375 if (!loadGlobalIndex()) {
2376 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2377 HitsPtr = &Hits;
2378 }
2379 }
2380
2381 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2382 NumIdentifierLookups,
2383 NumIdentifierLookupHits);
2384 ModuleMgr.visit(Visitor, HitsPtr);
2385 markIdentifierUpToDate(&II);
2386}
2387
2389 if (!II)
2390 return;
2391
2392 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2393
2394 // Update the generation for this identifier.
2395 if (getContext().getLangOpts().Modules)
2396 IdentifierGeneration[II] = getGeneration();
2397}
2398
2400 const PendingMacroInfo &PMInfo) {
2401 ModuleFile &M = *PMInfo.M;
2402
2403 BitstreamCursor &Cursor = M.MacroCursor;
2404 SavedStreamPosition SavedPosition(Cursor);
2405 if (llvm::Error Err =
2406 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2407 Error(std::move(Err));
2408 return;
2409 }
2410
2411 struct ModuleMacroRecord {
2412 SubmoduleID SubModID;
2413 MacroInfo *MI;
2415 };
2417
2418 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2419 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2420 // macro histroy.
2422 while (true) {
2424 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2425 if (!MaybeEntry) {
2426 Error(MaybeEntry.takeError());
2427 return;
2428 }
2429 llvm::BitstreamEntry Entry = MaybeEntry.get();
2430
2431 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2432 Error("malformed block record in AST file");
2433 return;
2434 }
2435
2436 Record.clear();
2437 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2438 if (!MaybePP) {
2439 Error(MaybePP.takeError());
2440 return;
2441 }
2442 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2444 break;
2445
2446 case PP_MODULE_MACRO: {
2447 ModuleMacros.push_back(ModuleMacroRecord());
2448 auto &Info = ModuleMacros.back();
2449 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2450 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2451 for (int I = 2, N = Record.size(); I != N; ++I)
2452 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2453 continue;
2454 }
2455
2456 default:
2457 Error("malformed block record in AST file");
2458 return;
2459 }
2460
2461 // We found the macro directive history; that's the last record
2462 // for this macro.
2463 break;
2464 }
2465
2466 // Module macros are listed in reverse dependency order.
2467 {
2468 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2470 for (auto &MMR : ModuleMacros) {
2471 Overrides.clear();
2472 for (unsigned ModID : MMR.Overrides) {
2473 Module *Mod = getSubmodule(ModID);
2474 auto *Macro = PP.getModuleMacro(Mod, II);
2475 assert(Macro && "missing definition for overridden macro");
2476 Overrides.push_back(Macro);
2477 }
2478
2479 bool Inserted = false;
2480 Module *Owner = getSubmodule(MMR.SubModID);
2481 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2482 }
2483 }
2484
2485 // Don't read the directive history for a module; we don't have anywhere
2486 // to put it.
2487 if (M.isModule())
2488 return;
2489
2490 // Deserialize the macro directives history in reverse source-order.
2491 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2492 unsigned Idx = 0, N = Record.size();
2493 while (Idx < N) {
2494 MacroDirective *MD = nullptr;
2495 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2497 switch (K) {
2499 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2500 MD = PP.AllocateDefMacroDirective(MI, Loc);
2501 break;
2502 }
2504 MD = PP.AllocateUndefMacroDirective(Loc);
2505 break;
2507 bool isPublic = Record[Idx++];
2508 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2509 break;
2510 }
2511
2512 if (!Latest)
2513 Latest = MD;
2514 if (Earliest)
2515 Earliest->setPrevious(MD);
2516 Earliest = MD;
2517 }
2518
2519 if (Latest)
2520 PP.setLoadedMacroDirective(II, Earliest, Latest);
2521}
2522
2523bool ASTReader::shouldDisableValidationForFile(
2524 const serialization::ModuleFile &M) const {
2525 if (DisableValidationKind == DisableValidationForModuleKind::None)
2526 return false;
2527
2528 // If a PCH is loaded and validation is disabled for PCH then disable
2529 // validation for the PCH and the modules it loads.
2530 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2531
2532 switch (K) {
2533 case MK_MainFile:
2534 case MK_Preamble:
2535 case MK_PCH:
2536 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2537 case MK_ImplicitModule:
2538 case MK_ExplicitModule:
2539 case MK_PrebuiltModule:
2540 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2541 }
2542
2543 return false;
2544}
2545
2546InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2547 // If this ID is bogus, just return an empty input file.
2548 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2549 return InputFileInfo();
2550
2551 // If we've already loaded this input file, return it.
2552 if (F.InputFileInfosLoaded[ID - 1].isValid())
2553 return F.InputFileInfosLoaded[ID - 1];
2554
2555 // Go find this input file.
2556 BitstreamCursor &Cursor = F.InputFilesCursor;
2557 SavedStreamPosition SavedPosition(Cursor);
2558 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2559 F.InputFileOffsets[ID - 1])) {
2560 // FIXME this drops errors on the floor.
2561 consumeError(std::move(Err));
2562 }
2563
2564 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2565 if (!MaybeCode) {
2566 // FIXME this drops errors on the floor.
2567 consumeError(MaybeCode.takeError());
2568 }
2569 unsigned Code = MaybeCode.get();
2570 RecordData Record;
2571 StringRef Blob;
2572
2573 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2574 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2575 "invalid record type for input file");
2576 else {
2577 // FIXME this drops errors on the floor.
2578 consumeError(Maybe.takeError());
2579 }
2580
2581 assert(Record[0] == ID && "Bogus stored ID or offset");
2582 InputFileInfo R;
2583 R.StoredSize = static_cast<off_t>(Record[1]);
2584 R.StoredTime = static_cast<time_t>(Record[2]);
2585 R.Overridden = static_cast<bool>(Record[3]);
2586 R.Transient = static_cast<bool>(Record[4]);
2587 R.TopLevel = static_cast<bool>(Record[5]);
2588 R.ModuleMap = static_cast<bool>(Record[6]);
2589 uint16_t AsRequestedLength = Record[7];
2590 R.UnresolvedImportedFilenameAsRequested = Blob.substr(0, AsRequestedLength);
2591 R.UnresolvedImportedFilename = Blob.substr(AsRequestedLength);
2592 if (R.UnresolvedImportedFilename.empty())
2594
2595 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2596 if (!MaybeEntry) // FIXME this drops errors on the floor.
2597 consumeError(MaybeEntry.takeError());
2598 llvm::BitstreamEntry Entry = MaybeEntry.get();
2599 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2600 "expected record type for input file hash");
2601
2602 Record.clear();
2603 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2604 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2605 "invalid record type for input file hash");
2606 else {
2607 // FIXME this drops errors on the floor.
2608 consumeError(Maybe.takeError());
2609 }
2610 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2611 static_cast<uint64_t>(Record[0]);
2612
2613 // Note that we've loaded this input file info.
2614 F.InputFileInfosLoaded[ID - 1] = R;
2615 return R;
2616}
2617
2618static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2619InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2620 // If this ID is bogus, just return an empty input file.
2621 if (ID == 0 || ID > F.InputFilesLoaded.size())
2622 return InputFile();
2623
2624 // If we've already loaded this input file, return it.
2625 if (F.InputFilesLoaded[ID-1].getFile())
2626 return F.InputFilesLoaded[ID-1];
2627
2628 if (F.InputFilesLoaded[ID-1].isNotFound())
2629 return InputFile();
2630
2631 // Go find this input file.
2632 BitstreamCursor &Cursor = F.InputFilesCursor;
2633 SavedStreamPosition SavedPosition(Cursor);
2634 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2635 F.InputFileOffsets[ID - 1])) {
2636 // FIXME this drops errors on the floor.
2637 consumeError(std::move(Err));
2638 }
2639
2640 InputFileInfo FI = getInputFileInfo(F, ID);
2641 off_t StoredSize = FI.StoredSize;
2642 time_t StoredTime = FI.StoredTime;
2643 bool Overridden = FI.Overridden;
2644 bool Transient = FI.Transient;
2645 auto Filename =
2646 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2647 uint64_t StoredContentHash = FI.ContentHash;
2648
2649 // For standard C++ modules, we don't need to check the inputs.
2650 bool SkipChecks = F.StandardCXXModule;
2651
2652 const HeaderSearchOptions &HSOpts =
2653 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2654
2655 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2656 // modules.
2658 SkipChecks = false;
2659 Overridden = false;
2660 }
2661
2662 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2663
2664 // For an overridden file, create a virtual file with the stored
2665 // size/timestamp.
2666 if ((Overridden || Transient || SkipChecks) && !File)
2667 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2668
2669 if (!File) {
2670 if (Complain) {
2671 std::string ErrorStr = "could not find file '";
2672 ErrorStr += *Filename;
2673 ErrorStr += "' referenced by AST file '";
2674 ErrorStr += F.FileName;
2675 ErrorStr += "'";
2676 Error(ErrorStr);
2677 }
2678 // Record that we didn't find the file.
2680 return InputFile();
2681 }
2682
2683 // Check if there was a request to override the contents of the file
2684 // that was part of the precompiled header. Overriding such a file
2685 // can lead to problems when lexing using the source locations from the
2686 // PCH.
2687 SourceManager &SM = getSourceManager();
2688 // FIXME: Reject if the overrides are different.
2689 if ((!Overridden && !Transient) && !SkipChecks &&
2690 SM.isFileOverridden(*File)) {
2691 if (Complain)
2692 Error(diag::err_fe_pch_file_overridden, *Filename);
2693
2694 // After emitting the diagnostic, bypass the overriding file to recover
2695 // (this creates a separate FileEntry).
2696 File = SM.bypassFileContentsOverride(*File);
2697 if (!File) {
2699 return InputFile();
2700 }
2701 }
2702
2703 struct Change {
2704 enum ModificationKind {
2705 Size,
2706 ModTime,
2707 Content,
2708 None,
2709 } Kind;
2710 std::optional<int64_t> Old = std::nullopt;
2711 std::optional<int64_t> New = std::nullopt;
2712 };
2713 auto HasInputContentChanged = [&](Change OriginalChange) {
2714 assert(ValidateASTInputFilesContent &&
2715 "We should only check the content of the inputs with "
2716 "ValidateASTInputFilesContent enabled.");
2717
2718 if (StoredContentHash == 0)
2719 return OriginalChange;
2720
2721 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2722 if (!MemBuffOrError) {
2723 if (!Complain)
2724 return OriginalChange;
2725 std::string ErrorStr = "could not get buffer for file '";
2726 ErrorStr += File->getName();
2727 ErrorStr += "'";
2728 Error(ErrorStr);
2729 return OriginalChange;
2730 }
2731
2732 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2733 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2734 return Change{Change::None};
2735
2736 return Change{Change::Content};
2737 };
2738 auto HasInputFileChanged = [&]() {
2739 if (StoredSize != File->getSize())
2740 return Change{Change::Size, StoredSize, File->getSize()};
2741 if (!shouldDisableValidationForFile(F) && StoredTime &&
2742 StoredTime != File->getModificationTime()) {
2743 Change MTimeChange = {Change::ModTime, StoredTime,
2744 File->getModificationTime()};
2745
2746 // In case the modification time changes but not the content,
2747 // accept the cached file as legit.
2748 if (ValidateASTInputFilesContent)
2749 return HasInputContentChanged(MTimeChange);
2750
2751 return MTimeChange;
2752 }
2753 return Change{Change::None};
2754 };
2755
2756 bool IsOutOfDate = false;
2757 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2758 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2759 // enabled, it is better to check the contents of the inputs. Since we can't
2760 // get correct modified time information for inputs from overriden inputs.
2761 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2762 F.StandardCXXModule && FileChange.Kind == Change::None)
2763 FileChange = HasInputContentChanged(FileChange);
2764
2765 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2766 // it is better to check the content of the input files because we cannot rely
2767 // on the file modification time, which will be the same (zero) for these
2768 // files.
2769 if (!StoredTime && ValidateASTInputFilesContent &&
2770 FileChange.Kind == Change::None)
2771 FileChange = HasInputContentChanged(FileChange);
2772
2773 // For an overridden file, there is nothing to validate.
2774 if (!Overridden && FileChange.Kind != Change::None) {
2775 if (Complain) {
2776 // Build a list of the PCH imports that got us here (in reverse).
2777 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2778 while (!ImportStack.back()->ImportedBy.empty())
2779 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2780
2781 // The top-level PCH is stale.
2782 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2783 Diag(diag::err_fe_ast_file_modified)
2784 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2785 << TopLevelPCHName << FileChange.Kind
2786 << (FileChange.Old && FileChange.New)
2787 << llvm::itostr(FileChange.Old.value_or(0))
2788 << llvm::itostr(FileChange.New.value_or(0));
2789
2790 // Print the import stack.
2791 if (ImportStack.size() > 1) {
2792 Diag(diag::note_pch_required_by)
2793 << *Filename << ImportStack[0]->FileName;
2794 for (unsigned I = 1; I < ImportStack.size(); ++I)
2795 Diag(diag::note_pch_required_by)
2796 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2797 }
2798
2799 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2800 }
2801
2802 IsOutOfDate = true;
2803 }
2804 // FIXME: If the file is overridden and we've already opened it,
2805 // issue an error (or split it into a separate FileEntry).
2806
2807 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2808
2809 // Note that we've loaded this input file.
2810 F.InputFilesLoaded[ID-1] = IF;
2811 return IF;
2812}
2813
2814ASTReader::TemporarilyOwnedStringRef
2816 ModuleFile &ModF) {
2817 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
2818}
2819
2820ASTReader::TemporarilyOwnedStringRef
2822 StringRef Prefix) {
2823 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
2824
2825 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
2826 Path == "<built-in>" || Path == "<command line>")
2827 return {Path, Buf};
2828
2829 Buf.clear();
2830 llvm::sys::path::append(Buf, Prefix, Path);
2831 StringRef ResolvedPath{Buf.data(), Buf.size()};
2832 return {ResolvedPath, Buf};
2833}
2834
2836 StringRef P,
2837 ModuleFile &ModF) {
2838 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
2839}
2840
2842 StringRef P,
2843 StringRef Prefix) {
2844 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
2845 return ResolvedPath->str();
2846}
2847
2848static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2849 switch (ARR) {
2850 case ASTReader::Failure: return true;
2851 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2852 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2855 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2856 case ASTReader::HadErrors: return true;
2857 case ASTReader::Success: return false;
2858 }
2859
2860 llvm_unreachable("unknown ASTReadResult");
2861}
2862
2863ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2864 BitstreamCursor &Stream, StringRef Filename,
2865 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
2866 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
2867 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2868 // FIXME this drops errors on the floor.
2869 consumeError(std::move(Err));
2870 return Failure;
2871 }
2872
2873 // Read all of the records in the options block.
2874 RecordData Record;
2875 ASTReadResult Result = Success;
2876 while (true) {
2877 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2878 if (!MaybeEntry) {
2879 // FIXME this drops errors on the floor.
2880 consumeError(MaybeEntry.takeError());
2881 return Failure;
2882 }
2883 llvm::BitstreamEntry Entry = MaybeEntry.get();
2884
2885 switch (Entry.Kind) {
2886 case llvm::BitstreamEntry::Error:
2887 case llvm::BitstreamEntry::SubBlock:
2888 return Failure;
2889
2890 case llvm::BitstreamEntry::EndBlock:
2891 return Result;
2892
2893 case llvm::BitstreamEntry::Record:
2894 // The interesting case.
2895 break;
2896 }
2897
2898 // Read and process a record.
2899 Record.clear();
2900 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2901 if (!MaybeRecordType) {
2902 // FIXME this drops errors on the floor.
2903 consumeError(MaybeRecordType.takeError());
2904 return Failure;
2905 }
2906 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2907 case LANGUAGE_OPTIONS: {
2908 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2909 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
2910 AllowCompatibleConfigurationMismatch))
2911 Result = ConfigurationMismatch;
2912 break;
2913 }
2914
2915 case TARGET_OPTIONS: {
2916 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2917 if (ParseTargetOptions(Record, Filename, Complain, Listener,
2918 AllowCompatibleConfigurationMismatch))
2919 Result = ConfigurationMismatch;
2920 break;
2921 }
2922
2923 case FILE_SYSTEM_OPTIONS: {
2924 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2925 if (!AllowCompatibleConfigurationMismatch &&
2926 ParseFileSystemOptions(Record, Complain, Listener))
2927 Result = ConfigurationMismatch;
2928 break;
2929 }
2930
2931 case HEADER_SEARCH_OPTIONS: {
2932 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2933 if (!AllowCompatibleConfigurationMismatch &&
2934 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
2935 Result = ConfigurationMismatch;
2936 break;
2937 }
2938
2940 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2941 if (!AllowCompatibleConfigurationMismatch &&
2942 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
2943 SuggestedPredefines))
2944 Result = ConfigurationMismatch;
2945 break;
2946 }
2947 }
2948}
2949
2951ASTReader::ReadControlBlock(ModuleFile &F,
2953 const ModuleFile *ImportedBy,
2954 unsigned ClientLoadCapabilities) {
2955 BitstreamCursor &Stream = F.Stream;
2956
2957 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2958 Error(std::move(Err));
2959 return Failure;
2960 }
2961
2962 // Lambda to read the unhashed control block the first time it's called.
2963 //
2964 // For PCM files, the unhashed control block cannot be read until after the
2965 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2966 // need to look ahead before reading the IMPORTS record. For consistency,
2967 // this block is always read somehow (see BitstreamEntry::EndBlock).
2968 bool HasReadUnhashedControlBlock = false;
2969 auto readUnhashedControlBlockOnce = [&]() {
2970 if (!HasReadUnhashedControlBlock) {
2971 HasReadUnhashedControlBlock = true;
2972 if (ASTReadResult Result =
2973 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2974 return Result;
2975 }
2976 return Success;
2977 };
2978
2979 bool DisableValidation = shouldDisableValidationForFile(F);
2980
2981 // Read all of the records and blocks in the control block.
2982 RecordData Record;
2983 unsigned NumInputs = 0;
2984 unsigned NumUserInputs = 0;
2985 StringRef BaseDirectoryAsWritten;
2986 while (true) {
2987 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2988 if (!MaybeEntry) {
2989 Error(MaybeEntry.takeError());
2990 return Failure;
2991 }
2992 llvm::BitstreamEntry Entry = MaybeEntry.get();
2993
2994 switch (Entry.Kind) {
2995 case llvm::BitstreamEntry::Error:
2996 Error("malformed block record in AST file");
2997 return Failure;
2998 case llvm::BitstreamEntry::EndBlock: {
2999 // Validate the module before returning. This call catches an AST with
3000 // no module name and no imports.
3001 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3002 return Result;
3003
3004 // Validate input files.
3005 const HeaderSearchOptions &HSOpts =
3006 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3007
3008 // All user input files reside at the index range [0, NumUserInputs), and
3009 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3010 // loaded module files, ignore missing inputs.
3011 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3012 F.Kind != MK_PrebuiltModule) {
3013 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3014
3015 // If we are reading a module, we will create a verification timestamp,
3016 // so we verify all input files. Otherwise, verify only user input
3017 // files.
3018
3019 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3023 N = NumUserInputs;
3024
3025 for (unsigned I = 0; I < N; ++I) {
3026 InputFile IF = getInputFile(F, I+1, Complain);
3027 if (!IF.getFile() || IF.isOutOfDate())
3028 return OutOfDate;
3029 }
3030 }
3031
3032 if (Listener)
3033 Listener->visitModuleFile(F.FileName, F.Kind);
3034
3035 if (Listener && Listener->needsInputFileVisitation()) {
3036 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3037 : NumUserInputs;
3038 for (unsigned I = 0; I < N; ++I) {
3039 bool IsSystem = I >= NumUserInputs;
3040 InputFileInfo FI = getInputFileInfo(F, I + 1);
3041 auto FilenameAsRequested = ResolveImportedPath(
3043 Listener->visitInputFile(
3044 *FilenameAsRequested, IsSystem, FI.Overridden,
3046 }
3047 }
3048
3049 return Success;
3050 }
3051
3052 case llvm::BitstreamEntry::SubBlock:
3053 switch (Entry.ID) {
3055 F.InputFilesCursor = Stream;
3056 if (llvm::Error Err = Stream.SkipBlock()) {
3057 Error(std::move(Err));
3058 return Failure;
3059 }
3060 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3061 Error("malformed block record in AST file");
3062 return Failure;
3063 }
3064 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3065 continue;
3066
3067 case OPTIONS_BLOCK_ID:
3068 // If we're reading the first module for this group, check its options
3069 // are compatible with ours. For modules it imports, no further checking
3070 // is required, because we checked them when we built it.
3071 if (Listener && !ImportedBy) {
3072 // Should we allow the configuration of the module file to differ from
3073 // the configuration of the current translation unit in a compatible
3074 // way?
3075 //
3076 // FIXME: Allow this for files explicitly specified with -include-pch.
3077 bool AllowCompatibleConfigurationMismatch =
3079
3080 ASTReadResult Result =
3081 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3082 AllowCompatibleConfigurationMismatch, *Listener,
3083 SuggestedPredefines);
3084 if (Result == Failure) {
3085 Error("malformed block record in AST file");
3086 return Result;
3087 }
3088
3089 if (DisableValidation ||
3090 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3091 Result = Success;
3092
3093 // If we can't load the module, exit early since we likely
3094 // will rebuild the module anyway. The stream may be in the
3095 // middle of a block.
3096 if (Result != Success)
3097 return Result;
3098 } else if (llvm::Error Err = Stream.SkipBlock()) {
3099 Error(std::move(Err));
3100 return Failure;
3101 }
3102 continue;
3103
3104 default:
3105 if (llvm::Error Err = Stream.SkipBlock()) {
3106 Error(std::move(Err));
3107 return Failure;
3108 }
3109 continue;
3110 }
3111
3112 case llvm::BitstreamEntry::Record:
3113 // The interesting case.
3114 break;
3115 }
3116
3117 // Read and process a record.
3118 Record.clear();
3119 StringRef Blob;
3120 Expected<unsigned> MaybeRecordType =
3121 Stream.readRecord(Entry.ID, Record, &Blob);
3122 if (!MaybeRecordType) {
3123 Error(MaybeRecordType.takeError());
3124 return Failure;
3125 }
3126 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3127 case METADATA: {
3128 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3129 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3130 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3131 : diag::err_ast_file_version_too_new)
3133 return VersionMismatch;
3134 }
3135
3136 bool hasErrors = Record[7];
3137 if (hasErrors && !DisableValidation) {
3138 // If requested by the caller and the module hasn't already been read
3139 // or compiled, mark modules on error as out-of-date.
3140 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3141 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3142 return OutOfDate;
3143
3144 if (!AllowASTWithCompilerErrors) {
3145 Diag(diag::err_ast_file_with_compiler_errors)
3147 return HadErrors;
3148 }
3149 }
3150 if (hasErrors) {
3151 Diags.ErrorOccurred = true;
3152 Diags.UncompilableErrorOccurred = true;
3153 Diags.UnrecoverableErrorOccurred = true;
3154 }
3155
3156 F.RelocatablePCH = Record[4];
3157 // Relative paths in a relocatable PCH are relative to our sysroot.
3158 if (F.RelocatablePCH)
3159 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3160
3162
3163 F.HasTimestamps = Record[6];
3164
3165 const std::string &CurBranch = getClangFullRepositoryVersion();
3166 StringRef ASTBranch = Blob;
3167 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3168 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3169 Diag(diag::err_ast_file_different_branch)
3170 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3171 << CurBranch;
3172 return VersionMismatch;
3173 }
3174 break;
3175 }
3176
3177 case IMPORT: {
3178 // Validate the AST before processing any imports (otherwise, untangling
3179 // them can be error-prone and expensive). A module will have a name and
3180 // will already have been validated, but this catches the PCH case.
3181 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3182 return Result;
3183
3184 unsigned Idx = 0;
3185 // Read information about the AST file.
3186 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3187
3188 // The import location will be the local one for now; we will adjust
3189 // all import locations of module imports after the global source
3190 // location info are setup, in ReadAST.
3191 auto [ImportLoc, ImportModuleFileIndex] =
3192 ReadUntranslatedSourceLocation(Record[Idx++]);
3193 // The import location must belong to the current module file itself.
3194 assert(ImportModuleFileIndex == 0);
3195
3196 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3197
3198 bool IsImportingStdCXXModule = Record[Idx++];
3199
3200 off_t StoredSize = 0;
3201 time_t StoredModTime = 0;
3202 ASTFileSignature StoredSignature;
3203 std::string ImportedFile;
3204
3205 // For prebuilt and explicit modules first consult the file map for
3206 // an override. Note that here we don't search prebuilt module
3207 // directories if we're not importing standard c++ module, only the
3208 // explicit name to file mappings. Also, we will still verify the
3209 // size/signature making sure it is essentially the same file but
3210 // perhaps in a different location.
3211 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3212 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3213 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3214
3215 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3216 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3217 return Missing;
3218 }
3219
3220 if (!IsImportingStdCXXModule) {
3221 StoredSize = (off_t)Record[Idx++];
3222 StoredModTime = (time_t)Record[Idx++];
3223
3224 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3225 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3226 SignatureBytes.end());
3227 Blob = Blob.substr(ASTFileSignature::size);
3228
3229 if (ImportedFile.empty()) {
3230 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3231 // ModuleCache as when writing.
3232 ImportedFile =
3233 ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3234 }
3235 }
3236
3237 // If our client can't cope with us being out of date, we can't cope with
3238 // our dependency being missing.
3239 unsigned Capabilities = ClientLoadCapabilities;
3240 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3241 Capabilities &= ~ARR_Missing;
3242
3243 // Load the AST file.
3244 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3245 Loaded, StoredSize, StoredModTime,
3246 StoredSignature, Capabilities);
3247
3248 // If we diagnosed a problem, produce a backtrace.
3249 bool recompilingFinalized =
3250 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3251 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3252 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3253 Diag(diag::note_module_file_imported_by)
3254 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3255 if (recompilingFinalized)
3256 Diag(diag::note_module_file_conflict);
3257
3258 switch (Result) {
3259 case Failure: return Failure;
3260 // If we have to ignore the dependency, we'll have to ignore this too.
3261 case Missing:
3262 case OutOfDate: return OutOfDate;
3263 case VersionMismatch: return VersionMismatch;
3264 case ConfigurationMismatch: return ConfigurationMismatch;
3265 case HadErrors: return HadErrors;
3266 case Success: break;
3267 }
3268 break;
3269 }
3270
3271 case ORIGINAL_FILE:
3272 F.OriginalSourceFileID = FileID::get(Record[0]);
3273 F.ActualOriginalSourceFileName = std::string(Blob);
3274 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3275 PathBuf, F.ActualOriginalSourceFileName, F);
3276 break;
3277
3278 case ORIGINAL_FILE_ID:
3279 F.OriginalSourceFileID = FileID::get(Record[0]);
3280 break;
3281
3282 case MODULE_NAME:
3283 F.ModuleName = std::string(Blob);
3284 Diag(diag::remark_module_import)
3285 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3286 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3287 if (Listener)
3288 Listener->ReadModuleName(F.ModuleName);
3289
3290 // Validate the AST as soon as we have a name so we can exit early on
3291 // failure.
3292 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3293 return Result;
3294
3295 break;
3296
3297 case MODULE_DIRECTORY: {
3298 // Save the BaseDirectory as written in the PCM for computing the module
3299 // filename for the ModuleCache.
3300 BaseDirectoryAsWritten = Blob;
3301 assert(!F.ModuleName.empty() &&
3302 "MODULE_DIRECTORY found before MODULE_NAME");
3303 F.BaseDirectory = std::string(Blob);
3304 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3305 break;
3306 // If we've already loaded a module map file covering this module, we may
3307 // have a better path for it (relative to the current build).
3308 Module *M = PP.getHeaderSearchInfo().lookupModule(
3309 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3310 /*AllowExtraModuleMapSearch*/ true);
3311 if (M && M->Directory) {
3312 // If we're implicitly loading a module, the base directory can't
3313 // change between the build and use.
3314 // Don't emit module relocation error if we have -fno-validate-pch
3315 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3318 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3319 if (!BuildDir || *BuildDir != M->Directory) {
3320 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3321 Diag(diag::err_imported_module_relocated)
3322 << F.ModuleName << Blob << M->Directory->getName();
3323 return OutOfDate;
3324 }
3325 }
3326 F.BaseDirectory = std::string(M->Directory->getName());
3327 }
3328 break;
3329 }
3330
3331 case MODULE_MAP_FILE:
3332 if (ASTReadResult Result =
3333 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3334 return Result;
3335 break;
3336
3337 case INPUT_FILE_OFFSETS:
3338 NumInputs = Record[0];
3339 NumUserInputs = Record[1];
3341 (const llvm::support::unaligned_uint64_t *)Blob.data();
3342 F.InputFilesLoaded.resize(NumInputs);
3343 F.InputFileInfosLoaded.resize(NumInputs);
3344 F.NumUserInputFiles = NumUserInputs;
3345 break;
3346 }
3347 }
3348}
3349
3350llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3351 unsigned ClientLoadCapabilities) {
3352 BitstreamCursor &Stream = F.Stream;
3353
3354 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3355 return Err;
3356 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3357
3358 // Read all of the records and blocks for the AST file.
3359 RecordData Record;
3360 while (true) {
3361 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3362 if (!MaybeEntry)
3363 return MaybeEntry.takeError();
3364 llvm::BitstreamEntry Entry = MaybeEntry.get();
3365
3366 switch (Entry.Kind) {
3367 case llvm::BitstreamEntry::Error:
3368 return llvm::createStringError(
3369 std::errc::illegal_byte_sequence,
3370 "error at end of module block in AST file");
3371 case llvm::BitstreamEntry::EndBlock:
3372 // Outside of C++, we do not store a lookup map for the translation unit.
3373 // Instead, mark it as needing a lookup map to be built if this module
3374 // contains any declarations lexically within it (which it always does!).
3375 // This usually has no cost, since we very rarely need the lookup map for
3376 // the translation unit outside C++.
3377 if (ASTContext *Ctx = ContextObj) {
3378 DeclContext *DC = Ctx->getTranslationUnitDecl();
3379 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3381 }
3382
3383 return llvm::Error::success();
3384 case llvm::BitstreamEntry::SubBlock:
3385 switch (Entry.ID) {
3386 case DECLTYPES_BLOCK_ID:
3387 // We lazily load the decls block, but we want to set up the
3388 // DeclsCursor cursor to point into it. Clone our current bitcode
3389 // cursor to it, enter the block and read the abbrevs in that block.
3390 // With the main cursor, we just skip over it.
3391 F.DeclsCursor = Stream;
3392 if (llvm::Error Err = Stream.SkipBlock())
3393 return Err;
3394 if (llvm::Error Err = ReadBlockAbbrevs(
3396 return Err;
3397 break;
3398
3400 F.MacroCursor = Stream;
3401 if (!PP.getExternalSource())
3402 PP.setExternalSource(this);
3403
3404 if (llvm::Error Err = Stream.SkipBlock())
3405 return Err;
3406 if (llvm::Error Err =
3407 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3408 return Err;
3409 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3410 break;
3411
3413 F.PreprocessorDetailCursor = Stream;
3414
3415 if (llvm::Error Err = Stream.SkipBlock()) {
3416 return Err;
3417 }
3418 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3420 return Err;
3422 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3423
3424 if (!PP.getPreprocessingRecord())
3425 PP.createPreprocessingRecord();
3426 if (!PP.getPreprocessingRecord()->getExternalSource())
3427 PP.getPreprocessingRecord()->SetExternalSource(*this);
3428 break;
3429
3431 if (llvm::Error Err = ReadSourceManagerBlock(F))
3432 return Err;
3433 break;
3434
3435 case SUBMODULE_BLOCK_ID:
3436 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3437 return Err;
3438 break;
3439
3440 case COMMENTS_BLOCK_ID: {
3441 BitstreamCursor C = Stream;
3442
3443 if (llvm::Error Err = Stream.SkipBlock())
3444 return Err;
3445 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3446 return Err;
3447 CommentsCursors.push_back(std::make_pair(C, &F));
3448 break;
3449 }
3450
3451 default:
3452 if (llvm::Error Err = Stream.SkipBlock())
3453 return Err;
3454 break;
3455 }
3456 continue;
3457
3458 case llvm::BitstreamEntry::Record:
3459 // The interesting case.
3460 break;
3461 }
3462
3463 // Read and process a record.
3464 Record.clear();
3465 StringRef Blob;
3466 Expected<unsigned> MaybeRecordType =
3467 Stream.readRecord(Entry.ID, Record, &Blob);
3468 if (!MaybeRecordType)
3469 return MaybeRecordType.takeError();
3470 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3471
3472 // If we're not loading an AST context, we don't care about most records.
3473 if (!ContextObj) {
3474 switch (RecordType) {
3475 case IDENTIFIER_TABLE:
3476 case IDENTIFIER_OFFSET:
3478 case STATISTICS:
3481 case PP_COUNTER_VALUE:
3483 case MODULE_OFFSET_MAP:
3487 case IMPORTED_MODULES:
3488 case MACRO_OFFSET:
3489 break;
3490 default:
3491 continue;
3492 }
3493 }
3494
3495 switch (RecordType) {
3496 default: // Default behavior: ignore.
3497 break;
3498
3499 case TYPE_OFFSET: {
3500 if (F.LocalNumTypes != 0)
3501 return llvm::createStringError(
3502 std::errc::illegal_byte_sequence,
3503 "duplicate TYPE_OFFSET record in AST file");
3504 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3505 F.LocalNumTypes = Record[0];
3506 F.BaseTypeIndex = getTotalNumTypes();
3507
3508 if (F.LocalNumTypes > 0)
3509 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3510
3511 break;
3512 }
3513
3514 case DECL_OFFSET: {
3515 if (F.LocalNumDecls != 0)
3516 return llvm::createStringError(
3517 std::errc::illegal_byte_sequence,
3518 "duplicate DECL_OFFSET record in AST file");
3519 F.DeclOffsets = (const DeclOffset *)Blob.data();
3520 F.LocalNumDecls = Record[0];
3521 F.BaseDeclIndex = getTotalNumDecls();
3522
3523 if (F.LocalNumDecls > 0)
3524 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3525
3526 break;
3527 }
3528
3529 case TU_UPDATE_LEXICAL: {
3530 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3531 LexicalContents Contents(
3532 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3533 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3534 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3536 break;
3537 }
3538
3539 case UPDATE_VISIBLE: {
3540 unsigned Idx = 0;
3541 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3542 auto *Data = (const unsigned char*)Blob.data();
3543 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3544 // If we've already loaded the decl, perform the updates when we finish
3545 // loading this block.
3546 if (Decl *D = GetExistingDecl(ID))
3547 PendingUpdateRecords.push_back(
3548 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3549 break;
3550 }
3551
3553 unsigned Idx = 0;
3554 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3555 auto *Data = (const unsigned char *)Blob.data();
3556 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3557 // If we've already loaded the decl, perform the updates when we finish
3558 // loading this block.
3559 if (Decl *D = GetExistingDecl(ID))
3560 PendingUpdateRecords.push_back(
3561 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3562 break;
3563 }
3564
3566 unsigned Idx = 0;
3567 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3568 auto *Data = (const unsigned char *)Blob.data();
3569 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3570 // If we've already loaded the decl, perform the updates when we finish
3571 // loading this block.
3572 if (Decl *D = GetExistingDecl(ID))
3573 PendingUpdateRecords.push_back(
3574 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3575 break;
3576 }
3577
3578 case IDENTIFIER_TABLE:
3580 reinterpret_cast<const unsigned char *>(Blob.data());
3581 if (Record[0]) {
3582 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3584 F.IdentifierTableData + sizeof(uint32_t),
3586 ASTIdentifierLookupTrait(*this, F));
3587
3588 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3589 }
3590 break;
3591
3592 case IDENTIFIER_OFFSET: {
3593 if (F.LocalNumIdentifiers != 0)
3594 return llvm::createStringError(
3595 std::errc::illegal_byte_sequence,
3596 "duplicate IDENTIFIER_OFFSET record in AST file");
3597 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3599 F.BaseIdentifierID = getTotalNumIdentifiers();
3600
3601 if (F.LocalNumIdentifiers > 0)
3602 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3604 break;
3605 }
3606
3608 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3609 break;
3610
3612 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3613 // about "interesting" decls (for instance, if we're building a module).
3614 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3615 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3616 break;
3617
3619 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3620 // them (ie: if we're not codegenerating this module).
3621 if (F.Kind == MK_MainFile ||
3622 getContext().getLangOpts().BuildingPCHWithObjectFile)
3623 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3624 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3625 break;
3626
3627 case SPECIAL_TYPES:
3628 if (SpecialTypes.empty()) {
3629 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3630 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3631 break;
3632 }
3633
3634 if (Record.empty())
3635 break;
3636
3637 if (SpecialTypes.size() != Record.size())
3638 return llvm::createStringError(std::errc::illegal_byte_sequence,
3639 "invalid special-types record");
3640
3641 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3642 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3643 if (!SpecialTypes[I])
3644 SpecialTypes[I] = ID;
3645 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3646 // merge step?
3647 }
3648 break;
3649
3650 case STATISTICS:
3651 TotalNumStatements += Record[0];
3652 TotalNumMacros += Record[1];
3653 TotalLexicalDeclContexts += Record[2];
3654 TotalVisibleDeclContexts += Record[3];
3655 break;
3656
3658 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3659 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3660 break;
3661
3662 case DELEGATING_CTORS:
3663 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3664 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3665 break;
3666
3668 if (Record.size() % 3 != 0)
3669 return llvm::createStringError(std::errc::illegal_byte_sequence,
3670 "invalid weak identifiers record");
3671
3672 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3673 // files. This isn't the way to do it :)
3674 WeakUndeclaredIdentifiers.clear();
3675
3676 // Translate the weak, undeclared identifiers into global IDs.
3677 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3678 WeakUndeclaredIdentifiers.push_back(
3679 getGlobalIdentifierID(F, Record[I++]));
3680 WeakUndeclaredIdentifiers.push_back(
3681 getGlobalIdentifierID(F, Record[I++]));
3682 WeakUndeclaredIdentifiers.push_back(
3683 ReadSourceLocation(F, Record, I).getRawEncoding());
3684 }
3685 break;
3686
3687 case SELECTOR_OFFSETS: {
3688 F.SelectorOffsets = (const uint32_t *)Blob.data();
3690 unsigned LocalBaseSelectorID = Record[1];
3691 F.BaseSelectorID = getTotalNumSelectors();
3692
3693 if (F.LocalNumSelectors > 0) {
3694 // Introduce the global -> local mapping for selectors within this
3695 // module.
3696 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3697
3698 // Introduce the local -> global mapping for selectors within this
3699 // module.
3701 std::make_pair(LocalBaseSelectorID,
3702 F.BaseSelectorID - LocalBaseSelectorID));
3703
3704 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3705 }
3706 break;
3707 }
3708
3709 case METHOD_POOL:
3710 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3711 if (Record[0])
3713 = ASTSelectorLookupTable::Create(
3716 ASTSelectorLookupTrait(*this, F));
3717 TotalNumMethodPoolEntries += Record[1];
3718 break;
3719
3721 if (!Record.empty()) {
3722 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3723 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3724 Record[Idx++]));
3725 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3726 getRawEncoding());
3727 }
3728 }
3729 break;
3730
3731 case PP_ASSUME_NONNULL_LOC: {
3732 unsigned Idx = 0;
3733 if (!Record.empty())
3734 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3735 ReadSourceLocation(F, Record, Idx));
3736 break;
3737 }
3738
3740 if (!Record.empty()) {
3742 unsigned Idx = 0;
3743 while (Idx < Record.size())
3744 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
3745 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3746 }
3747 break;
3748 }
3749
3751 if (!Record.empty()) {
3752 unsigned Idx = 0, End = Record.size() - 1;
3753 bool ReachedEOFWhileSkipping = Record[Idx++];
3754 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3755 if (ReachedEOFWhileSkipping) {
3756 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3757 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3758 bool FoundNonSkipPortion = Record[Idx++];
3759 bool FoundElse = Record[Idx++];
3760 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3761 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3762 FoundElse, ElseLoc);
3763 }
3764 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3765 while (Idx < End) {
3766 auto Loc = ReadSourceLocation(F, Record, Idx);
3767 bool WasSkipping = Record[Idx++];
3768 bool FoundNonSkip = Record[Idx++];
3769 bool FoundElse = Record[Idx++];
3770 ConditionalStack.push_back(
3771 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3772 }
3773 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3774 }
3775 break;
3776
3777 case PP_COUNTER_VALUE:
3778 if (!Record.empty() && Listener)
3779 Listener->ReadCounter(F, Record[0]);
3780 break;
3781
3782 case FILE_SORTED_DECLS:
3783 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
3785 break;
3786
3788 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3790 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3792 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3793 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3794 SLocSpaceSize);
3795 if (!F.SLocEntryBaseID) {
3796 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3797 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3798 return llvm::createStringError(std::errc::invalid_argument,
3799 "ran out of source locations");
3800 }
3801 // Make our entry in the range map. BaseID is negative and growing, so
3802 // we invert it. Because we invert it, though, we need the other end of
3803 // the range.
3804 unsigned RangeStart =
3806 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3808
3809 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3810 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3811 GlobalSLocOffsetMap.insert(
3812 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3813 - SLocSpaceSize,&F));
3814
3815 TotalNumSLocEntries += F.LocalNumSLocEntries;
3816 break;
3817 }
3818
3819 case MODULE_OFFSET_MAP:
3820 F.ModuleOffsetMap = Blob;
3821 break;
3822
3824 ParseLineTable(F, Record);
3825 break;
3826
3827 case EXT_VECTOR_DECLS:
3828 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3829 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
3830 break;
3831
3832 case VTABLE_USES:
3833 if (Record.size() % 3 != 0)
3834 return llvm::createStringError(std::errc::illegal_byte_sequence,
3835 "Invalid VTABLE_USES record");
3836
3837 // Later tables overwrite earlier ones.
3838 // FIXME: Modules will have some trouble with this. This is clearly not
3839 // the right way to do this.
3840 VTableUses.clear();
3841
3842 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3843 VTableUses.push_back(
3844 {ReadDeclID(F, Record, Idx),
3845 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
3846 (bool)Record[Idx++]});
3847 }
3848 break;
3849
3851
3852 if (Record.size() % 2 != 0)
3853 return llvm::createStringError(
3854 std::errc::illegal_byte_sequence,
3855 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3856
3857 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3858 PendingInstantiations.push_back(
3859 {ReadDeclID(F, Record, I),
3860 ReadSourceLocation(F, Record, I).getRawEncoding()});
3861 }
3862 break;
3863
3864 case SEMA_DECL_REFS:
3865 if (Record.size() != 3)
3866 return llvm::createStringError(std::errc::illegal_byte_sequence,
3867 "Invalid SEMA_DECL_REFS block");
3868 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3869 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
3870 break;
3871
3872 case PPD_ENTITIES_OFFSETS: {
3873 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3874 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3875 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3876
3877 unsigned LocalBasePreprocessedEntityID = Record[0];
3878
3879 unsigned StartingID;
3880 if (!PP.getPreprocessingRecord())
3881 PP.createPreprocessingRecord();
3882 if (!PP.getPreprocessingRecord()->getExternalSource())
3883 PP.getPreprocessingRecord()->SetExternalSource(*this);
3884 StartingID
3885 = PP.getPreprocessingRecord()
3886 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3887 F.BasePreprocessedEntityID = StartingID;
3888
3889 if (F.NumPreprocessedEntities > 0) {
3890 // Introduce the global -> local mapping for preprocessed entities in
3891 // this module.
3892 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3893
3894 // Introduce the local -> global mapping for preprocessed entities in
3895 // this module.
3897 std::make_pair(LocalBasePreprocessedEntityID,
3898 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3899 }
3900
3901 break;
3902 }
3903
3904 case PPD_SKIPPED_RANGES: {
3905 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3906 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3907 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3908
3909 if (!PP.getPreprocessingRecord())
3910 PP.createPreprocessingRecord();
3911 if (!PP.getPreprocessingRecord()->getExternalSource())
3912 PP.getPreprocessingRecord()->SetExternalSource(*this);
3913 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3914 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3915
3917 GlobalSkippedRangeMap.insert(
3918 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3919 break;
3920 }
3921
3923 if (Record.size() % 2 != 0)
3924 return llvm::createStringError(
3925 std::errc::illegal_byte_sequence,
3926 "invalid DECL_UPDATE_OFFSETS block in AST file");
3927 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3928 GlobalDeclID ID = ReadDeclID(F, Record, I);
3929 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
3930
3931 // If we've already loaded the decl, perform the updates when we finish
3932 // loading this block.
3933 if (Decl *D = GetExistingDecl(ID))
3934 PendingUpdateRecords.push_back(
3935 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3936 }
3937 break;
3938
3940 if (Record.size() % 3 != 0)
3941 return llvm::createStringError(
3942 std::errc::illegal_byte_sequence,
3943 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3944 "file");
3945 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3946 GlobalDeclID ID = ReadDeclID(F, Record, I);
3947
3948 uint64_t BaseOffset = F.DeclsBlockStartOffset;
3949 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
3950 uint64_t LocalLexicalOffset = Record[I++];
3951 uint64_t LexicalOffset =
3952 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
3953 uint64_t LocalVisibleOffset = Record[I++];
3954 uint64_t VisibleOffset =
3955 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
3956
3957 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};
3958
3959 assert(!GetExistingDecl(ID) &&
3960 "We shouldn't load the namespace in the front of delayed "
3961 "namespace lexical and visible block");
3962 }
3963 break;
3964 }
3965
3966 case RELATED_DECLS_MAP:
3967 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3968 GlobalDeclID ID = ReadDeclID(F, Record, I);
3969 auto &RelatedDecls = RelatedDeclsMap[ID];
3970 unsigned NN = Record[I++];
3971 RelatedDecls.reserve(NN);
3972 for (unsigned II = 0; II < NN; II++)
3973 RelatedDecls.push_back(ReadDeclID(F, Record, I));
3974 }
3975 break;
3976
3978 if (F.LocalNumObjCCategoriesInMap != 0)
3979 return llvm::createStringError(
3980 std::errc::illegal_byte_sequence,
3981 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3982
3984 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3985 break;
3986
3987 case OBJC_CATEGORIES:
3988 F.ObjCCategories.swap(Record);
3989 break;
3990
3992 // Later tables overwrite earlier ones.
3993 // FIXME: Modules will have trouble with this.
3994 CUDASpecialDeclRefs.clear();
3995 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3996 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
3997 break;
3998
4000 F.HeaderFileInfoTableData = Blob.data();
4002 if (Record[0]) {
4003 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4004 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4005 (const unsigned char *)F.HeaderFileInfoTableData,
4006 HeaderFileInfoTrait(*this, F));
4007
4008 PP.getHeaderSearchInfo().SetExternalSource(this);
4009 if (!PP.getHeaderSearchInfo().getExternalLookup())
4010 PP.getHeaderSearchInfo().SetExternalLookup(this);
4011 }
4012 break;
4013
4014 case FP_PRAGMA_OPTIONS:
4015 // Later tables overwrite earlier ones.
4016 FPPragmaOptions.swap(Record);
4017 break;
4018
4020 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4021 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4022 break;
4023
4024 case OPENCL_EXTENSIONS:
4025 for (unsigned I = 0, E = Record.size(); I != E; ) {
4026 auto Name = ReadString(Record, I);
4027 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4028 OptInfo.Supported = Record[I++] != 0;
4029 OptInfo.Enabled = Record[I++] != 0;
4030 OptInfo.WithPragma = Record[I++] != 0;
4031 OptInfo.Avail = Record[I++];
4032 OptInfo.Core = Record[I++];
4033 OptInfo.Opt = Record[I++];
4034 }
4035 break;
4036
4038 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4039 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4040 break;
4041
4042 case KNOWN_NAMESPACES:
4043 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4044 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4045 break;
4046
4047 case UNDEFINED_BUT_USED:
4048 if (Record.size() % 2 != 0)
4049 return llvm::createStringError(std::errc::illegal_byte_sequence,
4050 "invalid undefined-but-used record");
4051 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4052 UndefinedButUsed.push_back(
4053 {ReadDeclID(F, Record, I),
4054 ReadSourceLocation(F, Record, I).getRawEncoding()});
4055 }
4056 break;
4057
4059 for (unsigned I = 0, N = Record.size(); I != N;) {
4060 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4061 const uint64_t Count = Record[I++];
4062 DelayedDeleteExprs.push_back(Count);
4063 for (uint64_t C = 0; C < Count; ++C) {
4064 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4065 bool IsArrayForm = Record[I++] == 1;
4066 DelayedDeleteExprs.push_back(IsArrayForm);
4067 }
4068 }
4069 break;
4070
4071 case VTABLES_TO_EMIT:
4072 if (F.Kind == MK_MainFile ||
4073 getContext().getLangOpts().BuildingPCHWithObjectFile)
4074 for (unsigned I = 0, N = Record.size(); I != N;)
4075 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4076 break;
4077
4078 case IMPORTED_MODULES:
4079 if (!F.isModule()) {
4080 // If we aren't loading a module (which has its own exports), make
4081 // all of the imported modules visible.
4082 // FIXME: Deal with macros-only imports.
4083 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4084 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4085 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4086 if (GlobalID) {
4087 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4088 if (DeserializationListener)
4089 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4090 }
4091 }
4092 }
4093 break;
4094
4095 case MACRO_OFFSET: {
4096 if (F.LocalNumMacros != 0)
4097 return llvm::createStringError(
4098 std::errc::illegal_byte_sequence,
4099 "duplicate MACRO_OFFSET record in AST file");
4100 F.MacroOffsets = (const uint32_t *)Blob.data();
4101 F.LocalNumMacros = Record[0];
4102 unsigned LocalBaseMacroID = Record[1];
4104 F.BaseMacroID = getTotalNumMacros();
4105
4106 if (F.LocalNumMacros > 0) {
4107 // Introduce the global -> local mapping for macros within this module.
4108 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
4109
4110 // Introduce the local -> global mapping for macros within this module.
4112 std::make_pair(LocalBaseMacroID,
4113 F.BaseMacroID - LocalBaseMacroID));
4114
4115 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4116 }
4117 break;
4118 }
4119
4121 LateParsedTemplates.emplace_back(
4122 std::piecewise_construct, std::forward_as_tuple(&F),
4123 std::forward_as_tuple(Record.begin(), Record.end()));
4124 break;
4125
4127 if (Record.size() != 1)
4128 return llvm::createStringError(std::errc::illegal_byte_sequence,
4129 "invalid pragma optimize record");
4130 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4131 break;
4132
4134 if (Record.size() != 1)
4135 return llvm::createStringError(std::errc::illegal_byte_sequence,
4136 "invalid pragma ms_struct record");
4137 PragmaMSStructState = Record[0];
4138 break;
4139
4141 if (Record.size() != 2)
4142 return llvm::createStringError(
4143 std::errc::illegal_byte_sequence,
4144 "invalid pragma pointers to members record");
4145 PragmaMSPointersToMembersState = Record[0];
4146 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4147 break;
4148
4150 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4151 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4152 break;
4153
4155 if (Record.size() != 1)
4156 return llvm::createStringError(std::errc::illegal_byte_sequence,
4157 "invalid cuda pragma options record");
4158 ForceHostDeviceDepth = Record[0];
4159 break;
4160
4162 if (Record.size() < 3)
4163 return llvm::createStringError(std::errc::illegal_byte_sequence,
4164 "invalid pragma pack record");
4165 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4166 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4167 unsigned NumStackEntries = Record[2];
4168 unsigned Idx = 3;
4169 // Reset the stack when importing a new module.
4170 PragmaAlignPackStack.clear();
4171 for (unsigned I = 0; I < NumStackEntries; ++I) {
4172 PragmaAlignPackStackEntry Entry;
4173 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4174 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4175 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4176 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4177 Entry.SlotLabel = PragmaAlignPackStrings.back();
4178 PragmaAlignPackStack.push_back(Entry);
4179 }
4180 break;
4181 }
4182
4184 if (Record.size() < 3)
4185 return llvm::createStringError(std::errc::illegal_byte_sequence,
4186 "invalid pragma float control record");
4187 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4188 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4189 unsigned NumStackEntries = Record[2];
4190 unsigned Idx = 3;
4191 // Reset the stack when importing a new module.
4192 FpPragmaStack.clear();
4193 for (unsigned I = 0; I < NumStackEntries; ++I) {
4194 FpPragmaStackEntry Entry;
4195 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4196 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4197 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4198 FpPragmaStrings.push_back(ReadString(Record, Idx));
4199 Entry.SlotLabel = FpPragmaStrings.back();
4200 FpPragmaStack.push_back(Entry);
4201 }
4202 break;
4203 }
4204
4206 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4207 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4208 break;
4209 }
4210 }
4211}
4212
4213void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4214 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4215
4216 // Additional remapping information.
4217 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4218 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4219 F.ModuleOffsetMap = StringRef();
4220
4222 RemapBuilder MacroRemap(F.MacroRemap);
4223 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4224 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4225 RemapBuilder SelectorRemap(F.SelectorRemap);
4226
4227 auto &ImportedModuleVector = F.TransitiveImports;
4228 assert(ImportedModuleVector.empty());
4229
4230 while (Data < DataEnd) {
4231 // FIXME: Looking up dependency modules by filename is horrible. Let's
4232 // start fixing this with prebuilt, explicit and implicit modules and see
4233 // how it goes...
4234 using namespace llvm::support;
4235 ModuleKind Kind = static_cast<ModuleKind>(
4236 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4237 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4238 StringRef Name = StringRef((const char*)Data, Len);
4239 Data += Len;
4242 ? ModuleMgr.lookupByModuleName(Name)
4243 : ModuleMgr.lookupByFileName(Name));
4244 if (!OM) {
4245 std::string Msg = "refers to unknown module, cannot find ";
4246 Msg.append(std::string(Name));
4247 Error(Msg);
4248 return;
4249 }
4250
4251 ImportedModuleVector.push_back(OM);
4252
4253 uint32_t MacroIDOffset =
4254 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4255 uint32_t PreprocessedEntityIDOffset =
4256 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4257 uint32_t SubmoduleIDOffset =
4258 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4259 uint32_t SelectorIDOffset =
4260 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4261
4262 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4263 RemapBuilder &Remap) {
4264 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4265 if (Offset != None)
4266 Remap.insert(std::make_pair(Offset,
4267 static_cast<int>(BaseOffset - Offset)));
4268 };
4269
4270 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4271 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4272 PreprocessedEntityRemap);
4273 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4274 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4275 }
4276}
4277
4279ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4280 const ModuleFile *ImportedBy,
4281 unsigned ClientLoadCapabilities) {
4282 unsigned Idx = 0;
4283 F.ModuleMapPath = ReadPath(F, Record, Idx);
4284
4285 // Try to resolve ModuleName in the current header search context and
4286 // verify that it is found in the same module map file as we saved. If the
4287 // top-level AST file is a main file, skip this check because there is no
4288 // usable header search context.
4289 assert(!F.ModuleName.empty() &&
4290 "MODULE_NAME should come before MODULE_MAP_FILE");
4291 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4292 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4293 // An implicitly-loaded module file should have its module listed in some
4294 // module map file that we've already loaded.
4295 Module *M =
4296 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4297 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4298 OptionalFileEntryRef ModMap =
4299 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4300 // Don't emit module relocation error if we have -fno-validate-pch
4301 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4303 !ModMap) {
4304 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4305 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4306 // This module was defined by an imported (explicit) module.
4307 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4308 << ASTFE->getName();
4309 } else {
4310 // This module was built with a different module map.
4311 Diag(diag::err_imported_module_not_found)
4312 << F.ModuleName << F.FileName
4313 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4314 << !ImportedBy;
4315 // In case it was imported by a PCH, there's a chance the user is
4316 // just missing to include the search path to the directory containing
4317 // the modulemap.
4318 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4319 Diag(diag::note_imported_by_pch_module_not_found)
4320 << llvm::sys::path::parent_path(F.ModuleMapPath);
4321 }
4322 }
4323 return OutOfDate;
4324 }
4325
4326 assert(M && M->Name == F.ModuleName && "found module with different name");
4327
4328 // Check the primary module map file.
4329 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4330 if (!StoredModMap || *StoredModMap != ModMap) {
4331 assert(ModMap && "found module is missing module map file");
4332 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4333 "top-level import should be verified");
4334 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4335 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4336 Diag(diag::err_imported_module_modmap_changed)
4337 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4338 << ModMap->getName() << F.ModuleMapPath << NotImported;
4339 return OutOfDate;
4340 }
4341
4342 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4343 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4344 // FIXME: we should use input files rather than storing names.
4345 std::string Filename = ReadPath(F, Record, Idx);
4346 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4347 if (!SF) {
4348 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4349 Error("could not find file '" + Filename +"' referenced by AST file");
4350 return OutOfDate;
4351 }
4352 AdditionalStoredMaps.insert(*SF);
4353 }
4354
4355 // Check any additional module map files (e.g. module.private.modulemap)
4356 // that are not in the pcm.
4357 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4358 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4359 // Remove files that match
4360 // Note: SmallPtrSet::erase is really remove
4361 if (!AdditionalStoredMaps.erase(ModMap)) {
4362 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4363 Diag(diag::err_module_different_modmap)
4364 << F.ModuleName << /*new*/0 << ModMap.getName();
4365 return OutOfDate;
4366 }
4367 }
4368 }
4369
4370 // Check any additional module map files that are in the pcm, but not
4371 // found in header search. Cases that match are already removed.
4372 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4373 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4374 Diag(diag::err_module_different_modmap)
4375 << F.ModuleName << /*not new*/1 << ModMap.getName();
4376 return OutOfDate;
4377 }
4378 }
4379
4380 if (Listener)
4381 Listener->ReadModuleMapFile(F.ModuleMapPath);
4382 return Success;
4383}
4384
4385/// Move the given method to the back of the global list of methods.
4387 // Find the entry for this selector in the method pool.
4388 SemaObjC::GlobalMethodPool::iterator Known =
4389 S.ObjC().MethodPool.find(Method->getSelector());
4390 if (Known == S.ObjC().MethodPool.end())
4391 return;
4392
4393 // Retrieve the appropriate method list.
4394 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4395 : Known->second.second;
4396 bool Found = false;
4397 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4398 if (!Found) {
4399 if (List->getMethod() == Method) {
4400 Found = true;
4401 } else {
4402 // Keep searching.
4403 continue;
4404 }
4405 }
4406
4407 if (List->getNext())
4408 List->setMethod(List->getNext()->getMethod());
4409 else
4410 List->setMethod(Method);
4411 }
4412}
4413
4415 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4416 for (Decl *D : Names) {
4417 bool wasHidden = !D->isUnconditionallyVisible();
4419
4420 if (wasHidden && SemaObj) {
4421 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4422 moveMethodToBackOfGlobalList(*SemaObj, Method);
4423 }
4424 }
4425 }
4426}
4427
4429 Module::NameVisibilityKind NameVisibility,
4430 SourceLocation ImportLoc) {
4433 Stack.push_back(Mod);
4434 while (!Stack.empty()) {
4435 Mod = Stack.pop_back_val();
4436
4437 if (NameVisibility <= Mod->NameVisibility) {
4438 // This module already has this level of visibility (or greater), so
4439 // there is nothing more to do.
4440 continue;
4441 }
4442
4443 if (Mod->isUnimportable()) {
4444 // Modules that aren't importable cannot be made visible.
4445 continue;
4446 }
4447
4448 // Update the module's name visibility.
4449 Mod->NameVisibility = NameVisibility;
4450
4451 // If we've already deserialized any names from this module,
4452 // mark them as visible.
4453 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4454 if (Hidden != HiddenNamesMap.end()) {
4455 auto HiddenNames = std::move(*Hidden);
4456 HiddenNamesMap.erase(Hidden);
4457 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4458 assert(!HiddenNamesMap.contains(Mod) &&
4459 "making names visible added hidden names");
4460 }
4461
4462 // Push any exported modules onto the stack to be marked as visible.
4464 Mod->getExportedModules(Exports);
4466 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4467 Module *Exported = *I;
4468 if (Visited.insert(Exported).second)
4469 Stack.push_back(Exported);
4470 }
4471 }
4472}
4473
4474/// We've merged the definition \p MergedDef into the existing definition
4475/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4476/// visible.
4478 NamedDecl *MergedDef) {
4479 if (!Def->isUnconditionallyVisible()) {
4480 // If MergedDef is visible or becomes visible, make the definition visible.
4481 if (MergedDef->isUnconditionallyVisible())
4483 else {
4484 getContext().mergeDefinitionIntoModule(
4485 Def, MergedDef->getImportedOwningModule(),
4486 /*NotifyListeners*/ false);
4487 PendingMergedDefinitionsToDeduplicate.insert(Def);
4488 }
4489 }
4490}
4491
4493 if (GlobalIndex)
4494 return false;
4495
4496 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4497 !PP.getLangOpts().Modules)
4498 return true;
4499
4500 // Try to load the global index.
4501 TriedLoadingGlobalIndex = true;
4502 StringRef ModuleCachePath
4503 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4504 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4505 GlobalModuleIndex::readIndex(ModuleCachePath);
4506 if (llvm::Error Err = std::move(Result.second)) {
4507 assert(!Result.first);
4508 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4509 return true;
4510 }
4511
4512 GlobalIndex.reset(Result.first);
4513 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4514 return false;
4515}
4516
4518 return PP.getLangOpts().Modules && UseGlobalIndex &&
4519 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4520}
4521
4522/// Given a cursor at the start of an AST file, scan ahead and drop the
4523/// cursor into the start of the given block ID, returning false on success and
4524/// true on failure.
4525static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4526 while (true) {
4527 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4528 if (!MaybeEntry) {
4529 // FIXME this drops errors on the floor.
4530 consumeError(MaybeEntry.takeError());
4531 return true;
4532 }
4533 llvm::BitstreamEntry Entry = MaybeEntry.get();
4534
4535 switch (Entry.Kind) {
4536 case llvm::BitstreamEntry::Error:
4537 case llvm::BitstreamEntry::EndBlock:
4538 return true;
4539
4540 case llvm::BitstreamEntry::Record:
4541 // Ignore top-level records.
4542 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4543 break;
4544 else {
4545 // FIXME this drops errors on the floor.
4546 consumeError(Skipped.takeError());
4547 return true;
4548 }
4549
4550 case llvm::BitstreamEntry::SubBlock:
4551 if (Entry.ID == BlockID) {
4552 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4553 // FIXME this drops the error on the floor.
4554 consumeError(std::move(Err));
4555 return true;
4556 }
4557 // Found it!
4558 return false;
4559 }
4560
4561 if (llvm::Error Err = Cursor.SkipBlock()) {
4562 // FIXME this drops the error on the floor.
4563 consumeError(std::move(Err));
4564 return true;
4565 }
4566 }
4567 }
4568}
4569
4571 SourceLocation ImportLoc,
4572 unsigned ClientLoadCapabilities,
4573 ModuleFile **NewLoadedModuleFile) {
4574 llvm::TimeTraceScope scope("ReadAST", FileName);
4575
4576 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4578 CurrentDeserializingModuleKind, Type);
4579
4580 // Defer any pending actions until we get to the end of reading the AST file.
4581 Deserializing AnASTFile(this);
4582
4583 // Bump the generation number.
4584 unsigned PreviousGeneration = 0;
4585 if (ContextObj)
4586 PreviousGeneration = incrementGeneration(*ContextObj);
4587
4588 unsigned NumModules = ModuleMgr.size();
4590 if (ASTReadResult ReadResult =
4591 ReadASTCore(FileName, Type, ImportLoc,
4592 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4593 ClientLoadCapabilities)) {
4594 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4595
4596 // If we find that any modules are unusable, the global index is going
4597 // to be out-of-date. Just remove it.
4598 GlobalIndex.reset();
4599 ModuleMgr.setGlobalIndex(nullptr);
4600 return ReadResult;
4601 }
4602
4603 if (NewLoadedModuleFile && !Loaded.empty())
4604 *NewLoadedModuleFile = Loaded.back().Mod;
4605
4606 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4607 // remove modules from this point. Various fields are updated during reading
4608 // the AST block and removing the modules would result in dangling pointers.
4609 // They are generally only incidentally dereferenced, ie. a binary search
4610 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4611 // be dereferenced but it wouldn't actually be used.
4612
4613 // Load the AST blocks of all of the modules that we loaded. We can still
4614 // hit errors parsing the ASTs at this point.
4615 for (ImportedModule &M : Loaded) {
4616 ModuleFile &F = *M.Mod;
4617 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4618
4619 // Read the AST block.
4620 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4621 Error(std::move(Err));
4622 return Failure;
4623 }
4624
4625 // The AST block should always have a definition for the main module.
4626 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4627 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4628 return Failure;
4629 }
4630
4631 // Read the extension blocks.
4633 if (llvm::Error Err = ReadExtensionBlock(F)) {
4634 Error(std::move(Err));
4635 return Failure;
4636 }
4637 }
4638
4639 // Once read, set the ModuleFile bit base offset and update the size in
4640 // bits of all files we've seen.
4641 F.GlobalBitOffset = TotalModulesSizeInBits;
4642 TotalModulesSizeInBits += F.SizeInBits;
4643 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4644 }
4645
4646 // Preload source locations and interesting indentifiers.
4647 for (ImportedModule &M : Loaded) {
4648 ModuleFile &F = *M.Mod;
4649
4650 // Map the original source file ID into the ID space of the current
4651 // compilation.
4653 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4654
4655 for (auto Offset : F.PreloadIdentifierOffsets) {
4656 const unsigned char *Data = F.IdentifierTableData + Offset;
4657
4658 ASTIdentifierLookupTrait Trait(*this, F);
4659 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4660 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4661
4662 IdentifierInfo *II;
4663 if (!PP.getLangOpts().CPlusPlus) {
4664 // Identifiers present in both the module file and the importing
4665 // instance are marked out-of-date so that they can be deserialized
4666 // on next use via ASTReader::updateOutOfDateIdentifier().
4667 // Identifiers present in the module file but not in the importing
4668 // instance are ignored for now, preventing growth of the identifier
4669 // table. They will be deserialized on first use via ASTReader::get().
4670 auto It = PP.getIdentifierTable().find(Key);
4671 if (It == PP.getIdentifierTable().end())
4672 continue;
4673 II = It->second;
4674 } else {
4675 // With C++ modules, not many identifiers are considered interesting.
4676 // All identifiers in the module file can be placed into the identifier
4677 // table of the importing instance and marked as out-of-date. This makes
4678 // ASTReader::get() a no-op, and deserialization will take place on
4679 // first/next use via ASTReader::updateOutOfDateIdentifier().
4680 II = &PP.getIdentifierTable().getOwn(Key);
4681 }
4682
4683 II->setOutOfDate(true);
4684
4685 // Mark this identifier as being from an AST file so that we can track
4686 // whether we need to serialize it.
4687 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
4688
4689 // Associate the ID with the identifier so that the writer can reuse it.
4690 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4691 SetIdentifierInfo(ID, II);
4692 }
4693 }
4694
4695 // Builtins and library builtins have already been initialized. Mark all
4696 // identifiers as out-of-date, so that they are deserialized on first use.
4697 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4698 for (auto &Id : PP.getIdentifierTable())
4699 Id.second->setOutOfDate(true);
4700
4701 // Mark selectors as out of date.
4702 for (const auto &Sel : SelectorGeneration)
4703 SelectorOutOfDate[Sel.first] = true;
4704
4705 // Setup the import locations and notify the module manager that we've
4706 // committed to these module files.
4707 for (ImportedModule &M : Loaded) {
4708 ModuleFile &F = *M.Mod;
4709
4710 ModuleMgr.moduleFileAccepted(&F);
4711
4712 // Set the import location.
4713 F.DirectImportLoc = ImportLoc;
4714 // FIXME: We assume that locations from PCH / preamble do not need
4715 // any translation.
4716 if (!M.ImportedBy)
4717 F.ImportLoc = M.ImportLoc;
4718 else
4719 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4720 }
4721
4722 // Resolve any unresolved module exports.
4723 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4724 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4725 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4726 Module *ResolvedMod = getSubmodule(GlobalID);
4727
4728 switch (Unresolved.Kind) {
4729 case UnresolvedModuleRef::Conflict:
4730 if (ResolvedMod) {
4731 Module::Conflict Conflict;
4732 Conflict.Other = ResolvedMod;
4733 Conflict.Message = Unresolved.String.str();
4734 Unresolved.Mod->Conflicts.push_back(Conflict);
4735 }
4736 continue;
4737
4738 case UnresolvedModuleRef::Import:
4739 if (ResolvedMod)
4740 Unresolved.Mod->Imports.insert(ResolvedMod);
4741 continue;
4742
4743 case UnresolvedModuleRef::Affecting:
4744 if (ResolvedMod)
4745 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4746 continue;
4747
4748 case UnresolvedModuleRef::Export:
4749 if (ResolvedMod || Unresolved.IsWildcard)
4750 Unresolved.Mod->Exports.push_back(
4751 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4752 continue;
4753 }
4754 }
4755 UnresolvedModuleRefs.clear();
4756
4757 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4758 // Might be unnecessary as use declarations are only used to build the
4759 // module itself.
4760
4761 if (ContextObj)
4762 InitializeContext();
4763
4764 if (SemaObj)
4765 UpdateSema();
4766
4767 if (DeserializationListener)
4768 DeserializationListener->ReaderInitialized(this);
4769
4770 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4771 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4772 // If this AST file is a precompiled preamble, then set the
4773 // preamble file ID of the source manager to the file source file
4774 // from which the preamble was built.
4775 if (Type == MK_Preamble) {
4776 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4777 } else if (Type == MK_MainFile) {
4778 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4779 }
4780 }
4781
4782 // For any Objective-C class definitions we have already loaded, make sure
4783 // that we load any additional categories.
4784 if (ContextObj) {
4785 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4786 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4787 ObjCClassesLoaded[I], PreviousGeneration);
4788 }
4789 }
4790
4791 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4793 // Now we are certain that the module and all modules it depends on are
4794 // up-to-date. For implicitly-built module files, ensure the corresponding
4795 // timestamp files are up-to-date in this build session.
4796 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4797 ImportedModule &M = Loaded[I];
4798 if (M.Mod->Kind == MK_ImplicitModule &&
4799 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4800 updateModuleTimestamp(M.Mod->FileName);
4801 }
4802 }
4803
4804 return Success;
4805}
4806
4807static ASTFileSignature readASTFileSignature(StringRef PCH);
4808
4809/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4810static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4811 // FIXME checking magic headers is done in other places such as
4812 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4813 // always done the same. Unify it all with a helper.
4814 if (!Stream.canSkipToPos(4))
4815 return llvm::createStringError(std::errc::illegal_byte_sequence,
4816 "file too small to contain AST file magic");
4817 for (unsigned C : {'C', 'P', 'C', 'H'})
4818 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4819 if (Res.get() != C)
4820 return llvm::createStringError(
4821 std::errc::illegal_byte_sequence,
4822 "file doesn't start with AST file magic");
4823 } else
4824 return Res.takeError();
4825 return llvm::Error::success();
4826}
4827
4829 switch (Kind) {
4830 case MK_PCH:
4831 return 0; // PCH
4832 case MK_ImplicitModule:
4833 case MK_ExplicitModule:
4834 case MK_PrebuiltModule:
4835 return 1; // module
4836 case MK_MainFile:
4837 case MK_Preamble:
4838 return 2; // main source file
4839 }
4840 llvm_unreachable("unknown module kind");
4841}
4842
4844ASTReader::ReadASTCore(StringRef FileName,
4846 SourceLocation ImportLoc,
4847 ModuleFile *ImportedBy,
4849 off_t ExpectedSize, time_t ExpectedModTime,
4850 ASTFileSignature ExpectedSignature,
4851 unsigned ClientLoadCapabilities) {
4852 ModuleFile *M;
4853 std::string ErrorStr;
4855 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4856 getGeneration(), ExpectedSize, ExpectedModTime,
4857 ExpectedSignature, readASTFileSignature,
4858 M, ErrorStr);
4859
4860 switch (AddResult) {
4862 Diag(diag::remark_module_import)
4863 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4864 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4865 return Success;
4866
4868 // Load module file below.
4869 break;
4870
4872 // The module file was missing; if the client can handle that, return
4873 // it.
4874 if (ClientLoadCapabilities & ARR_Missing)
4875 return Missing;
4876
4877 // Otherwise, return an error.
4878 Diag(diag::err_ast_file_not_found)
4879 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4880 << ErrorStr;
4881 return Failure;
4882
4884 // We couldn't load the module file because it is out-of-date. If the
4885 // client can handle out-of-date, return it.
4886 if (ClientLoadCapabilities & ARR_OutOfDate)
4887 return OutOfDate;
4888
4889 // Otherwise, return an error.
4890 Diag(diag::err_ast_file_out_of_date)
4891 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4892 << ErrorStr;
4893 return Failure;
4894 }
4895
4896 assert(M && "Missing module file");
4897
4898 bool ShouldFinalizePCM = false;
4899 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4900 auto &MC = getModuleManager().getModuleCache();
4901 if (ShouldFinalizePCM)
4902 MC.finalizePCM(FileName);
4903 else
4904 MC.tryToDropPCM(FileName);
4905 });
4906 ModuleFile &F = *M;
4907 BitstreamCursor &Stream = F.Stream;
4908 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4909 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4910
4911 // Sniff for the signature.
4912 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4913 Diag(diag::err_ast_file_invalid)
4914 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4915 return Failure;
4916 }
4917
4918 // This is used for compatibility with older PCH formats.
4919 bool HaveReadControlBlock = false;
4920 while (true) {
4921 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4922 if (!MaybeEntry) {
4923 Error(MaybeEntry.takeError());
4924 return Failure;
4925 }
4926 llvm::BitstreamEntry Entry = MaybeEntry.get();
4927
4928 switch (Entry.Kind) {
4929 case llvm::BitstreamEntry::Error:
4930 case llvm::BitstreamEntry::Record:
4931 case llvm::BitstreamEntry::EndBlock:
4932 Error("invalid record at top-level of AST file");
4933 return Failure;
4934
4935 case llvm::BitstreamEntry::SubBlock:
4936 break;
4937 }
4938
4939 switch (Entry.ID) {
4940 case CONTROL_BLOCK_ID:
4941 HaveReadControlBlock = true;
4942 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4943 case Success:
4944 // Check that we didn't try to load a non-module AST file as a module.
4945 //
4946 // FIXME: Should we also perform the converse check? Loading a module as
4947 // a PCH file sort of works, but it's a bit wonky.
4949 Type == MK_PrebuiltModule) &&
4950 F.ModuleName.empty()) {
4951 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4952 if (Result != OutOfDate ||
4953 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4954 Diag(diag::err_module_file_not_module) << FileName;
4955 return Result;
4956 }
4957 break;
4958
4959 case Failure: return Failure;
4960 case Missing: return Missing;
4961 case OutOfDate: return OutOfDate;
4962 case VersionMismatch: return VersionMismatch;
4963 case ConfigurationMismatch: return ConfigurationMismatch;
4964 case HadErrors: return HadErrors;
4965 }
4966 break;
4967
4968 case AST_BLOCK_ID:
4969 if (!HaveReadControlBlock) {
4970 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4971 Diag(diag::err_ast_file_version_too_old)
4973 return VersionMismatch;
4974 }
4975
4976 // Record that we've loaded this module.
4977 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4978 ShouldFinalizePCM = true;
4979 return Success;
4980
4981 default:
4982 if (llvm::Error Err = Stream.SkipBlock()) {
4983 Error(std::move(Err));
4984 return Failure;
4985 }
4986 break;
4987 }
4988 }
4989
4990 llvm_unreachable("unexpected break; expected return");
4991}
4992
4994ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4995 unsigned ClientLoadCapabilities) {
4996 const HeaderSearchOptions &HSOpts =
4997 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4998 bool AllowCompatibleConfigurationMismatch =
5000 bool DisableValidation = shouldDisableValidationForFile(F);
5001
5002 ASTReadResult Result = readUnhashedControlBlockImpl(
5003 &F, F.Data, F.FileName, ClientLoadCapabilities,
5004 AllowCompatibleConfigurationMismatch, Listener.get(),
5005 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5006
5007 // If F was directly imported by another module, it's implicitly validated by
5008 // the importing module.
5009 if (DisableValidation || WasImportedBy ||
5010 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5011 return Success;
5012
5013 if (Result == Failure) {
5014 Error("malformed block record in AST file");
5015 return Failure;
5016 }
5017
5018 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5019 // If this module has already been finalized in the ModuleCache, we're stuck
5020 // with it; we can only load a single version of each module.
5021 //
5022 // This can happen when a module is imported in two contexts: in one, as a
5023 // user module; in another, as a system module (due to an import from
5024 // another module marked with the [system] flag). It usually indicates a
5025 // bug in the module map: this module should also be marked with [system].
5026 //
5027 // If -Wno-system-headers (the default), and the first import is as a
5028 // system module, then validation will fail during the as-user import,
5029 // since -Werror flags won't have been validated. However, it's reasonable
5030 // to treat this consistently as a system module.
5031 //
5032 // If -Wsystem-headers, the PCM on disk was built with
5033 // -Wno-system-headers, and the first import is as a user module, then
5034 // validation will fail during the as-system import since the PCM on disk
5035 // doesn't guarantee that -Werror was respected. However, the -Werror
5036 // flags were checked during the initial as-user import.
5037 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
5038 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5039 return Success;
5040 }
5041 }
5042
5043 return Result;
5044}
5045
5046ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5047 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5048 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5049 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5050 // Initialize a stream.
5051 BitstreamCursor Stream(StreamData);
5052
5053 // Sniff for the signature.
5054 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5055 // FIXME this drops the error on the floor.
5056 consumeError(std::move(Err));
5057 return Failure;
5058 }
5059
5060 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5062 return Failure;
5063
5064 // Read all of the records in the options block.
5065 RecordData Record;
5066 ASTReadResult Result = Success;
5067 while (true) {
5068 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5069 if (!MaybeEntry) {
5070 // FIXME this drops the error on the floor.
5071 consumeError(MaybeEntry.takeError());
5072 return Failure;
5073 }
5074 llvm::BitstreamEntry Entry = MaybeEntry.get();
5075
5076 switch (Entry.Kind) {
5077 case llvm::BitstreamEntry::Error:
5078 case llvm::BitstreamEntry::SubBlock:
5079 return Failure;
5080
5081 case llvm::BitstreamEntry::EndBlock:
5082 return Result;
5083
5084 case llvm::BitstreamEntry::Record:
5085 // The interesting case.
5086 break;
5087 }
5088
5089 // Read and process a record.
5090 Record.clear();
5091 StringRef Blob;
5092 Expected<unsigned> MaybeRecordType =
5093 Stream.readRecord(Entry.ID, Record, &Blob);
5094 if (!MaybeRecordType) {
5095 // FIXME this drops the error.
5096 return Failure;
5097 }
5098 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5099 case SIGNATURE:
5100 if (F) {
5101 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5103 "Dummy AST file signature not backpatched in ASTWriter.");
5104 }
5105 break;
5106 case AST_BLOCK_HASH:
5107 if (F) {
5108 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5110 "Dummy AST block hash not backpatched in ASTWriter.");
5111 }
5112 break;
5113 case DIAGNOSTIC_OPTIONS: {
5114 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5115 if (Listener && ValidateDiagnosticOptions &&
5116 !AllowCompatibleConfigurationMismatch &&
5117 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5118 Result = OutOfDate; // Don't return early. Read the signature.
5119 break;
5120 }
5121 case HEADER_SEARCH_PATHS: {
5122 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5123 if (Listener && !AllowCompatibleConfigurationMismatch &&
5124 ParseHeaderSearchPaths(Record, Complain, *Listener))
5125 Result = ConfigurationMismatch;
5126 break;
5127 }
5129 if (!F)
5130 break;
5131 if (F->PragmaDiagMappings.empty())
5132 F->PragmaDiagMappings.swap(Record);
5133 else
5134 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5135 Record.begin(), Record.end());
5136 break;
5138 if (F)
5139 F->SearchPathUsage = ReadBitVector(Record, Blob);
5140 break;
5141 case VFS_USAGE:
5142 if (F)
5143 F->VFSUsage = ReadBitVector(Record, Blob);
5144 break;
5145 }
5146 }
5147}
5148
5149/// Parse a record and blob containing module file extension metadata.
5152 StringRef Blob,
5153 ModuleFileExtensionMetadata &Metadata) {
5154 if (Record.size() < 4) return true;
5155
5156 Metadata.MajorVersion = Record[0];
5157 Metadata.MinorVersion = Record[1];
5158
5159 unsigned BlockNameLen = Record[2];
5160 unsigned UserInfoLen = Record[3];
5161
5162 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5163
5164 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5165 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5166 Blob.data() + BlockNameLen + UserInfoLen);
5167 return false;
5168}
5169
5170llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5171 BitstreamCursor &Stream = F.Stream;
5172
5173 RecordData Record;
5174 while (true) {
5175 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5176 if (!MaybeEntry)
5177 return MaybeEntry.takeError();
5178 llvm::BitstreamEntry Entry = MaybeEntry.get();
5179
5180 switch (Entry.Kind) {
5181 case llvm::BitstreamEntry::SubBlock:
5182 if (llvm::Error Err = Stream.SkipBlock())
5183 return Err;
5184 continue;
5185 case llvm::BitstreamEntry::EndBlock:
5186 return llvm::Error::success();
5187 case llvm::BitstreamEntry::Error:
5188 return llvm::createStringError(std::errc::illegal_byte_sequence,
5189 "malformed block record in AST file");
5190 case llvm::BitstreamEntry::Record:
5191 break;
5192 }
5193
5194 Record.clear();
5195 StringRef Blob;
5196 Expected<unsigned> MaybeRecCode =
5197 Stream.readRecord(Entry.ID, Record, &Blob);
5198 if (!MaybeRecCode)
5199 return MaybeRecCode.takeError();
5200 switch (MaybeRecCode.get()) {
5201 case EXTENSION_METADATA: {
5203 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5204 return llvm::createStringError(
5205 std::errc::illegal_byte_sequence,
5206 "malformed EXTENSION_METADATA in AST file");
5207
5208 // Find a module file extension with this block name.
5209 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5210 if (Known == ModuleFileExtensions.end()) break;
5211
5212 // Form a reader.
5213 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5214 F, Stream)) {
5215 F.ExtensionReaders.push_back(std::move(Reader));
5216 }
5217
5218 break;
5219 }
5220 }
5221 }
5222
5223 return llvm::Error::success();
5224}
5225
5227 assert(ContextObj && "no context to initialize");
5228 ASTContext &Context = *ContextObj;
5229
5230 // If there's a listener, notify them that we "read" the translation unit.
5231 if (DeserializationListener)
5232 DeserializationListener->DeclRead(
5234 Context.getTranslationUnitDecl());
5235
5236 // FIXME: Find a better way to deal with collisions between these
5237 // built-in types. Right now, we just ignore the problem.
5238
5239 // Load the special types.
5240 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5241 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5242 if (!Context.CFConstantStringTypeDecl)
5243 Context.setCFConstantStringType(GetType(String));
5244 }
5245
5246 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5247 QualType FileType = GetType(File);
5248 if (FileType.isNull()) {
5249 Error("FILE type is NULL");
5250 return;
5251 }
5252
5253 if (!Context.FILEDecl) {
5254 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5255 Context.setFILEDecl(Typedef->getDecl());
5256 else {
5257 const TagType *Tag = FileType->getAs<TagType>();
5258 if (!Tag) {
5259 Error("Invalid FILE type in AST file");
5260 return;
5261 }
5262 Context.setFILEDecl(Tag->getDecl());
5263 }
5264 }
5265 }
5266
5267 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5268 QualType Jmp_bufType = GetType(Jmp_buf);
5269 if (Jmp_bufType.isNull()) {
5270 Error("jmp_buf type is NULL");
5271 return;
5272 }
5273
5274 if (!Context.jmp_bufDecl) {
5275 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5276 Context.setjmp_bufDecl(Typedef->getDecl());
5277 else {
5278 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5279 if (!Tag) {
5280 Error("Invalid jmp_buf type in AST file");
5281 return;
5282 }
5283 Context.setjmp_bufDecl(Tag->getDecl());
5284 }
5285 }
5286 }
5287
5288 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5289 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5290 if (Sigjmp_bufType.isNull()) {
5291 Error("sigjmp_buf type is NULL");
5292 return;
5293 }
5294
5295 if (!Context.sigjmp_bufDecl) {
5296 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5297 Context.setsigjmp_bufDecl(Typedef->getDecl());
5298 else {
5299 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5300 assert(Tag && "Invalid sigjmp_buf type in AST file");
5301 Context.setsigjmp_bufDecl(Tag->getDecl());
5302 }
5303 }
5304 }
5305
5306 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5307 if (Context.ObjCIdRedefinitionType.isNull())
5308 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5309 }
5310
5311 if (TypeID ObjCClassRedef =
5313 if (Context.ObjCClassRedefinitionType.isNull())
5314 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5315 }
5316
5317 if (TypeID ObjCSelRedef =
5318 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5319 if (Context.ObjCSelRedefinitionType.isNull())
5320 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5321 }
5322
5323 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5324 QualType Ucontext_tType = GetType(Ucontext_t);
5325 if (Ucontext_tType.isNull()) {
5326 Error("ucontext_t type is NULL");
5327 return;
5328 }
5329
5330 if (!Context.ucontext_tDecl) {
5331 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5332 Context.setucontext_tDecl(Typedef->getDecl());
5333 else {
5334 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5335 assert(Tag && "Invalid ucontext_t type in AST file");
5336 Context.setucontext_tDecl(Tag->getDecl());
5337 }
5338 }
5339 }
5340 }
5341
5342 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5343
5344 // If there were any CUDA special declarations, deserialize them.
5345 if (!CUDASpecialDeclRefs.empty()) {
5346 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5348 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5349 }
5350
5351 // Re-export any modules that were imported by a non-module AST file.
5352 // FIXME: This does not make macro-only imports visible again.
5353 for (auto &Import : PendingImportedModules) {
5354 if (Module *Imported = getSubmodule(Import.ID)) {
5355 makeModuleVisible(Imported, Module::AllVisible,
5356 /*ImportLoc=*/Import.ImportLoc);
5357 if (Import.ImportLoc.isValid())
5358 PP.makeModuleVisible(Imported, Import.ImportLoc);
5359 // This updates visibility for Preprocessor only. For Sema, which can be
5360 // nullptr here, we do the same later, in UpdateSema().
5361 }
5362 }
5363
5364 // Hand off these modules to Sema.
5365 PendingImportedModulesSema.append(PendingImportedModules);
5366 PendingImportedModules.clear();
5367}
5368
5370 // Nothing to do for now.
5371}
5372
5373/// Reads and return the signature record from \p PCH's control block, or
5374/// else returns 0.
5376 BitstreamCursor Stream(PCH);
5377 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5378 // FIXME this drops the error on the floor.
5379 consumeError(std::move(Err));
5380 return ASTFileSignature();
5381 }
5382
5383 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5385 return ASTFileSignature();
5386
5387 // Scan for SIGNATURE inside the diagnostic options block.
5389 while (true) {
5391 Stream.advanceSkippingSubblocks();
5392 if (!MaybeEntry) {
5393 // FIXME this drops the error on the floor.
5394 consumeError(MaybeEntry.takeError());
5395 return ASTFileSignature();
5396 }
5397 llvm::BitstreamEntry Entry = MaybeEntry.get();
5398
5399 if (Entry.Kind != llvm::BitstreamEntry::Record)
5400 return ASTFileSignature();
5401
5402 Record.clear();
5403 StringRef Blob;
5404 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5405 if (!MaybeRecord) {
5406 // FIXME this drops the error on the floor.
5407 consumeError(MaybeRecord.takeError());
5408 return ASTFileSignature();
5409 }
5410 if (SIGNATURE == MaybeRecord.get()) {
5411 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5412 assert(Signature != ASTFileSignature::createDummy() &&
5413 "Dummy AST file signature not backpatched in ASTWriter.");
5414 return Signature;
5415 }
5416 }
5417}
5418
5419/// Retrieve the name of the original source file name
5420/// directly from the AST file, without actually loading the AST
5421/// file.
5423 const std::string &ASTFileName, FileManager &FileMgr,
5424 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5425 // Open the AST file.
5426 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5427 /*RequiresNullTerminator=*/false,
5428 /*MaybeLimit=*/std::nullopt,
5429 /*IsText=*/false);
5430 if (!Buffer) {
5431 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5432 << ASTFileName << Buffer.getError().message();
5433 return std::string();
5434 }
5435
5436 // Initialize the stream
5437 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5438
5439 // Sniff for the signature.
5440 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5441 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5442 return std::string();
5443 }
5444
5445 // Scan for the CONTROL_BLOCK_ID block.
5446 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5447 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5448 return std::string();
5449 }
5450
5451 // Scan for ORIGINAL_FILE inside the control block.
5453 while (true) {
5455 Stream.advanceSkippingSubblocks();
5456 if (!MaybeEntry) {
5457 // FIXME this drops errors on the floor.
5458 consumeError(MaybeEntry.takeError());
5459 return std::string();
5460 }
5461 llvm::BitstreamEntry Entry = MaybeEntry.get();
5462
5463 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5464 return std::string();
5465
5466 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5467 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5468 return std::string();
5469 }
5470
5471 Record.clear();
5472 StringRef Blob;
5473 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5474 if (!MaybeRecord) {
5475 // FIXME this drops the errors on the floor.
5476 consumeError(MaybeRecord.takeError());
5477 return std::string();
5478 }
5479 if (ORIGINAL_FILE == MaybeRecord.get())
5480 return Blob.str();
5481 }
5482}
5483
5484namespace {
5485
5486 class SimplePCHValidator : public ASTReaderListener {
5487 const LangOptions &ExistingLangOpts;
5488 const TargetOptions &ExistingTargetOpts;
5489 const PreprocessorOptions &ExistingPPOpts;
5490 std::string ExistingModuleCachePath;
5491 FileManager &FileMgr;
5492 bool StrictOptionMatches;
5493
5494 public:
5495 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5496 const TargetOptions &ExistingTargetOpts,
5497 const PreprocessorOptions &ExistingPPOpts,
5498 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5499 bool StrictOptionMatches)
5500 : ExistingLangOpts(ExistingLangOpts),
5501 ExistingTargetOpts(ExistingTargetOpts),
5502 ExistingPPOpts(ExistingPPOpts),
5503 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5504 StrictOptionMatches(StrictOptionMatches) {}
5505
5506 bool ReadLanguageOptions(const LangOptions &LangOpts,
5507 StringRef ModuleFilename, bool Complain,
5508 bool AllowCompatibleDifferences) override {
5509 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5510 nullptr, AllowCompatibleDifferences);
5511 }
5512
5513 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5514 StringRef ModuleFilename, bool Complain,
5515 bool AllowCompatibleDifferences) override {
5516 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5517 nullptr, AllowCompatibleDifferences);
5518 }
5519
5520 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5521 StringRef ModuleFilename,
5522 StringRef SpecificModuleCachePath,
5523 bool Complain) override {
5525 SpecificModuleCachePath,
5526 ExistingModuleCachePath, ModuleFilename,
5527 nullptr, ExistingLangOpts, ExistingPPOpts);
5528 }
5529
5530 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5531 StringRef ModuleFilename, bool ReadMacros,
5532 bool Complain,
5533 std::string &SuggestedPredefines) override {
5535 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5536 FileMgr, SuggestedPredefines, ExistingLangOpts,
5537 StrictOptionMatches ? OptionValidateStrictMatches
5539 }
5540 };
5541
5542} // namespace
5543
5545 StringRef Filename, FileManager &FileMgr,
5546 const InMemoryModuleCache &ModuleCache,
5547 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5548 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5549 unsigned ClientLoadCapabilities) {
5550 // Open the AST file.
5551 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5552 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5553 if (!Buffer) {
5554 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5555 // read again later, but we do not have the context here to determine if it
5556 // is safe to change the result of InMemoryModuleCache::getPCMState().
5557
5558 // FIXME: This allows use of the VFS; we do not allow use of the
5559 // VFS when actually loading a module.
5560 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5561 if (!BufferOrErr)
5562 return true;
5563 OwnedBuffer = std::move(*BufferOrErr);
5564 Buffer = OwnedBuffer.get();
5565 }
5566
5567 // Initialize the stream
5568 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5569 BitstreamCursor Stream(Bytes);
5570
5571 // Sniff for the signature.
5572 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5573 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5574 return true;
5575 }
5576
5577 // Scan for the CONTROL_BLOCK_ID block.
5579 return true;
5580
5581 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5582 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5583 bool NeedsImports = Listener.needsImportVisitation();
5584 BitstreamCursor InputFilesCursor;
5585 uint64_t InputFilesOffsetBase = 0;
5586
5588 std::string ModuleDir;
5589 bool DoneWithControlBlock = false;
5590 SmallString<0> PathBuf;
5591 PathBuf.reserve(256);
5592 while (!DoneWithControlBlock) {
5593 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5594 if (!MaybeEntry) {
5595 // FIXME this drops the error on the floor.
5596 consumeError(MaybeEntry.takeError());
5597 return true;
5598 }
5599 llvm::BitstreamEntry Entry = MaybeEntry.get();
5600
5601 switch (Entry.Kind) {
5602 case llvm::BitstreamEntry::SubBlock: {
5603 switch (Entry.ID) {
5604 case OPTIONS_BLOCK_ID: {
5605 std::string IgnoredSuggestedPredefines;
5606 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5607 /*AllowCompatibleConfigurationMismatch*/ false,
5608 Listener, IgnoredSuggestedPredefines) != Success)
5609 return true;
5610 break;
5611 }
5612
5614 InputFilesCursor = Stream;
5615 if (llvm::Error Err = Stream.SkipBlock()) {
5616 // FIXME this drops the error on the floor.
5617 consumeError(std::move(Err));
5618 return true;
5619 }
5620 if (NeedsInputFiles &&
5621 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5622 return true;
5623 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5624 break;
5625
5626 default:
5627 if (llvm::Error Err = Stream.SkipBlock()) {
5628 // FIXME this drops the error on the floor.
5629 consumeError(std::move(Err));
5630 return true;
5631 }
5632 break;
5633 }
5634
5635 continue;
5636 }
5637
5638 case llvm::BitstreamEntry::EndBlock:
5639 DoneWithControlBlock = true;
5640 break;
5641
5642 case llvm::BitstreamEntry::Error:
5643 return true;
5644
5645 case llvm::BitstreamEntry::Record:
5646 break;
5647 }
5648
5649 if (DoneWithControlBlock) break;
5650
5651 Record.clear();
5652 StringRef Blob;
5653 Expected<unsigned> MaybeRecCode =
5654 Stream.readRecord(Entry.ID, Record, &Blob);
5655 if (!MaybeRecCode) {
5656 // FIXME this drops the error.
5657 return Failure;
5658 }
5659 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5660 case METADATA:
5661 if (Record[0] != VERSION_MAJOR)
5662 return true;
5663 if (Listener.ReadFullVersionInformation(Blob))
5664 return true;
5665 break;
5666 case MODULE_NAME:
5667 Listener.ReadModuleName(Blob);
5668 break;
5669 case MODULE_DIRECTORY:
5670 ModuleDir = std::string(Blob);
5671 break;
5672 case MODULE_MAP_FILE: {
5673 unsigned Idx = 0;
5674 std::string PathStr = ReadString(Record, Idx);
5675 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
5676 Listener.ReadModuleMapFile(*Path);
5677 break;
5678 }
5679 case INPUT_FILE_OFFSETS: {
5680 if (!NeedsInputFiles)
5681 break;
5682
5683 unsigned NumInputFiles = Record[0];
5684 unsigned NumUserFiles = Record[1];
5685 const llvm::support::unaligned_uint64_t *InputFileOffs =
5686 (const llvm::support::unaligned_uint64_t *)Blob.data();
5687 for (unsigned I = 0; I != NumInputFiles; ++I) {
5688 // Go find this input file.
5689 bool isSystemFile = I >= NumUserFiles;
5690
5691 if (isSystemFile && !NeedsSystemInputFiles)
5692 break; // the rest are system input files
5693
5694 BitstreamCursor &Cursor = InputFilesCursor;
5695 SavedStreamPosition SavedPosition(Cursor);
5696 if (llvm::Error Err =
5697 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5698 // FIXME this drops errors on the floor.
5699 consumeError(std::move(Err));
5700 }
5701
5702 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5703 if (!MaybeCode) {
5704 // FIXME this drops errors on the floor.
5705 consumeError(MaybeCode.takeError());
5706 }
5707 unsigned Code = MaybeCode.get();
5708
5710 StringRef Blob;
5711 bool shouldContinue = false;
5712 Expected<unsigned> MaybeRecordType =
5713 Cursor.readRecord(Code, Record, &Blob);
5714 if (!MaybeRecordType) {
5715 // FIXME this drops errors on the floor.
5716 consumeError(MaybeRecordType.takeError());
5717 }
5718 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5719 case INPUT_FILE_HASH:
5720 break;
5721 case INPUT_FILE:
5722 bool Overridden = static_cast<bool>(Record[3]);
5723 auto Filename = ResolveImportedPath(PathBuf, Blob, ModuleDir);
5724 shouldContinue = Listener.visitInputFile(
5725 *Filename, isSystemFile, Overridden, /*IsExplicitModule=*/false);
5726 break;
5727 }
5728 if (!shouldContinue)
5729 break;
5730 }
5731 break;
5732 }
5733
5734 case IMPORT: {
5735 if (!NeedsImports)
5736 break;
5737
5738 unsigned Idx = 0;
5739 // Read information about the AST file.
5740
5741 // Skip Kind
5742 Idx++;
5743
5744 // Skip ImportLoc
5745 Idx++;
5746
5747 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
5748
5749 bool IsStandardCXXModule = Record[Idx++];
5750
5751 // In C++20 Modules, we don't record the path to imported
5752 // modules in the BMI files.
5753 if (IsStandardCXXModule) {
5754 Listener.visitImport(ModuleName, /*Filename=*/"");
5755 continue;
5756 }
5757
5758 // Skip Size and ModTime.
5759 Idx += 1 + 1;
5760 // Skip signature.
5761 Blob = Blob.substr(ASTFileSignature::size);
5762
5763 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
5764 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
5765 Listener.visitImport(ModuleName, *Filename);
5766 break;
5767 }
5768
5769 default:
5770 // No other validation to perform.
5771 break;
5772 }
5773 }
5774
5775 // Look for module file extension blocks, if requested.
5776 if (FindModuleFileExtensions) {
5777 BitstreamCursor SavedStream = Stream;
5778 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5779 bool DoneWithExtensionBlock = false;
5780 while (!DoneWithExtensionBlock) {
5781 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5782 if (!MaybeEntry) {
5783 // FIXME this drops the error.
5784 return true;
5785 }
5786 llvm::BitstreamEntry Entry = MaybeEntry.get();
5787
5788 switch (Entry.Kind) {
5789 case llvm::BitstreamEntry::SubBlock:
5790 if (llvm::Error Err = Stream.SkipBlock()) {
5791 // FIXME this drops the error on the floor.
5792 consumeError(std::move(Err));
5793 return true;
5794 }
5795 continue;
5796
5797 case llvm::BitstreamEntry::EndBlock:
5798 DoneWithExtensionBlock = true;
5799 continue;
5800
5801 case llvm::BitstreamEntry::Error:
5802 return true;
5803
5804 case llvm::BitstreamEntry::Record:
5805 break;
5806 }
5807
5808 Record.clear();
5809 StringRef Blob;
5810 Expected<unsigned> MaybeRecCode =
5811 Stream.readRecord(Entry.ID, Record, &Blob);
5812 if (!MaybeRecCode) {
5813 // FIXME this drops the error.
5814 return true;
5815 }
5816 switch (MaybeRecCode.get()) {
5817 case EXTENSION_METADATA: {
5819 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5820 return true;
5821
5822 Listener.readModuleFileExtension(Metadata);
5823 break;
5824 }
5825 }
5826 }
5827 }
5828 Stream = SavedStream;
5829 }
5830
5831 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5832 if (readUnhashedControlBlockImpl(
5833 nullptr, Bytes, Filename, ClientLoadCapabilities,
5834 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5835 ValidateDiagnosticOptions) != Success)
5836 return true;
5837
5838 return false;
5839}
5840
5842 const InMemoryModuleCache &ModuleCache,
5843 const PCHContainerReader &PCHContainerRdr,
5844 const LangOptions &LangOpts,
5845 const TargetOptions &TargetOpts,
5846 const PreprocessorOptions &PPOpts,
5847 StringRef ExistingModuleCachePath,
5848 bool RequireStrictOptionMatches) {
5849 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5850 ExistingModuleCachePath, FileMgr,
5851 RequireStrictOptionMatches);
5852 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5853 PCHContainerRdr,
5854 /*FindModuleFileExtensions=*/false, validator,
5855 /*ValidateDiagnosticOptions=*/true);
5856}
5857
5858llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5859 unsigned ClientLoadCapabilities) {
5860 // Enter the submodule block.
5861 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5862 return Err;
5863
5864 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5865 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
5866 // If we don't know the top-level module, there's no point in doing qualified
5867 // lookup of its submodules; it won't find anything anywhere within this tree.
5868 // Let's skip that and avoid some string lookups.
5869 auto CreateModule = !KnowsTopLevelModule
5872
5873 bool First = true;
5874 Module *CurrentModule = nullptr;
5875 RecordData Record;
5876 while (true) {
5878 F.Stream.advanceSkippingSubblocks();
5879 if (!MaybeEntry)
5880 return MaybeEntry.takeError();
5881 llvm::BitstreamEntry Entry = MaybeEntry.get();
5882
5883 switch (Entry.Kind) {
5884 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5885 case llvm::BitstreamEntry::Error:
5886 return llvm::createStringError(std::errc::illegal_byte_sequence,
5887 "malformed block record in AST file");
5888 case llvm::BitstreamEntry::EndBlock:
5889 return llvm::Error::success();
5890 case llvm::BitstreamEntry::Record:
5891 // The interesting case.
5892 break;
5893 }
5894
5895 // Read a record.
5896 StringRef Blob;
5897 Record.clear();
5898 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5899 if (!MaybeKind)
5900 return MaybeKind.takeError();
5901 unsigned Kind = MaybeKind.get();
5902
5903 if ((Kind == SUBMODULE_METADATA) != First)
5904 return llvm::createStringError(
5905 std::errc::illegal_byte_sequence,
5906 "submodule metadata record should be at beginning of block");
5907 First = false;
5908
5909 // Submodule information is only valid if we have a current module.
5910 // FIXME: Should we error on these cases?
5911 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5912 Kind != SUBMODULE_DEFINITION)
5913 continue;
5914
5915 switch (Kind) {
5916 default: // Default behavior: ignore.
5917 break;
5918
5919 case SUBMODULE_DEFINITION: {
5920 if (Record.size() < 13)
5921 return llvm::createStringError(std::errc::illegal_byte_sequence,
5922 "malformed module definition");
5923
5924 StringRef Name = Blob;
5925 unsigned Idx = 0;
5926 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5927 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5929 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5930 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
5931 bool IsFramework = Record[Idx++];
5932 bool IsExplicit = Record[Idx++];
5933 bool IsSystem = Record[Idx++];
5934 bool IsExternC = Record[Idx++];
5935 bool InferSubmodules = Record[Idx++];
5936 bool InferExplicitSubmodules = Record[Idx++];
5937 bool InferExportWildcard = Record[Idx++];
5938 bool ConfigMacrosExhaustive = Record[Idx++];
5939 bool ModuleMapIsPrivate = Record[Idx++];
5940 bool NamedModuleHasInit = Record[Idx++];
5941
5942 Module *ParentModule = nullptr;
5943 if (Parent)
5944 ParentModule = getSubmodule(Parent);
5945
5946 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
5947 IsFramework, IsExplicit);
5948
5949 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5950 if (GlobalIndex >= SubmodulesLoaded.size() ||
5951 SubmodulesLoaded[GlobalIndex])
5952 return llvm::createStringError(std::errc::invalid_argument,
5953 "too many submodules");
5954
5955 if (!ParentModule) {
5956 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5957 // Don't emit module relocation error if we have -fno-validate-pch
5958 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5960 CurFile != F.File) {
5961 auto ConflictError =
5962 PartialDiagnostic(diag::err_module_file_conflict,
5963 ContextObj->DiagAllocator)
5964 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5965 << F.File.getName();
5966 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5967 }
5968 }
5969
5970 F.DidReadTopLevelSubmodule = true;
5971 CurrentModule->setASTFile(F.File);
5972 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5973 }
5974
5975 CurrentModule->Kind = Kind;
5976 // Note that we may be rewriting an existing location and it is important
5977 // to keep doing that. In particular, we would like to prefer a
5978 // `DefinitionLoc` loaded from the module file instead of the location
5979 // created in the current source manager, because it allows the new
5980 // location to be marked as "unaffecting" when writing and avoid creating
5981 // duplicate locations for the same module map file.
5982 CurrentModule->DefinitionLoc = DefinitionLoc;
5983 CurrentModule->Signature = F.Signature;
5984 CurrentModule->IsFromModuleFile = true;
5985 if (InferredAllowedBy.isValid())
5986 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
5987 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5988 CurrentModule->IsExternC = IsExternC;
5989 CurrentModule->InferSubmodules = InferSubmodules;
5990 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5991 CurrentModule->InferExportWildcard = InferExportWildcard;
5992 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5993 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5994 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5995 if (DeserializationListener)
5996 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5997
5998 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5999
6000 // Clear out data that will be replaced by what is in the module file.
6001 CurrentModule->LinkLibraries.clear();
6002 CurrentModule->ConfigMacros.clear();
6003 CurrentModule->UnresolvedConflicts.clear();
6004 CurrentModule->Conflicts.clear();
6005
6006 // The module is available unless it's missing a requirement; relevant
6007 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6008 // Missing headers that were present when the module was built do not
6009 // make it unavailable -- if we got this far, this must be an explicitly
6010 // imported module file.
6011 CurrentModule->Requirements.clear();
6012 CurrentModule->MissingHeaders.clear();
6013 CurrentModule->IsUnimportable =
6014 ParentModule && ParentModule->IsUnimportable;
6015 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6016 break;
6017 }
6018
6020 // FIXME: This doesn't work for framework modules as `Filename` is the
6021 // name as written in the module file and does not include
6022 // `Headers/`, so this path will never exist.
6023 auto Filename = ResolveImportedPath(PathBuf, Blob, F);
6024 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(*Filename)) {
6025 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6026 // FIXME: NameAsWritten
6027 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
6028 }
6029 // Note that it's too late at this point to return out of date if the
6030 // name from the PCM doesn't match up with the one in the module map,
6031 // but also quite unlikely since we will have already checked the
6032 // modification time and size of the module map file itself.
6033 }
6034 break;
6035 }
6036
6037 case SUBMODULE_HEADER:
6040 // We lazily associate headers with their modules via the HeaderInfo table.
6041 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6042 // of complete filenames or remove it entirely.
6043 break;
6044
6047 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6048 // them here.
6049 break;
6050
6051 case SUBMODULE_TOPHEADER: {
6052 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6053 CurrentModule->addTopHeaderFilename(*HeaderName);
6054 break;
6055 }
6056
6058 // See comments in SUBMODULE_UMBRELLA_HEADER
6059 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6060 if (auto Umbrella =
6061 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6062 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6063 // FIXME: NameAsWritten
6064 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6065 }
6066 }
6067 break;
6068 }
6069
6070 case SUBMODULE_METADATA: {
6071 F.BaseSubmoduleID = getTotalNumSubmodules();
6073 unsigned LocalBaseSubmoduleID = Record[1];
6074 if (F.LocalNumSubmodules > 0) {
6075 // Introduce the global -> local mapping for submodules within this
6076 // module.
6077 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6078
6079 // Introduce the local -> global mapping for submodules within this
6080 // module.
6082 std::make_pair(LocalBaseSubmoduleID,
6083 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6084
6085 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6086 }
6087 break;
6088 }
6089
6090 case SUBMODULE_IMPORTS:
6091 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6092 UnresolvedModuleRef Unresolved;
6093 Unresolved.File = &F;
6094 Unresolved.Mod = CurrentModule;
6095 Unresolved.ID = Record[Idx];
6096 Unresolved.Kind = UnresolvedModuleRef::Import;
6097 Unresolved.IsWildcard = false;
6098 UnresolvedModuleRefs.push_back(Unresolved);
6099 }
6100 break;
6101
6103 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6104 UnresolvedModuleRef Unresolved;
6105 Unresolved.File = &F;
6106 Unresolved.Mod = CurrentModule;
6107 Unresolved.ID = Record[Idx];
6108 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6109 Unresolved.IsWildcard = false;
6110 UnresolvedModuleRefs.push_back(Unresolved);
6111 }
6112 break;
6113
6114 case SUBMODULE_EXPORTS:
6115 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6116 UnresolvedModuleRef Unresolved;
6117 Unresolved.File = &F;
6118 Unresolved.Mod = CurrentModule;
6119 Unresolved.ID = Record[Idx];
6120 Unresolved.Kind = UnresolvedModuleRef::Export;
6121 Unresolved.IsWildcard = Record[Idx + 1];
6122 UnresolvedModuleRefs.push_back(Unresolved);
6123 }
6124
6125 // Once we've loaded the set of exports, there's no reason to keep
6126 // the parsed, unresolved exports around.
6127 CurrentModule->UnresolvedExports.clear();
6128 break;
6129
6130 case SUBMODULE_REQUIRES:
6131 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6132 PP.getTargetInfo());
6133 break;
6134
6136 ModMap.resolveLinkAsDependencies(CurrentModule);
6137 CurrentModule->LinkLibraries.push_back(
6138 Module::LinkLibrary(std::string(Blob), Record[0]));
6139 break;
6140
6142 CurrentModule->ConfigMacros.push_back(Blob.str());
6143 break;
6144
6145 case SUBMODULE_CONFLICT: {
6146 UnresolvedModuleRef Unresolved;
6147 Unresolved.File = &F;
6148 Unresolved.Mod = CurrentModule;
6149 Unresolved.ID = Record[0];
6150 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6151 Unresolved.IsWildcard = false;
6152 Unresolved.String = Blob;
6153 UnresolvedModuleRefs.push_back(Unresolved);
6154 break;
6155 }
6156
6158 if (!ContextObj)
6159 break;
6161 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6162 Inits.push_back(ReadDeclID(F, Record, I));
6163 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6164 break;
6165 }
6166
6168 CurrentModule->ExportAsModule = Blob.str();
6169 ModMap.addLinkAsDependency(CurrentModule);
6170 break;
6171 }
6172 }
6173}
6174
6175/// Parse the record that corresponds to a LangOptions data
6176/// structure.
6177///
6178/// This routine parses the language options from the AST file and then gives
6179/// them to the AST listener if one is set.
6180///
6181/// \returns true if the listener deems the file unacceptable, false otherwise.
6182bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6183 StringRef ModuleFilename, bool Complain,
6184 ASTReaderListener &Listener,
6185 bool AllowCompatibleDifferences) {
6186 LangOptions LangOpts;
6187 unsigned Idx = 0;
6188#define LANGOPT(Name, Bits, Default, Description) \
6189 LangOpts.Name = Record[Idx++];
6190#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6191 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6192#include "clang/Basic/LangOptions.def"
6193#define SANITIZER(NAME, ID) \
6194 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6195#include "clang/Basic/Sanitizers.def"
6196
6197 for (unsigned N = Record[Idx++]; N; --N)
6198 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6199
6200 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6201 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6202 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6203
6204 LangOpts.CurrentModule = ReadString(Record, Idx);
6205
6206 // Comment options.
6207 for (unsigned N = Record[Idx++]; N; --N) {
6208 LangOpts.CommentOpts.BlockCommandNames.push_back(
6209 ReadString(Record, Idx));
6210 }
6211 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6212
6213 // OpenMP offloading options.
6214 for (unsigned N = Record[Idx++]; N; --N) {
6215 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6216 }
6217
6218 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6219
6220 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6221 AllowCompatibleDifferences);
6222}
6223
6224bool ASTReader::ParseTargetOptions(const RecordData &Record,
6225 StringRef ModuleFilename, bool Complain,
6226 ASTReaderListener &Listener,
6227 bool AllowCompatibleDifferences) {
6228 unsigned Idx = 0;
6229 TargetOptions TargetOpts;
6230 TargetOpts.Triple = ReadString(Record, Idx);
6231 TargetOpts.CPU = ReadString(Record, Idx);
6232 TargetOpts.TuneCPU = ReadString(Record, Idx);
6233 TargetOpts.ABI = ReadString(Record, Idx);
6234 for (unsigned N = Record[Idx++]; N; --N) {
6235 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6236 }
6237 for (unsigned N = Record[Idx++]; N; --N) {
6238 TargetOpts.Features.push_back(ReadString(Record, Idx));
6239 }
6240
6241 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6242 AllowCompatibleDifferences);
6243}
6244
6245bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6246 StringRef ModuleFilename, bool Complain,
6247 ASTReaderListener &Listener) {
6249 unsigned Idx = 0;
6250#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6251#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6252 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6253#include "clang/Basic/DiagnosticOptions.def"
6254
6255 for (unsigned N = Record[Idx++]; N; --N)
6256 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6257 for (unsigned N = Record[Idx++]; N; --N)
6258 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6259
6260 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6261}
6262
6263bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6264 ASTReaderListener &Listener) {
6265 FileSystemOptions FSOpts;
6266 unsigned Idx = 0;
6267 FSOpts.WorkingDir = ReadString(Record, Idx);
6268 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6269}
6270
6271bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6272 StringRef ModuleFilename,
6273 bool Complain,
6274 ASTReaderListener &Listener) {
6275 HeaderSearchOptions HSOpts;
6276 unsigned Idx = 0;
6277 HSOpts.Sysroot = ReadString(Record, Idx);
6278
6279 HSOpts.ResourceDir = ReadString(Record, Idx);
6280 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6281 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6282 HSOpts.DisableModuleHash = Record[Idx++];
6283 HSOpts.ImplicitModuleMaps = Record[Idx++];
6284 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6285 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6286 HSOpts.UseBuiltinIncludes = Record[Idx++];
6287 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6288 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6289 HSOpts.UseLibcxx = Record[Idx++];
6290 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6291
6292 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6293 SpecificModuleCachePath, Complain);
6294}
6295
6296bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6297 ASTReaderListener &Listener) {
6298 HeaderSearchOptions HSOpts;
6299 unsigned Idx = 0;
6300
6301 // Include entries.
6302 for (unsigned N = Record[Idx++]; N; --N) {
6303 std::string Path = ReadString(Record, Idx);
6305 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6306 bool IsFramework = Record[Idx++];
6307 bool IgnoreSysRoot = Record[Idx++];
6308 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6309 IgnoreSysRoot);
6310 }
6311
6312 // System header prefixes.
6313 for (unsigned N = Record[Idx++]; N; --N) {
6314 std::string Prefix = ReadString(Record, Idx);
6315 bool IsSystemHeader = Record[Idx++];
6316 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6317 }
6318
6319 // VFS overlay files.
6320 for (unsigned N = Record[Idx++]; N; --N) {
6321 std::string VFSOverlayFile = ReadString(Record, Idx);
6322 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6323 }
6324
6325 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6326}
6327
6328bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6329 StringRef ModuleFilename,
6330 bool Complain,
6331 ASTReaderListener &Listener,
6332 std::string &SuggestedPredefines) {
6333 PreprocessorOptions PPOpts;
6334 unsigned Idx = 0;
6335
6336 // Macro definitions/undefs
6337 bool ReadMacros = Record[Idx++];
6338 if (ReadMacros) {
6339 for (unsigned N = Record[Idx++]; N; --N) {
6340 std::string Macro = ReadString(Record, Idx);
6341 bool IsUndef = Record[Idx++];
6342 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6343 }
6344 }
6345
6346 // Includes
6347 for (unsigned N = Record[Idx++]; N; --N) {
6348 PPOpts.Includes.push_back(ReadString(Record, Idx));
6349 }
6350
6351 // Macro Includes
6352 for (unsigned N = Record[Idx++]; N; --N) {
6353 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6354 }
6355
6356 PPOpts.UsePredefines = Record[Idx++];
6357 PPOpts.DetailedRecord = Record[Idx++];
6358 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6360 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6361 SuggestedPredefines.clear();
6362 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6363 Complain, SuggestedPredefines);
6364}
6365
6366std::pair<ModuleFile *, unsigned>
6367ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6368 GlobalPreprocessedEntityMapType::iterator
6369 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6370 assert(I != GlobalPreprocessedEntityMap.end() &&
6371 "Corrupted global preprocessed entity map");
6372 ModuleFile *M = I->second;
6373 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6374 return std::make_pair(M, LocalIndex);
6375}
6376
6377llvm::iterator_range<PreprocessingRecord::iterator>
6378ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6379 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6380 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6382
6383 return llvm::make_range(PreprocessingRecord::iterator(),
6385}
6386
6387bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6388 unsigned int ClientLoadCapabilities) {
6389 return ClientLoadCapabilities & ARR_OutOfDate &&
6390 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6391}
6392
6393llvm::iterator_range<ASTReader::ModuleDeclIterator>
6395 return llvm::make_range(
6396 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6397 ModuleDeclIterator(this, &Mod,
6399}
6400
6402 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6403 assert(I != GlobalSkippedRangeMap.end() &&
6404 "Corrupted global skipped range map");
6405 ModuleFile *M = I->second;
6406 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6407 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6408 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6409 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6410 ReadSourceLocation(*M, RawRange.getEnd()));
6411 assert(Range.isValid());
6412 return Range;
6413}
6414
6416 PreprocessedEntityID PPID = Index+1;
6417 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6418 ModuleFile &M = *PPInfo.first;
6419 unsigned LocalIndex = PPInfo.second;
6420 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6421
6422 if (!PP.getPreprocessingRecord()) {
6423 Error("no preprocessing record");
6424 return nullptr;
6425 }
6426
6428 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6429 M.MacroOffsetsBase + PPOffs.getOffset())) {
6430 Error(std::move(Err));
6431 return nullptr;
6432 }
6433
6435 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6436 if (!MaybeEntry) {
6437 Error(MaybeEntry.takeError());
6438 return nullptr;
6439 }
6440 llvm::BitstreamEntry Entry = MaybeEntry.get();
6441
6442 if (Entry.Kind != llvm::BitstreamEntry::Record)
6443 return nullptr;
6444
6445 // Read the record.
6446 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6447 ReadSourceLocation(M, PPOffs.getEnd()));
6448 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6449 StringRef Blob;
6451 Expected<unsigned> MaybeRecType =
6452 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6453 if (!MaybeRecType) {
6454 Error(MaybeRecType.takeError());
6455 return nullptr;
6456 }
6457 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6458 case PPD_MACRO_EXPANSION: {
6459 bool isBuiltin = Record[0];
6460 IdentifierInfo *Name = nullptr;
6461 MacroDefinitionRecord *Def = nullptr;
6462 if (isBuiltin)
6463 Name = getLocalIdentifier(M, Record[1]);
6464 else {
6465 PreprocessedEntityID GlobalID =
6466 getGlobalPreprocessedEntityID(M, Record[1]);
6467 Def = cast<MacroDefinitionRecord>(
6468 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6469 }
6470
6471 MacroExpansion *ME;
6472 if (isBuiltin)
6473 ME = new (PPRec) MacroExpansion(Name, Range);
6474 else
6475 ME = new (PPRec) MacroExpansion(Def, Range);
6476
6477 return ME;
6478 }
6479
6480 case PPD_MACRO_DEFINITION: {
6481 // Decode the identifier info and then check again; if the macro is
6482 // still defined and associated with the identifier,
6483 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6484 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6485
6486 if (DeserializationListener)
6487 DeserializationListener->MacroDefinitionRead(PPID, MD);
6488
6489 return MD;
6490 }
6491
6493 const char *FullFileNameStart = Blob.data() + Record[0];
6494 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6496 if (!FullFileName.empty())
6497 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6498
6499 // FIXME: Stable encoding
6501 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6503 = new (PPRec) InclusionDirective(PPRec, Kind,
6504 StringRef(Blob.data(), Record[0]),
6505 Record[1], Record[3],
6506 File,
6507 Range);
6508 return ID;
6509 }
6510 }
6511
6512 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6513}
6514
6515/// Find the next module that contains entities and return the ID
6516/// of the first entry.
6517///
6518/// \param SLocMapI points at a chunk of a module that contains no
6519/// preprocessed entities or the entities it contains are not the ones we are
6520/// looking for.
6521PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6522 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6523 ++SLocMapI;
6524 for (GlobalSLocOffsetMapType::const_iterator
6525 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6526 ModuleFile &M = *SLocMapI->second;
6528 return M.BasePreprocessedEntityID;
6529 }
6530
6531 return getTotalNumPreprocessedEntities();
6532}
6533
6534namespace {
6535
6536struct PPEntityComp {
6537 const ASTReader &Reader;
6538 ModuleFile &M;
6539
6540 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6541
6542 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6543 SourceLocation LHS = getLoc(L);
6544 SourceLocation RHS = getLoc(R);
6545 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6546 }
6547
6548 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6549 SourceLocation LHS = getLoc(L);
6550 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6551 }
6552
6553 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6554 SourceLocation RHS = getLoc(R);
6555 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6556 }
6557
6558 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6559 return Reader.ReadSourceLocation(M, PPE.getBegin());
6560 }
6561};
6562
6563} // namespace
6564
6565PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6566 bool EndsAfter) const {
6567 if (SourceMgr.isLocalSourceLocation(Loc))
6568 return getTotalNumPreprocessedEntities();
6569
6570 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6571 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6572 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6573 "Corrupted global sloc offset map");
6574
6575 if (SLocMapI->second->NumPreprocessedEntities == 0)
6576 return findNextPreprocessedEntity(SLocMapI);
6577
6578 ModuleFile &M = *SLocMapI->second;
6579
6580 using pp_iterator = const PPEntityOffset *;
6581
6582 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6583 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6584
6585 size_t Count = M.NumPreprocessedEntities;
6586 size_t Half;
6587 pp_iterator First = pp_begin;
6588 pp_iterator PPI;
6589
6590 if (EndsAfter) {
6591 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6592 PPEntityComp(*this, M));
6593 } else {
6594 // Do a binary search manually instead of using std::lower_bound because
6595 // The end locations of entities may be unordered (when a macro expansion
6596 // is inside another macro argument), but for this case it is not important
6597 // whether we get the first macro expansion or its containing macro.
6598 while (Count > 0) {
6599 Half = Count / 2;
6600 PPI = First;
6601 std::advance(PPI, Half);
6602 if (SourceMgr.isBeforeInTranslationUnit(
6603 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6604 First = PPI;
6605 ++First;
6606 Count = Count - Half - 1;
6607 } else
6608 Count = Half;
6609 }
6610 }
6611
6612 if (PPI == pp_end)
6613 return findNextPreprocessedEntity(SLocMapI);
6614
6615 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6616}
6617
6618/// Returns a pair of [Begin, End) indices of preallocated
6619/// preprocessed entities that \arg Range encompasses.
6620std::pair<unsigned, unsigned>
6622 if (Range.isInvalid())
6623 return std::make_pair(0,0);
6624 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6625
6626 PreprocessedEntityID BeginID =
6627 findPreprocessedEntity(Range.getBegin(), false);
6628 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6629 return std::make_pair(BeginID, EndID);
6630}
6631
6632/// Optionally returns true or false if the preallocated preprocessed
6633/// entity with index \arg Index came from file \arg FID.
6634std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6635 FileID FID) {
6636 if (FID.isInvalid())
6637 return false;
6638
6639 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6640 ModuleFile &M = *PPInfo.first;
6641 unsigned LocalIndex = PPInfo.second;
6642 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6643
6644 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6645 if (Loc.isInvalid())
6646 return false;
6647
6648 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6649 return true;
6650 else
6651 return false;
6652}
6653
6654namespace {
6655
6656 /// Visitor used to search for information about a header file.
6657 class HeaderFileInfoVisitor {
6658 FileEntryRef FE;
6659 std::optional<HeaderFileInfo> HFI;
6660
6661 public:
6662 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6663
6664 bool operator()(ModuleFile &M) {
6667 if (!Table)
6668 return false;
6669
6670 // Look in the on-disk hash table for an entry for this file name.
6671 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6672 if (Pos == Table->end())
6673 return false;
6674
6675 HFI = *Pos;
6676 return true;
6677 }
6678
6679 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6680 };
6681
6682} // namespace
6683
6685 HeaderFileInfoVisitor Visitor(FE);
6686 ModuleMgr.visit(Visitor);
6687 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6688 return *HFI;
6689
6690 return HeaderFileInfo();
6691}
6692
6694 using DiagState = DiagnosticsEngine::DiagState;
6696
6697 for (ModuleFile &F : ModuleMgr) {
6698 unsigned Idx = 0;
6699 auto &Record = F.PragmaDiagMappings;
6700 if (Record.empty())
6701 continue;
6702
6703 DiagStates.clear();
6704
6705 auto ReadDiagState = [&](const DiagState &BasedOn,
6706 bool IncludeNonPragmaStates) {
6707 unsigned BackrefID = Record[Idx++];
6708 if (BackrefID != 0)
6709 return DiagStates[BackrefID - 1];
6710
6711 // A new DiagState was created here.
6712 Diag.DiagStates.push_back(BasedOn);
6713 DiagState *NewState = &Diag.DiagStates.back();
6714 DiagStates.push_back(NewState);
6715 unsigned Size = Record[Idx++];
6716 assert(Idx + Size * 2 <= Record.size() &&
6717 "Invalid data, not enough diag/map pairs");
6718 while (Size--) {
6719 unsigned DiagID = Record[Idx++];
6720 DiagnosticMapping NewMapping =
6722 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6723 continue;
6724
6725 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6726
6727 // If this mapping was specified as a warning but the severity was
6728 // upgraded due to diagnostic settings, simulate the current diagnostic
6729 // settings (and use a warning).
6730 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6732 NewMapping.setUpgradedFromWarning(false);
6733 }
6734
6735 Mapping = NewMapping;
6736 }
6737 return NewState;
6738 };
6739
6740 // Read the first state.
6741 DiagState *FirstState;
6742 if (F.Kind == MK_ImplicitModule) {
6743 // Implicitly-built modules are reused with different diagnostic
6744 // settings. Use the initial diagnostic state from Diag to simulate this
6745 // compilation's diagnostic settings.
6746 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6747 DiagStates.push_back(FirstState);
6748
6749 // Skip the initial diagnostic state from the serialized module.
6750 assert(Record[1] == 0 &&
6751 "Invalid data, unexpected backref in initial state");
6752 Idx = 3 + Record[2] * 2;
6753 assert(Idx < Record.size() &&
6754 "Invalid data, not enough state change pairs in initial state");
6755 } else if (F.isModule()) {
6756 // For an explicit module, preserve the flags from the module build
6757 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6758 // -Wblah flags.
6759 unsigned Flags = Record[Idx++];
6760 DiagState Initial;
6761 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6762 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6763 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6764 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6765 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6766 Initial.ExtBehavior = (diag::Severity)Flags;
6767 FirstState = ReadDiagState(Initial, true);
6768
6769 assert(F.OriginalSourceFileID.isValid());
6770
6771 // Set up the root buffer of the module to start with the initial
6772 // diagnostic state of the module itself, to cover files that contain no
6773 // explicit transitions (for which we did not serialize anything).
6774 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6775 .StateTransitions.push_back({FirstState, 0});
6776 } else {
6777 // For prefix ASTs, start with whatever the user configured on the
6778 // command line.
6779 Idx++; // Skip flags.
6780 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6781 }
6782
6783 // Read the state transitions.
6784 unsigned NumLocations = Record[Idx++];
6785 while (NumLocations--) {
6786 assert(Idx < Record.size() &&
6787 "Invalid data, missing pragma diagnostic states");
6788 FileID FID = ReadFileID(F, Record, Idx);
6789 assert(FID.isValid() && "invalid FileID for transition");
6790 unsigned Transitions = Record[Idx++];
6791
6792 // Note that we don't need to set up Parent/ParentOffset here, because
6793 // we won't be changing the diagnostic state within imported FileIDs
6794 // (other than perhaps appending to the main source file, which has no
6795 // parent).
6796 auto &F = Diag.DiagStatesByLoc.Files[FID];
6797 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6798 for (unsigned I = 0; I != Transitions; ++I) {
6799 unsigned Offset = Record[Idx++];
6800 auto *State = ReadDiagState(*FirstState, false);
6801 F.StateTransitions.push_back({State, Offset});
6802 }
6803 }
6804
6805 // Read the final state.
6806 assert(Idx < Record.size() &&
6807 "Invalid data, missing final pragma diagnostic state");
6808 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6809 auto *CurState = ReadDiagState(*FirstState, false);
6810
6811 if (!F.isModule()) {
6812 Diag.DiagStatesByLoc.CurDiagState = CurState;
6813 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6814
6815 // Preserve the property that the imaginary root file describes the
6816 // current state.
6817 FileID NullFile;
6818 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6819 if (T.empty())
6820 T.push_back({CurState, 0});
6821 else
6822 T[0].State = CurState;
6823 }
6824
6825 // Don't try to read these mappings again.
6826 Record.clear();
6827 }
6828}
6829
6830/// Get the correct cursor and offset for loading a type.
6831ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
6832 auto [M, Index] = translateTypeIDToIndex(ID);
6833 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
6835}
6836
6837static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6838 switch (code) {
6839#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6840 case TYPE_##CODE_ID: return Type::CLASS_ID;
6841#include "clang/Serialization/TypeBitCodes.def"
6842 default:
6843 return std::nullopt;
6844 }
6845}
6846
6847/// Read and return the type with the given index..
6848///
6849/// The index is the type ID, shifted and minus the number of predefs. This
6850/// routine actually reads the record corresponding to the type at the given
6851/// location. It is a helper routine for GetType, which deals with reading type
6852/// IDs.
6853QualType ASTReader::readTypeRecord(TypeID ID) {
6854 assert(ContextObj && "reading type with no AST context");
6855 ASTContext &Context = *ContextObj;
6856 RecordLocation Loc = TypeCursorForIndex(ID);
6857 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6858
6859 // Keep track of where we are in the stream, then jump back there
6860 // after reading this type.
6861 SavedStreamPosition SavedPosition(DeclsCursor);
6862
6863 ReadingKindTracker ReadingKind(Read_Type, *this);
6864
6865 // Note that we are loading a type record.
6866 Deserializing AType(this);
6867
6868 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6869 Error(std::move(Err));
6870 return QualType();
6871 }
6872 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6873 if (!RawCode) {
6874 Error(RawCode.takeError());
6875 return QualType();
6876 }
6877
6878 ASTRecordReader Record(*this, *Loc.F);
6879 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6880 if (!Code) {
6881 Error(Code.takeError());
6882 return QualType();
6883 }
6884 if (Code.get() == TYPE_EXT_QUAL) {
6885 QualType baseType = Record.readQualType();
6886 Qualifiers quals = Record.readQualifiers();
6887 return Context.getQualifiedType(baseType, quals);
6888 }
6889
6890 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6891 if (!maybeClass) {
6892 Error("Unexpected code for type");
6893 return QualType();
6894 }
6895
6897 return TypeReader.read(*maybeClass);
6898}
6899
6900namespace clang {
6901
6902class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6904
6905 ASTRecordReader &Reader;
6906 LocSeq *Seq;
6907
6908 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6909 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6910
6911 TypeSourceInfo *GetTypeSourceInfo() {
6912 return Reader.readTypeSourceInfo();
6913 }
6914
6915 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6916 return Reader.readNestedNameSpecifierLoc();
6917 }
6918
6919 Attr *ReadAttr() {
6920 return Reader.readAttr();
6921 }
6922
6923public:
6925 : Reader(Reader), Seq(Seq) {}
6926
6927 // We want compile-time assurance that we've enumerated all of
6928 // these, so unfortunately we have to declare them first, then
6929 // define them out-of-line.
6930#define ABSTRACT_TYPELOC(CLASS, PARENT)
6931#define TYPELOC(CLASS, PARENT) \
6932 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6933#include "clang/AST/TypeLocNodes.def"
6934
6935 void VisitFunctionTypeLoc(FunctionTypeLoc);
6936 void VisitArrayTypeLoc(ArrayTypeLoc);
6937};
6938
6939} // namespace clang
6940
6941void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6942 // nothing to do
6943}
6944
6945void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6946 TL.setBuiltinLoc(readSourceLocation());
6947 if (TL.needsExtraLocalData()) {
6948 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6949 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6950 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6951 TL.setModeAttr(Reader.readInt());
6952 }
6953}
6954
6955void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6956 TL.setNameLoc(readSourceLocation());
6957}
6958
6959void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6960 TL.setStarLoc(readSourceLocation());
6961}
6962
6963void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6964 // nothing to do
6965}
6966
6967void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6968 // nothing to do
6969}
6970
6971void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6972 // nothing to do
6973}
6974
6975void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6976 TL.setExpansionLoc(readSourceLocation());
6977}
6978
6979void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6980 TL.setCaretLoc(readSourceLocation());
6981}
6982
6983void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6984 TL.setAmpLoc(readSourceLocation());
6985}
6986
6987void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6988 TL.setAmpAmpLoc(readSourceLocation());
6989}
6990
6991void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6992 TL.setStarLoc(readSourceLocation());
6993 TL.setClassTInfo(GetTypeSourceInfo());
6994}
6995
6997 TL.setLBracketLoc(readSourceLocation());
6998 TL.setRBracketLoc(readSourceLocation());
6999 if (Reader.readBool())
7000 TL.setSizeExpr(Reader.readExpr());
7001 else
7002 TL.setSizeExpr(nullptr);
7003}
7004
7005void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7006 VisitArrayTypeLoc(TL);
7007}
7008
7009void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7010 VisitArrayTypeLoc(TL);
7011}
7012
7013void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7014 VisitArrayTypeLoc(TL);
7015}
7016
7017void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7019 VisitArrayTypeLoc(TL);
7020}
7021
7022void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7024
7025 TL.setAttrNameLoc(readSourceLocation());
7026 TL.setAttrOperandParensRange(readSourceRange());
7027 TL.setAttrExprOperand(Reader.readExpr());
7028}
7029
7030void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7032 TL.setNameLoc(readSourceLocation());
7033}
7034
7035void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7036 TL.setNameLoc(readSourceLocation());
7037}
7038
7039void TypeLocReader::VisitDependentVectorTypeLoc(
7041 TL.setNameLoc(readSourceLocation());
7042}
7043
7044void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7045 TL.setNameLoc(readSourceLocation());
7046}
7047
7048void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7049 TL.setAttrNameLoc(readSourceLocation());
7050 TL.setAttrOperandParensRange(readSourceRange());
7051 TL.setAttrRowOperand(Reader.readExpr());
7052 TL.setAttrColumnOperand(Reader.readExpr());
7053}
7054
7055void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7057 TL.setAttrNameLoc(readSourceLocation());
7058 TL.setAttrOperandParensRange(readSourceRange());
7059 TL.setAttrRowOperand(Reader.readExpr());
7060 TL.setAttrColumnOperand(Reader.readExpr());
7061}
7062
7064 TL.setLocalRangeBegin(readSourceLocation());
7065 TL.setLParenLoc(readSourceLocation());
7066 TL.setRParenLoc(readSourceLocation());
7067 TL.setExceptionSpecRange(readSourceRange());
7068 TL.setLocalRangeEnd(readSourceLocation());
7069 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7070 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7071 }
7072}
7073
7074void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7075 VisitFunctionTypeLoc(TL);
7076}
7077
7078void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7079 VisitFunctionTypeLoc(TL);
7080}
7081
7082void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7083 TL.setNameLoc(readSourceLocation());
7084}
7085
7086void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7087 TL.setNameLoc(readSourceLocation());
7088}
7089
7090void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7091 TL.setNameLoc(readSourceLocation());
7092}
7093
7094void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7095 TL.setTypeofLoc(readSourceLocation());
7096 TL.setLParenLoc(readSourceLocation());
7097 TL.setRParenLoc(readSourceLocation());
7098}
7099
7100void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7101 TL.setTypeofLoc(readSourceLocation());
7102 TL.setLParenLoc(readSourceLocation());
7103 TL.setRParenLoc(readSourceLocation());
7104 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7105}
7106
7107void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7108 TL.setDecltypeLoc(readSourceLocation());
7109 TL.setRParenLoc(readSourceLocation());
7110}
7111
7112void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7113 TL.setEllipsisLoc(readSourceLocation());
7114}
7115
7116void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7117 TL.setKWLoc(readSourceLocation());
7118 TL.setLParenLoc(readSourceLocation());
7119 TL.setRParenLoc(readSourceLocation());
7120 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7121}
7122
7124 auto NNS = readNestedNameSpecifierLoc();
7125 auto TemplateKWLoc = readSourceLocation();
7126 auto ConceptNameLoc = readDeclarationNameInfo();
7127 auto FoundDecl = readDeclAs<NamedDecl>();
7128 auto NamedConcept = readDeclAs<ConceptDecl>();
7129 auto *CR = ConceptReference::Create(
7130 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7131 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7132 return CR;
7133}
7134
7135void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7136 TL.setNameLoc(readSourceLocation());
7137 if (Reader.readBool())
7138 TL.setConceptReference(Reader.readConceptReference());
7139 if (Reader.readBool())
7140 TL.setRParenLoc(readSourceLocation());
7141}
7142
7143void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7145 TL.setTemplateNameLoc(readSourceLocation());
7146}
7147
7148void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7149 TL.setNameLoc(readSourceLocation());
7150}
7151
7152void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
7153 TL.setNameLoc(readSourceLocation());
7154}
7155
7156void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7157 TL.setAttr(ReadAttr());
7158}
7159
7160void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7161 // Nothing to do
7162}
7163
7164void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7165 // Nothing to do.
7166}
7167
7168void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7170 // Nothing to do.
7171}
7172
7173void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7174 TL.setNameLoc(readSourceLocation());
7175}
7176
7177void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7179 TL.setNameLoc(readSourceLocation());
7180}
7181
7182void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7184 TL.setNameLoc(readSourceLocation());
7185}
7186
7187void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7189 TL.setTemplateKeywordLoc(readSourceLocation());
7190 TL.setTemplateNameLoc(readSourceLocation());
7191 TL.setLAngleLoc(readSourceLocation());
7192 TL.setRAngleLoc(readSourceLocation());
7193 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7194 TL.setArgLocInfo(i,
7195 Reader.readTemplateArgumentLocInfo(
7196 TL.getTypePtr()->template_arguments()[i].getKind()));
7197}
7198
7199void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7200 TL.setLParenLoc(readSourceLocation());
7201 TL.setRParenLoc(readSourceLocation());
7202}
7203
7204void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7205 TL.setElaboratedKeywordLoc(readSourceLocation());
7206 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7207}
7208
7209void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7210 TL.setNameLoc(readSourceLocation());
7211}
7212
7213void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7214 TL.setElaboratedKeywordLoc(readSourceLocation());
7215 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7216 TL.setNameLoc(readSourceLocation());
7217}
7218
7219void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7221 TL.setElaboratedKeywordLoc(readSourceLocation());
7222 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7223 TL.setTemplateKeywordLoc(readSourceLocation());
7224 TL.setTemplateNameLoc(readSourceLocation());
7225 TL.setLAngleLoc(readSourceLocation());
7226 TL.setRAngleLoc(readSourceLocation());
7227 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7228 TL.setArgLocInfo(I,
7229 Reader.readTemplateArgumentLocInfo(
7230 TL.getTypePtr()->template_arguments()[I].getKind()));
7231}
7232
7233void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7234 TL.setEllipsisLoc(readSourceLocation());
7235}
7236
7237void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7238 TL.setNameLoc(readSourceLocation());
7239 TL.setNameEndLoc(readSourceLocation());
7240}
7241
7242void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7243 if (TL.getNumProtocols()) {
7244 TL.setProtocolLAngleLoc(readSourceLocation());
7245 TL.setProtocolRAngleLoc(readSourceLocation());
7246 }
7247 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7248 TL.setProtocolLoc(i, readSourceLocation());
7249}
7250
7251void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7252 TL.setHasBaseTypeAsWritten(Reader.readBool());
7253 TL.setTypeArgsLAngleLoc(readSourceLocation());
7254 TL.setTypeArgsRAngleLoc(readSourceLocation());
7255 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7256 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7257 TL.setProtocolLAngleLoc(readSourceLocation());
7258 TL.setProtocolRAngleLoc(readSourceLocation());
7259 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7260 TL.setProtocolLoc(i, readSourceLocation());
7261}
7262
7263void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7264 TL.setStarLoc(readSourceLocation());
7265}
7266
7267void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7268 TL.setKWLoc(readSourceLocation());
7269 TL.setLParenLoc(readSourceLocation());
7270 TL.setRParenLoc(readSourceLocation());
7271}
7272
7273void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7274 TL.setKWLoc(readSourceLocation());
7275}
7276
7277void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7278 TL.setNameLoc(readSourceLocation());
7279}
7280void TypeLocReader::VisitDependentBitIntTypeLoc(
7282 TL.setNameLoc(readSourceLocation());
7283}
7284
7286 LocSeq::State Seq(ParentSeq);
7287 TypeLocReader TLR(*this, Seq);
7288 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7289 TLR.Visit(TL);
7290}
7291
7293 QualType InfoTy = readType();
7294 if (InfoTy.isNull())
7295 return nullptr;
7296
7297 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7298 readTypeLoc(TInfo->getTypeLoc());
7299 return TInfo;
7300}
7301
7303 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7304}
7305
7307 return ID >> 32;
7308}
7309
7311 // We don't need to erase the higher bits since if these bits are not 0,
7312 // it must be larger than NUM_PREDEF_TYPE_IDS.
7314}
7315
7316std::pair<ModuleFile *, unsigned>
7317ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7318 assert(!isPredefinedType(ID) &&
7319 "Predefined type shouldn't be in TypesLoaded");
7320 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7321 assert(ModuleFileIndex && "Untranslated Local Decl?");
7322
7323 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7324 assert(OwningModuleFile &&
7325 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7326
7327 return {OwningModuleFile,
7328 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7329}
7330
7332 assert(ContextObj && "reading type with no AST context");
7333 ASTContext &Context = *ContextObj;
7334
7335 unsigned FastQuals = ID & Qualifiers::FastMask;
7336
7337 if (isPredefinedType(ID)) {
7338 QualType T;
7339 unsigned Index = getIndexForTypeID(ID);
7340 switch ((PredefinedTypeIDs)Index) {
7342 // We should never use this one.
7343 llvm_unreachable("Invalid predefined type");
7344 break;
7346 return QualType();
7348 T = Context.VoidTy;
7349 break;
7351 T = Context.BoolTy;
7352 break;
7355 // FIXME: Check that the signedness of CharTy is correct!
7356 T = Context.CharTy;
7357 break;
7359 T = Context.UnsignedCharTy;
7360 break;
7362 T = Context.UnsignedShortTy;
7363 break;
7365 T = Context.UnsignedIntTy;
7366 break;
7368 T = Context.UnsignedLongTy;
7369 break;
7371 T = Context.UnsignedLongLongTy;
7372 break;
7374 T = Context.UnsignedInt128Ty;
7375 break;
7377 T = Context.SignedCharTy;
7378 break;
7380 T = Context.WCharTy;
7381 break;
7383 T = Context.ShortTy;
7384 break;
7385 case PREDEF_TYPE_INT_ID:
7386 T = Context.IntTy;
7387 break;
7389 T = Context.LongTy;
7390 break;
7392 T = Context.LongLongTy;
7393 break;
7395 T = Context.Int128Ty;
7396 break;
7398 T = Context.BFloat16Ty;
7399 break;
7401 T = Context.HalfTy;
7402 break;
7404 T = Context.FloatTy;
7405 break;
7407 T = Context.DoubleTy;
7408 break;
7410 T = Context.LongDoubleTy;
7411 break;
7413 T = Context.ShortAccumTy;
7414 break;
7416 T = Context.AccumTy;
7417 break;
7419 T = Context.LongAccumTy;
7420 break;
7422 T = Context.UnsignedShortAccumTy;
7423 break;
7425 T = Context.UnsignedAccumTy;
7426 break;
7428 T = Context.UnsignedLongAccumTy;
7429 break;
7431 T = Context.ShortFractTy;
7432 break;
7434 T = Context.FractTy;
7435 break;
7437 T = Context.LongFractTy;
7438 break;
7440 T = Context.UnsignedShortFractTy;
7441 break;
7443 T = Context.UnsignedFractTy;
7444 break;
7446 T = Context.UnsignedLongFractTy;
7447 break;
7449 T = Context.SatShortAccumTy;
7450 break;
7452 T = Context.SatAccumTy;
7453 break;
7455 T = Context.SatLongAccumTy;
7456 break;
7458 T = Context.SatUnsignedShortAccumTy;
7459 break;
7461 T = Context.SatUnsignedAccumTy;
7462 break;
7464 T = Context.SatUnsignedLongAccumTy;
7465 break;
7467 T = Context.SatShortFractTy;
7468 break;
7470 T = Context.SatFractTy;
7471 break;
7473 T = Context.SatLongFractTy;
7474 break;
7476 T = Context.SatUnsignedShortFractTy;
7477 break;
7479 T = Context.SatUnsignedFractTy;
7480 break;
7482 T = Context.SatUnsignedLongFractTy;
7483 break;
7485 T = Context.Float16Ty;
7486 break;
7488 T = Context.Float128Ty;
7489 break;
7491 T = Context.Ibm128Ty;
7492 break;
7494 T = Context.OverloadTy;
7495 break;
7497 T = Context.UnresolvedTemplateTy;
7498 break;
7500 T = Context.BoundMemberTy;
7501 break;
7503 T = Context.PseudoObjectTy;
7504 break;
7506 T = Context.DependentTy;
7507 break;
7509 T = Context.UnknownAnyTy;
7510 break;
7512 T = Context.NullPtrTy;
7513 break;
7515 T = Context.Char8Ty;
7516 break;
7518 T = Context.Char16Ty;
7519 break;
7521 T = Context.Char32Ty;
7522 break;
7524 T = Context.ObjCBuiltinIdTy;
7525 break;
7527 T = Context.ObjCBuiltinClassTy;
7528 break;
7530 T = Context.ObjCBuiltinSelTy;
7531 break;
7532#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7533 case PREDEF_TYPE_##Id##_ID: \
7534 T = Context.SingletonId; \
7535 break;
7536#include "clang/Basic/OpenCLImageTypes.def"
7537#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7538 case PREDEF_TYPE_##Id##_ID: \
7539 T = Context.Id##Ty; \
7540 break;
7541#include "clang/Basic/OpenCLExtensionTypes.def"
7543 T = Context.OCLSamplerTy;
7544 break;
7546 T = Context.OCLEventTy;
7547 break;
7549 T = Context.OCLClkEventTy;
7550 break;
7552 T = Context.OCLQueueTy;
7553 break;
7555 T = Context.OCLReserveIDTy;
7556 break;
7558 T = Context.getAutoDeductType();
7559 break;
7561 T = Context.getAutoRRefDeductType();
7562 break;
7564 T = Context.ARCUnbridgedCastTy;
7565 break;
7567 T = Context.BuiltinFnTy;
7568 break;
7570 T = Context.IncompleteMatrixIdxTy;
7571 break;
7573 T = Context.ArraySectionTy;
7574 break;
7576 T = Context.OMPArrayShapingTy;
7577 break;
7579 T = Context.OMPIteratorTy;
7580 break;
7581#define SVE_TYPE(Name, Id, SingletonId) \
7582 case PREDEF_TYPE_##Id##_ID: \
7583 T = Context.SingletonId; \
7584 break;
7585#include "clang/Basic/AArch64SVEACLETypes.def"
7586#define PPC_VECTOR_TYPE(Name, Id, Size) \
7587 case PREDEF_TYPE_##Id##_ID: \
7588 T = Context.Id##Ty; \
7589 break;
7590#include "clang/Basic/PPCTypes.def"
7591#define RVV_TYPE(Name, Id, SingletonId) \
7592 case PREDEF_TYPE_##Id##_ID: \
7593 T = Context.SingletonId; \
7594 break;
7595#include "clang/Basic/RISCVVTypes.def"
7596#define WASM_TYPE(Name, Id, SingletonId) \
7597 case PREDEF_TYPE_##Id##_ID: \
7598 T = Context.SingletonId; \
7599 break;
7600#include "clang/Basic/WebAssemblyReferenceTypes.def"
7601#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
7602 case PREDEF_TYPE_##Id##_ID: \
7603 T = Context.SingletonId; \
7604 break;
7605#include "clang/Basic/AMDGPUTypes.def"
7606#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
7607 case PREDEF_TYPE_##Id##_ID: \
7608 T = Context.SingletonId; \
7609 break;
7610#include "clang/Basic/HLSLIntangibleTypes.def"
7611 }
7612
7613 assert(!T.isNull() && "Unknown predefined type");
7614 return T.withFastQualifiers(FastQuals);
7615 }
7616
7617 unsigned Index = translateTypeIDToIndex(ID).second;
7618
7619 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7620 if (TypesLoaded[Index].isNull()) {
7621 TypesLoaded[Index] = readTypeRecord(ID);
7622 if (TypesLoaded[Index].isNull())
7623 return QualType();
7624
7625 TypesLoaded[Index]->setFromAST();
7626 if (DeserializationListener)
7627 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7628 TypesLoaded[Index]);
7629 }
7630
7631 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7632}
7633
7635 return GetType(getGlobalTypeID(F, LocalID));
7636}
7637
7639 LocalTypeID LocalID) const {
7640 if (isPredefinedType(LocalID))
7641 return LocalID;
7642
7643 if (!F.ModuleOffsetMap.empty())
7644 ReadModuleOffsetMap(F);
7645
7646 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
7647 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
7648
7649 if (ModuleFileIndex == 0)
7651
7652 ModuleFile &MF =
7653 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
7654 ModuleFileIndex = MF.Index + 1;
7655 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
7656}
7657
7660 switch (Kind) {
7662 return readExpr();
7664 return readTypeSourceInfo();
7666 NestedNameSpecifierLoc QualifierLoc =
7667 readNestedNameSpecifierLoc();
7668 SourceLocation TemplateNameLoc = readSourceLocation();
7669 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7670 TemplateNameLoc, SourceLocation());
7671 }
7673 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7674 SourceLocation TemplateNameLoc = readSourceLocation();
7675 SourceLocation EllipsisLoc = readSourceLocation();
7676 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7677 TemplateNameLoc, EllipsisLoc);
7678 }
7685 // FIXME: Is this right?
7686 return TemplateArgumentLocInfo();
7687 }
7688 llvm_unreachable("unexpected template argument loc");
7689}
7690
7692 TemplateArgument Arg = readTemplateArgument();
7693
7695 if (readBool()) // bool InfoHasSameExpr.
7697 }
7698 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7699}
7700
7703 Result.setLAngleLoc(readSourceLocation());
7704 Result.setRAngleLoc(readSourceLocation());
7705 unsigned NumArgsAsWritten = readInt();
7706 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7707 Result.addArgument(readTemplateArgumentLoc());
7708}
7709
7713 readTemplateArgumentListInfo(Result);
7714 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7715}
7716
7718
7720 if (NumCurrentElementsDeserializing) {
7721 // We arrange to not care about the complete redeclaration chain while we're
7722 // deserializing. Just remember that the AST has marked this one as complete
7723 // but that it's not actually complete yet, so we know we still need to
7724 // complete it later.
7725 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7726 return;
7727 }
7728
7729 if (!D->getDeclContext()) {
7730 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7731 return;
7732 }
7733
7734 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7735
7736 // If this is a named declaration, complete it by looking it up
7737 // within its context.
7738 //
7739 // FIXME: Merging a function definition should merge
7740 // all mergeable entities within it.
7741 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7742 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7743 if (!getContext().getLangOpts().CPlusPlus &&
7744 isa<TranslationUnitDecl>(DC)) {
7745 // Outside of C++, we don't have a lookup table for the TU, so update
7746 // the identifier instead. (For C++ modules, we don't store decls
7747 // in the serialized identifier table, so we do the lookup in the TU.)
7748 auto *II = Name.getAsIdentifierInfo();
7749 assert(II && "non-identifier name in C?");
7750 if (II->isOutOfDate())
7751 updateOutOfDateIdentifier(*II);
7752 } else
7753 DC->lookup(Name);
7754 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7755 // Find all declarations of this kind from the relevant context.
7756 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7757 auto *DC = cast<DeclContext>(DCDecl);
7759 FindExternalLexicalDecls(
7760 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7761 }
7762 }
7763 }
7764
7765 RedeclarableTemplateDecl *Template = nullptr;
7767 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
7768 Template = CTSD->getSpecializedTemplate();
7769 Args = CTSD->getTemplateArgs().asArray();
7770 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
7771 Template = VTSD->getSpecializedTemplate();
7772 Args = VTSD->getTemplateArgs().asArray();
7773 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7774 if (auto *Tmplt = FD->getPrimaryTemplate()) {
7775 Template = Tmplt;
7776 Args = FD->getTemplateSpecializationArgs()->asArray();
7777 }
7778 }
7779
7780 if (Template) {
7781 // For partitial specialization, load all the specializations for safety.
7784 Template->loadLazySpecializationsImpl();
7785 else
7786 Template->loadLazySpecializationsImpl(Args);
7787 }
7788}
7789
7792 RecordLocation Loc = getLocalBitOffset(Offset);
7793 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7794 SavedStreamPosition SavedPosition(Cursor);
7795 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7796 Error(std::move(Err));
7797 return nullptr;
7798 }
7799 ReadingKindTracker ReadingKind(Read_Decl, *this);
7800 Deserializing D(this);
7801
7802 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7803 if (!MaybeCode) {
7804 Error(MaybeCode.takeError());
7805 return nullptr;
7806 }
7807 unsigned Code = MaybeCode.get();
7808
7809 ASTRecordReader Record(*this, *Loc.F);
7810 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7811 if (!MaybeRecCode) {
7812 Error(MaybeRecCode.takeError());
7813 return nullptr;
7814 }
7815 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7816 Error("malformed AST file: missing C++ ctor initializers");
7817 return nullptr;
7818 }
7819
7820 return Record.readCXXCtorInitializers();
7821}
7822
7824 assert(ContextObj && "reading base specifiers with no AST context");
7825 ASTContext &Context = *ContextObj;
7826
7827 RecordLocation Loc = getLocalBitOffset(Offset);
7828 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7829 SavedStreamPosition SavedPosition(Cursor);
7830 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7831 Error(std::move(Err));
7832 return nullptr;
7833 }
7834 ReadingKindTracker ReadingKind(Read_Decl, *this);
7835 Deserializing D(this);
7836
7837 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7838 if (!MaybeCode) {
7839 Error(MaybeCode.takeError());
7840 return nullptr;
7841 }
7842 unsigned Code = MaybeCode.get();
7843
7844 ASTRecordReader Record(*this, *Loc.F);
7845 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7846 if (!MaybeRecCode) {
7847 Error(MaybeCode.takeError());
7848 return nullptr;
7849 }
7850 unsigned RecCode = MaybeRecCode.get();
7851
7852 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7853 Error("malformed AST file: missing C++ base specifiers");
7854 return nullptr;
7855 }
7856
7857 unsigned NumBases = Record.readInt();
7858 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7859 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7860 for (unsigned I = 0; I != NumBases; ++I)
7861 Bases[I] = Record.readCXXBaseSpecifier();
7862 return Bases;
7863}
7864
7866 LocalDeclID LocalID) const {
7867 if (LocalID < NUM_PREDEF_DECL_IDS)
7868 return GlobalDeclID(LocalID.getRawValue());
7869
7870 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
7871 DeclID ID = LocalID.getLocalDeclIndex();
7872
7873 if (!F.ModuleOffsetMap.empty())
7874 ReadModuleOffsetMap(F);
7875
7876 ModuleFile *OwningModuleFile =
7877 OwningModuleFileIndex == 0
7878 ? &F
7879 : F.TransitiveImports[OwningModuleFileIndex - 1];
7880
7881 if (OwningModuleFileIndex == 0)
7882 ID -= NUM_PREDEF_DECL_IDS;
7883
7884 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
7885 return GlobalDeclID(NewModuleFileIndex, ID);
7886}
7887
7889 // Predefined decls aren't from any module.
7890 if (ID < NUM_PREDEF_DECL_IDS)
7891 return false;
7892
7893 unsigned ModuleFileIndex = ID.getModuleFileIndex();
7894 return M.Index == ModuleFileIndex - 1;
7895}
7896
7898 // Predefined decls aren't from any module.
7899 if (ID < NUM_PREDEF_DECL_IDS)
7900 return nullptr;
7901
7902 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
7903 assert(ModuleFileIndex && "Untranslated Local Decl?");
7904
7905 return &getModuleManager()[ModuleFileIndex - 1];
7906}
7907
7909 if (!D->isFromASTFile())
7910 return nullptr;
7911
7912 return getOwningModuleFile(D->getGlobalID());
7913}
7914
7916 if (ID < NUM_PREDEF_DECL_IDS)
7917 return SourceLocation();
7918
7919 if (Decl *D = GetExistingDecl(ID))
7920 return D->getLocation();
7921
7923 DeclCursorForID(ID, Loc);
7924 return Loc;
7925}
7926
7927Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
7928 assert(ContextObj && "reading predefined decl without AST context");
7929 ASTContext &Context = *ContextObj;
7930 Decl *NewLoaded = nullptr;
7931 switch (ID) {
7933 return nullptr;
7934
7936 return Context.getTranslationUnitDecl();
7937
7939 if (Context.ObjCIdDecl)
7940 return Context.ObjCIdDecl;
7941 NewLoaded = Context.getObjCIdDecl();
7942 break;
7943
7945 if (Context.ObjCSelDecl)
7946 return Context.ObjCSelDecl;
7947 NewLoaded = Context.getObjCSelDecl();
7948 break;
7949
7951 if (Context.ObjCClassDecl)
7952 return Context.ObjCClassDecl;
7953 NewLoaded = Context.getObjCClassDecl();
7954 break;
7955
7957 if (Context.ObjCProtocolClassDecl)
7958 return Context.ObjCProtocolClassDecl;
7959 NewLoaded = Context.getObjCProtocolDecl();
7960 break;
7961
7963 if (Context.Int128Decl)
7964 return Context.Int128Decl;
7965 NewLoaded = Context.getInt128Decl();
7966 break;
7967
7969 if (Context.UInt128Decl)
7970 return Context.UInt128Decl;
7971 NewLoaded = Context.getUInt128Decl();
7972 break;
7973
7975 if (Context.ObjCInstanceTypeDecl)
7976 return Context.ObjCInstanceTypeDecl;
7977 NewLoaded = Context.getObjCInstanceTypeDecl();
7978 break;
7979
7981 if (Context.BuiltinVaListDecl)
7982 return Context.BuiltinVaListDecl;
7983 NewLoaded = Context.getBuiltinVaListDecl();
7984 break;
7985
7987 if (Context.VaListTagDecl)
7988 return Context.VaListTagDecl;
7989 NewLoaded = Context.getVaListTagDecl();
7990 break;
7991
7993 if (Context.BuiltinMSVaListDecl)
7994 return Context.BuiltinMSVaListDecl;
7995 NewLoaded = Context.getBuiltinMSVaListDecl();
7996 break;
7997
7999 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8000 return Context.getMSGuidTagDecl();
8001
8003 if (Context.ExternCContext)
8004 return Context.ExternCContext;
8005 NewLoaded = Context.getExternCContextDecl();
8006 break;
8007
8009 if (Context.MakeIntegerSeqDecl)
8010 return Context.MakeIntegerSeqDecl;
8011 NewLoaded = Context.getMakeIntegerSeqDecl();
8012 break;
8013
8015 if (Context.CFConstantStringTypeDecl)
8016 return Context.CFConstantStringTypeDecl;
8017 NewLoaded = Context.getCFConstantStringDecl();
8018 break;
8019
8021 if (Context.CFConstantStringTagDecl)
8022 return Context.CFConstantStringTagDecl;
8023 NewLoaded = Context.getCFConstantStringTagDecl();
8024 break;
8025
8027 if (Context.TypePackElementDecl)
8028 return Context.TypePackElementDecl;
8029 NewLoaded = Context.getTypePackElementDecl();
8030 break;
8031
8033 if (Context.BuiltinCommonTypeDecl)
8034 return Context.BuiltinCommonTypeDecl;
8035 NewLoaded = Context.getBuiltinCommonTypeDecl();
8036 break;
8037
8039 llvm_unreachable("Invalid decl ID");
8040 break;
8041 }
8042
8043 assert(NewLoaded && "Failed to load predefined decl?");
8044
8045 if (DeserializationListener)
8046 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8047
8048 return NewLoaded;
8049}
8050
8051unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8052 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8053 if (!OwningModuleFile) {
8054 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8055 return GlobalID.getRawValue();
8056 }
8057
8058 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8059}
8060
8062 assert(ContextObj && "reading decl with no AST context");
8063
8064 if (ID < NUM_PREDEF_DECL_IDS) {
8065 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8066 if (D) {
8067 // Track that we have merged the declaration with ID \p ID into the
8068 // pre-existing predefined declaration \p D.
8069 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8070 if (Merged.empty())
8071 Merged.push_back(ID);
8072 }
8073 return D;
8074 }
8075
8076 unsigned Index = translateGlobalDeclIDToIndex(ID);
8077
8078 if (Index >= DeclsLoaded.size()) {
8079 assert(0 && "declaration ID out-of-range for AST file");
8080 Error("declaration ID out-of-range for AST file");
8081 return nullptr;
8082 }
8083
8084 return DeclsLoaded[Index];
8085}
8086
8088 if (ID < NUM_PREDEF_DECL_IDS)
8089 return GetExistingDecl(ID);
8090
8091 unsigned Index = translateGlobalDeclIDToIndex(ID);
8092
8093 if (Index >= DeclsLoaded.size()) {
8094 assert(0 && "declaration ID out-of-range for AST file");
8095 Error("declaration ID out-of-range for AST file");
8096 return nullptr;
8097 }
8098
8099 if (!DeclsLoaded[Index]) {
8100 ReadDeclRecord(ID);
8101 if (DeserializationListener)
8102 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8103 }
8104
8105 return DeclsLoaded[Index];
8106}
8107
8109 GlobalDeclID GlobalID) {
8110 if (GlobalID < NUM_PREDEF_DECL_IDS)
8111 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8112
8113 if (!M.ModuleOffsetMap.empty())
8114 ReadModuleOffsetMap(M);
8115
8116 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8117 DeclID ID = GlobalID.getLocalDeclIndex();
8118
8119 if (Owner == &M) {
8120 ID += NUM_PREDEF_DECL_IDS;
8121 return LocalDeclID::get(*this, M, ID);
8122 }
8123
8124 uint64_t OrignalModuleFileIndex = 0;
8125 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8126 if (M.TransitiveImports[I] == Owner) {
8127 OrignalModuleFileIndex = I + 1;
8128 break;
8129 }
8130
8131 if (!OrignalModuleFileIndex)
8132 return LocalDeclID();
8133
8134 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8135}
8136
8138 unsigned &Idx) {
8139 if (Idx >= Record.size()) {
8140 Error("Corrupted AST file");
8141 return GlobalDeclID(0);
8142 }
8143
8144 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8145}
8146
8147/// Resolve the offset of a statement into a statement.
8148///
8149/// This operation will read a new statement from the external
8150/// source each time it is called, and is meant to be used via a
8151/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8153 // Switch case IDs are per Decl.
8154 ClearSwitchCaseIDs();
8155
8156 // Offset here is a global offset across the entire chain.
8157 RecordLocation Loc = getLocalBitOffset(Offset);
8158 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8159 Error(std::move(Err));
8160 return nullptr;
8161 }
8162 assert(NumCurrentElementsDeserializing == 0 &&
8163 "should not be called while already deserializing");
8164 Deserializing D(this);
8165 return ReadStmtFromStream(*Loc.F);
8166}
8167
8168bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8169 const Decl *D) {
8170 assert(D);
8171
8172 auto It = SpecLookups.find(D);
8173 if (It == SpecLookups.end())
8174 return false;
8175
8176 // Get Decl may violate the iterator from SpecializationsLookups so we store
8177 // the DeclIDs in ahead.
8179 It->second.Table.findAll();
8180
8181 // Since we've loaded all the specializations, we can erase it from
8182 // the lookup table.
8183 SpecLookups.erase(It);
8184
8185 bool NewSpecsFound = false;
8186 Deserializing LookupResults(this);
8187 for (auto &Info : Infos) {
8188 if (GetExistingDecl(Info))
8189 continue;
8190 NewSpecsFound = true;
8191 GetDecl(Info);
8192 }
8193
8194 return NewSpecsFound;
8195}
8196
8197bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) {
8198 assert(D);
8199
8200 bool NewSpecsFound =
8201 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8202 if (OnlyPartial)
8203 return NewSpecsFound;
8204
8205 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8206 return NewSpecsFound;
8207}
8208
8209bool ASTReader::LoadExternalSpecializationsImpl(
8210 SpecLookupTableTy &SpecLookups, const Decl *D,
8211 ArrayRef<TemplateArgument> TemplateArgs) {
8212 assert(D);
8213
8214 auto It = SpecLookups.find(D);
8215 if (It == SpecLookups.end())
8216 return false;
8217
8218 Deserializing LookupResults(this);
8219 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8220
8221 // Get Decl may violate the iterator from SpecLookups
8223 It->second.Table.find(HashValue);
8224
8225 bool NewSpecsFound = false;
8226 for (auto &Info : Infos) {
8227 if (GetExistingDecl(Info))
8228 continue;
8229 NewSpecsFound = true;
8230 GetDecl(Info);
8231 }
8232
8233 return NewSpecsFound;
8234}
8235
8237 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8238 assert(D);
8239
8240 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8241 PartialSpecializationsLookups, D, TemplateArgs);
8242 NewDeclsFound |=
8243 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8244
8245 return NewDeclsFound;
8246}
8247
8249 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8250 SmallVectorImpl<Decl *> &Decls) {
8251 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8252
8253 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8254 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8255 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8256 auto K = (Decl::Kind)+LexicalDecls[I];
8257 if (!IsKindWeWant(K))
8258 continue;
8259
8260 auto ID = (DeclID) + LexicalDecls[I + 1];
8261
8262 // Don't add predefined declarations to the lexical context more
8263 // than once.
8264 if (ID < NUM_PREDEF_DECL_IDS) {
8265 if (PredefsVisited[ID])
8266 continue;
8267
8268 PredefsVisited[ID] = true;
8269 }
8270
8271 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8272 assert(D->getKind() == K && "wrong kind for lexical decl");
8273 if (!DC->isDeclInLexicalTraversal(D))
8274 Decls.push_back(D);
8275 }
8276 }
8277 };
8278
8279 if (isa<TranslationUnitDecl>(DC)) {
8280 for (const auto &Lexical : TULexicalDecls)
8281 Visit(Lexical.first, Lexical.second);
8282 } else {
8283 auto I = LexicalDecls.find(DC);
8284 if (I != LexicalDecls.end())
8285 Visit(I->second.first, I->second.second);
8286 }
8287
8288 ++NumLexicalDeclContextsRead;
8289}
8290
8291namespace {
8292
8293class UnalignedDeclIDComp {
8294 ASTReader &Reader;
8295 ModuleFile &Mod;
8296
8297public:
8298 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8299 : Reader(Reader), Mod(M) {}
8300
8301 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8302 SourceLocation LHS = getLocation(L);
8303 SourceLocation RHS = getLocation(R);
8304 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8305 }
8306
8307 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8308 SourceLocation RHS = getLocation(R);
8309 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8310 }
8311
8312 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8313 SourceLocation LHS = getLocation(L);
8314 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8315 }
8316
8317 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8318 return Reader.getSourceManager().getFileLoc(
8320 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8321 }
8322};
8323
8324} // namespace
8325
8327 unsigned Offset, unsigned Length,
8328 SmallVectorImpl<Decl *> &Decls) {
8329 SourceManager &SM = getSourceManager();
8330
8331 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8332 if (I == FileDeclIDs.end())
8333 return;
8334
8335 FileDeclsInfo &DInfo = I->second;
8336 if (DInfo.Decls.empty())
8337 return;
8338
8340 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8341 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8342
8343 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8345 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8346 if (BeginIt != DInfo.Decls.begin())
8347 --BeginIt;
8348
8349 // If we are pointing at a top-level decl inside an objc container, we need
8350 // to backtrack until we find it otherwise we will fail to report that the
8351 // region overlaps with an objc container.
8352 while (BeginIt != DInfo.Decls.begin() &&
8353 GetDecl(getGlobalDeclID(*DInfo.Mod,
8354 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8355 ->isTopLevelDeclInObjCContainer())
8356 --BeginIt;
8357
8359 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8360 if (EndIt != DInfo.Decls.end())
8361 ++EndIt;
8362
8363 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8364 ++DIt)
8365 Decls.push_back(GetDecl(getGlobalDeclID(
8366 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8367}
8368
8369bool
8371 DeclarationName Name) {
8372 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8373 "DeclContext has no visible decls in storage");
8374 if (!Name)
8375 return false;
8376
8377 auto It = Lookups.find(DC);
8378 if (It == Lookups.end())
8379 return false;
8380
8381 Deserializing LookupResults(this);
8382
8383 // Load the list of declarations.
8386
8387 for (GlobalDeclID ID : It->second.Table.find(Name)) {
8388 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8389 if (ND->getDeclName() == Name && Found.insert(ND).second)
8390 Decls.push_back(ND);
8391 }
8392
8393 ++NumVisibleDeclContextsRead;
8394 SetExternalVisibleDeclsForName(DC, Name, Decls);
8395 return !Decls.empty();
8396}
8397
8399 if (!DC->hasExternalVisibleStorage())
8400 return;
8401
8402 auto It = Lookups.find(DC);
8403 assert(It != Lookups.end() &&
8404 "have external visible storage but no lookup tables");
8405
8406 DeclsMap Decls;
8407
8408 for (GlobalDeclID ID : It->second.Table.findAll()) {
8409 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8410 Decls[ND->getDeclName()].push_back(ND);
8411 }
8412
8413 ++NumVisibleDeclContextsRead;
8414
8415 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8416 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8417 }
8418 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8419}
8420
8423 auto I = Lookups.find(Primary);
8424 return I == Lookups.end() ? nullptr : &I->second;
8425}
8426
8429 assert(D->isCanonicalDecl());
8430 auto &LookupTable =
8431 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8432 auto I = LookupTable.find(D);
8433 return I == LookupTable.end() ? nullptr : &I->second;
8434}
8435
8437 assert(D->isCanonicalDecl());
8438 return (PartialSpecializationsLookups.find(D) !=
8439 PartialSpecializationsLookups.end()) ||
8440 (SpecializationsLookups.find(D) != SpecializationsLookups.end());
8441}
8442
8443/// Under non-PCH compilation the consumer receives the objc methods
8444/// before receiving the implementation, and codegen depends on this.
8445/// We simulate this by deserializing and passing to consumer the methods of the
8446/// implementation before passing the deserialized implementation decl.
8448 ASTConsumer *Consumer) {
8449 assert(ImplD && Consumer);
8450
8451 for (auto *I : ImplD->methods())
8452 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8453
8454 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8455}
8456
8457void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8458 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8459 PassObjCImplDeclToConsumer(ImplD, Consumer);
8460 else
8461 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8462}
8463
8464void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8465 Consumer->HandleVTable(RD);
8466}
8467
8469 this->Consumer = Consumer;
8470
8471 if (Consumer)
8472 PassInterestingDeclsToConsumer();
8473
8474 if (DeserializationListener)
8475 DeserializationListener->ReaderInitialized(this);
8476}
8477
8479 std::fprintf(stderr, "*** AST File Statistics:\n");
8480
8481 unsigned NumTypesLoaded =
8482 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8483 unsigned NumDeclsLoaded =
8484 DeclsLoaded.size() -
8485 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8486 unsigned NumIdentifiersLoaded =
8487 IdentifiersLoaded.size() -
8488 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8489 unsigned NumMacrosLoaded =
8490 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8491 unsigned NumSelectorsLoaded =
8492 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8493
8494 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8495 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8496 NumSLocEntriesRead, TotalNumSLocEntries,
8497 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8498 if (!TypesLoaded.empty())
8499 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8500 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8501 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8502 if (!DeclsLoaded.empty())
8503 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8504 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8505 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8506 if (!IdentifiersLoaded.empty())
8507 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8508 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8509 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8510 if (!MacrosLoaded.empty())
8511 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8512 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8513 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8514 if (!SelectorsLoaded.empty())
8515 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8516 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8517 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8518 if (TotalNumStatements)
8519 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8520 NumStatementsRead, TotalNumStatements,
8521 ((float)NumStatementsRead/TotalNumStatements * 100));
8522 if (TotalNumMacros)
8523 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8524 NumMacrosRead, TotalNumMacros,
8525 ((float)NumMacrosRead/TotalNumMacros * 100));
8526 if (TotalLexicalDeclContexts)
8527 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8528 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8529 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8530 * 100));
8531 if (TotalVisibleDeclContexts)
8532 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8533 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8534 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8535 * 100));
8536 if (TotalNumMethodPoolEntries)
8537 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8538 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8539 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8540 * 100));
8541 if (NumMethodPoolLookups)
8542 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8543 NumMethodPoolHits, NumMethodPoolLookups,
8544 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8545 if (NumMethodPoolTableLookups)
8546 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8547 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8548 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8549 * 100.0));
8550 if (NumIdentifierLookupHits)
8551 std::fprintf(stderr,
8552 " %u / %u identifier table lookups succeeded (%f%%)\n",
8553 NumIdentifierLookupHits, NumIdentifierLookups,
8554 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8555
8556 if (GlobalIndex) {
8557 std::fprintf(stderr, "\n");
8558 GlobalIndex->printStats();
8559 }
8560
8561 std::fprintf(stderr, "\n");
8562 dump();
8563 std::fprintf(stderr, "\n");
8564}
8565
8566template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8567LLVM_DUMP_METHOD static void
8568dumpModuleIDMap(StringRef Name,
8569 const ContinuousRangeMap<Key, ModuleFile *,
8570 InitialCapacity> &Map) {
8571 if (Map.begin() == Map.end())
8572 return;
8573
8575
8576 llvm::errs() << Name << ":\n";
8577 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8578 I != IEnd; ++I)
8579 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
8580 << "\n";
8581}
8582
8583LLVM_DUMP_METHOD void ASTReader::dump() {
8584 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8585 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8586 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8587 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8588 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8589 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8590 dumpModuleIDMap("Global preprocessed entity map",
8591 GlobalPreprocessedEntityMap);
8592
8593 llvm::errs() << "\n*** PCH/Modules Loaded:";
8594 for (ModuleFile &M : ModuleMgr)
8595 M.dump();
8596}
8597
8598/// Return the amount of memory used by memory buffers, breaking down
8599/// by heap-backed versus mmap'ed memory.
8601 for (ModuleFile &I : ModuleMgr) {
8602 if (llvm::MemoryBuffer *buf = I.Buffer) {
8603 size_t bytes = buf->getBufferSize();
8604 switch (buf->getBufferKind()) {
8605 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8606 sizes.malloc_bytes += bytes;
8607 break;
8608 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8609 sizes.mmap_bytes += bytes;
8610 break;
8611 }
8612 }
8613 }
8614}
8615
8617 SemaObj = &S;
8618 S.addExternalSource(this);
8619
8620 // Makes sure any declarations that were deserialized "too early"
8621 // still get added to the identifier's declaration chains.
8622 for (GlobalDeclID ID : PreloadedDeclIDs) {
8623 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8624 pushExternalDeclIntoScope(D, D->getDeclName());
8625 }
8626 PreloadedDeclIDs.clear();
8627
8628 // FIXME: What happens if these are changed by a module import?
8629 if (!FPPragmaOptions.empty()) {
8630 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8631 FPOptionsOverride NewOverrides =
8632 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8633 SemaObj->CurFPFeatures =
8634 NewOverrides.applyOverrides(SemaObj->getLangOpts());
8635 }
8636
8637 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
8638 Decl *D = GetDecl(ID);
8639 if (auto *FD = dyn_cast<FunctionDecl>(D))
8640 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
8641 else if (auto *BD = dyn_cast<BlockDecl>(D))
8642 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
8643 else
8644 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
8645 }
8646 DeclsWithEffectsToVerify.clear();
8647
8648 SemaObj->OpenCLFeatures = OpenCLExtensions;
8649
8650 UpdateSema();
8651}
8652
8654 assert(SemaObj && "no Sema to update");
8655
8656 // Load the offsets of the declarations that Sema references.
8657 // They will be lazily deserialized when needed.
8658 if (!SemaDeclRefs.empty()) {
8659 assert(SemaDeclRefs.size() % 3 == 0);
8660 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8661 if (!SemaObj->StdNamespace)
8662 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
8663 if (!SemaObj->StdBadAlloc)
8664 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
8665 if (!SemaObj->StdAlignValT)
8666 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
8667 }
8668 SemaDeclRefs.clear();
8669 }
8670
8671 // Update the state of pragmas. Use the same API as if we had encountered the
8672 // pragma in the source.
8673 if(OptimizeOffPragmaLocation.isValid())
8674 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8675 if (PragmaMSStructState != -1)
8676 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8677 if (PointersToMembersPragmaLocation.isValid()) {
8678 SemaObj->ActOnPragmaMSPointersToMembers(
8680 PragmaMSPointersToMembersState,
8681 PointersToMembersPragmaLocation);
8682 }
8683 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8684
8685 if (PragmaAlignPackCurrentValue) {
8686 // The bottom of the stack might have a default value. It must be adjusted
8687 // to the current value to ensure that the packing state is preserved after
8688 // popping entries that were included/imported from a PCH/module.
8689 bool DropFirst = false;
8690 if (!PragmaAlignPackStack.empty() &&
8691 PragmaAlignPackStack.front().Location.isInvalid()) {
8692 assert(PragmaAlignPackStack.front().Value ==
8693 SemaObj->AlignPackStack.DefaultValue &&
8694 "Expected a default alignment value");
8695 SemaObj->AlignPackStack.Stack.emplace_back(
8696 PragmaAlignPackStack.front().SlotLabel,
8697 SemaObj->AlignPackStack.CurrentValue,
8698 SemaObj->AlignPackStack.CurrentPragmaLocation,
8699 PragmaAlignPackStack.front().PushLocation);
8700 DropFirst = true;
8701 }
8702 for (const auto &Entry :
8703 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8704 SemaObj->AlignPackStack.Stack.emplace_back(
8705 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8706 }
8707 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8708 assert(*PragmaAlignPackCurrentValue ==
8709 SemaObj->AlignPackStack.DefaultValue &&
8710 "Expected a default align and pack value");
8711 // Keep the current values.
8712 } else {
8713 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8714 SemaObj->AlignPackStack.CurrentPragmaLocation =
8715 PragmaAlignPackCurrentLocation;
8716 }
8717 }
8718 if (FpPragmaCurrentValue) {
8719 // The bottom of the stack might have a default value. It must be adjusted
8720 // to the current value to ensure that fp-pragma state is preserved after
8721 // popping entries that were included/imported from a PCH/module.
8722 bool DropFirst = false;
8723 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8724 assert(FpPragmaStack.front().Value ==
8725 SemaObj->FpPragmaStack.DefaultValue &&
8726 "Expected a default pragma float_control value");
8727 SemaObj->FpPragmaStack.Stack.emplace_back(
8728 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8729 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8730 FpPragmaStack.front().PushLocation);
8731 DropFirst = true;
8732 }
8733 for (const auto &Entry :
8734 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8735 SemaObj->FpPragmaStack.Stack.emplace_back(
8736 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8737 if (FpPragmaCurrentLocation.isInvalid()) {
8738 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8739 "Expected a default pragma float_control value");
8740 // Keep the current values.
8741 } else {
8742 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8743 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8744 }
8745 }
8746
8747 // For non-modular AST files, restore visiblity of modules.
8748 for (auto &Import : PendingImportedModulesSema) {
8749 if (Import.ImportLoc.isInvalid())
8750 continue;
8751 if (Module *Imported = getSubmodule(Import.ID)) {
8752 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8753 }
8754 }
8755 PendingImportedModulesSema.clear();
8756}
8757
8759 // Note that we are loading an identifier.
8760 Deserializing AnIdentifier(this);
8761
8762 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8763 NumIdentifierLookups,
8764 NumIdentifierLookupHits);
8765
8766 // We don't need to do identifier table lookups in C++ modules (we preload
8767 // all interesting declarations, and don't need to use the scope for name
8768 // lookups). Perform the lookup in PCH files, though, since we don't build
8769 // a complete initial identifier table if we're carrying on from a PCH.
8770 if (PP.getLangOpts().CPlusPlus) {
8771 for (auto *F : ModuleMgr.pch_modules())
8772 if (Visitor(*F))
8773 break;
8774 } else {
8775 // If there is a global index, look there first to determine which modules
8776 // provably do not have any results for this identifier.
8778 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8779 if (!loadGlobalIndex()) {
8780 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8781 HitsPtr = &Hits;
8782 }
8783 }
8784
8785 ModuleMgr.visit(Visitor, HitsPtr);
8786 }
8787
8788 IdentifierInfo *II = Visitor.getIdentifierInfo();
8789 markIdentifierUpToDate(II);
8790 return II;
8791}
8792
8793namespace clang {
8794
8795 /// An identifier-lookup iterator that enumerates all of the
8796 /// identifiers stored within a set of AST files.
8798 /// The AST reader whose identifiers are being enumerated.
8799 const ASTReader &Reader;
8800
8801 /// The current index into the chain of AST files stored in
8802 /// the AST reader.
8803 unsigned Index;
8804
8805 /// The current position within the identifier lookup table
8806 /// of the current AST file.
8807 ASTIdentifierLookupTable::key_iterator Current;
8808
8809 /// The end position within the identifier lookup table of
8810 /// the current AST file.
8811 ASTIdentifierLookupTable::key_iterator End;
8812
8813 /// Whether to skip any modules in the ASTReader.
8814 bool SkipModules;
8815
8816 public:
8817 explicit ASTIdentifierIterator(const ASTReader &Reader,
8818 bool SkipModules = false);
8819
8820 StringRef Next() override;
8821 };
8822
8823} // namespace clang
8824
8826 bool SkipModules)
8827 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8828}
8829
8831 while (Current == End) {
8832 // If we have exhausted all of our AST files, we're done.
8833 if (Index == 0)
8834 return StringRef();
8835
8836 --Index;
8837 ModuleFile &F = Reader.ModuleMgr[Index];
8838 if (SkipModules && F.isModule())
8839 continue;
8840
8841 ASTIdentifierLookupTable *IdTable =
8843 Current = IdTable->key_begin();
8844 End = IdTable->key_end();
8845 }
8846
8847 // We have any identifiers remaining in the current AST file; return
8848 // the next one.
8849 StringRef Result = *Current;
8850 ++Current;
8851 return Result;
8852}
8853
8854namespace {
8855
8856/// A utility for appending two IdentifierIterators.
8857class ChainedIdentifierIterator : public IdentifierIterator {
8858 std::unique_ptr<IdentifierIterator> Current;
8859 std::unique_ptr<IdentifierIterator> Queued;
8860
8861public:
8862 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8863 std::unique_ptr<IdentifierIterator> Second)
8864 : Current(std::move(First)), Queued(std::move(Second)) {}
8865
8866 StringRef Next() override {
8867 if (!Current)
8868 return StringRef();
8869
8870 StringRef result = Current->Next();
8871 if (!result.empty())
8872 return result;
8873
8874 // Try the queued iterator, which may itself be empty.
8875 Current.reset();
8876 std::swap(Current, Queued);
8877 return Next();
8878 }
8879};
8880
8881} // namespace
8882
8884 if (!loadGlobalIndex()) {
8885 std::unique_ptr<IdentifierIterator> ReaderIter(
8886 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8887 std::unique_ptr<IdentifierIterator> ModulesIter(
8888 GlobalIndex->createIdentifierIterator());
8889 return new ChainedIdentifierIterator(std::move(ReaderIter),
8890 std::move(ModulesIter));
8891 }
8892
8893 return new ASTIdentifierIterator(*this);
8894}
8895
8896namespace clang {
8897namespace serialization {
8898
8900 ASTReader &Reader;
8901 Selector Sel;
8902 unsigned PriorGeneration;
8903 unsigned InstanceBits = 0;
8904 unsigned FactoryBits = 0;
8905 bool InstanceHasMoreThanOneDecl = false;
8906 bool FactoryHasMoreThanOneDecl = false;
8907 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8908 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8909
8910 public:
8912 unsigned PriorGeneration)
8913 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8914
8916 if (!M.SelectorLookupTable)
8917 return false;
8918
8919 // If we've already searched this module file, skip it now.
8920 if (M.Generation <= PriorGeneration)
8921 return true;
8922
8923 ++Reader.NumMethodPoolTableLookups;
8924 ASTSelectorLookupTable *PoolTable
8926 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8927 if (Pos == PoolTable->end())
8928 return false;
8929
8930 ++Reader.NumMethodPoolTableHits;
8931 ++Reader.NumSelectorsRead;
8932 // FIXME: Not quite happy with the statistics here. We probably should
8933 // disable this tracking when called via LoadSelector.
8934 // Also, should entries without methods count as misses?
8935 ++Reader.NumMethodPoolEntriesRead;
8937 if (Reader.DeserializationListener)
8938 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8939
8940 // Append methods in the reverse order, so that later we can process them
8941 // in the order they appear in the source code by iterating through
8942 // the vector in the reverse order.
8943 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8944 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8945 InstanceBits = Data.InstanceBits;
8946 FactoryBits = Data.FactoryBits;
8947 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8948 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8949 return false;
8950 }
8951
8952 /// Retrieve the instance methods found by this visitor.
8954 return InstanceMethods;
8955 }
8956
8957 /// Retrieve the instance methods found by this visitor.
8959 return FactoryMethods;
8960 }
8961
8962 unsigned getInstanceBits() const { return InstanceBits; }
8963 unsigned getFactoryBits() const { return FactoryBits; }
8964
8966 return InstanceHasMoreThanOneDecl;
8967 }
8968
8969 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8970 };
8971
8972} // namespace serialization
8973} // namespace clang
8974
8975/// Add the given set of methods to the method list.
8977 ObjCMethodList &List) {
8978 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8979 S.ObjC().addMethodToGlobalList(&List, M);
8980}
8981
8983 // Get the selector generation and update it to the current generation.
8984 unsigned &Generation = SelectorGeneration[Sel];
8985 unsigned PriorGeneration = Generation;
8986 Generation = getGeneration();
8987 SelectorOutOfDate[Sel] = false;
8988
8989 // Search for methods defined with this selector.
8990 ++NumMethodPoolLookups;
8991 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8992 ModuleMgr.visit(Visitor);
8993
8994 if (Visitor.getInstanceMethods().empty() &&
8995 Visitor.getFactoryMethods().empty())
8996 return;
8997
8998 ++NumMethodPoolHits;
8999
9000 if (!getSema())
9001 return;
9002
9003 Sema &S = *getSema();
9004 auto &Methods = S.ObjC().MethodPool[Sel];
9005
9006 Methods.first.setBits(Visitor.getInstanceBits());
9007 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9008 Methods.second.setBits(Visitor.getFactoryBits());
9009 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9010
9011 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9012 // when building a module we keep every method individually and may need to
9013 // update hasMoreThanOneDecl as we add the methods.
9014 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9015 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9016}
9017
9019 if (SelectorOutOfDate[Sel])
9020 ReadMethodPool(Sel);
9021}
9022
9025 Namespaces.clear();
9026
9027 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9028 if (NamespaceDecl *Namespace
9029 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9030 Namespaces.push_back(Namespace);
9031 }
9032}
9033
9035 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9036 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9037 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9038 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
9040 Undefined.insert(std::make_pair(D, Loc));
9041 }
9042 UndefinedButUsed.clear();
9043}
9044
9046 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9047 Exprs) {
9048 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9049 FieldDecl *FD =
9050 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9051 uint64_t Count = DelayedDeleteExprs[Idx++];
9052 for (uint64_t C = 0; C < Count; ++C) {
9053 SourceLocation DeleteLoc =
9054 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9055 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9056 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9057 }
9058 }
9059}
9060
9062 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9063 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9064 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9065 if (Var)
9066 TentativeDefs.push_back(Var);
9067 }
9068 TentativeDefinitions.clear();
9069}
9070
9073 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9075 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9076 if (D)
9077 Decls.push_back(D);
9078 }
9079 UnusedFileScopedDecls.clear();
9080}
9081
9084 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9086 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9087 if (D)
9088 Decls.push_back(D);
9089 }
9090 DelegatingCtorDecls.clear();
9091}
9092
9094 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9096 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9097 if (D)
9098 Decls.push_back(D);
9099 }
9100 ExtVectorDecls.clear();
9101}
9102
9105 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9106 ++I) {
9107 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9108 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9109 if (D)
9110 Decls.insert(D);
9111 }
9112 UnusedLocalTypedefNameCandidates.clear();
9113}
9114
9117 for (auto I : DeclsToCheckForDeferredDiags) {
9118 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9119 if (D)
9120 Decls.insert(D);
9121 }
9122 DeclsToCheckForDeferredDiags.clear();
9123}
9124
9126 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9127 if (ReferencedSelectorsData.empty())
9128 return;
9129
9130 // If there are @selector references added them to its pool. This is for
9131 // implementation of -Wselector.
9132 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9133 unsigned I = 0;
9134 while (I < DataSize) {
9135 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9136 SourceLocation SelLoc
9137 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9138 Sels.push_back(std::make_pair(Sel, SelLoc));
9139 }
9140 ReferencedSelectorsData.clear();
9141}
9142
9144 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9145 if (WeakUndeclaredIdentifiers.empty())
9146 return;
9147
9148 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9149 IdentifierInfo *WeakId
9150 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9151 IdentifierInfo *AliasId
9152 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9154 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9155 WeakInfo WI(AliasId, Loc);
9156 WeakIDs.push_back(std::make_pair(WeakId, WI));
9157 }
9158 WeakUndeclaredIdentifiers.clear();
9159}
9160
9162 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9164 VTableUse &TableInfo = VTableUses[Idx++];
9165 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9166 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9167 VT.DefinitionRequired = TableInfo.Used;
9168 VTables.push_back(VT);
9169 }
9170
9171 VTableUses.clear();
9172}
9173
9175 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9176 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9177 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9178 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9180
9181 Pending.push_back(std::make_pair(D, Loc));
9182 }
9183 PendingInstantiations.clear();
9184}
9185
9187 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9188 &LPTMap) {
9189 for (auto &LPT : LateParsedTemplates) {
9190 ModuleFile *FMod = LPT.first;
9191 RecordDataImpl &LateParsed = LPT.second;
9192 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9193 /* In loop */) {
9194 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9195
9196 auto LT = std::make_unique<LateParsedTemplate>();
9197 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9198 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9199
9201 assert(F && "No module");
9202
9203 unsigned TokN = LateParsed[Idx++];
9204 LT->Toks.reserve(TokN);
9205 for (unsigned T = 0; T < TokN; ++T)
9206 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9207
9208 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9209 }
9210 }
9211
9212 LateParsedTemplates.clear();
9213}
9214
9216 if (!Lambda->getLambdaContextDecl())
9217 return;
9218
9219 auto LambdaInfo =
9220 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9221 Lambda->getLambdaIndexInContext());
9222
9223 // Handle the import and then include case for lambdas.
9224 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9225 Iter != LambdaDeclarationsForMerging.end() &&
9226 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9228 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9229 Lambda->setPreviousDecl(Previous);
9230 // FIXME: It will be best to use the Previous type when we creating the
9231 // lambda directly. But that requires us to get the lambda context decl and
9232 // lambda index before creating the lambda, which needs a drastic change in
9233 // the parser.
9234 const_cast<QualType &>(Lambda->TypeForDecl->CanonicalType) =
9235 Previous->TypeForDecl->CanonicalType;
9236 return;
9237 }
9238
9239 // Keep track of this lambda so it can be merged with another lambda that
9240 // is loaded later.
9241 LambdaDeclarationsForMerging.insert(
9242 {LambdaInfo, const_cast<CXXRecordDecl *>(Lambda)});
9243}
9244
9246 // It would be complicated to avoid reading the methods anyway. So don't.
9247 ReadMethodPool(Sel);
9248}
9249
9251 assert(ID && "Non-zero identifier ID required");
9252 unsigned Index = translateIdentifierIDToIndex(ID).second;
9253 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9254 IdentifiersLoaded[Index] = II;
9255 if (DeserializationListener)
9256 DeserializationListener->IdentifierRead(ID, II);
9257}
9258
9259/// Set the globally-visible declarations associated with the given
9260/// identifier.
9261///
9262/// If the AST reader is currently in a state where the given declaration IDs
9263/// cannot safely be resolved, they are queued until it is safe to resolve
9264/// them.
9265///
9266/// \param II an IdentifierInfo that refers to one or more globally-visible
9267/// declarations.
9268///
9269/// \param DeclIDs the set of declaration IDs with the name @p II that are
9270/// visible at global scope.
9271///
9272/// \param Decls if non-null, this vector will be populated with the set of
9273/// deserialized declarations. These declarations will not be pushed into
9274/// scope.
9277 SmallVectorImpl<Decl *> *Decls) {
9278 if (NumCurrentElementsDeserializing && !Decls) {
9279 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9280 return;
9281 }
9282
9283 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9284 if (!SemaObj) {
9285 // Queue this declaration so that it will be added to the
9286 // translation unit scope and identifier's declaration chain
9287 // once a Sema object is known.
9288 PreloadedDeclIDs.push_back(DeclIDs[I]);
9289 continue;
9290 }
9291
9292 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9293
9294 // If we're simply supposed to record the declarations, do so now.
9295 if (Decls) {
9296 Decls->push_back(D);
9297 continue;
9298 }
9299
9300 // Introduce this declaration into the translation-unit scope
9301 // and add it to the declaration chain for this identifier, so
9302 // that (unqualified) name lookup will find it.
9303 pushExternalDeclIntoScope(D, II);
9304 }
9305}
9306
9307std::pair<ModuleFile *, unsigned>
9308ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9309 if (ID == 0)
9310 return {nullptr, 0};
9311
9312 unsigned ModuleFileIndex = ID >> 32;
9313 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9314
9315 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9316 assert(getModuleManager().size() > ModuleFileIndex - 1);
9317
9318 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9319 assert(LocalID < MF.LocalNumIdentifiers);
9320 return {&MF, MF.BaseIdentifierID + LocalID};
9321}
9322
9324 if (ID == 0)
9325 return nullptr;
9326
9327 if (IdentifiersLoaded.empty()) {
9328 Error("no identifier table in AST file");
9329 return nullptr;
9330 }
9331
9332 auto [M, Index] = translateIdentifierIDToIndex(ID);
9333 if (!IdentifiersLoaded[Index]) {
9334 assert(M != nullptr && "Untranslated Identifier ID?");
9335 assert(Index >= M->BaseIdentifierID);
9336 unsigned LocalIndex = Index - M->BaseIdentifierID;
9337 const unsigned char *Data =
9338 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9339
9340 ASTIdentifierLookupTrait Trait(*this, *M);
9341 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9342 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9343 auto &II = PP.getIdentifierTable().get(Key);
9344 IdentifiersLoaded[Index] = &II;
9345 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9346 markIdentifierFromAST(*this, II, IsModule);
9347 if (DeserializationListener)
9348 DeserializationListener->IdentifierRead(ID, &II);
9349 }
9350
9351 return IdentifiersLoaded[Index];
9352}
9353
9355 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
9356}
9357
9359 if (LocalID < NUM_PREDEF_IDENT_IDS)
9360 return LocalID;
9361
9362 if (!M.ModuleOffsetMap.empty())
9363 ReadModuleOffsetMap(M);
9364
9365 unsigned ModuleFileIndex = LocalID >> 32;
9366 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9367 ModuleFile *MF =
9368 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9369 assert(MF && "malformed identifier ID encoding?");
9370
9371 if (!ModuleFileIndex)
9372 LocalID -= NUM_PREDEF_IDENT_IDS;
9373
9374 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9375}
9376
9378 if (ID == 0)
9379 return nullptr;
9380
9381 if (MacrosLoaded.empty()) {
9382 Error("no macro table in AST file");
9383 return nullptr;
9384 }
9385
9387 if (!MacrosLoaded[ID]) {
9389 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
9390 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
9391 ModuleFile *M = I->second;
9392 unsigned Index = ID - M->BaseMacroID;
9393 MacrosLoaded[ID] =
9394 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
9395
9396 if (DeserializationListener)
9397 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
9398 MacrosLoaded[ID]);
9399 }
9400
9401 return MacrosLoaded[ID];
9402}
9403
9405 if (LocalID < NUM_PREDEF_MACRO_IDS)
9406 return LocalID;
9407
9408 if (!M.ModuleOffsetMap.empty())
9409 ReadModuleOffsetMap(M);
9410
9412 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
9413 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
9414
9415 return LocalID + I->second;
9416}
9417
9419ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9420 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9421 return LocalID;
9422
9423 if (!M.ModuleOffsetMap.empty())
9424 ReadModuleOffsetMap(M);
9425
9428 assert(I != M.SubmoduleRemap.end()
9429 && "Invalid index into submodule index remap");
9430
9431 return LocalID + I->second;
9432}
9433
9435 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9436 assert(GlobalID == 0 && "Unhandled global submodule ID");
9437 return nullptr;
9438 }
9439
9440 if (GlobalID > SubmodulesLoaded.size()) {
9441 Error("submodule ID out of range in AST file");
9442 return nullptr;
9443 }
9444
9445 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9446}
9447
9449 return getSubmodule(ID);
9450}
9451
9453 if (ID & 1) {
9454 // It's a module, look it up by submodule ID.
9455 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9456 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9457 } else {
9458 // It's a prefix (preamble, PCH, ...). Look it up by index.
9459 unsigned IndexFromEnd = ID >> 1;
9460 assert(IndexFromEnd && "got reference to unknown module file");
9461 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9462 }
9463}
9464
9466 if (!M)
9467 return 1;
9468
9469 // For a file representing a module, use the submodule ID of the top-level
9470 // module as the file ID. For any other kind of file, the number of such
9471 // files loaded beforehand will be the same on reload.
9472 // FIXME: Is this true even if we have an explicit module file and a PCH?
9473 if (M->isModule())
9474 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9475
9476 auto PCHModules = getModuleManager().pch_modules();
9477 auto I = llvm::find(PCHModules, M);
9478 assert(I != PCHModules.end() && "emitting reference to unknown file");
9479 return (I - PCHModules.end()) << 1;
9480}
9481
9482std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9483 if (Module *M = getSubmodule(ID))
9484 return ASTSourceDescriptor(*M);
9485
9486 // If there is only a single PCH, return it instead.
9487 // Chained PCH are not supported.
9488 const auto &PCHChain = ModuleMgr.pch_modules();
9489 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9490 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9491 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9492 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9493 return ASTSourceDescriptor(ModuleName,
9494 llvm::sys::path::parent_path(MF.FileName),
9495 FileName, MF.Signature);
9496 }
9497 return std::nullopt;
9498}
9499
9501 auto I = DefinitionSource.find(FD);
9502 if (I == DefinitionSource.end())
9503 return EK_ReplyHazy;
9504 return I->second ? EK_Never : EK_Always;
9505}
9506
9508 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9509}
9510
9512 if (ID == 0)
9513 return Selector();
9514
9515 if (ID > SelectorsLoaded.size()) {
9516 Error("selector ID out of range in AST file");
9517 return Selector();
9518 }
9519
9520 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9521 // Load this selector from the selector table.
9522 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9523 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9524 ModuleFile &M = *I->second;
9525 ASTSelectorLookupTrait Trait(*this, M);
9526 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9527 SelectorsLoaded[ID - 1] =
9528 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9529 if (DeserializationListener)
9530 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9531 }
9532
9533 return SelectorsLoaded[ID - 1];
9534}
9535
9537 return DecodeSelector(ID);
9538}
9539
9541 // ID 0 (the null selector) is considered an external selector.
9542 return getTotalNumSelectors() + 1;
9543}
9544
9546ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9547 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9548 return LocalID;
9549
9550 if (!M.ModuleOffsetMap.empty())
9551 ReadModuleOffsetMap(M);
9552
9555 assert(I != M.SelectorRemap.end()
9556 && "Invalid index into selector index remap");
9557
9558 return LocalID + I->second;
9559}
9560
9563 switch (Name.getNameKind()) {
9568
9571
9575
9582 break;
9583 }
9584 return DeclarationNameLoc();
9585}
9586
9588 DeclarationNameInfo NameInfo;
9589 NameInfo.setName(readDeclarationName());
9590 NameInfo.setLoc(readSourceLocation());
9591 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9592 return NameInfo;
9593}
9594
9596 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9597}
9598
9601 unsigned NumTPLists = readInt();
9602 Info.NumTemplParamLists = NumTPLists;
9603 if (NumTPLists) {
9604 Info.TemplParamLists =
9605 new (getContext()) TemplateParameterList *[NumTPLists];
9606 for (unsigned i = 0; i != NumTPLists; ++i)
9608 }
9609}
9610
9613 SourceLocation TemplateLoc = readSourceLocation();
9614 SourceLocation LAngleLoc = readSourceLocation();
9615 SourceLocation RAngleLoc = readSourceLocation();
9616
9617 unsigned NumParams = readInt();
9619 Params.reserve(NumParams);
9620 while (NumParams--)
9621 Params.push_back(readDeclAs<NamedDecl>());
9622
9623 bool HasRequiresClause = readBool();
9624 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9625
9627 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9628 return TemplateParams;
9629}
9630
9633 bool Canonicalize) {
9634 unsigned NumTemplateArgs = readInt();
9635 TemplArgs.reserve(NumTemplateArgs);
9636 while (NumTemplateArgs--)
9637 TemplArgs.push_back(readTemplateArgument(Canonicalize));
9638}
9639
9640/// Read a UnresolvedSet structure.
9642 unsigned NumDecls = readInt();
9643 Set.reserve(getContext(), NumDecls);
9644 while (NumDecls--) {
9645 GlobalDeclID ID = readDeclID();
9647 Set.addLazyDecl(getContext(), ID, AS);
9648 }
9649}
9650
9653 bool isVirtual = readBool();
9654 bool isBaseOfClass = readBool();
9655 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9656 bool inheritConstructors = readBool();
9659 SourceLocation EllipsisLoc = readSourceLocation();
9660 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9661 EllipsisLoc);
9662 Result.setInheritConstructors(inheritConstructors);
9663 return Result;
9664}
9665
9668 ASTContext &Context = getContext();
9669 unsigned NumInitializers = readInt();
9670 assert(NumInitializers && "wrote ctor initializers but have no inits");
9671 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9672 for (unsigned i = 0; i != NumInitializers; ++i) {
9673 TypeSourceInfo *TInfo = nullptr;
9674 bool IsBaseVirtual = false;
9675 FieldDecl *Member = nullptr;
9676 IndirectFieldDecl *IndirectMember = nullptr;
9677
9679 switch (Type) {
9681 TInfo = readTypeSourceInfo();
9682 IsBaseVirtual = readBool();
9683 break;
9684
9686 TInfo = readTypeSourceInfo();
9687 break;
9688
9690 Member = readDeclAs<FieldDecl>();
9691 break;
9692
9694 IndirectMember = readDeclAs<IndirectFieldDecl>();
9695 break;
9696 }
9697
9698 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9699 Expr *Init = readExpr();
9700 SourceLocation LParenLoc = readSourceLocation();
9701 SourceLocation RParenLoc = readSourceLocation();
9702
9703 CXXCtorInitializer *BOMInit;
9705 BOMInit = new (Context)
9706 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9707 RParenLoc, MemberOrEllipsisLoc);
9709 BOMInit = new (Context)
9710 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9711 else if (Member)
9712 BOMInit = new (Context)
9713 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9714 Init, RParenLoc);
9715 else
9716 BOMInit = new (Context)
9717 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9718 LParenLoc, Init, RParenLoc);
9719
9720 if (/*IsWritten*/readBool()) {
9721 unsigned SourceOrder = readInt();
9722 BOMInit->setSourceOrder(SourceOrder);
9723 }
9724
9725 CtorInitializers[i] = BOMInit;
9726 }
9727
9728 return CtorInitializers;
9729}
9730
9733 ASTContext &Context = getContext();
9734 unsigned N = readInt();
9736 for (unsigned I = 0; I != N; ++I) {
9737 auto Kind = readNestedNameSpecifierKind();
9738 switch (Kind) {
9742 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9743 break;
9744 }
9745
9747 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9749 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9750 break;
9751 }
9752
9754 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9756 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9757 break;
9758 }
9759
9762 bool Template = readBool();
9764 if (!T)
9765 return NestedNameSpecifierLoc();
9766 SourceLocation ColonColonLoc = readSourceLocation();
9767
9768 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9769 Builder.Extend(Context,
9770 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9771 T->getTypeLoc(), ColonColonLoc);
9772 break;
9773 }
9774
9776 SourceLocation ColonColonLoc = readSourceLocation();
9777 Builder.MakeGlobal(Context, ColonColonLoc);
9778 break;
9779 }
9780
9782 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9784 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9785 break;
9786 }
9787 }
9788 }
9789
9790 return Builder.getWithLocInContext(Context);
9791}
9792
9794 unsigned &Idx, LocSeq *Seq) {
9797 return SourceRange(beg, end);
9798}
9799
9801 const StringRef Blob) {
9802 unsigned Count = Record[0];
9803 const char *Byte = Blob.data();
9804 llvm::BitVector Ret = llvm::BitVector(Count, false);
9805 for (unsigned I = 0; I < Count; ++Byte)
9806 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9807 if (*Byte & (1 << Bit))
9808 Ret[I] = true;
9809 return Ret;
9810}
9811
9812/// Read a floating-point value
9813llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9814 return llvm::APFloat(Sem, readAPInt());
9815}
9816
9817// Read a string
9818std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9819 unsigned Len = Record[Idx++];
9820 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9821 Idx += Len;
9822 return Result;
9823}
9824
9825StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
9826 StringRef &Blob) {
9827 unsigned Len = Record[Idx++];
9828 StringRef Result = Blob.substr(0, Len);
9829 Blob = Blob.substr(Len);
9830 return Result;
9831}
9832
9834 unsigned &Idx) {
9835 return ReadPath(F.BaseDirectory, Record, Idx);
9836}
9837
9838std::string ASTReader::ReadPath(StringRef BaseDirectory,
9839 const RecordData &Record, unsigned &Idx) {
9840 std::string Filename = ReadString(Record, Idx);
9841 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
9842}
9843
9844std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
9845 const RecordData &Record, unsigned &Idx,
9846 StringRef &Blob) {
9847 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
9848 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
9849}
9850
9852 unsigned &Idx) {
9853 unsigned Major = Record[Idx++];
9854 unsigned Minor = Record[Idx++];
9855 unsigned Subminor = Record[Idx++];
9856 if (Minor == 0)
9857 return VersionTuple(Major);
9858 if (Subminor == 0)
9859 return VersionTuple(Major, Minor - 1);
9860 return VersionTuple(Major, Minor - 1, Subminor - 1);
9861}
9862
9864 const RecordData &Record,
9865 unsigned &Idx) {
9866 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9868}
9869
9870DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9871 return Diag(CurrentImportLoc, DiagID);
9872}
9873
9875 return Diags.Report(Loc, DiagID);
9876}
9877
9879 llvm::function_ref<void()> Fn) {
9880 // When Sema is available, avoid duplicate errors.
9881 if (SemaObj) {
9882 SemaObj->runWithSufficientStackSpace(Loc, Fn);
9883 return;
9884 }
9885
9886 StackHandler.runWithSufficientStackSpace(Loc, Fn);
9887}
9888
9889/// Retrieve the identifier table associated with the
9890/// preprocessor.
9892 return PP.getIdentifierTable();
9893}
9894
9895/// Record that the given ID maps to the given switch-case
9896/// statement.
9898 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9899 "Already have a SwitchCase with this ID");
9900 (*CurrSwitchCaseStmts)[ID] = SC;
9901}
9902
9903/// Retrieve the switch-case statement with the given ID.
9905 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9906 return (*CurrSwitchCaseStmts)[ID];
9907}
9908
9910 CurrSwitchCaseStmts->clear();
9911}
9912
9914 ASTContext &Context = getContext();
9915 std::vector<RawComment *> Comments;
9916 for (SmallVectorImpl<std::pair<BitstreamCursor,
9917 serialization::ModuleFile *>>::iterator
9918 I = CommentsCursors.begin(),
9919 E = CommentsCursors.end();
9920 I != E; ++I) {
9921 Comments.clear();
9922 BitstreamCursor &Cursor = I->first;
9923 serialization::ModuleFile &F = *I->second;
9924 SavedStreamPosition SavedPosition(Cursor);
9925
9927 while (true) {
9929 Cursor.advanceSkippingSubblocks(
9930 BitstreamCursor::AF_DontPopBlockAtEnd);
9931 if (!MaybeEntry) {
9932 Error(MaybeEntry.takeError());
9933 return;
9934 }
9935 llvm::BitstreamEntry Entry = MaybeEntry.get();
9936
9937 switch (Entry.Kind) {
9938 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9939 case llvm::BitstreamEntry::Error:
9940 Error("malformed block record in AST file");
9941 return;
9942 case llvm::BitstreamEntry::EndBlock:
9943 goto NextCursor;
9944 case llvm::BitstreamEntry::Record:
9945 // The interesting case.
9946 break;
9947 }
9948
9949 // Read a record.
9950 Record.clear();
9951 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9952 if (!MaybeComment) {
9953 Error(MaybeComment.takeError());
9954 return;
9955 }
9956 switch ((CommentRecordTypes)MaybeComment.get()) {
9957 case COMMENTS_RAW_COMMENT: {
9958 unsigned Idx = 0;
9959 SourceRange SR = ReadSourceRange(F, Record, Idx);
9962 bool IsTrailingComment = Record[Idx++];
9963 bool IsAlmostTrailingComment = Record[Idx++];
9964 Comments.push_back(new (Context) RawComment(
9965 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9966 break;
9967 }
9968 }
9969 }
9970 NextCursor:
9971 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9972 FileToOffsetToComment;
9973 for (RawComment *C : Comments) {
9974 SourceLocation CommentLoc = C->getBeginLoc();
9975 if (CommentLoc.isValid()) {
9976 std::pair<FileID, unsigned> Loc =
9977 SourceMgr.getDecomposedLoc(CommentLoc);
9978 if (Loc.first.isValid())
9979 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9980 }
9981 }
9982 }
9983}
9984
9986 serialization::ModuleFile &MF, bool IncludeSystem,
9987 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9988 bool IsSystem)>
9989 Visitor) {
9990 unsigned NumUserInputs = MF.NumUserInputFiles;
9991 unsigned NumInputs = MF.InputFilesLoaded.size();
9992 assert(NumUserInputs <= NumInputs);
9993 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9994 for (unsigned I = 0; I < N; ++I) {
9995 bool IsSystem = I >= NumUserInputs;
9996 InputFileInfo IFI = getInputFileInfo(MF, I+1);
9997 Visitor(IFI, IsSystem);
9998 }
9999}
10000
10002 bool IncludeSystem, bool Complain,
10003 llvm::function_ref<void(const serialization::InputFile &IF,
10004 bool isSystem)> Visitor) {
10005 unsigned NumUserInputs = MF.NumUserInputFiles;
10006 unsigned NumInputs = MF.InputFilesLoaded.size();
10007 assert(NumUserInputs <= NumInputs);
10008 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10009 for (unsigned I = 0; I < N; ++I) {
10010 bool IsSystem = I >= NumUserInputs;
10011 InputFile IF = getInputFile(MF, I+1, Complain);
10012 Visitor(IF, IsSystem);
10013 }
10014}
10015
10018 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10019 unsigned NumInputs = MF.InputFilesLoaded.size();
10020 for (unsigned I = 0; I < NumInputs; ++I) {
10021 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10022 if (IFI.TopLevel && IFI.ModuleMap)
10023 if (auto FE = getInputFile(MF, I + 1).getFile())
10024 Visitor(*FE);
10025 }
10026}
10027
10028void ASTReader::finishPendingActions() {
10029 while (
10030 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
10031 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
10032 !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
10033 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
10034 !PendingObjCExtensionIvarRedeclarations.empty()) {
10035 // If any identifiers with corresponding top-level declarations have
10036 // been loaded, load those declarations now.
10037 using TopLevelDeclsMap =
10038 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10039 TopLevelDeclsMap TopLevelDecls;
10040
10041 while (!PendingIdentifierInfos.empty()) {
10042 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10044 std::move(PendingIdentifierInfos.back().second);
10045 PendingIdentifierInfos.pop_back();
10046
10047 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10048 }
10049
10050 // Load each function type that we deferred loading because it was a
10051 // deduced type that might refer to a local type declared within itself.
10052 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10053 auto *FD = PendingDeducedFunctionTypes[I].first;
10054 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10055
10056 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10057 // If we gave a function a deduced return type, remember that we need to
10058 // propagate that along the redeclaration chain.
10059 if (DT->isDeduced()) {
10060 PendingDeducedTypeUpdates.insert(
10061 {FD->getCanonicalDecl(), FD->getReturnType()});
10062 continue;
10063 }
10064
10065 // The function has undeduced DeduceType return type. We hope we can
10066 // find the deduced type by iterating the redecls in other modules
10067 // later.
10068 PendingUndeducedFunctionDecls.push_back(FD);
10069 continue;
10070 }
10071 }
10072 PendingDeducedFunctionTypes.clear();
10073
10074 // Load each variable type that we deferred loading because it was a
10075 // deduced type that might refer to a local type declared within itself.
10076 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10077 auto *VD = PendingDeducedVarTypes[I].first;
10078 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10079 }
10080 PendingDeducedVarTypes.clear();
10081
10082 // For each decl chain that we wanted to complete while deserializing, mark
10083 // it as "still needs to be completed".
10084 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
10085 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
10086 }
10087 PendingIncompleteDeclChains.clear();
10088
10089 // Load pending declaration chains.
10090 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10091 loadPendingDeclChain(PendingDeclChains[I].first,
10092 PendingDeclChains[I].second);
10093 PendingDeclChains.clear();
10094
10095 // Make the most recent of the top-level declarations visible.
10096 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10097 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10098 IdentifierInfo *II = TLD->first;
10099 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10100 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10101 }
10102 }
10103
10104 // Load any pending macro definitions.
10105 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10106 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10108 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10109 // Initialize the macro history from chained-PCHs ahead of module imports.
10110 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10111 ++IDIdx) {
10112 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10113 if (!Info.M->isModule())
10114 resolvePendingMacro(II, Info);
10115 }
10116 // Handle module imports.
10117 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10118 ++IDIdx) {
10119 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10120 if (Info.M->isModule())
10121 resolvePendingMacro(II, Info);
10122 }
10123 }
10124 PendingMacroIDs.clear();
10125
10126 // Wire up the DeclContexts for Decls that we delayed setting until
10127 // recursive loading is completed.
10128 while (!PendingDeclContextInfos.empty()) {
10129 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10130 PendingDeclContextInfos.pop_front();
10131 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10132 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10133 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10134 }
10135
10136 // Perform any pending declaration updates.
10137 while (!PendingUpdateRecords.empty()) {
10138 auto Update = PendingUpdateRecords.pop_back_val();
10139 ReadingKindTracker ReadingKind(Read_Decl, *this);
10140 loadDeclUpdateRecords(Update);
10141 }
10142
10143 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10144 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10145 auto DuplicateIvars =
10146 PendingObjCExtensionIvarRedeclarations.back().second;
10149 ExtensionsPair.first->getASTContext(),
10150 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10151 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10152 /*Complain =*/false,
10153 /*ErrorOnTagTypeMismatch =*/true);
10154 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10155 // Merge redeclared ivars with their predecessors.
10156 for (auto IvarPair : DuplicateIvars) {
10157 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10158 // Change semantic DeclContext but keep the lexical one.
10159 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10160 Ivar->getLexicalDeclContext(),
10161 getContext());
10162 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10163 }
10164 // Invalidate duplicate extension and the cached ivar list.
10165 ExtensionsPair.first->setInvalidDecl();
10166 ExtensionsPair.second->getClassInterface()
10167 ->getDefinition()
10168 ->setIvarList(nullptr);
10169 } else {
10170 for (auto IvarPair : DuplicateIvars) {
10171 Diag(IvarPair.first->getLocation(),
10172 diag::err_duplicate_ivar_declaration)
10173 << IvarPair.first->getIdentifier();
10174 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10175 }
10176 }
10177 PendingObjCExtensionIvarRedeclarations.pop_back();
10178 }
10179 }
10180
10181 // At this point, all update records for loaded decls are in place, so any
10182 // fake class definitions should have become real.
10183 assert(PendingFakeDefinitionData.empty() &&
10184 "faked up a class definition but never saw the real one");
10185
10186 // If we deserialized any C++ or Objective-C class definitions, any
10187 // Objective-C protocol definitions, or any redeclarable templates, make sure
10188 // that all redeclarations point to the definitions. Note that this can only
10189 // happen now, after the redeclaration chains have been fully wired.
10190 for (Decl *D : PendingDefinitions) {
10191 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10192 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
10193 // Make sure that the TagType points at the definition.
10194 const_cast<TagType*>(TagT)->decl = TD;
10195 }
10196
10197 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
10198 for (auto *R = getMostRecentExistingDecl(RD); R;
10199 R = R->getPreviousDecl()) {
10200 assert((R == D) ==
10201 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10202 "declaration thinks it's the definition but it isn't");
10203 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10204 }
10205 }
10206
10207 continue;
10208 }
10209
10210 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10211 // Make sure that the ObjCInterfaceType points at the definition.
10212 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10213 ->Decl = ID;
10214
10215 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10216 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10217
10218 continue;
10219 }
10220
10221 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10222 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10223 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10224
10225 continue;
10226 }
10227
10228 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10229 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10230 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10231 }
10232 PendingDefinitions.clear();
10233
10234 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10235 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10236 if (auto *VD = dyn_cast<VarDecl>(D))
10237 return VD->isThisDeclarationADefinition() ||
10238 VD->isThisDeclarationADemotedDefinition();
10239
10240 if (auto *TD = dyn_cast<TagDecl>(D))
10241 return TD->isThisDeclarationADefinition() ||
10242 TD->isThisDeclarationADemotedDefinition();
10243
10244 if (auto *FD = dyn_cast<FunctionDecl>(D))
10245 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10246
10247 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10248 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10249
10250 // Conservatively return false here.
10251 return false;
10252 };
10253
10254 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10255 return hasDefinitionImpl(D, hasDefinitionImpl);
10256 };
10257
10258 // It is not good to prevent multiple declarations since the forward
10259 // declaration is common. Let's try to avoid duplicated definitions
10260 // only.
10262 continue;
10263
10264 Module *PM = Previous->getOwningModule();
10265 Module *DM = D->getOwningModule();
10266 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10267 << cast<NamedDecl>(Previous) << PM->getTopLevelModuleName()
10268 << (DM ? DM->getTopLevelModuleName() : "global module");
10269 Diag(Previous->getLocation(), diag::note_also_found);
10270 }
10271 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10272
10273 // Load the bodies of any functions or methods we've encountered. We do
10274 // this now (delayed) so that we can be sure that the declaration chains
10275 // have been fully wired up (hasBody relies on this).
10276 // FIXME: We shouldn't require complete redeclaration chains here.
10277 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10278 PBEnd = PendingBodies.end();
10279 PB != PBEnd; ++PB) {
10280 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10281 // FIXME: Check for =delete/=default?
10282 const FunctionDecl *Defn = nullptr;
10283 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10284 FD->setLazyBody(PB->second);
10285 } else {
10286 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10287 mergeDefinitionVisibility(NonConstDefn, FD);
10288
10289 if (!FD->isLateTemplateParsed() &&
10290 !NonConstDefn->isLateTemplateParsed() &&
10291 // We only perform ODR checks for decls not in the explicit
10292 // global module fragment.
10293 !shouldSkipCheckingODR(FD) &&
10294 !shouldSkipCheckingODR(NonConstDefn) &&
10295 FD->getODRHash() != NonConstDefn->getODRHash()) {
10296 if (!isa<CXXMethodDecl>(FD)) {
10297 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10298 } else if (FD->getLexicalParent()->isFileContext() &&
10299 NonConstDefn->getLexicalParent()->isFileContext()) {
10300 // Only diagnose out-of-line method definitions. If they are
10301 // in class definitions, then an error will be generated when
10302 // processing the class bodies.
10303 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10304 }
10305 }
10306 }
10307 continue;
10308 }
10309
10310 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10311 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10312 MD->setLazyBody(PB->second);
10313 }
10314 PendingBodies.clear();
10315
10316 // Inform any classes that had members added that they now have more members.
10317 for (auto [RD, MD] : PendingAddedClassMembers) {
10318 RD->addedMember(MD);
10319 }
10320 PendingAddedClassMembers.clear();
10321
10322 // Do some cleanup.
10323 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10325 PendingMergedDefinitionsToDeduplicate.clear();
10326}
10327
10328void ASTReader::diagnoseOdrViolations() {
10329 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10330 PendingRecordOdrMergeFailures.empty() &&
10331 PendingFunctionOdrMergeFailures.empty() &&
10332 PendingEnumOdrMergeFailures.empty() &&
10333 PendingObjCInterfaceOdrMergeFailures.empty() &&
10334 PendingObjCProtocolOdrMergeFailures.empty())
10335 return;
10336
10337 // Trigger the import of the full definition of each class that had any
10338 // odr-merging problems, so we can produce better diagnostics for them.
10339 // These updates may in turn find and diagnose some ODR failures, so take
10340 // ownership of the set first.
10341 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10342 PendingOdrMergeFailures.clear();
10343 for (auto &Merge : OdrMergeFailures) {
10344 Merge.first->buildLookup();
10345 Merge.first->decls_begin();
10346 Merge.first->bases_begin();
10347 Merge.first->vbases_begin();
10348 for (auto &RecordPair : Merge.second) {
10349 auto *RD = RecordPair.first;
10350 RD->decls_begin();
10351 RD->bases_begin();
10352 RD->vbases_begin();
10353 }
10354 }
10355
10356 // Trigger the import of the full definition of each record in C/ObjC.
10357 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10358 PendingRecordOdrMergeFailures.clear();
10359 for (auto &Merge : RecordOdrMergeFailures) {
10360 Merge.first->decls_begin();
10361 for (auto &D : Merge.second)
10362 D->decls_begin();
10363 }
10364
10365 // Trigger the import of the full interface definition.
10366 auto ObjCInterfaceOdrMergeFailures =
10367 std::move(PendingObjCInterfaceOdrMergeFailures);
10368 PendingObjCInterfaceOdrMergeFailures.clear();
10369 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10370 Merge.first->decls_begin();
10371 for (auto &InterfacePair : Merge.second)
10372 InterfacePair.first->decls_begin();
10373 }
10374
10375 // Trigger the import of functions.
10376 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10377 PendingFunctionOdrMergeFailures.clear();
10378 for (auto &Merge : FunctionOdrMergeFailures) {
10379 Merge.first->buildLookup();
10380 Merge.first->decls_begin();
10381 Merge.first->getBody();
10382 for (auto &FD : Merge.second) {
10383 FD->buildLookup();
10384 FD->decls_begin();
10385 FD->getBody();
10386 }
10387 }
10388
10389 // Trigger the import of enums.
10390 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10391 PendingEnumOdrMergeFailures.clear();
10392 for (auto &Merge : EnumOdrMergeFailures) {
10393 Merge.first->decls_begin();
10394 for (auto &Enum : Merge.second) {
10395 Enum->decls_begin();
10396 }
10397 }
10398
10399 // Trigger the import of the full protocol definition.
10400 auto ObjCProtocolOdrMergeFailures =
10401 std::move(PendingObjCProtocolOdrMergeFailures);
10402 PendingObjCProtocolOdrMergeFailures.clear();
10403 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10404 Merge.first->decls_begin();
10405 for (auto &ProtocolPair : Merge.second)
10406 ProtocolPair.first->decls_begin();
10407 }
10408
10409 // For each declaration from a merged context, check that the canonical
10410 // definition of that context also contains a declaration of the same
10411 // entity.
10412 //
10413 // Caution: this loop does things that might invalidate iterators into
10414 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10415 while (!PendingOdrMergeChecks.empty()) {
10416 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10417
10418 // FIXME: Skip over implicit declarations for now. This matters for things
10419 // like implicitly-declared special member functions. This isn't entirely
10420 // correct; we can end up with multiple unmerged declarations of the same
10421 // implicit entity.
10422 if (D->isImplicit())
10423 continue;
10424
10425 DeclContext *CanonDef = D->getDeclContext();
10426
10427 bool Found = false;
10428 const Decl *DCanon = D->getCanonicalDecl();
10429
10430 for (auto *RI : D->redecls()) {
10431 if (RI->getLexicalDeclContext() == CanonDef) {
10432 Found = true;
10433 break;
10434 }
10435 }
10436 if (Found)
10437 continue;
10438
10439 // Quick check failed, time to do the slow thing. Note, we can't just
10440 // look up the name of D in CanonDef here, because the member that is
10441 // in CanonDef might not be found by name lookup (it might have been
10442 // replaced by a more recent declaration in the lookup table), and we
10443 // can't necessarily find it in the redeclaration chain because it might
10444 // be merely mergeable, not redeclarable.
10446 for (auto *CanonMember : CanonDef->decls()) {
10447 if (CanonMember->getCanonicalDecl() == DCanon) {
10448 // This can happen if the declaration is merely mergeable and not
10449 // actually redeclarable (we looked for redeclarations earlier).
10450 //
10451 // FIXME: We should be able to detect this more efficiently, without
10452 // pulling in all of the members of CanonDef.
10453 Found = true;
10454 break;
10455 }
10456 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10457 if (ND->getDeclName() == D->getDeclName())
10458 Candidates.push_back(ND);
10459 }
10460
10461 if (!Found) {
10462 // The AST doesn't like TagDecls becoming invalid after they've been
10463 // completed. We only really need to mark FieldDecls as invalid here.
10464 if (!isa<TagDecl>(D))
10465 D->setInvalidDecl();
10466
10467 // Ensure we don't accidentally recursively enter deserialization while
10468 // we're producing our diagnostic.
10469 Deserializing RecursionGuard(this);
10470
10471 std::string CanonDefModule =
10473 cast<Decl>(CanonDef));
10474 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10476 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10477
10478 if (Candidates.empty())
10479 Diag(cast<Decl>(CanonDef)->getLocation(),
10480 diag::note_module_odr_violation_no_possible_decls) << D;
10481 else {
10482 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10483 Diag(Candidates[I]->getLocation(),
10484 diag::note_module_odr_violation_possible_decl)
10485 << Candidates[I];
10486 }
10487
10488 DiagnosedOdrMergeFailures.insert(CanonDef);
10489 }
10490 }
10491
10492 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10493 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10494 ObjCInterfaceOdrMergeFailures.empty() &&
10495 ObjCProtocolOdrMergeFailures.empty())
10496 return;
10497
10498 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10499 getPreprocessor().getLangOpts());
10500
10501 // Issue any pending ODR-failure diagnostics.
10502 for (auto &Merge : OdrMergeFailures) {
10503 // If we've already pointed out a specific problem with this class, don't
10504 // bother issuing a general "something's different" diagnostic.
10505 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10506 continue;
10507
10508 bool Diagnosed = false;
10509 CXXRecordDecl *FirstRecord = Merge.first;
10510 for (auto &RecordPair : Merge.second) {
10511 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10512 RecordPair.second)) {
10513 Diagnosed = true;
10514 break;
10515 }
10516 }
10517
10518 if (!Diagnosed) {
10519 // All definitions are updates to the same declaration. This happens if a
10520 // module instantiates the declaration of a class template specialization
10521 // and two or more other modules instantiate its definition.
10522 //
10523 // FIXME: Indicate which modules had instantiations of this definition.
10524 // FIXME: How can this even happen?
10525 Diag(Merge.first->getLocation(),
10526 diag::err_module_odr_violation_different_instantiations)
10527 << Merge.first;
10528 }
10529 }
10530
10531 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10532 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10533 for (auto &Merge : RecordOdrMergeFailures) {
10534 // If we've already pointed out a specific problem with this class, don't
10535 // bother issuing a general "something's different" diagnostic.
10536 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10537 continue;
10538
10539 RecordDecl *FirstRecord = Merge.first;
10540 bool Diagnosed = false;
10541 for (auto *SecondRecord : Merge.second) {
10542 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10543 Diagnosed = true;
10544 break;
10545 }
10546 }
10547 (void)Diagnosed;
10548 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10549 }
10550
10551 // Issue ODR failures diagnostics for functions.
10552 for (auto &Merge : FunctionOdrMergeFailures) {
10553 FunctionDecl *FirstFunction = Merge.first;
10554 bool Diagnosed = false;
10555 for (auto &SecondFunction : Merge.second) {
10556 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10557 Diagnosed = true;
10558 break;
10559 }
10560 }
10561 (void)Diagnosed;
10562 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10563 }
10564
10565 // Issue ODR failures diagnostics for enums.
10566 for (auto &Merge : EnumOdrMergeFailures) {
10567 // If we've already pointed out a specific problem with this enum, don't
10568 // bother issuing a general "something's different" diagnostic.
10569 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10570 continue;
10571
10572 EnumDecl *FirstEnum = Merge.first;
10573 bool Diagnosed = false;
10574 for (auto &SecondEnum : Merge.second) {
10575 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10576 Diagnosed = true;
10577 break;
10578 }
10579 }
10580 (void)Diagnosed;
10581 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10582 }
10583
10584 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10585 // If we've already pointed out a specific problem with this interface,
10586 // don't bother issuing a general "something's different" diagnostic.
10587 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10588 continue;
10589
10590 bool Diagnosed = false;
10591 ObjCInterfaceDecl *FirstID = Merge.first;
10592 for (auto &InterfacePair : Merge.second) {
10593 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10594 InterfacePair.second)) {
10595 Diagnosed = true;
10596 break;
10597 }
10598 }
10599 (void)Diagnosed;
10600 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10601 }
10602
10603 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10604 // If we've already pointed out a specific problem with this protocol,
10605 // don't bother issuing a general "something's different" diagnostic.
10606 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10607 continue;
10608
10609 ObjCProtocolDecl *FirstProtocol = Merge.first;
10610 bool Diagnosed = false;
10611 for (auto &ProtocolPair : Merge.second) {
10612 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10613 ProtocolPair.second)) {
10614 Diagnosed = true;
10615 break;
10616 }
10617 }
10618 (void)Diagnosed;
10619 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10620 }
10621}
10622
10624 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10625 ReadTimer->startTimer();
10626}
10627
10629 assert(NumCurrentElementsDeserializing &&
10630 "FinishedDeserializing not paired with StartedDeserializing");
10631 if (NumCurrentElementsDeserializing == 1) {
10632 // We decrease NumCurrentElementsDeserializing only after pending actions
10633 // are finished, to avoid recursively re-calling finishPendingActions().
10634 finishPendingActions();
10635 }
10636 --NumCurrentElementsDeserializing;
10637
10638 if (NumCurrentElementsDeserializing == 0) {
10639 // Propagate exception specification and deduced type updates along
10640 // redeclaration chains.
10641 //
10642 // We do this now rather than in finishPendingActions because we want to
10643 // be able to walk the complete redeclaration chains of the updated decls.
10644 while (!PendingExceptionSpecUpdates.empty() ||
10645 !PendingDeducedTypeUpdates.empty() ||
10646 !PendingUndeducedFunctionDecls.empty()) {
10647 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10648 PendingExceptionSpecUpdates.clear();
10649 for (auto Update : ESUpdates) {
10650 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10651 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10652 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10653 if (auto *Listener = getContext().getASTMutationListener())
10654 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10655 for (auto *Redecl : Update.second->redecls())
10656 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10657 }
10658
10659 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10660 PendingDeducedTypeUpdates.clear();
10661 for (auto Update : DTUpdates) {
10662 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10663 // FIXME: If the return type is already deduced, check that it matches.
10665 Update.second);
10666 }
10667
10668 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10669 PendingUndeducedFunctionDecls.clear();
10670 // We hope we can find the deduced type for the functions by iterating
10671 // redeclarations in other modules.
10672 for (FunctionDecl *UndeducedFD : UDTUpdates)
10673 (void)UndeducedFD->getMostRecentDecl();
10674 }
10675
10676 if (ReadTimer)
10677 ReadTimer->stopTimer();
10678
10679 diagnoseOdrViolations();
10680
10681 // We are not in recursive loading, so it's safe to pass the "interesting"
10682 // decls to the consumer.
10683 if (Consumer)
10684 PassInterestingDeclsToConsumer();
10685 }
10686}
10687
10688void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10689 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10690 // Remove any fake results before adding any real ones.
10691 auto It = PendingFakeLookupResults.find(II);
10692 if (It != PendingFakeLookupResults.end()) {
10693 for (auto *ND : It->second)
10694 SemaObj->IdResolver.RemoveDecl(ND);
10695 // FIXME: this works around module+PCH performance issue.
10696 // Rather than erase the result from the map, which is O(n), just clear
10697 // the vector of NamedDecls.
10698 It->second.clear();
10699 }
10700 }
10701
10702 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10703 SemaObj->TUScope->AddDecl(D);
10704 } else if (SemaObj->TUScope) {
10705 // Adding the decl to IdResolver may have failed because it was already in
10706 // (even though it was not added in scope). If it is already in, make sure
10707 // it gets in the scope as well.
10708 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10709 SemaObj->TUScope->AddDecl(D);
10710 }
10711}
10712
10714 ASTContext *Context,
10715 const PCHContainerReader &PCHContainerRdr,
10716 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10717 StringRef isysroot,
10718 DisableValidationForModuleKind DisableValidationKind,
10719 bool AllowASTWithCompilerErrors,
10720 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10721 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10722 std::unique_ptr<llvm::Timer> ReadTimer)
10723 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
10725 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10726 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10727 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
10728 StackHandler(Diags), PP(PP), ContextObj(Context),
10729 ModuleMgr(PP.getFileManager(), ModuleCache, PCHContainerRdr,
10730 PP.getHeaderSearchInfo()),
10731 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10732 DisableValidationKind(DisableValidationKind),
10733 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10734 AllowConfigurationMismatch(AllowConfigurationMismatch),
10735 ValidateSystemInputs(ValidateSystemInputs),
10736 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10737 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10738 SourceMgr.setExternalSLocEntrySource(this);
10739
10740 PathBuf.reserve(256);
10741
10742 for (const auto &Ext : Extensions) {
10743 auto BlockName = Ext->getExtensionMetadata().BlockName;
10744 auto Known = ModuleFileExtensions.find(BlockName);
10745 if (Known != ModuleFileExtensions.end()) {
10746 Diags.Report(diag::warn_duplicate_module_file_extension)
10747 << BlockName;
10748 continue;
10749 }
10750
10751 ModuleFileExtensions.insert({BlockName, Ext});
10752 }
10753}
10754
10756 if (OwnsDeserializationListener)
10757 delete DeserializationListener;
10758}
10759
10761 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10762}
10763
10765 unsigned AbbrevID) {
10766 Idx = 0;
10767 Record.clear();
10768 return Cursor.readRecord(AbbrevID, Record);
10769}
10770//===----------------------------------------------------------------------===//
10771//// OMPClauseReader implementation
10772////===----------------------------------------------------------------------===//
10773
10774// This has to be in namespace clang because it's friended by all
10775// of the OMP clauses.
10776namespace clang {
10777
10778class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10780 ASTContext &Context;
10781
10782public:
10784 : Record(Record), Context(Record.getContext()) {}
10785#define GEN_CLANG_CLAUSE_CLASS
10786#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10787#include "llvm/Frontend/OpenMP/OMP.inc"
10791};
10792
10793} // end namespace clang
10794
10796 return OMPClauseReader(*this).readClause();
10797}
10798
10800 OMPClause *C = nullptr;
10801 switch (llvm::omp::Clause(Record.readInt())) {
10802 case llvm::omp::OMPC_if:
10803 C = new (Context) OMPIfClause();
10804 break;
10805 case llvm::omp::OMPC_final:
10806 C = new (Context) OMPFinalClause();
10807 break;
10808 case llvm::omp::OMPC_num_threads:
10809 C = new (Context) OMPNumThreadsClause();
10810 break;
10811 case llvm::omp::OMPC_safelen:
10812 C = new (Context) OMPSafelenClause();
10813 break;
10814 case llvm::omp::OMPC_simdlen:
10815 C = new (Context) OMPSimdlenClause();
10816 break;
10817 case llvm::omp::OMPC_sizes: {
10818 unsigned NumSizes = Record.readInt();
10819 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10820 break;
10821 }
10822 case llvm::omp::OMPC_permutation: {
10823 unsigned NumLoops = Record.readInt();
10824 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
10825 break;
10826 }
10827 case llvm::omp::OMPC_full:
10828 C = OMPFullClause::CreateEmpty(Context);
10829 break;
10830 case llvm::omp::OMPC_partial:
10832 break;
10833 case llvm::omp::OMPC_allocator:
10834 C = new (Context) OMPAllocatorClause();
10835 break;
10836 case llvm::omp::OMPC_collapse:
10837 C = new (Context) OMPCollapseClause();
10838 break;
10839 case llvm::omp::OMPC_default:
10840 C = new (Context) OMPDefaultClause();
10841 break;
10842 case llvm::omp::OMPC_proc_bind:
10843 C = new (Context) OMPProcBindClause();
10844 break;
10845 case llvm::omp::OMPC_schedule:
10846 C = new (Context) OMPScheduleClause();
10847 break;
10848 case llvm::omp::OMPC_ordered:
10849 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10850 break;
10851 case llvm::omp::OMPC_nowait:
10852 C = new (Context) OMPNowaitClause();
10853 break;
10854 case llvm::omp::OMPC_untied:
10855 C = new (Context) OMPUntiedClause();
10856 break;
10857 case llvm::omp::OMPC_mergeable:
10858 C = new (Context) OMPMergeableClause();
10859 break;
10860 case llvm::omp::OMPC_read:
10861 C = new (Context) OMPReadClause();
10862 break;
10863 case llvm::omp::OMPC_write:
10864 C = new (Context) OMPWriteClause();
10865 break;
10866 case llvm::omp::OMPC_update:
10867 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10868 break;
10869 case llvm::omp::OMPC_capture:
10870 C = new (Context) OMPCaptureClause();
10871 break;
10872 case llvm::omp::OMPC_compare:
10873 C = new (Context) OMPCompareClause();
10874 break;
10875 case llvm::omp::OMPC_fail:
10876 C = new (Context) OMPFailClause();
10877 break;
10878 case llvm::omp::OMPC_seq_cst:
10879 C = new (Context) OMPSeqCstClause();
10880 break;
10881 case llvm::omp::OMPC_acq_rel:
10882 C = new (Context) OMPAcqRelClause();
10883 break;
10884 case llvm::omp::OMPC_absent: {
10885 unsigned NumKinds = Record.readInt();
10886 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
10887 break;
10888 }
10889 case llvm::omp::OMPC_holds:
10890 C = new (Context) OMPHoldsClause();
10891 break;
10892 case llvm::omp::OMPC_contains: {
10893 unsigned NumKinds = Record.readInt();
10894 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
10895 break;
10896 }
10897 case llvm::omp::OMPC_no_openmp:
10898 C = new (Context) OMPNoOpenMPClause();
10899 break;
10900 case llvm::omp::OMPC_no_openmp_routines:
10901 C = new (Context) OMPNoOpenMPRoutinesClause();
10902 break;
10903 case llvm::omp::OMPC_no_parallelism:
10904 C = new (Context) OMPNoParallelismClause();
10905 break;
10906 case llvm::omp::OMPC_acquire:
10907 C = new (Context) OMPAcquireClause();
10908 break;
10909 case llvm::omp::OMPC_release:
10910 C = new (Context) OMPReleaseClause();
10911 break;
10912 case llvm::omp::OMPC_relaxed:
10913 C = new (Context) OMPRelaxedClause();
10914 break;
10915 case llvm::omp::OMPC_weak:
10916 C = new (Context) OMPWeakClause();
10917 break;
10918 case llvm::omp::OMPC_threads:
10919 C = new (Context) OMPThreadsClause();
10920 break;
10921 case llvm::omp::OMPC_simd:
10922 C = new (Context) OMPSIMDClause();
10923 break;
10924 case llvm::omp::OMPC_nogroup:
10925 C = new (Context) OMPNogroupClause();
10926 break;
10927 case llvm::omp::OMPC_unified_address:
10928 C = new (Context) OMPUnifiedAddressClause();
10929 break;
10930 case llvm::omp::OMPC_unified_shared_memory:
10931 C = new (Context) OMPUnifiedSharedMemoryClause();
10932 break;
10933 case llvm::omp::OMPC_reverse_offload:
10934 C = new (Context) OMPReverseOffloadClause();
10935 break;
10936 case llvm::omp::OMPC_dynamic_allocators:
10937 C = new (Context) OMPDynamicAllocatorsClause();
10938 break;
10939 case llvm::omp::OMPC_atomic_default_mem_order:
10940 C = new (Context) OMPAtomicDefaultMemOrderClause();
10941 break;
10942 case llvm::omp::OMPC_at:
10943 C = new (Context) OMPAtClause();
10944 break;
10945 case llvm::omp::OMPC_severity:
10946 C = new (Context) OMPSeverityClause();
10947 break;
10948 case llvm::omp::OMPC_message:
10949 C = new (Context) OMPMessageClause();
10950 break;
10951 case llvm::omp::OMPC_private:
10952 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10953 break;
10954 case llvm::omp::OMPC_firstprivate:
10955 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10956 break;
10957 case llvm::omp::OMPC_lastprivate:
10958 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10959 break;
10960 case llvm::omp::OMPC_shared:
10961 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10962 break;
10963 case llvm::omp::OMPC_reduction: {
10964 unsigned N = Record.readInt();
10965 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10966 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10967 break;
10968 }
10969 case llvm::omp::OMPC_task_reduction:
10970 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10971 break;
10972 case llvm::omp::OMPC_in_reduction:
10973 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10974 break;
10975 case llvm::omp::OMPC_linear:
10976 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10977 break;
10978 case llvm::omp::OMPC_aligned:
10979 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10980 break;
10981 case llvm::omp::OMPC_copyin:
10982 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10983 break;
10984 case llvm::omp::OMPC_copyprivate:
10985 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10986 break;
10987 case llvm::omp::OMPC_flush:
10988 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10989 break;
10990 case llvm::omp::OMPC_depobj:
10992 break;
10993 case llvm::omp::OMPC_depend: {
10994 unsigned NumVars = Record.readInt();
10995 unsigned NumLoops = Record.readInt();
10996 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10997 break;
10998 }
10999 case llvm::omp::OMPC_device:
11000 C = new (Context) OMPDeviceClause();
11001 break;
11002 case llvm::omp::OMPC_map: {
11004 Sizes.NumVars = Record.readInt();
11005 Sizes.NumUniqueDeclarations = Record.readInt();
11006 Sizes.NumComponentLists = Record.readInt();
11007 Sizes.NumComponents = Record.readInt();
11008 C = OMPMapClause::CreateEmpty(Context, Sizes);
11009 break;
11010 }
11011 case llvm::omp::OMPC_num_teams:
11012 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11013 break;
11014 case llvm::omp::OMPC_thread_limit:
11015 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11016 break;
11017 case llvm::omp::OMPC_priority:
11018 C = new (Context) OMPPriorityClause();
11019 break;
11020 case llvm::omp::OMPC_grainsize:
11021 C = new (Context) OMPGrainsizeClause();
11022 break;
11023 case llvm::omp::OMPC_num_tasks:
11024 C = new (Context) OMPNumTasksClause();
11025 break;
11026 case llvm::omp::OMPC_hint:
11027 C = new (Context) OMPHintClause();
11028 break;
11029 case llvm::omp::OMPC_dist_schedule:
11030 C = new (Context) OMPDistScheduleClause();
11031 break;
11032 case llvm::omp::OMPC_defaultmap:
11033 C = new (Context) OMPDefaultmapClause();
11034 break;
11035 case llvm::omp::OMPC_to: {
11037 Sizes.NumVars = Record.readInt();
11038 Sizes.NumUniqueDeclarations = Record.readInt();
11039 Sizes.NumComponentLists = Record.readInt();
11040 Sizes.NumComponents = Record.readInt();
11041 C = OMPToClause::CreateEmpty(Context, Sizes);
11042 break;
11043 }
11044 case llvm::omp::OMPC_from: {
11046 Sizes.NumVars = Record.readInt();
11047 Sizes.NumUniqueDeclarations = Record.readInt();
11048 Sizes.NumComponentLists = Record.readInt();
11049 Sizes.NumComponents = Record.readInt();
11050 C = OMPFromClause::CreateEmpty(Context, Sizes);
11051 break;
11052 }
11053 case llvm::omp::OMPC_use_device_ptr: {
11055 Sizes.NumVars = Record.readInt();
11056 Sizes.NumUniqueDeclarations = Record.readInt();
11057 Sizes.NumComponentLists = Record.readInt();
11058 Sizes.NumComponents = Record.readInt();
11059 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11060 break;
11061 }
11062 case llvm::omp::OMPC_use_device_addr: {
11064 Sizes.NumVars = Record.readInt();
11065 Sizes.NumUniqueDeclarations = Record.readInt();
11066 Sizes.NumComponentLists = Record.readInt();
11067 Sizes.NumComponents = Record.readInt();
11068 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11069 break;
11070 }
11071 case llvm::omp::OMPC_is_device_ptr: {
11073 Sizes.NumVars = Record.readInt();
11074 Sizes.NumUniqueDeclarations = Record.readInt();
11075 Sizes.NumComponentLists = Record.readInt();
11076 Sizes.NumComponents = Record.readInt();
11077 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11078 break;
11079 }
11080 case llvm::omp::OMPC_has_device_addr: {
11082 Sizes.NumVars = Record.readInt();
11083 Sizes.NumUniqueDeclarations = Record.readInt();
11084 Sizes.NumComponentLists = Record.readInt();
11085 Sizes.NumComponents = Record.readInt();
11086 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11087 break;
11088 }
11089 case llvm::omp::OMPC_allocate:
11090 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11091 break;
11092 case llvm::omp::OMPC_nontemporal:
11093 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11094 break;
11095 case llvm::omp::OMPC_inclusive:
11096 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11097 break;
11098 case llvm::omp::OMPC_exclusive:
11099 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11100 break;
11101 case llvm::omp::OMPC_order:
11102 C = new (Context) OMPOrderClause();
11103 break;
11104 case llvm::omp::OMPC_init:
11105 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11106 break;
11107 case llvm::omp::OMPC_use:
11108 C = new (Context) OMPUseClause();
11109 break;
11110 case llvm::omp::OMPC_destroy:
11111 C = new (Context) OMPDestroyClause();
11112 break;
11113 case llvm::omp::OMPC_novariants:
11114 C = new (Context) OMPNovariantsClause();
11115 break;
11116 case llvm::omp::OMPC_nocontext:
11117 C = new (Context) OMPNocontextClause();
11118 break;
11119 case llvm::omp::OMPC_detach:
11120 C = new (Context) OMPDetachClause();
11121 break;
11122 case llvm::omp::OMPC_uses_allocators:
11123 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11124 break;
11125 case llvm::omp::OMPC_affinity:
11126 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11127 break;
11128 case llvm::omp::OMPC_filter:
11129 C = new (Context) OMPFilterClause();
11130 break;
11131 case llvm::omp::OMPC_bind:
11132 C = OMPBindClause::CreateEmpty(Context);
11133 break;
11134 case llvm::omp::OMPC_align:
11135 C = new (Context) OMPAlignClause();
11136 break;
11137 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11138 C = new (Context) OMPXDynCGroupMemClause();
11139 break;
11140 case llvm::omp::OMPC_doacross: {
11141 unsigned NumVars = Record.readInt();
11142 unsigned NumLoops = Record.readInt();
11143 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11144 break;
11145 }
11146 case llvm::omp::OMPC_ompx_attribute:
11147 C = new (Context) OMPXAttributeClause();
11148 break;
11149 case llvm::omp::OMPC_ompx_bare:
11150 C = new (Context) OMPXBareClause();
11151 break;
11152#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11153 case llvm::omp::Enum: \
11154 break;
11155#include "llvm/Frontend/OpenMP/OMPKinds.def"
11156 default:
11157 break;
11158 }
11159 assert(C && "Unknown OMPClause type");
11160
11161 Visit(C);
11162 C->setLocStart(Record.readSourceLocation());
11163 C->setLocEnd(Record.readSourceLocation());
11164
11165 return C;
11166}
11167
11169 C->setPreInitStmt(Record.readSubStmt(),
11170 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11171}
11172
11175 C->setPostUpdateExpr(Record.readSubExpr());
11176}
11177
11178void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11180 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11181 C->setNameModifierLoc(Record.readSourceLocation());
11182 C->setColonLoc(Record.readSourceLocation());
11183 C->setCondition(Record.readSubExpr());
11184 C->setLParenLoc(Record.readSourceLocation());
11185}
11186
11187void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11189 C->setCondition(Record.readSubExpr());
11190 C->setLParenLoc(Record.readSourceLocation());
11191}
11192
11193void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11195 C->setNumThreads(Record.readSubExpr());
11196 C->setLParenLoc(Record.readSourceLocation());
11197}
11198
11199void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11200 C->setSafelen(Record.readSubExpr());
11201 C->setLParenLoc(Record.readSourceLocation());
11202}
11203
11204void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11205 C->setSimdlen(Record.readSubExpr());
11206 C->setLParenLoc(Record.readSourceLocation());
11207}
11208
11209void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11210 for (Expr *&E : C->getSizesRefs())
11211 E = Record.readSubExpr();
11212 C->setLParenLoc(Record.readSourceLocation());
11213}
11214
11215void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11216 for (Expr *&E : C->getArgsRefs())
11217 E = Record.readSubExpr();
11218 C->setLParenLoc(Record.readSourceLocation());
11219}
11220
11221void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11222
11223void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11224 C->setFactor(Record.readSubExpr());
11225 C->setLParenLoc(Record.readSourceLocation());
11226}
11227
11228void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11229 C->setAllocator(Record.readExpr());
11230 C->setLParenLoc(Record.readSourceLocation());
11231}
11232
11233void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11234 C->setNumForLoops(Record.readSubExpr());
11235 C->setLParenLoc(Record.readSourceLocation());
11236}
11237
11238void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11239 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11240 C->setLParenLoc(Record.readSourceLocation());
11241 C->setDefaultKindKwLoc(Record.readSourceLocation());
11242}
11243
11244void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11245 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11246 C->setLParenLoc(Record.readSourceLocation());
11247 C->setProcBindKindKwLoc(Record.readSourceLocation());
11248}
11249
11250void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11252 C->setScheduleKind(
11253 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11254 C->setFirstScheduleModifier(
11255 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11256 C->setSecondScheduleModifier(
11257 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11258 C->setChunkSize(Record.readSubExpr());
11259 C->setLParenLoc(Record.readSourceLocation());
11260 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11261 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11262 C->setScheduleKindLoc(Record.readSourceLocation());
11263 C->setCommaLoc(Record.readSourceLocation());
11264}
11265
11266void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11267 C->setNumForLoops(Record.readSubExpr());
11268 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11269 C->setLoopNumIterations(I, Record.readSubExpr());
11270 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11271 C->setLoopCounter(I, Record.readSubExpr());
11272 C->setLParenLoc(Record.readSourceLocation());
11273}
11274
11275void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11276 C->setEventHandler(Record.readSubExpr());
11277 C->setLParenLoc(Record.readSourceLocation());
11278}
11279
11280void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11281
11282void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11283
11284void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11285
11286void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11287
11288void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11289
11290void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11291 if (C->isExtended()) {
11292 C->setLParenLoc(Record.readSourceLocation());
11293 C->setArgumentLoc(Record.readSourceLocation());
11294 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11295 }
11296}
11297
11298void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11299
11300void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11301
11302// Read the parameter of fail clause. This will have been saved when
11303// OMPClauseWriter is called.
11304void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11305 C->setLParenLoc(Record.readSourceLocation());
11306 SourceLocation FailParameterLoc = Record.readSourceLocation();
11307 C->setFailParameterLoc(FailParameterLoc);
11308 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11309 C->setFailParameter(CKind);
11310}
11311
11312void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11313 unsigned Count = C->getDirectiveKinds().size();
11314 C->setLParenLoc(Record.readSourceLocation());
11316 DKVec.reserve(Count);
11317 for (unsigned I = 0; I < Count; I++) {
11318 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11319 }
11320 C->setDirectiveKinds(DKVec);
11321}
11322
11323void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11324 C->setExpr(Record.readExpr());
11325 C->setLParenLoc(Record.readSourceLocation());
11326}
11327
11328void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11329 unsigned Count = C->getDirectiveKinds().size();
11330 C->setLParenLoc(Record.readSourceLocation());
11332 DKVec.reserve(Count);
11333 for (unsigned I = 0; I < Count; I++) {
11334 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11335 }
11336 C->setDirectiveKinds(DKVec);
11337}
11338
11339void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11340
11341void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11343
11344void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11345
11346void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11347
11348void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11349
11350void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11351
11352void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11353
11354void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11355
11356void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11357
11358void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11359
11360void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11361
11362void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11363
11364void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11365 unsigned NumVars = C->varlist_size();
11367 Vars.reserve(NumVars);
11368 for (unsigned I = 0; I != NumVars; ++I)
11369 Vars.push_back(Record.readSubExpr());
11370 C->setVarRefs(Vars);
11371 C->setIsTarget(Record.readBool());
11372 C->setIsTargetSync(Record.readBool());
11373 C->setLParenLoc(Record.readSourceLocation());
11374 C->setVarLoc(Record.readSourceLocation());
11375}
11376
11377void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11378 C->setInteropVar(Record.readSubExpr());
11379 C->setLParenLoc(Record.readSourceLocation());
11380 C->setVarLoc(Record.readSourceLocation());
11381}
11382
11383void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11384 C->setInteropVar(Record.readSubExpr());
11385 C->setLParenLoc(Record.readSourceLocation());
11386 C->setVarLoc(Record.readSourceLocation());
11387}
11388
11389void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11391 C->setCondition(Record.readSubExpr());
11392 C->setLParenLoc(Record.readSourceLocation());
11393}
11394
11395void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11397 C->setCondition(Record.readSubExpr());
11398 C->setLParenLoc(Record.readSourceLocation());
11399}
11400
11401void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11402
11403void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11405
11406void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11407
11408void
11409OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11410}
11411
11412void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11414 C->setAtomicDefaultMemOrderKind(
11415 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11416 C->setLParenLoc(Record.readSourceLocation());
11417 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11418}
11419
11420void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
11421 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
11422 C->setLParenLoc(Record.readSourceLocation());
11423 C->setAtKindKwLoc(Record.readSourceLocation());
11424}
11425
11426void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
11427 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
11428 C->setLParenLoc(Record.readSourceLocation());
11429 C->setSeverityKindKwLoc(Record.readSourceLocation());
11430}
11431
11432void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
11433 C->setMessageString(Record.readSubExpr());
11434 C->setLParenLoc(Record.readSourceLocation());
11435}
11436
11437void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11438 C->setLParenLoc(Record.readSourceLocation());
11439 unsigned NumVars = C->varlist_size();
11441 Vars.reserve(NumVars);
11442 for (unsigned i = 0; i != NumVars; ++i)
11443 Vars.push_back(Record.readSubExpr());
11444 C->setVarRefs(Vars);
11445 Vars.clear();
11446 for (unsigned i = 0; i != NumVars; ++i)
11447 Vars.push_back(Record.readSubExpr());
11448 C->setPrivateCopies(Vars);
11449}
11450
11451void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11453 C->setLParenLoc(Record.readSourceLocation());
11454 unsigned NumVars = C->varlist_size();
11456 Vars.reserve(NumVars);
11457 for (unsigned i = 0; i != NumVars; ++i)
11458 Vars.push_back(Record.readSubExpr());
11459 C->setVarRefs(Vars);
11460 Vars.clear();
11461 for (unsigned i = 0; i != NumVars; ++i)
11462 Vars.push_back(Record.readSubExpr());
11463 C->setPrivateCopies(Vars);
11464 Vars.clear();
11465 for (unsigned i = 0; i != NumVars; ++i)
11466 Vars.push_back(Record.readSubExpr());
11467 C->setInits(Vars);
11468}
11469
11470void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11472 C->setLParenLoc(Record.readSourceLocation());
11473 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11474 C->setKindLoc(Record.readSourceLocation());
11475 C->setColonLoc(Record.readSourceLocation());
11476 unsigned NumVars = C->varlist_size();
11478 Vars.reserve(NumVars);
11479 for (unsigned i = 0; i != NumVars; ++i)
11480 Vars.push_back(Record.readSubExpr());
11481 C->setVarRefs(Vars);
11482 Vars.clear();
11483 for (unsigned i = 0; i != NumVars; ++i)
11484 Vars.push_back(Record.readSubExpr());
11485 C->setPrivateCopies(Vars);
11486 Vars.clear();
11487 for (unsigned i = 0; i != NumVars; ++i)
11488 Vars.push_back(Record.readSubExpr());
11489 C->setSourceExprs(Vars);
11490 Vars.clear();
11491 for (unsigned i = 0; i != NumVars; ++i)
11492 Vars.push_back(Record.readSubExpr());
11493 C->setDestinationExprs(Vars);
11494 Vars.clear();
11495 for (unsigned i = 0; i != NumVars; ++i)
11496 Vars.push_back(Record.readSubExpr());
11497 C->setAssignmentOps(Vars);
11498}
11499
11500void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11501 C->setLParenLoc(Record.readSourceLocation());
11502 unsigned NumVars = C->varlist_size();
11504 Vars.reserve(NumVars);
11505 for (unsigned i = 0; i != NumVars; ++i)
11506 Vars.push_back(Record.readSubExpr());
11507 C->setVarRefs(Vars);
11508}
11509
11510void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11512 C->setLParenLoc(Record.readSourceLocation());
11513 C->setModifierLoc(Record.readSourceLocation());
11514 C->setColonLoc(Record.readSourceLocation());
11515 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11516 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11517 C->setQualifierLoc(NNSL);
11518 C->setNameInfo(DNI);
11519
11520 unsigned NumVars = C->varlist_size();
11522 Vars.reserve(NumVars);
11523 for (unsigned i = 0; i != NumVars; ++i)
11524 Vars.push_back(Record.readSubExpr());
11525 C->setVarRefs(Vars);
11526 Vars.clear();
11527 for (unsigned i = 0; i != NumVars; ++i)
11528 Vars.push_back(Record.readSubExpr());
11529 C->setPrivates(Vars);
11530 Vars.clear();
11531 for (unsigned i = 0; i != NumVars; ++i)
11532 Vars.push_back(Record.readSubExpr());
11533 C->setLHSExprs(Vars);
11534 Vars.clear();
11535 for (unsigned i = 0; i != NumVars; ++i)
11536 Vars.push_back(Record.readSubExpr());
11537 C->setRHSExprs(Vars);
11538 Vars.clear();
11539 for (unsigned i = 0; i != NumVars; ++i)
11540 Vars.push_back(Record.readSubExpr());
11541 C->setReductionOps(Vars);
11542 if (C->getModifier() == OMPC_REDUCTION_inscan) {
11543 Vars.clear();
11544 for (unsigned i = 0; i != NumVars; ++i)
11545 Vars.push_back(Record.readSubExpr());
11546 C->setInscanCopyOps(Vars);
11547 Vars.clear();
11548 for (unsigned i = 0; i != NumVars; ++i)
11549 Vars.push_back(Record.readSubExpr());
11550 C->setInscanCopyArrayTemps(Vars);
11551 Vars.clear();
11552 for (unsigned i = 0; i != NumVars; ++i)
11553 Vars.push_back(Record.readSubExpr());
11554 C->setInscanCopyArrayElems(Vars);
11555 }
11556}
11557
11558void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11560 C->setLParenLoc(Record.readSourceLocation());
11561 C->setColonLoc(Record.readSourceLocation());
11562 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11563 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11564 C->setQualifierLoc(NNSL);
11565 C->setNameInfo(DNI);
11566
11567 unsigned NumVars = C->varlist_size();
11569 Vars.reserve(NumVars);
11570 for (unsigned I = 0; I != NumVars; ++I)
11571 Vars.push_back(Record.readSubExpr());
11572 C->setVarRefs(Vars);
11573 Vars.clear();
11574 for (unsigned I = 0; I != NumVars; ++I)
11575 Vars.push_back(Record.readSubExpr());
11576 C->setPrivates(Vars);
11577 Vars.clear();
11578 for (unsigned I = 0; I != NumVars; ++I)
11579 Vars.push_back(Record.readSubExpr());
11580 C->setLHSExprs(Vars);
11581 Vars.clear();
11582 for (unsigned I = 0; I != NumVars; ++I)
11583 Vars.push_back(Record.readSubExpr());
11584 C->setRHSExprs(Vars);
11585 Vars.clear();
11586 for (unsigned I = 0; I != NumVars; ++I)
11587 Vars.push_back(Record.readSubExpr());
11588 C->setReductionOps(Vars);
11589}
11590
11591void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11593 C->setLParenLoc(Record.readSourceLocation());
11594 C->setColonLoc(Record.readSourceLocation());
11595 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11596 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11597 C->setQualifierLoc(NNSL);
11598 C->setNameInfo(DNI);
11599
11600 unsigned NumVars = C->varlist_size();
11602 Vars.reserve(NumVars);
11603 for (unsigned I = 0; I != NumVars; ++I)
11604 Vars.push_back(Record.readSubExpr());
11605 C->setVarRefs(Vars);
11606 Vars.clear();
11607 for (unsigned I = 0; I != NumVars; ++I)
11608 Vars.push_back(Record.readSubExpr());
11609 C->setPrivates(Vars);
11610 Vars.clear();
11611 for (unsigned I = 0; I != NumVars; ++I)
11612 Vars.push_back(Record.readSubExpr());
11613 C->setLHSExprs(Vars);
11614 Vars.clear();
11615 for (unsigned I = 0; I != NumVars; ++I)
11616 Vars.push_back(Record.readSubExpr());
11617 C->setRHSExprs(Vars);
11618 Vars.clear();
11619 for (unsigned I = 0; I != NumVars; ++I)
11620 Vars.push_back(Record.readSubExpr());
11621 C->setReductionOps(Vars);
11622 Vars.clear();
11623 for (unsigned I = 0; I != NumVars; ++I)
11624 Vars.push_back(Record.readSubExpr());
11625 C->setTaskgroupDescriptors(Vars);
11626}
11627
11628void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11630 C->setLParenLoc(Record.readSourceLocation());
11631 C->setColonLoc(Record.readSourceLocation());
11632 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11633 C->setModifierLoc(Record.readSourceLocation());
11634 unsigned NumVars = C->varlist_size();
11636 Vars.reserve(NumVars);
11637 for (unsigned i = 0; i != NumVars; ++i)
11638 Vars.push_back(Record.readSubExpr());
11639 C->setVarRefs(Vars);
11640 Vars.clear();
11641 for (unsigned i = 0; i != NumVars; ++i)
11642 Vars.push_back(Record.readSubExpr());
11643 C->setPrivates(Vars);
11644 Vars.clear();
11645 for (unsigned i = 0; i != NumVars; ++i)
11646 Vars.push_back(Record.readSubExpr());
11647 C->setInits(Vars);
11648 Vars.clear();
11649 for (unsigned i = 0; i != NumVars; ++i)
11650 Vars.push_back(Record.readSubExpr());
11651 C->setUpdates(Vars);
11652 Vars.clear();
11653 for (unsigned i = 0; i != NumVars; ++i)
11654 Vars.push_back(Record.readSubExpr());
11655 C->setFinals(Vars);
11656 C->setStep(Record.readSubExpr());
11657 C->setCalcStep(Record.readSubExpr());
11658 Vars.clear();
11659 for (unsigned I = 0; I != NumVars + 1; ++I)
11660 Vars.push_back(Record.readSubExpr());
11661 C->setUsedExprs(Vars);
11662}
11663
11664void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11665 C->setLParenLoc(Record.readSourceLocation());
11666 C->setColonLoc(Record.readSourceLocation());
11667 unsigned NumVars = C->varlist_size();
11669 Vars.reserve(NumVars);
11670 for (unsigned i = 0; i != NumVars; ++i)
11671 Vars.push_back(Record.readSubExpr());
11672 C->setVarRefs(Vars);
11673 C->setAlignment(Record.readSubExpr());
11674}
11675
11676void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11677 C->setLParenLoc(Record.readSourceLocation());
11678 unsigned NumVars = C->varlist_size();
11680 Exprs.reserve(NumVars);
11681 for (unsigned i = 0; i != NumVars; ++i)
11682 Exprs.push_back(Record.readSubExpr());
11683 C->setVarRefs(Exprs);
11684 Exprs.clear();
11685 for (unsigned i = 0; i != NumVars; ++i)
11686 Exprs.push_back(Record.readSubExpr());
11687 C->setSourceExprs(Exprs);
11688 Exprs.clear();
11689 for (unsigned i = 0; i != NumVars; ++i)
11690 Exprs.push_back(Record.readSubExpr());
11691 C->setDestinationExprs(Exprs);
11692 Exprs.clear();
11693 for (unsigned i = 0; i != NumVars; ++i)
11694 Exprs.push_back(Record.readSubExpr());
11695 C->setAssignmentOps(Exprs);
11696}
11697
11698void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11699 C->setLParenLoc(Record.readSourceLocation());
11700 unsigned NumVars = C->varlist_size();
11702 Exprs.reserve(NumVars);
11703 for (unsigned i = 0; i != NumVars; ++i)
11704 Exprs.push_back(Record.readSubExpr());
11705 C->setVarRefs(Exprs);
11706 Exprs.clear();
11707 for (unsigned i = 0; i != NumVars; ++i)
11708 Exprs.push_back(Record.readSubExpr());
11709 C->setSourceExprs(Exprs);
11710 Exprs.clear();
11711 for (unsigned i = 0; i != NumVars; ++i)
11712 Exprs.push_back(Record.readSubExpr());
11713 C->setDestinationExprs(Exprs);
11714 Exprs.clear();
11715 for (unsigned i = 0; i != NumVars; ++i)
11716 Exprs.push_back(Record.readSubExpr());
11717 C->setAssignmentOps(Exprs);
11718}
11719
11720void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11721 C->setLParenLoc(Record.readSourceLocation());
11722 unsigned NumVars = C->varlist_size();
11724 Vars.reserve(NumVars);
11725 for (unsigned i = 0; i != NumVars; ++i)
11726 Vars.push_back(Record.readSubExpr());
11727 C->setVarRefs(Vars);
11728}
11729
11730void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11731 C->setDepobj(Record.readSubExpr());
11732 C->setLParenLoc(Record.readSourceLocation());
11733}
11734
11735void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11736 C->setLParenLoc(Record.readSourceLocation());
11737 C->setModifier(Record.readSubExpr());
11738 C->setDependencyKind(
11739 static_cast<OpenMPDependClauseKind>(Record.readInt()));
11740 C->setDependencyLoc(Record.readSourceLocation());
11741 C->setColonLoc(Record.readSourceLocation());
11742 C->setOmpAllMemoryLoc(Record.readSourceLocation());
11743 unsigned NumVars = C->varlist_size();
11745 Vars.reserve(NumVars);
11746 for (unsigned I = 0; I != NumVars; ++I)
11747 Vars.push_back(Record.readSubExpr());
11748 C->setVarRefs(Vars);
11749 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11750 C->setLoopData(I, Record.readSubExpr());
11751}
11752
11753void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11755 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11756 C->setDevice(Record.readSubExpr());
11757 C->setModifierLoc(Record.readSourceLocation());
11758 C->setLParenLoc(Record.readSourceLocation());
11759}
11760
11761void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11762 C->setLParenLoc(Record.readSourceLocation());
11763 bool HasIteratorModifier = false;
11764 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11765 C->setMapTypeModifier(
11766 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11767 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11768 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11769 HasIteratorModifier = true;
11770 }
11771 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11772 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11773 C->setMapType(
11774 static_cast<OpenMPMapClauseKind>(Record.readInt()));
11775 C->setMapLoc(Record.readSourceLocation());
11776 C->setColonLoc(Record.readSourceLocation());
11777 auto NumVars = C->varlist_size();
11778 auto UniqueDecls = C->getUniqueDeclarationsNum();
11779 auto TotalLists = C->getTotalComponentListNum();
11780 auto TotalComponents = C->getTotalComponentsNum();
11781
11783 Vars.reserve(NumVars);
11784 for (unsigned i = 0; i != NumVars; ++i)
11785 Vars.push_back(Record.readExpr());
11786 C->setVarRefs(Vars);
11787
11788 SmallVector<Expr *, 16> UDMappers;
11789 UDMappers.reserve(NumVars);
11790 for (unsigned I = 0; I < NumVars; ++I)
11791 UDMappers.push_back(Record.readExpr());
11792 C->setUDMapperRefs(UDMappers);
11793
11794 if (HasIteratorModifier)
11795 C->setIteratorModifier(Record.readExpr());
11796
11798 Decls.reserve(UniqueDecls);
11799 for (unsigned i = 0; i < UniqueDecls; ++i)
11800 Decls.push_back(Record.readDeclAs<ValueDecl>());
11801 C->setUniqueDecls(Decls);
11802
11803 SmallVector<unsigned, 16> ListsPerDecl;
11804 ListsPerDecl.reserve(UniqueDecls);
11805 for (unsigned i = 0; i < UniqueDecls; ++i)
11806 ListsPerDecl.push_back(Record.readInt());
11807 C->setDeclNumLists(ListsPerDecl);
11808
11809 SmallVector<unsigned, 32> ListSizes;
11810 ListSizes.reserve(TotalLists);
11811 for (unsigned i = 0; i < TotalLists; ++i)
11812 ListSizes.push_back(Record.readInt());
11813 C->setComponentListSizes(ListSizes);
11814
11816 Components.reserve(TotalComponents);
11817 for (unsigned i = 0; i < TotalComponents; ++i) {
11818 Expr *AssociatedExprPr = Record.readExpr();
11819 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11820 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11821 /*IsNonContiguous=*/false);
11822 }
11823 C->setComponents(Components, ListSizes);
11824}
11825
11826void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11827 C->setAllocatorModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
11828 C->setLParenLoc(Record.readSourceLocation());
11829 C->setColonLoc(Record.readSourceLocation());
11830 C->setAllocator(Record.readSubExpr());
11831 unsigned NumVars = C->varlist_size();
11833 Vars.reserve(NumVars);
11834 for (unsigned i = 0; i != NumVars; ++i)
11835 Vars.push_back(Record.readSubExpr());
11836 C->setVarRefs(Vars);
11837}
11838
11839void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11841 C->setLParenLoc(Record.readSourceLocation());
11842 unsigned NumVars = C->varlist_size();
11844 Vars.reserve(NumVars);
11845 for (unsigned I = 0; I != NumVars; ++I)
11846 Vars.push_back(Record.readSubExpr());
11847 C->setVarRefs(Vars);
11848}
11849
11850void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11852 C->setLParenLoc(Record.readSourceLocation());
11853 unsigned NumVars = C->varlist_size();
11855 Vars.reserve(NumVars);
11856 for (unsigned I = 0; I != NumVars; ++I)
11857 Vars.push_back(Record.readSubExpr());
11858 C->setVarRefs(Vars);
11859}
11860
11861void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11863 C->setPriority(Record.readSubExpr());
11864 C->setLParenLoc(Record.readSourceLocation());
11865}
11866
11867void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11869 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11870 C->setGrainsize(Record.readSubExpr());
11871 C->setModifierLoc(Record.readSourceLocation());
11872 C->setLParenLoc(Record.readSourceLocation());
11873}
11874
11875void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11877 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11878 C->setNumTasks(Record.readSubExpr());
11879 C->setModifierLoc(Record.readSourceLocation());
11880 C->setLParenLoc(Record.readSourceLocation());
11881}
11882
11883void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11884 C->setHint(Record.readSubExpr());
11885 C->setLParenLoc(Record.readSourceLocation());
11886}
11887
11888void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11890 C->setDistScheduleKind(
11891 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11892 C->setChunkSize(Record.readSubExpr());
11893 C->setLParenLoc(Record.readSourceLocation());
11894 C->setDistScheduleKindLoc(Record.readSourceLocation());
11895 C->setCommaLoc(Record.readSourceLocation());
11896}
11897
11898void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11899 C->setDefaultmapKind(
11900 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11901 C->setDefaultmapModifier(
11902 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11903 C->setLParenLoc(Record.readSourceLocation());
11904 C->setDefaultmapModifierLoc(Record.readSourceLocation());
11905 C->setDefaultmapKindLoc(Record.readSourceLocation());
11906}
11907
11908void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11909 C->setLParenLoc(Record.readSourceLocation());
11910 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11911 C->setMotionModifier(
11912 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11913 C->setMotionModifierLoc(I, Record.readSourceLocation());
11914 }
11915 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11916 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11917 C->setColonLoc(Record.readSourceLocation());
11918 auto NumVars = C->varlist_size();
11919 auto UniqueDecls = C->getUniqueDeclarationsNum();
11920 auto TotalLists = C->getTotalComponentListNum();
11921 auto TotalComponents = C->getTotalComponentsNum();
11922
11924 Vars.reserve(NumVars);
11925 for (unsigned i = 0; i != NumVars; ++i)
11926 Vars.push_back(Record.readSubExpr());
11927 C->setVarRefs(Vars);
11928
11929 SmallVector<Expr *, 16> UDMappers;
11930 UDMappers.reserve(NumVars);
11931 for (unsigned I = 0; I < NumVars; ++I)
11932 UDMappers.push_back(Record.readSubExpr());
11933 C->setUDMapperRefs(UDMappers);
11934
11936 Decls.reserve(UniqueDecls);
11937 for (unsigned i = 0; i < UniqueDecls; ++i)
11938 Decls.push_back(Record.readDeclAs<ValueDecl>());
11939 C->setUniqueDecls(Decls);
11940
11941 SmallVector<unsigned, 16> ListsPerDecl;
11942 ListsPerDecl.reserve(UniqueDecls);
11943 for (unsigned i = 0; i < UniqueDecls; ++i)
11944 ListsPerDecl.push_back(Record.readInt());
11945 C->setDeclNumLists(ListsPerDecl);
11946
11947 SmallVector<unsigned, 32> ListSizes;
11948 ListSizes.reserve(TotalLists);
11949 for (unsigned i = 0; i < TotalLists; ++i)
11950 ListSizes.push_back(Record.readInt());
11951 C->setComponentListSizes(ListSizes);
11952
11954 Components.reserve(TotalComponents);
11955 for (unsigned i = 0; i < TotalComponents; ++i) {
11956 Expr *AssociatedExprPr = Record.readSubExpr();
11957 bool IsNonContiguous = Record.readBool();
11958 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11959 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11960 }
11961 C->setComponents(Components, ListSizes);
11962}
11963
11964void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11965 C->setLParenLoc(Record.readSourceLocation());
11966 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11967 C->setMotionModifier(
11968 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11969 C->setMotionModifierLoc(I, Record.readSourceLocation());
11970 }
11971 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11972 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11973 C->setColonLoc(Record.readSourceLocation());
11974 auto NumVars = C->varlist_size();
11975 auto UniqueDecls = C->getUniqueDeclarationsNum();
11976 auto TotalLists = C->getTotalComponentListNum();
11977 auto TotalComponents = C->getTotalComponentsNum();
11978
11980 Vars.reserve(NumVars);
11981 for (unsigned i = 0; i != NumVars; ++i)
11982 Vars.push_back(Record.readSubExpr());
11983 C->setVarRefs(Vars);
11984
11985 SmallVector<Expr *, 16> UDMappers;
11986 UDMappers.reserve(NumVars);
11987 for (unsigned I = 0; I < NumVars; ++I)
11988 UDMappers.push_back(Record.readSubExpr());
11989 C->setUDMapperRefs(UDMappers);
11990
11992 Decls.reserve(UniqueDecls);
11993 for (unsigned i = 0; i < UniqueDecls; ++i)
11994 Decls.push_back(Record.readDeclAs<ValueDecl>());
11995 C->setUniqueDecls(Decls);
11996
11997 SmallVector<unsigned, 16> ListsPerDecl;
11998 ListsPerDecl.reserve(UniqueDecls);
11999 for (unsigned i = 0; i < UniqueDecls; ++i)
12000 ListsPerDecl.push_back(Record.readInt());
12001 C->setDeclNumLists(ListsPerDecl);
12002
12003 SmallVector<unsigned, 32> ListSizes;
12004 ListSizes.reserve(TotalLists);
12005 for (unsigned i = 0; i < TotalLists; ++i)
12006 ListSizes.push_back(Record.readInt());
12007 C->setComponentListSizes(ListSizes);
12008
12010 Components.reserve(TotalComponents);
12011 for (unsigned i = 0; i < TotalComponents; ++i) {
12012 Expr *AssociatedExprPr = Record.readSubExpr();
12013 bool IsNonContiguous = Record.readBool();
12014 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12015 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12016 }
12017 C->setComponents(Components, ListSizes);
12018}
12019
12020void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12021 C->setLParenLoc(Record.readSourceLocation());
12022 auto NumVars = C->varlist_size();
12023 auto UniqueDecls = C->getUniqueDeclarationsNum();
12024 auto TotalLists = C->getTotalComponentListNum();
12025 auto TotalComponents = C->getTotalComponentsNum();
12026
12028 Vars.reserve(NumVars);
12029 for (unsigned i = 0; i != NumVars; ++i)
12030 Vars.push_back(Record.readSubExpr());
12031 C->setVarRefs(Vars);
12032 Vars.clear();
12033 for (unsigned i = 0; i != NumVars; ++i)
12034 Vars.push_back(Record.readSubExpr());
12035 C->setPrivateCopies(Vars);
12036 Vars.clear();
12037 for (unsigned i = 0; i != NumVars; ++i)
12038 Vars.push_back(Record.readSubExpr());
12039 C->setInits(Vars);
12040
12042 Decls.reserve(UniqueDecls);
12043 for (unsigned i = 0; i < UniqueDecls; ++i)
12044 Decls.push_back(Record.readDeclAs<ValueDecl>());
12045 C->setUniqueDecls(Decls);
12046
12047 SmallVector<unsigned, 16> ListsPerDecl;
12048 ListsPerDecl.reserve(UniqueDecls);
12049 for (unsigned i = 0; i < UniqueDecls; ++i)
12050 ListsPerDecl.push_back(Record.readInt());
12051 C->setDeclNumLists(ListsPerDecl);
12052
12053 SmallVector<unsigned, 32> ListSizes;
12054 ListSizes.reserve(TotalLists);
12055 for (unsigned i = 0; i < TotalLists; ++i)
12056 ListSizes.push_back(Record.readInt());
12057 C->setComponentListSizes(ListSizes);
12058
12060 Components.reserve(TotalComponents);
12061 for (unsigned i = 0; i < TotalComponents; ++i) {
12062 auto *AssociatedExprPr = Record.readSubExpr();
12063 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12064 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12065 /*IsNonContiguous=*/false);
12066 }
12067 C->setComponents(Components, ListSizes);
12068}
12069
12070void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12071 C->setLParenLoc(Record.readSourceLocation());
12072 auto NumVars = C->varlist_size();
12073 auto UniqueDecls = C->getUniqueDeclarationsNum();
12074 auto TotalLists = C->getTotalComponentListNum();
12075 auto TotalComponents = C->getTotalComponentsNum();
12076
12078 Vars.reserve(NumVars);
12079 for (unsigned i = 0; i != NumVars; ++i)
12080 Vars.push_back(Record.readSubExpr());
12081 C->setVarRefs(Vars);
12082
12084 Decls.reserve(UniqueDecls);
12085 for (unsigned i = 0; i < UniqueDecls; ++i)
12086 Decls.push_back(Record.readDeclAs<ValueDecl>());
12087 C->setUniqueDecls(Decls);
12088
12089 SmallVector<unsigned, 16> ListsPerDecl;
12090 ListsPerDecl.reserve(UniqueDecls);
12091 for (unsigned i = 0; i < UniqueDecls; ++i)
12092 ListsPerDecl.push_back(Record.readInt());
12093 C->setDeclNumLists(ListsPerDecl);
12094
12095 SmallVector<unsigned, 32> ListSizes;
12096 ListSizes.reserve(TotalLists);
12097 for (unsigned i = 0; i < TotalLists; ++i)
12098 ListSizes.push_back(Record.readInt());
12099 C->setComponentListSizes(ListSizes);
12100
12102 Components.reserve(TotalComponents);
12103 for (unsigned i = 0; i < TotalComponents; ++i) {
12104 Expr *AssociatedExpr = Record.readSubExpr();
12105 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12106 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12107 /*IsNonContiguous*/ false);
12108 }
12109 C->setComponents(Components, ListSizes);
12110}
12111
12112void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12113 C->setLParenLoc(Record.readSourceLocation());
12114 auto NumVars = C->varlist_size();
12115 auto UniqueDecls = C->getUniqueDeclarationsNum();
12116 auto TotalLists = C->getTotalComponentListNum();
12117 auto TotalComponents = C->getTotalComponentsNum();
12118
12120 Vars.reserve(NumVars);
12121 for (unsigned i = 0; i != NumVars; ++i)
12122 Vars.push_back(Record.readSubExpr());
12123 C->setVarRefs(Vars);
12124 Vars.clear();
12125
12127 Decls.reserve(UniqueDecls);
12128 for (unsigned i = 0; i < UniqueDecls; ++i)
12129 Decls.push_back(Record.readDeclAs<ValueDecl>());
12130 C->setUniqueDecls(Decls);
12131
12132 SmallVector<unsigned, 16> ListsPerDecl;
12133 ListsPerDecl.reserve(UniqueDecls);
12134 for (unsigned i = 0; i < UniqueDecls; ++i)
12135 ListsPerDecl.push_back(Record.readInt());
12136 C->setDeclNumLists(ListsPerDecl);
12137
12138 SmallVector<unsigned, 32> ListSizes;
12139 ListSizes.reserve(TotalLists);
12140 for (unsigned i = 0; i < TotalLists; ++i)
12141 ListSizes.push_back(Record.readInt());
12142 C->setComponentListSizes(ListSizes);
12143
12145 Components.reserve(TotalComponents);
12146 for (unsigned i = 0; i < TotalComponents; ++i) {
12147 Expr *AssociatedExpr = Record.readSubExpr();
12148 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12149 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12150 /*IsNonContiguous=*/false);
12151 }
12152 C->setComponents(Components, ListSizes);
12153}
12154
12155void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12156 C->setLParenLoc(Record.readSourceLocation());
12157 auto NumVars = C->varlist_size();
12158 auto UniqueDecls = C->getUniqueDeclarationsNum();
12159 auto TotalLists = C->getTotalComponentListNum();
12160 auto TotalComponents = C->getTotalComponentsNum();
12161
12163 Vars.reserve(NumVars);
12164 for (unsigned I = 0; I != NumVars; ++I)
12165 Vars.push_back(Record.readSubExpr());
12166 C->setVarRefs(Vars);
12167 Vars.clear();
12168
12170 Decls.reserve(UniqueDecls);
12171 for (unsigned I = 0; I < UniqueDecls; ++I)
12172 Decls.push_back(Record.readDeclAs<ValueDecl>());
12173 C->setUniqueDecls(Decls);
12174
12175 SmallVector<unsigned, 16> ListsPerDecl;
12176 ListsPerDecl.reserve(UniqueDecls);
12177 for (unsigned I = 0; I < UniqueDecls; ++I)
12178 ListsPerDecl.push_back(Record.readInt());
12179 C->setDeclNumLists(ListsPerDecl);
12180
12181 SmallVector<unsigned, 32> ListSizes;
12182 ListSizes.reserve(TotalLists);
12183 for (unsigned i = 0; i < TotalLists; ++i)
12184 ListSizes.push_back(Record.readInt());
12185 C->setComponentListSizes(ListSizes);
12186
12188 Components.reserve(TotalComponents);
12189 for (unsigned I = 0; I < TotalComponents; ++I) {
12190 Expr *AssociatedExpr = Record.readSubExpr();
12191 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12192 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12193 /*IsNonContiguous=*/false);
12194 }
12195 C->setComponents(Components, ListSizes);
12196}
12197
12198void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12199 C->setLParenLoc(Record.readSourceLocation());
12200 unsigned NumVars = C->varlist_size();
12202 Vars.reserve(NumVars);
12203 for (unsigned i = 0; i != NumVars; ++i)
12204 Vars.push_back(Record.readSubExpr());
12205 C->setVarRefs(Vars);
12206 Vars.clear();
12207 Vars.reserve(NumVars);
12208 for (unsigned i = 0; i != NumVars; ++i)
12209 Vars.push_back(Record.readSubExpr());
12210 C->setPrivateRefs(Vars);
12211}
12212
12213void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12214 C->setLParenLoc(Record.readSourceLocation());
12215 unsigned NumVars = C->varlist_size();
12217 Vars.reserve(NumVars);
12218 for (unsigned i = 0; i != NumVars; ++i)
12219 Vars.push_back(Record.readSubExpr());
12220 C->setVarRefs(Vars);
12221}
12222
12223void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12224 C->setLParenLoc(Record.readSourceLocation());
12225 unsigned NumVars = C->varlist_size();
12227 Vars.reserve(NumVars);
12228 for (unsigned i = 0; i != NumVars; ++i)
12229 Vars.push_back(Record.readSubExpr());
12230 C->setVarRefs(Vars);
12231}
12232
12233void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12234 C->setLParenLoc(Record.readSourceLocation());
12235 unsigned NumOfAllocators = C->getNumberOfAllocators();
12237 Data.reserve(NumOfAllocators);
12238 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12239 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12240 D.Allocator = Record.readSubExpr();
12241 D.AllocatorTraits = Record.readSubExpr();
12242 D.LParenLoc = Record.readSourceLocation();
12243 D.RParenLoc = Record.readSourceLocation();
12244 }
12245 C->setAllocatorsData(Data);
12246}
12247
12248void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12249 C->setLParenLoc(Record.readSourceLocation());
12250 C->setModifier(Record.readSubExpr());
12251 C->setColonLoc(Record.readSourceLocation());
12252 unsigned NumOfLocators = C->varlist_size();
12253 SmallVector<Expr *, 4> Locators;
12254 Locators.reserve(NumOfLocators);
12255 for (unsigned I = 0; I != NumOfLocators; ++I)
12256 Locators.push_back(Record.readSubExpr());
12257 C->setVarRefs(Locators);
12258}
12259
12260void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12261 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12262 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12263 C->setLParenLoc(Record.readSourceLocation());
12264 C->setKindKwLoc(Record.readSourceLocation());
12265 C->setModifierKwLoc(Record.readSourceLocation());
12266}
12267
12268void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12270 C->setThreadID(Record.readSubExpr());
12271 C->setLParenLoc(Record.readSourceLocation());
12272}
12273
12274void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12275 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12276 C->setLParenLoc(Record.readSourceLocation());
12277 C->setBindKindLoc(Record.readSourceLocation());
12278}
12279
12280void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12281 C->setAlignment(Record.readExpr());
12282 C->setLParenLoc(Record.readSourceLocation());
12283}
12284
12285void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12287 C->setSize(Record.readSubExpr());
12288 C->setLParenLoc(Record.readSourceLocation());
12289}
12290
12291void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12292 C->setLParenLoc(Record.readSourceLocation());
12293 C->setDependenceType(
12294 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12295 C->setDependenceLoc(Record.readSourceLocation());
12296 C->setColonLoc(Record.readSourceLocation());
12297 unsigned NumVars = C->varlist_size();
12299 Vars.reserve(NumVars);
12300 for (unsigned I = 0; I != NumVars; ++I)
12301 Vars.push_back(Record.readSubExpr());
12302 C->setVarRefs(Vars);
12303 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12304 C->setLoopData(I, Record.readSubExpr());
12305}
12306
12307void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12308 AttrVec Attrs;
12309 Record.readAttributes(Attrs);
12310 C->setAttrs(Attrs);
12311 C->setLocStart(Record.readSourceLocation());
12312 C->setLParenLoc(Record.readSourceLocation());
12313 C->setLocEnd(Record.readSourceLocation());
12314}
12315
12316void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12317
12320 TI.Sets.resize(readUInt32());
12321 for (auto &Set : TI.Sets) {
12322 Set.Kind = readEnum<llvm::omp::TraitSet>();
12323 Set.Selectors.resize(readUInt32());
12324 for (auto &Selector : Set.Selectors) {
12325 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12326 Selector.ScoreOrCondition = nullptr;
12327 if (readBool())
12328 Selector.ScoreOrCondition = readExprRef();
12329 Selector.Properties.resize(readUInt32());
12330 for (auto &Property : Selector.Properties)
12331 Property.Kind = readEnum<llvm::omp::TraitProperty>();
12332 }
12333 }
12334 return &TI;
12335}
12336
12338 if (!Data)
12339 return;
12340 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12341 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12342 skipInts(3);
12343 }
12344 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12345 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12346 Clauses[I] = readOMPClause();
12347 Data->setClauses(Clauses);
12348 if (Data->hasAssociatedStmt())
12349 Data->setAssociatedStmt(readStmt());
12350 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12351 Data->getChildren()[I] = readStmt();
12352}
12353
12355 unsigned NumVars = readInt();
12357 for (unsigned I = 0; I < NumVars; ++I)
12358 VarList.push_back(readSubExpr());
12359 return VarList;
12360}
12361
12363 unsigned NumExprs = readInt();
12365 for (unsigned I = 0; I < NumExprs; ++I)
12366 ExprList.push_back(readSubExpr());
12367 return ExprList;
12368}
12369
12371 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
12374
12375 switch (ClauseKind) {
12377 SourceLocation LParenLoc = readSourceLocation();
12378 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
12379 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
12380 EndLoc);
12381 }
12382 case OpenACCClauseKind::If: {
12383 SourceLocation LParenLoc = readSourceLocation();
12384 Expr *CondExpr = readSubExpr();
12385 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
12386 EndLoc);
12387 }
12389 SourceLocation LParenLoc = readSourceLocation();
12390 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
12391 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
12392 CondExpr, EndLoc);
12393 }
12395 SourceLocation LParenLoc = readSourceLocation();
12396 unsigned NumClauses = readInt();
12398 for (unsigned I = 0; I < NumClauses; ++I)
12399 IntExprs.push_back(readSubExpr());
12400 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
12401 IntExprs, EndLoc);
12402 }
12404 SourceLocation LParenLoc = readSourceLocation();
12405 Expr *IntExpr = readSubExpr();
12406 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
12407 IntExpr, EndLoc);
12408 }
12410 SourceLocation LParenLoc = readSourceLocation();
12411 Expr *IntExpr = readSubExpr();
12412 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
12413 IntExpr, EndLoc);
12414 }
12416 SourceLocation LParenLoc = readSourceLocation();
12417 Expr *IntExpr = readSubExpr();
12418 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
12419 IntExpr, EndLoc);
12420 }
12422 SourceLocation LParenLoc = readSourceLocation();
12424 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12425 VarList, EndLoc);
12426 }
12428 SourceLocation LParenLoc = readSourceLocation();
12430 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12431 VarList, EndLoc);
12432 }
12434 SourceLocation LParenLoc = readSourceLocation();
12436 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
12437 VarList, EndLoc);
12438 }
12440 SourceLocation LParenLoc = readSourceLocation();
12442 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
12443 VarList, EndLoc);
12444 }
12446 SourceLocation LParenLoc = readSourceLocation();
12448 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
12449 VarList, EndLoc);
12450 }
12452 SourceLocation LParenLoc = readSourceLocation();
12454 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
12455 VarList, EndLoc);
12456 }
12458 SourceLocation LParenLoc = readSourceLocation();
12460 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
12461 VarList, EndLoc);
12462 }
12464 SourceLocation LParenLoc = readSourceLocation();
12466 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
12467 VarList, EndLoc);
12468 }
12470 SourceLocation LParenLoc = readSourceLocation();
12472 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
12473 VarList, EndLoc);
12474 }
12478 SourceLocation LParenLoc = readSourceLocation();
12480 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
12481 LParenLoc, VarList, EndLoc);
12482 }
12486 SourceLocation LParenLoc = readSourceLocation();
12487 bool IsReadOnly = readBool();
12489 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
12490 LParenLoc, IsReadOnly, VarList, EndLoc);
12491 }
12495 SourceLocation LParenLoc = readSourceLocation();
12496 bool IsZero = readBool();
12498 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
12499 LParenLoc, IsZero, VarList, EndLoc);
12500 }
12504 SourceLocation LParenLoc = readSourceLocation();
12505 bool IsZero = readBool();
12507 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
12508 LParenLoc, IsZero, VarList, EndLoc);
12509 }
12511 SourceLocation LParenLoc = readSourceLocation();
12512 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
12513 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12514 AsyncExpr, EndLoc);
12515 }
12517 SourceLocation LParenLoc = readSourceLocation();
12518 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
12519 SourceLocation QueuesLoc = readSourceLocation();
12521 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
12522 DevNumExpr, QueuesLoc, QueueIdExprs,
12523 EndLoc);
12524 }
12527 SourceLocation LParenLoc = readSourceLocation();
12529 unsigned NumArchs = readInt();
12530
12531 for (unsigned I = 0; I < NumArchs; ++I) {
12532 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
12534 Archs.emplace_back(Ident, Loc);
12535 }
12536
12537 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
12538 LParenLoc, Archs, EndLoc);
12539 }
12541 SourceLocation LParenLoc = readSourceLocation();
12542 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();
12544 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
12545 VarList, EndLoc);
12546 }
12548 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
12550 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
12552 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
12554 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
12556 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
12558 SourceLocation LParenLoc = readSourceLocation();
12559 bool HasForce = readBool();
12560 Expr *LoopCount = readSubExpr();
12561 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
12562 HasForce, LoopCount, EndLoc);
12563 }
12565 SourceLocation LParenLoc = readSourceLocation();
12566 unsigned NumClauses = readInt();
12567 llvm::SmallVector<Expr *> SizeExprs;
12568 for (unsigned I = 0; I < NumClauses; ++I)
12569 SizeExprs.push_back(readSubExpr());
12570 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
12571 SizeExprs, EndLoc);
12572 }
12574 SourceLocation LParenLoc = readSourceLocation();
12575 unsigned NumExprs = readInt();
12578 for (unsigned I = 0; I < NumExprs; ++I) {
12579 GangKinds.push_back(readEnum<OpenACCGangKind>());
12580 Exprs.push_back(readSubExpr());
12581 }
12582 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
12583 GangKinds, Exprs, EndLoc);
12584 }
12586 SourceLocation LParenLoc = readSourceLocation();
12587 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
12588 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
12589 WorkerExpr, EndLoc);
12590 }
12592 SourceLocation LParenLoc = readSourceLocation();
12593 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
12594 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
12595 VectorExpr, EndLoc);
12596 }
12597
12606 llvm_unreachable("Clause serialization not yet implemented");
12607 }
12608 llvm_unreachable("Invalid Clause Kind");
12609}
12610
12613 for (unsigned I = 0; I < Clauses.size(); ++I)
12614 Clauses[I] = readOpenACCClause();
12615}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:4828
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8447
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:4810
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:519
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:867
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7306
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:635
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
Definition: ASTReader.cpp:1084
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4386
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:2848
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:1058
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:5150
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:574
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:686
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:8976
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:526
static bool isPredefinedType(serialization::TypeID ID)
Definition: ASTReader.cpp:7310
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1070
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
Definition: ASTReader.cpp:485
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6837
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:919
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8568
OptionValidation
Definition: ASTReader.cpp:670
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:673
@ OptionValidateNone
Definition: ASTReader.cpp:671
@ OptionValidateContradictions
Definition: ASTReader.cpp:672
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:395
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
#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:5375
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:4525
static unsigned getIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7302
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:906
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:131
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:84
Defines the Diagnostic-related interfaces.
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1718::IndirectLocalPathEntry::EntryKind Kind
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 ExceptionSpecificationType enumeration and various utility functions.
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:3032
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.
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.
static std::string getName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the clang::SanitizerKind enum.
uint32_t Id
Definition: SemaARM.cpp:1134
This file declares semantic analysis for CUDA constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines utilities for dealing with stack allocation and stack space.
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
#define bool
Definition: amdgpuintrin.h:20
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:1173
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1192
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1191
BuiltinTemplateDecl * getBuiltinCommonTypeDecl() const
CanQualType LongTy
Definition: ASTContext.h:1169
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1169
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1182
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
ExternCContextDecl * getExternCContextDecl() const
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1175
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:1178
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1289
CanQualType FloatTy
Definition: ASTContext.h:1172
CanQualType DoubleTy
Definition: ASTContext.h:1172
CanQualType SatLongAccumTy
Definition: ASTContext.h:1178
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2108
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1201
CanQualType Char16Ty
Definition: ASTContext.h:1167
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2086
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1177
CanQualType DependentTy
Definition: ASTContext.h:1188
CanQualType NullPtrTy
Definition: ASTContext.h:1187
CanQualType OMPIteratorTy
Definition: ASTContext.h:1201
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:867
CanQualType SatShortFractTy
Definition: ASTContext.h:1181
CanQualType Ibm128Ty
Definition: ASTContext.h:1172
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1179
CanQualType ArraySectionTy
Definition: ASTContext.h:1200
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1192
CanQualType BoolTy
Definition: ASTContext.h:1161
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1177
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1192
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1188
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2120
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1175
CanQualType ShortFractTy
Definition: ASTContext.h:1176
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1182
CanQualType CharTy
Definition: ASTContext.h:1162
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1169
CanQualType PseudoObjectTy
Definition: ASTContext.h:1191
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
CanQualType SignedCharTy
Definition: ASTContext.h:1169
CanQualType OverloadTy
Definition: ASTContext.h:1188
CanQualType OCLClkEventTy
Definition: ASTContext.h:1197
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:1179
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:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1197
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1177
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:754
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2270
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1198
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1183
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1533
CanQualType ShortTy
Definition: ASTContext.h:1169
CanQualType FractTy
Definition: ASTContext.h:1176
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1174
CanQualType Char32Ty
Definition: ASTContext.h:1168
CanQualType SatFractTy
Definition: ASTContext.h:1181
CanQualType SatLongFractTy
Definition: ASTContext.h:1181
CanQualType OCLQueueTy
Definition: ASTContext.h:1198
CanQualType LongFractTy
Definition: ASTContext.h:1176
CanQualType SatShortAccumTy
Definition: ASTContext.h:1178
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1185
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1199
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2096
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1180
CanQualType LongLongTy
Definition: ASTContext.h:1169
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
CanQualType WCharTy
Definition: ASTContext.h:1163
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:1101
CanQualType Char8Ty
Definition: ASTContext.h:1166
CanQualType HalfTy
Definition: ASTContext.h:1184
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1175
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1197
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:8797
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8825
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8830
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:116
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:129
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:223
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:144
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:235
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, StringRef ModuleFilename, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:155
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:193
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:164
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:206
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:177
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:249
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:134
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:246
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:218
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:242
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:124
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:214
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:128
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:227
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:383
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:6634
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6415
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2388
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:931
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:9419
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9500
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9891
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1890
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7888
friend class ASTIdentifierIterator
Definition: ASTReader.h:388
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1685
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9897
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9870
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2501
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:2077
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9818
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:9115
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8616
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1732
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1745
@ 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:1736
@ 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:1740
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:9045
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:8326
std::string ReadPathBlob(StringRef BaseDirectory, const RecordData &Record, unsigned &Idx, StringRef &Blob)
Definition: ASTReader.cpp:9844
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6401
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:7638
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8583
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1985
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2535
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9507
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:8248
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:7908
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9482
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8422
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7634
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9909
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2370
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:9275
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4492
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9913
SourceManager & getSourceManager() const
Definition: ASTReader.h:1717
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7915
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:4428
bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial) override
Load all the external specializations for the Decl.
Definition: ASTReader.cpp:8197
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5369
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2513
static std::string ResolveImportedPathAndAllocate(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
Definition: ASTReader.cpp:2835
static StringRef ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx, StringRef &Blob)
Definition: ASTReader.cpp:9825
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7791
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.
Definition: ASTReader.cpp:9985
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:8468
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:8108
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2399
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:8370
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:9061
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7717
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:8137
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:1613
~ASTReader() override
bool haveUnloadedSpecializations(const Decl *D) const
If we have any unloaded specialization for D.
Definition: ASTReader.cpp:8436
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:7719
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:1905
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
Definition: ASTReader.cpp:9250
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:2116
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:6621
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8758
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:9354
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:9448
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6394
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:8152
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9536
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1991
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:9377
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:9034
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:9082
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7331
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2239
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9793
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:7865
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:9143
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8398
void AssignedLambdaNumbering(CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:9215
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:9103
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, 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:5544
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:9093
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2508
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:1868
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:9071
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:9125
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9511
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:4570
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1898
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9833
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9465
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:9323
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:403
@ Success
The control block was read successfully.
Definition: ASTReader.h:406
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:423
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:416
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:409
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:419
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:426
@ Missing
The AST file was missing.
Definition: ASTReader.h:412
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9851
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1932
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9904
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:9358
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:9186
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8883
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:9161
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:4517
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9540
static TemporarilyOwnedStringRef ResolveImportedPath(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
Definition: ASTReader.cpp:2815
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:9018
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:8061
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9800
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:9452
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:9245
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6693
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4414
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8653
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:8087
ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
Definition: ASTReader.cpp:1648
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:9174
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1894
serialization::reader::LazySpecializationInfoLookupTable * getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial)
Get the loaded specializations lookup tables for D, if any.
Definition: ASTReader.cpp:8428
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9863
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:9023
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:9434
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8478
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:4477
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:9546
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Definition: ASTReader.cpp:9878
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:8982
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5226
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:7823
FileManager & getFileManager() const
Definition: ASTReader.h:1718
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, 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:5841
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:2363
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2245
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6684
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:9404
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.
Definition: ASTReader.cpp:9813
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7691
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7285
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9641
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9631
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9599
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9562
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9652
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:9587
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7659
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:7292
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7701
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9595
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
SourceRange readSourceRange(LocSeq *Seq=nullptr)
Read a source range, advancing Idx.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
Definition: ASTReader.cpp:9732
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:7123
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.
OMPTraitInfo * readOMPTraitInfo()
Read an OMPTraitInfo object, advancing Idx.
TemplateParameterList * readTemplateParameterList()
Read a template parameter list, advancing Idx.
Definition: ASTReader.cpp:9612
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.
Definition: ASTReader.cpp:9667
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7711
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.
SourceLocation readSourceLocation(LocSeq *Seq=nullptr)
Read a source location, advancing Idx.
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:1648
Wrapper for source info for arrays.
Definition: TypeLoc.h:1592
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1598
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1606
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1618
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2669
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2661
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2653
Attr - This represents one attribute.
Definition: Attr.h:43
Type source information for an attributed type.
Definition: TypeLoc.h:875
void setAttr(const Attr *A)
Definition: TypeLoc.h:901
void setConceptReference(ConceptReference *CR)
Definition: TypeLoc.h:2232
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2226
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:925
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1345
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1351
Wrapper for source info for builtin types.
Definition: TypeLoc.h:565
void setWrittenTypeSpec(TypeSpecifierType written)
Definition: TypeLoc.h:651
bool needsExtraLocalData() const
Definition: TypeLoc.h:594
void setModeAttr(bool written)
Definition: TypeLoc.h:663
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:571
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition: TypeLoc.h:640
void setWrittenSignSpec(TypeSpecifierSign written)
Definition: TypeLoc.h:624
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2318
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2505
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
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:1779
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition: DeclCXX.h:1807
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
base_class_iterator vbases_begin()
Definition: DeclCXX.h:644
Represents a C++ temporary.
Definition: ExprCXX.h:1457
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1092
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 ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:162
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:172
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:177
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:186
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:167
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 ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:195
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
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:124
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:87
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
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:1293
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2676
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:2649
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2664
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1424
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2670
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:2690
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1624
unsigned getModuleFileIndex() const
Definition: DeclID.h:128
DeclID getRawValue() const
Definition: DeclID.h:118
unsigned getLocalDeclIndex() const
Definition: DeclBase.cpp:2219
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: DeclID.h:111
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:1050
static void add(Kind k)
Definition: DeclBase.cpp:221
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:848
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:973
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:805
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:786
SourceLocation getLocation() const
Definition: DeclBase.h:442
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1038
DeclContext * getDeclContext()
Definition: DeclBase.h:451
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
Kind getKind() const
Definition: DeclBase.h:445
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.cpp:110
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:859
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:735
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2118
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2115
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2333
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1804
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1825
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1923
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2503
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2523
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2491
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2547
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2539
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2555
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2531
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:7095
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1895
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1220
Carries a Clang diagnostic in an llvm::Error.
static llvm::Error create(SourceLocation Loc, PartialDiagnostic Diag)
Creates a new DiagnosticError that contains the given diagnostic at the given location.
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 > 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:1493
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:585
bool getEnableAllWarnings() const
Definition: Diagnostic.h:687
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:234
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:954
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:713
bool getWarningsAsErrors() const
Definition: Diagnostic.h:695
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:804
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:580
StringRef getName() const
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
Represents an enum.
Definition: Decl.h:3847
Wrapper for source info for enum types.
Definition: TypeLoc.h:749
This represents one expression.
Definition: Expr.h:110
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:978
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:1041
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:1048
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:942
Represents a member of a struct/union/class.
Definition: Decl.h:3033
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:355
off_t getSize() const
Definition: FileEntry.h:347
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:256
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:245
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:1935
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2267
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
Wrapper for source info for functions.
Definition: TypeLoc.h:1459
unsigned getNumParams() const
Definition: TypeLoc.h:1531
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1479
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1495
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1538
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1503
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1487
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1517
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:952
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:434
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.
In-memory cache for modules.
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:3321
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1429
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:505
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:563
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:577
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:573
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:554
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:560
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:941
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:1202
void setAttrRowOperand(Expr *e)
Definition: TypeLoc.h:1958
void setAttrColumnOperand(Expr *e)
Definition: TypeLoc.h:1964
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1973
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1952
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1363
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1369
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1381
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:67
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:1218
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:817
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
Definition: ModuleMap.cpp:1352
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:1203
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition: ModuleMap.h:200
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:551
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
Definition: ModuleMap.cpp:871
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:56
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:130
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1299
Describes a module or submodule.
Definition: Module.h:115
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:703
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition: Module.cpp:314
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:377
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:499
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition: Module.h:332
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition: Module.h:422
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:414
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:416
@ AllVisible
All of the names in this module are visible.
Definition: Module.h:418
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:121
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:312
ModuleKind Kind
The kind of this module.
Definition: Module.h:160
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition: Module.h:743
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition: Module.h:534
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition: Module.h:713
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:360
std::string Name
The name of this module.
Definition: Module.h:118
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:366
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:405
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:491
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:460
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition: Module.h:727
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Module.h:323
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:169
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition: Module.h:410
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:395
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:173
ASTFileSignature Signature
The module signature.
Definition: Module.h:179
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition: Module.h:387
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition: Module.cpp:385
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Module.h:512
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:347
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:439
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition: Module.h:719
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition: Module.h:189
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition: Module.h:343
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:382
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Module.h:708
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:524
This represents a decl that may have a name.
Definition: Decl.h:253
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
Represents a C++ namespace alias.
Definition: DeclCXX.h:3138
Represent a C++ namespace.
Definition: Decl.h:551
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.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
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:448
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:493
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:414
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:715
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:612
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 'message' clause in the '#pragma omp error' directive.
This represents the 'no_openmp' clause in the '#pragma omp assume' directive.
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:761
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.
Definition: OpenMPClause.h:968
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:806
This represents 'schedule' clause in the '#pragma omp ...' directive.
This represents 'seq_cst' clause in the '#pragma omp atomic|flush' directives.
This represents 'severity' clause in the '#pragma omp error' directive.
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:841
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:873
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:1015
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1122
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1132
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1144
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
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
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
void setLazyBody(uint64_t Offset)
Definition: DeclObjC.h:528
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1401
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1407
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1015
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:1019
unsigned getNumProtocols() const
Definition: TypeLoc.h:1049
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1007
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition: TypeLoc.h:1028
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1037
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1045
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:1077
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:1058
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
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:772
unsigned getNumProtocols() const
Definition: TypeLoc.h:809
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:818
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:795
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:805
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)
This is the base type for all OpenACC Clauses.
Definition: OpenACCClause.h:24
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, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsReadOnly, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsZero, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsZero, ArrayRef< Expr * > VarList, 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 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 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, SourceLocation EndLoc)
static OpenACCGangClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< OpenACCGangKind > GangKinds, ArrayRef< Expr * > IntExprs, 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 OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, 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, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, 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:303
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:459
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:887
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:598
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:898
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:842
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:468
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2613
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2143
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1234
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1230
Represents a parameter to a function.
Definition: Decl.h:1725
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2705
Wrapper for source info for pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
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:138
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
const TargetInfo & getTargetInfo() const
FileManager & getFileManager() const
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
HeaderSearch & getHeaderSearchInfo() const
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
void setCounterValue(unsigned V)
DiagnosticsEngine & getDiagnostics() const
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:289
The collection of all-type qualifiers we support.
Definition: Type.h:324
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:369
@ FastMask
The fast qualifier mask.
Definition: Type.h:372
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1443
Represents a struct/union/class.
Definition: Decl.h:4148
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
Declaration of a redeclarable template.
Definition: DeclTemplate.h:721
void loadLazySpecializationsImpl(bool OnlyPartial=false) const
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4981
void AddDecl(Decl *D)
Definition: Scope.h:346
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:463
SemaObjC & ObjC()
Definition: Sema.h:1110
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:871
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:562
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:592
IdentifierResolver IdResolver
Definition: Sema.h:2996
PragmaMsStackAction
Definition: Sema.h:1430
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:334
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:854
This object establishes a SourceLocationSequence.
Serialized encoding of a sequence of SourceLocations.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
void setExternalSLocEntrySource(ExternalSLocEntrySource *Source)
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
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
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:84
DiagnosticStorage * getStorage() const
Retrieve storage for this particular diagnostic.
Definition: Diagnostic.h:1114
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:864
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:311
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:632
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
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:295
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1718
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1694
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1735
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1702
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1710
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6729
Wrapper for template type parameters.
Definition: TypeLoc.h:758
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:150
void setLength(unsigned Len)
Definition: Token.h:141
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
void setAnnotationValue(void *val)
Definition: Token.h:238
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:244
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: Type.h:3226
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6996
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:7063
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6924
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:170
bool isNull() const
Definition: TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:2092
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1828
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2035
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:2027
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2043
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2177
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2171
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:2183
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2174
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:716
Wrapper for source info for types used via transparent aliases.
Definition: TypeLoc.h:682
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
Represents a variable declaration or definition.
Definition: Decl.h:882
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1872
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:2107
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1209
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:8911
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8953
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8958
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:1047
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:1042
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:1052
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1076
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1093
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:980
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1002
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:975
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:937
Trait class used to search the on-disk hash table containing all of the header search information.
Class that performs lookup to specialized decls.
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:893
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:2052
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1156
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1211
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1170
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:1039
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:1012
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:961
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:970
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1069
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1117
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1051
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:991
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:985
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:940
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1054
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:997
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1060
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1102
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:901
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1075
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1093
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1087
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:904
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:1018
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1072
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:1003
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:1033
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:943
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:1015
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:934
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:979
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1114
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:928
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:907
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:1045
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:925
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:922
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:964
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1066
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:1027
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:913
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:1024
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:973
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:967
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:1021
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:919
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1099
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:910
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:931
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1105
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:955
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:949
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:946
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:958
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:994
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:898
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1096
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:1036
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1090
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:895
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:1042
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:1030
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1063
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:952
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1111
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
Definition: ASTBitCodes.h:1146
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1078
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:937
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1084
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1057
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:982
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1108
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:1000
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:976
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:916
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1081
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:1009
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:1006
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:1048
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:988
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1446
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1326
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1449
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1335
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1176
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1204
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1207
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1192
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1189
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1195
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1201
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1186
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1198
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
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:87
@ 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:431
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:842
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:824
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:862
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:821
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:870
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:827
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:818
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:810
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:838
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:854
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:831
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:851
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:866
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:814
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:845
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:848
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:835
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:858
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:873
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
@ 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:877
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:747
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:761
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:751
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:757
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:765
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:472
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:769
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:784
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:780
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:775
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:787
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:791
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:405
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:413
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:422
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:410
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:419
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:407
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:416
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:425
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:439
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:444
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:441
void updateModuleTimestamp(StringRef ModuleFilename)
Definition: ASTCommon.cpp:510
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:795
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:804
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:797
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:800
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:448
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:589
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:523
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:709
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:615
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:519
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:578
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:461
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:611
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:715
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:548
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:608
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:605
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
Definition: ASTBitCodes.h:722
@ CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
Definition: ASTBitCodes.h:740
@ DECLS_WITH_EFFECTS_TO_VERIFY
Record code for Sema's vector of functions/blocks with effects to be verified.
Definition: ASTBitCodes.h:733
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:558
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:665
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:706
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:473
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:625
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:539
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:676
@ RELATED_DECLS_MAP
Record code for related declarations that have to be deserialized together from the same module.
Definition: ASTBitCodes.h:729
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:585
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:686
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:653
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:555
@ VTABLES_TO_EMIT
Record code for vtables to emit.
Definition: ASTBitCodes.h:725
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:481
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:646
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:535
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:719
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:700
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:563
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:543
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:575
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:662
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:632
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:679
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:526
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:551
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:697
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:636
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:532
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:671
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:510
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:658
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:602
@ 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:629
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:599
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:567
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:703
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:500
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:572
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:668
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:621
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:682
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:297
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:509
bool isa(CodeGen::Address addr)
Definition: Address.h:328
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:198
@ CPlusPlus
Definition: LangStandard.h:55
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
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
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:178
@ 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'.
@ 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
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:220
OpenACCDefaultClauseKind
Definition: OpenACCKinds.h:476
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:81
@ PREDEF_DECL_COMMON_TYPE_ID
The internal '__builtin_common_type' template.
Definition: DeclID.h:87
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:36
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:84
@ 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_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:57
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:48
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:54
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:42
@ NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: DeclID.h:90
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:51
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:63
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:66
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:78
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: DeclID.h:33
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:60
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:72
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:39
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:75
@ 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:201
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
Definition: OpenMPKinds.h:158
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition: OpenMPKinds.h:55
OpenMPGrainsizeClauseModifier
Definition: OpenMPKinds.h:207
OpenMPNumTasksClauseModifier
Definition: OpenMPKinds.h:213
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:227
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:2605
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
Definition: OpenMPKinds.h:128
@ Success
Template argument deduction was successful.
U cast(CodeGen::Address addr)
Definition: Address.h:325
@ 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
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
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:76
static ASTFileSignature createDummy()
Definition: Module.h:86
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
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.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5194
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:515
Module * Other
The module that this module conflicts with.
Definition: Module.h:517
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:520
Information about a header directive as found in the module map file.
Definition: Module.h:258
A library or framework to link against when an entity from this module is used.
Definition: Module.h:474
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:708
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:722
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:709
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:715
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition: Sanitizers.h:176
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:182
Helper class that saves the current stream position and then restores it when destroyed.
PragmaMsStackAction Action
Definition: Sema.h:1441
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:472
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:2063