clang 19.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"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
29#include "clang/AST/Expr.h"
30#include "clang/AST/ExprCXX.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeLoc.h"
52#include "clang/Basic/LLVM.h"
54#include "clang/Basic/Module.h"
68#include "clang/Basic/Version.h"
71#include "clang/Lex/MacroInfo.h"
72#include "clang/Lex/ModuleMap.h"
76#include "clang/Lex/Token.h"
78#include "clang/Sema/Scope.h"
79#include "clang/Sema/Sema.h"
80#include "clang/Sema/SemaCUDA.h"
81#include "clang/Sema/SemaObjC.h"
82#include "clang/Sema/Weak.h"
94#include "llvm/ADT/APFloat.h"
95#include "llvm/ADT/APInt.h"
96#include "llvm/ADT/APSInt.h"
97#include "llvm/ADT/ArrayRef.h"
98#include "llvm/ADT/DenseMap.h"
99#include "llvm/ADT/FloatingPointMode.h"
100#include "llvm/ADT/FoldingSet.h"
101#include "llvm/ADT/Hashing.h"
102#include "llvm/ADT/IntrusiveRefCntPtr.h"
103#include "llvm/ADT/STLExtras.h"
104#include "llvm/ADT/ScopeExit.h"
105#include "llvm/ADT/SmallPtrSet.h"
106#include "llvm/ADT/SmallString.h"
107#include "llvm/ADT/SmallVector.h"
108#include "llvm/ADT/StringExtras.h"
109#include "llvm/ADT/StringMap.h"
110#include "llvm/ADT/StringRef.h"
111#include "llvm/ADT/iterator_range.h"
112#include "llvm/Bitstream/BitstreamReader.h"
113#include "llvm/Support/Casting.h"
114#include "llvm/Support/Compiler.h"
115#include "llvm/Support/Compression.h"
116#include "llvm/Support/DJB.h"
117#include "llvm/Support/Endian.h"
118#include "llvm/Support/Error.h"
119#include "llvm/Support/ErrorHandling.h"
120#include "llvm/Support/FileSystem.h"
121#include "llvm/Support/LEB128.h"
122#include "llvm/Support/MemoryBuffer.h"
123#include "llvm/Support/Path.h"
124#include "llvm/Support/SaveAndRestore.h"
125#include "llvm/Support/TimeProfiler.h"
126#include "llvm/Support/Timer.h"
127#include "llvm/Support/VersionTuple.h"
128#include "llvm/Support/raw_ostream.h"
129#include "llvm/TargetParser/Triple.h"
130#include <algorithm>
131#include <cassert>
132#include <cstddef>
133#include <cstdint>
134#include <cstdio>
135#include <ctime>
136#include <iterator>
137#include <limits>
138#include <map>
139#include <memory>
140#include <optional>
141#include <string>
142#include <system_error>
143#include <tuple>
144#include <utility>
145#include <vector>
146
147using namespace clang;
148using namespace clang::serialization;
149using namespace clang::serialization::reader;
150using llvm::BitstreamCursor;
151
152//===----------------------------------------------------------------------===//
153// ChainedASTReaderListener implementation
154//===----------------------------------------------------------------------===//
155
156bool
158 return First->ReadFullVersionInformation(FullVersion) ||
159 Second->ReadFullVersionInformation(FullVersion);
160}
161
163 First->ReadModuleName(ModuleName);
164 Second->ReadModuleName(ModuleName);
165}
166
167void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
168 First->ReadModuleMapFile(ModuleMapPath);
169 Second->ReadModuleMapFile(ModuleMapPath);
170}
171
172bool
174 bool Complain,
175 bool AllowCompatibleDifferences) {
176 return First->ReadLanguageOptions(LangOpts, Complain,
177 AllowCompatibleDifferences) ||
178 Second->ReadLanguageOptions(LangOpts, Complain,
179 AllowCompatibleDifferences);
180}
181
183 const TargetOptions &TargetOpts, bool Complain,
184 bool AllowCompatibleDifferences) {
185 return First->ReadTargetOptions(TargetOpts, Complain,
186 AllowCompatibleDifferences) ||
187 Second->ReadTargetOptions(TargetOpts, Complain,
188 AllowCompatibleDifferences);
189}
190
192 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
193 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
194 Second->ReadDiagnosticOptions(DiagOpts, Complain);
195}
196
197bool
199 bool Complain) {
200 return First->ReadFileSystemOptions(FSOpts, Complain) ||
201 Second->ReadFileSystemOptions(FSOpts, Complain);
202}
203
205 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
206 bool Complain) {
207 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
208 Complain) ||
209 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
210 Complain);
211}
212
214 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
215 std::string &SuggestedPredefines) {
216 return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
217 SuggestedPredefines) ||
218 Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
219 SuggestedPredefines);
220}
221
223 unsigned Value) {
224 First->ReadCounter(M, Value);
225 Second->ReadCounter(M, Value);
226}
227
229 return First->needsInputFileVisitation() ||
230 Second->needsInputFileVisitation();
231}
232
234 return First->needsSystemInputFileVisitation() ||
235 Second->needsSystemInputFileVisitation();
236}
237
239 ModuleKind Kind) {
240 First->visitModuleFile(Filename, Kind);
241 Second->visitModuleFile(Filename, Kind);
242}
243
245 bool isSystem,
246 bool isOverridden,
247 bool isExplicitModule) {
248 bool Continue = false;
249 if (First->needsInputFileVisitation() &&
250 (!isSystem || First->needsSystemInputFileVisitation()))
251 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
252 isExplicitModule);
253 if (Second->needsInputFileVisitation() &&
254 (!isSystem || Second->needsSystemInputFileVisitation()))
255 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
256 isExplicitModule);
257 return Continue;
258}
259
261 const ModuleFileExtensionMetadata &Metadata) {
262 First->readModuleFileExtension(Metadata);
263 Second->readModuleFileExtension(Metadata);
264}
265
266//===----------------------------------------------------------------------===//
267// PCH validator implementation
268//===----------------------------------------------------------------------===//
269
271
272/// Compare the given set of language options against an existing set of
273/// language options.
274///
275/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
276/// \param AllowCompatibleDifferences If true, differences between compatible
277/// language options will be permitted.
278///
279/// \returns true if the languagae options mis-match, false otherwise.
280static bool checkLanguageOptions(const LangOptions &LangOpts,
281 const LangOptions &ExistingLangOpts,
282 DiagnosticsEngine *Diags,
283 bool AllowCompatibleDifferences = true) {
284#define LANGOPT(Name, Bits, Default, Description) \
285 if (ExistingLangOpts.Name != LangOpts.Name) { \
286 if (Diags) { \
287 if (Bits == 1) \
288 Diags->Report(diag::err_pch_langopt_mismatch) \
289 << Description << LangOpts.Name << ExistingLangOpts.Name; \
290 else \
291 Diags->Report(diag::err_pch_langopt_value_mismatch) \
292 << Description; \
293 } \
294 return true; \
295 }
296
297#define VALUE_LANGOPT(Name, Bits, Default, Description) \
298 if (ExistingLangOpts.Name != LangOpts.Name) { \
299 if (Diags) \
300 Diags->Report(diag::err_pch_langopt_value_mismatch) \
301 << Description; \
302 return true; \
303 }
304
305#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
306 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
307 if (Diags) \
308 Diags->Report(diag::err_pch_langopt_value_mismatch) \
309 << Description; \
310 return true; \
311 }
312
313#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
314 if (!AllowCompatibleDifferences) \
315 LANGOPT(Name, Bits, Default, Description)
316
317#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
318 if (!AllowCompatibleDifferences) \
319 ENUM_LANGOPT(Name, Bits, Default, Description)
320
321#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
322 if (!AllowCompatibleDifferences) \
323 VALUE_LANGOPT(Name, Bits, Default, Description)
324
325#define BENIGN_LANGOPT(Name, Bits, Default, Description)
326#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
327#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
328#include "clang/Basic/LangOptions.def"
329
330 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
331 if (Diags)
332 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
333 return true;
334 }
335
336 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
337 if (Diags)
338 Diags->Report(diag::err_pch_langopt_value_mismatch)
339 << "target Objective-C runtime";
340 return true;
341 }
342
343 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
345 if (Diags)
346 Diags->Report(diag::err_pch_langopt_value_mismatch)
347 << "block command names";
348 return true;
349 }
350
351 // Sanitizer feature mismatches are treated as compatible differences. If
352 // compatible differences aren't allowed, we still only want to check for
353 // mismatches of non-modular sanitizers (the only ones which can affect AST
354 // generation).
355 if (!AllowCompatibleDifferences) {
356 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
357 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
358 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
359 ExistingSanitizers.clear(ModularSanitizers);
360 ImportedSanitizers.clear(ModularSanitizers);
361 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
362 const std::string Flag = "-fsanitize=";
363 if (Diags) {
364#define SANITIZER(NAME, ID) \
365 { \
366 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
367 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
368 if (InExistingModule != InImportedModule) \
369 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
370 << InExistingModule << (Flag + NAME); \
371 }
372#include "clang/Basic/Sanitizers.def"
373 }
374 return true;
375 }
376 }
377
378 return false;
379}
380
381/// Compare the given set of target options against an existing set of
382/// target options.
383///
384/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
385///
386/// \returns true if the target options mis-match, false otherwise.
387static bool checkTargetOptions(const TargetOptions &TargetOpts,
388 const TargetOptions &ExistingTargetOpts,
389 DiagnosticsEngine *Diags,
390 bool AllowCompatibleDifferences = true) {
391#define CHECK_TARGET_OPT(Field, Name) \
392 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
393 if (Diags) \
394 Diags->Report(diag::err_pch_targetopt_mismatch) \
395 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
396 return true; \
397 }
398
399 // The triple and ABI must match exactly.
400 CHECK_TARGET_OPT(Triple, "target");
401 CHECK_TARGET_OPT(ABI, "target ABI");
402
403 // We can tolerate different CPUs in many cases, notably when one CPU
404 // supports a strict superset of another. When allowing compatible
405 // differences skip this check.
406 if (!AllowCompatibleDifferences) {
407 CHECK_TARGET_OPT(CPU, "target CPU");
408 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
409 }
410
411#undef CHECK_TARGET_OPT
412
413 // Compare feature sets.
414 SmallVector<StringRef, 4> ExistingFeatures(
415 ExistingTargetOpts.FeaturesAsWritten.begin(),
416 ExistingTargetOpts.FeaturesAsWritten.end());
417 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
418 TargetOpts.FeaturesAsWritten.end());
419 llvm::sort(ExistingFeatures);
420 llvm::sort(ReadFeatures);
421
422 // We compute the set difference in both directions explicitly so that we can
423 // diagnose the differences differently.
424 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
425 std::set_difference(
426 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
427 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
428 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
429 ExistingFeatures.begin(), ExistingFeatures.end(),
430 std::back_inserter(UnmatchedReadFeatures));
431
432 // If we are allowing compatible differences and the read feature set is
433 // a strict subset of the existing feature set, there is nothing to diagnose.
434 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
435 return false;
436
437 if (Diags) {
438 for (StringRef Feature : UnmatchedReadFeatures)
439 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
440 << /* is-existing-feature */ false << Feature;
441 for (StringRef Feature : UnmatchedExistingFeatures)
442 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
443 << /* is-existing-feature */ true << Feature;
444 }
445
446 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
447}
448
449bool
451 bool Complain,
452 bool AllowCompatibleDifferences) {
453 const LangOptions &ExistingLangOpts = PP.getLangOpts();
454 return checkLanguageOptions(LangOpts, ExistingLangOpts,
455 Complain ? &Reader.Diags : nullptr,
456 AllowCompatibleDifferences);
457}
458
460 bool Complain,
461 bool AllowCompatibleDifferences) {
462 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
463 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
464 Complain ? &Reader.Diags : nullptr,
465 AllowCompatibleDifferences);
466}
467
468namespace {
469
470using MacroDefinitionsMap =
471 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
472using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
473
474} // namespace
475
477 DiagnosticsEngine &Diags,
478 bool Complain) {
479 using Level = DiagnosticsEngine::Level;
480
481 // Check current mappings for new -Werror mappings, and the stored mappings
482 // for cases that were explicitly mapped to *not* be errors that are now
483 // errors because of options like -Werror.
484 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
485
486 for (DiagnosticsEngine *MappingSource : MappingSources) {
487 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
488 diag::kind DiagID = DiagIDMappingPair.first;
489 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
490 if (CurLevel < DiagnosticsEngine::Error)
491 continue; // not significant
492 Level StoredLevel =
493 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
494 if (StoredLevel < DiagnosticsEngine::Error) {
495 if (Complain)
496 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
497 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
498 return true;
499 }
500 }
501 }
502
503 return false;
504}
505
508 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
509 return true;
510 return Ext >= diag::Severity::Error;
511}
512
514 DiagnosticsEngine &Diags, bool IsSystem,
515 bool SystemHeaderWarningsInModule,
516 bool Complain) {
517 // Top-level options
518 if (IsSystem) {
519 if (Diags.getSuppressSystemWarnings())
520 return false;
521 // If -Wsystem-headers was not enabled before, and it was not explicit,
522 // be conservative
523 if (StoredDiags.getSuppressSystemWarnings() &&
524 !SystemHeaderWarningsInModule) {
525 if (Complain)
526 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
527 return true;
528 }
529 }
530
531 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
532 if (Complain)
533 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
534 return true;
535 }
536
537 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
538 !StoredDiags.getEnableAllWarnings()) {
539 if (Complain)
540 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
541 return true;
542 }
543
544 if (isExtHandlingFromDiagsError(Diags) &&
545 !isExtHandlingFromDiagsError(StoredDiags)) {
546 if (Complain)
547 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
548 return true;
549 }
550
551 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
552}
553
554/// Return the top import module if it is implicit, nullptr otherwise.
556 Preprocessor &PP) {
557 // If the original import came from a file explicitly generated by the user,
558 // don't check the diagnostic mappings.
559 // FIXME: currently this is approximated by checking whether this is not a
560 // module import of an implicitly-loaded module file.
561 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
562 // the transitive closure of its imports, since unrelated modules cannot be
563 // imported until after this module finishes validation.
564 ModuleFile *TopImport = &*ModuleMgr.rbegin();
565 while (!TopImport->ImportedBy.empty())
566 TopImport = TopImport->ImportedBy[0];
567 if (TopImport->Kind != MK_ImplicitModule)
568 return nullptr;
569
570 StringRef ModuleName = TopImport->ModuleName;
571 assert(!ModuleName.empty() && "diagnostic options read before module name");
572
573 Module *M =
574 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
575 assert(M && "missing module");
576 return M;
577}
578
580 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
581 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
584 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
585 // This should never fail, because we would have processed these options
586 // before writing them to an ASTFile.
587 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
588
589 ModuleManager &ModuleMgr = Reader.getModuleManager();
590 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
591
592 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
593 if (!TopM)
594 return false;
595
596 Module *Importer = PP.getCurrentModule();
597
598 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
599 bool SystemHeaderWarningsInModule =
600 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
601 Importer->Name);
602
603 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
604 // contains the union of their flags.
605 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
606 SystemHeaderWarningsInModule, Complain);
607}
608
609/// Collect the macro definitions provided by the given preprocessor
610/// options.
611static void
613 MacroDefinitionsMap &Macros,
614 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
615 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
616 StringRef Macro = PPOpts.Macros[I].first;
617 bool IsUndef = PPOpts.Macros[I].second;
618
619 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
620 StringRef MacroName = MacroPair.first;
621 StringRef MacroBody = MacroPair.second;
622
623 // For an #undef'd macro, we only care about the name.
624 if (IsUndef) {
625 if (MacroNames && !Macros.count(MacroName))
626 MacroNames->push_back(MacroName);
627
628 Macros[MacroName] = std::make_pair("", true);
629 continue;
630 }
631
632 // For a #define'd macro, figure out the actual definition.
633 if (MacroName.size() == Macro.size())
634 MacroBody = "1";
635 else {
636 // Note: GCC drops anything following an end-of-line character.
637 StringRef::size_type End = MacroBody.find_first_of("\n\r");
638 MacroBody = MacroBody.substr(0, End);
639 }
640
641 if (MacroNames && !Macros.count(MacroName))
642 MacroNames->push_back(MacroName);
643 Macros[MacroName] = std::make_pair(MacroBody, false);
644 }
645}
646
651};
652
653/// Check the preprocessor options deserialized from the control block
654/// against the preprocessor options in an existing preprocessor.
655///
656/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
657/// \param Validation If set to OptionValidateNone, ignore differences in
658/// preprocessor options. If set to OptionValidateContradictions,
659/// require that options passed both in the AST file and on the command
660/// line (-D or -U) match, but tolerate options missing in one or the
661/// other. If set to OptionValidateContradictions, require that there
662/// are no differences in the options between the two.
664 const PreprocessorOptions &PPOpts,
665 const PreprocessorOptions &ExistingPPOpts, bool ReadMacros,
666 DiagnosticsEngine *Diags, FileManager &FileMgr,
667 std::string &SuggestedPredefines, const LangOptions &LangOpts,
669 if (ReadMacros) {
670 // Check macro definitions.
671 MacroDefinitionsMap ASTFileMacros;
672 collectMacroDefinitions(PPOpts, ASTFileMacros);
673 MacroDefinitionsMap ExistingMacros;
674 SmallVector<StringRef, 4> ExistingMacroNames;
675 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
676 &ExistingMacroNames);
677
678 // Use a line marker to enter the <command line> file, as the defines and
679 // undefines here will have come from the command line.
680 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
681
682 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
683 // Dig out the macro definition in the existing preprocessor options.
684 StringRef MacroName = ExistingMacroNames[I];
685 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
686
687 // Check whether we know anything about this macro name or not.
688 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
689 ASTFileMacros.find(MacroName);
690 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
691 if (Validation == OptionValidateStrictMatches) {
692 // If strict matches are requested, don't tolerate any extra defines
693 // on the command line that are missing in the AST file.
694 if (Diags) {
695 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
696 }
697 return true;
698 }
699 // FIXME: Check whether this identifier was referenced anywhere in the
700 // AST file. If so, we should reject the AST file. Unfortunately, this
701 // information isn't in the control block. What shall we do about it?
702
703 if (Existing.second) {
704 SuggestedPredefines += "#undef ";
705 SuggestedPredefines += MacroName.str();
706 SuggestedPredefines += '\n';
707 } else {
708 SuggestedPredefines += "#define ";
709 SuggestedPredefines += MacroName.str();
710 SuggestedPredefines += ' ';
711 SuggestedPredefines += Existing.first.str();
712 SuggestedPredefines += '\n';
713 }
714 continue;
715 }
716
717 // If the macro was defined in one but undef'd in the other, we have a
718 // conflict.
719 if (Existing.second != Known->second.second) {
720 if (Diags) {
721 Diags->Report(diag::err_pch_macro_def_undef)
722 << MacroName << Known->second.second;
723 }
724 return true;
725 }
726
727 // If the macro was #undef'd in both, or if the macro bodies are
728 // identical, it's fine.
729 if (Existing.second || Existing.first == Known->second.first) {
730 ASTFileMacros.erase(Known);
731 continue;
732 }
733
734 // The macro bodies differ; complain.
735 if (Diags) {
736 Diags->Report(diag::err_pch_macro_def_conflict)
737 << MacroName << Known->second.first << Existing.first;
738 }
739 return true;
740 }
741
742 // Leave the <command line> file and return to <built-in>.
743 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
744
745 if (Validation == OptionValidateStrictMatches) {
746 // If strict matches are requested, don't tolerate any extra defines in
747 // the AST file that are missing on the command line.
748 for (const auto &MacroName : ASTFileMacros.keys()) {
749 if (Diags) {
750 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
751 }
752 return true;
753 }
754 }
755 }
756
757 // Check whether we're using predefines.
758 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
759 Validation != OptionValidateNone) {
760 if (Diags) {
761 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
762 }
763 return true;
764 }
765
766 // Detailed record is important since it is used for the module cache hash.
767 if (LangOpts.Modules &&
768 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
769 Validation != OptionValidateNone) {
770 if (Diags) {
771 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
772 }
773 return true;
774 }
775
776 // Compute the #include and #include_macros lines we need.
777 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
778 StringRef File = ExistingPPOpts.Includes[I];
779
780 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
781 !ExistingPPOpts.PCHThroughHeader.empty()) {
782 // In case the through header is an include, we must add all the includes
783 // to the predefines so the start point can be determined.
784 SuggestedPredefines += "#include \"";
785 SuggestedPredefines += File;
786 SuggestedPredefines += "\"\n";
787 continue;
788 }
789
790 if (File == ExistingPPOpts.ImplicitPCHInclude)
791 continue;
792
793 if (llvm::is_contained(PPOpts.Includes, File))
794 continue;
795
796 SuggestedPredefines += "#include \"";
797 SuggestedPredefines += File;
798 SuggestedPredefines += "\"\n";
799 }
800
801 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
802 StringRef File = ExistingPPOpts.MacroIncludes[I];
803 if (llvm::is_contained(PPOpts.MacroIncludes, File))
804 continue;
805
806 SuggestedPredefines += "#__include_macros \"";
807 SuggestedPredefines += File;
808 SuggestedPredefines += "\"\n##\n";
809 }
810
811 return false;
812}
813
815 bool ReadMacros, bool Complain,
816 std::string &SuggestedPredefines) {
817 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
818
820 PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr,
821 PP.getFileManager(), SuggestedPredefines, PP.getLangOpts());
822}
823
825 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
826 std::string &SuggestedPredefines) {
827 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros,
828 nullptr, PP.getFileManager(),
829 SuggestedPredefines, PP.getLangOpts(),
831}
832
833/// Check that the specified and the existing module cache paths are equivalent.
834///
835/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
836/// \returns true when the module cache paths differ.
837static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
838 StringRef SpecificModuleCachePath,
839 StringRef ExistingModuleCachePath,
840 DiagnosticsEngine *Diags,
841 const LangOptions &LangOpts,
842 const PreprocessorOptions &PPOpts) {
843 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
844 SpecificModuleCachePath == ExistingModuleCachePath)
845 return false;
846 auto EqualOrErr =
847 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
848 if (EqualOrErr && *EqualOrErr)
849 return false;
850 if (Diags)
851 Diags->Report(diag::err_pch_modulecache_mismatch)
852 << SpecificModuleCachePath << ExistingModuleCachePath;
853 return true;
854}
855
857 StringRef SpecificModuleCachePath,
858 bool Complain) {
860 SpecificModuleCachePath,
862 Complain ? &Reader.Diags : nullptr,
864}
865
868}
869
870//===----------------------------------------------------------------------===//
871// AST reader implementation
872//===----------------------------------------------------------------------===//
873
874static uint64_t readULEB(const unsigned char *&P) {
875 unsigned Length = 0;
876 const char *Error = nullptr;
877
878 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
879 if (Error)
880 llvm::report_fatal_error(Error);
881 P += Length;
882 return Val;
883}
884
885/// Read ULEB-encoded key length and data length.
886static std::pair<unsigned, unsigned>
887readULEBKeyDataLength(const unsigned char *&P) {
888 unsigned KeyLen = readULEB(P);
889 if ((unsigned)KeyLen != KeyLen)
890 llvm::report_fatal_error("key too large");
891
892 unsigned DataLen = readULEB(P);
893 if ((unsigned)DataLen != DataLen)
894 llvm::report_fatal_error("data too large");
895
896 return std::make_pair(KeyLen, DataLen);
897}
898
900 bool TakeOwnership) {
901 DeserializationListener = Listener;
902 OwnsDeserializationListener = TakeOwnership;
903}
904
906 return serialization::ComputeHash(Sel);
907}
908
909std::pair<unsigned, unsigned>
911 return readULEBKeyDataLength(d);
912}
913
915ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
916 using namespace llvm::support;
917
918 SelectorTable &SelTable = Reader.getContext().Selectors;
919 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
920 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
921 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
922 if (N == 0)
923 return SelTable.getNullarySelector(FirstII);
924 else if (N == 1)
925 return SelTable.getUnarySelector(FirstII);
926
928 Args.push_back(FirstII);
929 for (unsigned I = 1; I != N; ++I)
930 Args.push_back(Reader.getLocalIdentifier(
931 F, endian::readNext<uint32_t, llvm::endianness::little>(d)));
932
933 return SelTable.getSelector(N, Args.data());
934}
935
938 unsigned DataLen) {
939 using namespace llvm::support;
940
942
943 Result.ID = Reader.getGlobalSelectorID(
944 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
945 unsigned FullInstanceBits =
946 endian::readNext<uint16_t, llvm::endianness::little>(d);
947 unsigned FullFactoryBits =
948 endian::readNext<uint16_t, llvm::endianness::little>(d);
949 Result.InstanceBits = FullInstanceBits & 0x3;
950 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
951 Result.FactoryBits = FullFactoryBits & 0x3;
952 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
953 unsigned NumInstanceMethods = FullInstanceBits >> 3;
954 unsigned NumFactoryMethods = FullFactoryBits >> 3;
955
956 // Load instance methods
957 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
958 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
959 F,
960 LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))))
961 Result.Instance.push_back(Method);
962 }
963
964 // Load factory methods
965 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
966 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
967 F,
968 LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))))
969 Result.Factory.push_back(Method);
970 }
971
972 return Result;
973}
974
976 return llvm::djbHash(a);
977}
978
979std::pair<unsigned, unsigned>
981 return readULEBKeyDataLength(d);
982}
983
985ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
986 assert(n >= 2 && d[n-1] == '\0');
987 return StringRef((const char*) d, n-1);
988}
989
990/// Whether the given identifier is "interesting".
991static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
992 bool IsModule) {
993 bool IsInteresting =
994 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
996 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
997 return II.hadMacroDefinition() || II.isPoisoned() ||
998 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
999 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1000 II.getFETokenInfo());
1001}
1002
1003static bool readBit(unsigned &Bits) {
1004 bool Value = Bits & 0x1;
1005 Bits >>= 1;
1006 return Value;
1007}
1008
1010 using namespace llvm::support;
1011
1012 unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(d);
1013 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1014}
1015
1017 if (!II.isFromAST()) {
1018 II.setIsFromAST();
1019 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1020 if (isInterestingIdentifier(Reader, II, IsModule))
1022 }
1023}
1024
1026 const unsigned char* d,
1027 unsigned DataLen) {
1028 using namespace llvm::support;
1029
1030 unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(d);
1031 bool IsInteresting = RawID & 0x01;
1032
1033 // Wipe out the "is interesting" bit.
1034 RawID = RawID >> 1;
1035
1036 // Build the IdentifierInfo and link the identifier ID with it.
1037 IdentifierInfo *II = KnownII;
1038 if (!II) {
1039 II = &Reader.getIdentifierTable().getOwn(k);
1040 KnownII = II;
1041 }
1042 markIdentifierFromAST(Reader, *II);
1043 Reader.markIdentifierUpToDate(II);
1044
1045 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1046 if (!IsInteresting) {
1047 // For uninteresting identifiers, there's nothing else to do. Just notify
1048 // the reader that we've finished loading this identifier.
1049 Reader.SetIdentifierInfo(ID, II);
1050 return II;
1051 }
1052
1053 unsigned ObjCOrBuiltinID =
1054 endian::readNext<uint16_t, llvm::endianness::little>(d);
1055 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1056 bool CPlusPlusOperatorKeyword = readBit(Bits);
1057 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1058 bool Poisoned = readBit(Bits);
1059 bool ExtensionToken = readBit(Bits);
1060 bool HadMacroDefinition = readBit(Bits);
1061
1062 assert(Bits == 0 && "Extra bits in the identifier?");
1063 DataLen -= 8;
1064
1065 // Set or check the various bits in the IdentifierInfo structure.
1066 // Token IDs are read-only.
1067 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1069 if (!F.isModule())
1070 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1071 assert(II->isExtensionToken() == ExtensionToken &&
1072 "Incorrect extension token flag");
1073 (void)ExtensionToken;
1074 if (Poisoned)
1075 II->setIsPoisoned(true);
1076 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1077 "Incorrect C++ operator keyword flag");
1078 (void)CPlusPlusOperatorKeyword;
1079
1080 // If this identifier is a macro, deserialize the macro
1081 // definition.
1082 if (HadMacroDefinition) {
1083 uint32_t MacroDirectivesOffset =
1084 endian::readNext<uint32_t, llvm::endianness::little>(d);
1085 DataLen -= 4;
1086
1087 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1088 }
1089
1090 Reader.SetIdentifierInfo(ID, II);
1091
1092 // Read all of the declarations visible at global scope with this
1093 // name.
1094 if (DataLen > 0) {
1096 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1097 DeclIDs.push_back(Reader.getGlobalDeclID(
1098 F,
1099 LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))));
1100 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1101 }
1102
1103 return II;
1104}
1105
1107 : Kind(Name.getNameKind()) {
1108 switch (Kind) {
1110 Data = (uint64_t)Name.getAsIdentifierInfo();
1111 break;
1115 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1116 break;
1118 Data = Name.getCXXOverloadedOperator();
1119 break;
1121 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1122 break;
1124 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1125 ->getDeclName().getAsIdentifierInfo();
1126 break;
1131 Data = 0;
1132 break;
1133 }
1134}
1135
1137 llvm::FoldingSetNodeID ID;
1138 ID.AddInteger(Kind);
1139
1140 switch (Kind) {
1144 ID.AddString(((IdentifierInfo*)Data)->getName());
1145 break;
1149 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1150 break;
1152 ID.AddInteger((OverloadedOperatorKind)Data);
1153 break;
1158 break;
1159 }
1160
1161 return ID.ComputeHash();
1162}
1163
1164ModuleFile *
1165ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1166 using namespace llvm::support;
1167
1168 uint32_t ModuleFileID =
1169 endian::readNext<uint32_t, llvm::endianness::little>(d);
1170 return Reader.getLocalModuleFile(F, ModuleFileID);
1171}
1172
1173std::pair<unsigned, unsigned>
1174ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1175 return readULEBKeyDataLength(d);
1176}
1177
1179ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1180 using namespace llvm::support;
1181
1182 auto Kind = (DeclarationName::NameKind)*d++;
1183 uint64_t Data;
1184 switch (Kind) {
1188 Data = (uint64_t)Reader.getLocalIdentifier(
1189 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1190 break;
1194 Data = (uint64_t)Reader
1195 .getLocalSelector(
1196 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1197 .getAsOpaquePtr();
1198 break;
1200 Data = *d++; // OverloadedOperatorKind
1201 break;
1206 Data = 0;
1207 break;
1208 }
1209
1210 return DeclarationNameKey(Kind, Data);
1211}
1212
1213void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1214 const unsigned char *d,
1215 unsigned DataLen,
1216 data_type_builder &Val) {
1217 using namespace llvm::support;
1218
1219 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1220 LocalDeclID LocalID(endian::readNext<DeclID, llvm::endianness::little>(d));
1221 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1222 }
1223}
1224
1225bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1226 BitstreamCursor &Cursor,
1227 uint64_t Offset,
1228 DeclContext *DC) {
1229 assert(Offset != 0);
1230
1231 SavedStreamPosition SavedPosition(Cursor);
1232 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1233 Error(std::move(Err));
1234 return true;
1235 }
1236
1237 RecordData Record;
1238 StringRef Blob;
1239 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1240 if (!MaybeCode) {
1241 Error(MaybeCode.takeError());
1242 return true;
1243 }
1244 unsigned Code = MaybeCode.get();
1245
1246 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1247 if (!MaybeRecCode) {
1248 Error(MaybeRecCode.takeError());
1249 return true;
1250 }
1251 unsigned RecCode = MaybeRecCode.get();
1252 if (RecCode != DECL_CONTEXT_LEXICAL) {
1253 Error("Expected lexical block");
1254 return true;
1255 }
1256
1257 assert(!isa<TranslationUnitDecl>(DC) &&
1258 "expected a TU_UPDATE_LEXICAL record for TU");
1259 // If we are handling a C++ class template instantiation, we can see multiple
1260 // lexical updates for the same record. It's important that we select only one
1261 // of them, so that field numbering works properly. Just pick the first one we
1262 // see.
1263 auto &Lex = LexicalDecls[DC];
1264 if (!Lex.first) {
1265 Lex = std::make_pair(
1266 &M, llvm::ArrayRef(
1267 reinterpret_cast<const unalighed_decl_id_t *>(Blob.data()),
1268 Blob.size() / sizeof(DeclID)));
1269 }
1271 return false;
1272}
1273
1274bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1275 BitstreamCursor &Cursor,
1276 uint64_t Offset,
1277 GlobalDeclID ID) {
1278 assert(Offset != 0);
1279
1280 SavedStreamPosition SavedPosition(Cursor);
1281 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1282 Error(std::move(Err));
1283 return true;
1284 }
1285
1286 RecordData Record;
1287 StringRef Blob;
1288 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1289 if (!MaybeCode) {
1290 Error(MaybeCode.takeError());
1291 return true;
1292 }
1293 unsigned Code = MaybeCode.get();
1294
1295 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1296 if (!MaybeRecCode) {
1297 Error(MaybeRecCode.takeError());
1298 return true;
1299 }
1300 unsigned RecCode = MaybeRecCode.get();
1301 if (RecCode != DECL_CONTEXT_VISIBLE) {
1302 Error("Expected visible lookup table block");
1303 return true;
1304 }
1305
1306 // We can't safely determine the primary context yet, so delay attaching the
1307 // lookup table until we're done with recursive deserialization.
1308 auto *Data = (const unsigned char*)Blob.data();
1309 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1310 return false;
1311}
1312
1313void ASTReader::Error(StringRef Msg) const {
1314 Error(diag::err_fe_pch_malformed, Msg);
1315 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1316 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1317 Diag(diag::note_module_cache_path)
1318 << PP.getHeaderSearchInfo().getModuleCachePath();
1319 }
1320}
1321
1322void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1323 StringRef Arg3) const {
1324 if (Diags.isDiagnosticInFlight())
1325 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1326 else
1327 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1328}
1329
1330void ASTReader::Error(llvm::Error &&Err) const {
1331 llvm::Error RemainingErr =
1332 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1333 auto Diag = E.getDiagnostic().second;
1334
1335 // Ideally we'd just emit it, but have to handle a possible in-flight
1336 // diagnostic. Note that the location is currently ignored as well.
1337 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1338 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1339 StringRef Arg1, Arg2, Arg3;
1340 switch (NumArgs) {
1341 case 3:
1342 Arg3 = Diag.getStringArg(2);
1343 [[fallthrough]];
1344 case 2:
1345 Arg2 = Diag.getStringArg(1);
1346 [[fallthrough]];
1347 case 1:
1348 Arg1 = Diag.getStringArg(0);
1349 }
1350 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1351 });
1352 if (RemainingErr)
1353 Error(toString(std::move(RemainingErr)));
1354}
1355
1356//===----------------------------------------------------------------------===//
1357// Source Manager Deserialization
1358//===----------------------------------------------------------------------===//
1359
1360/// Read the line table in the source manager block.
1361void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1362 unsigned Idx = 0;
1363 LineTableInfo &LineTable = SourceMgr.getLineTable();
1364
1365 // Parse the file names
1366 std::map<int, int> FileIDs;
1367 FileIDs[-1] = -1; // For unspecified filenames.
1368 for (unsigned I = 0; Record[Idx]; ++I) {
1369 // Extract the file name
1370 auto Filename = ReadPath(F, Record, Idx);
1371 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1372 }
1373 ++Idx;
1374
1375 // Parse the line entries
1376 std::vector<LineEntry> Entries;
1377 while (Idx < Record.size()) {
1378 FileID FID = ReadFileID(F, Record, Idx);
1379
1380 // Extract the line entries
1381 unsigned NumEntries = Record[Idx++];
1382 assert(NumEntries && "no line entries for file ID");
1383 Entries.clear();
1384 Entries.reserve(NumEntries);
1385 for (unsigned I = 0; I != NumEntries; ++I) {
1386 unsigned FileOffset = Record[Idx++];
1387 unsigned LineNo = Record[Idx++];
1388 int FilenameID = FileIDs[Record[Idx++]];
1391 unsigned IncludeOffset = Record[Idx++];
1392 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1393 FileKind, IncludeOffset));
1394 }
1395 LineTable.AddEntry(FID, Entries);
1396 }
1397}
1398
1399/// Read a source manager block
1400llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1401 using namespace SrcMgr;
1402
1403 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1404
1405 // Set the source-location entry cursor to the current position in
1406 // the stream. This cursor will be used to read the contents of the
1407 // source manager block initially, and then lazily read
1408 // source-location entries as needed.
1409 SLocEntryCursor = F.Stream;
1410
1411 // The stream itself is going to skip over the source manager block.
1412 if (llvm::Error Err = F.Stream.SkipBlock())
1413 return Err;
1414
1415 // Enter the source manager block.
1416 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1417 return Err;
1418 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1419
1420 RecordData Record;
1421 while (true) {
1423 SLocEntryCursor.advanceSkippingSubblocks();
1424 if (!MaybeE)
1425 return MaybeE.takeError();
1426 llvm::BitstreamEntry E = MaybeE.get();
1427
1428 switch (E.Kind) {
1429 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1430 case llvm::BitstreamEntry::Error:
1431 return llvm::createStringError(std::errc::illegal_byte_sequence,
1432 "malformed block record in AST file");
1433 case llvm::BitstreamEntry::EndBlock:
1434 return llvm::Error::success();
1435 case llvm::BitstreamEntry::Record:
1436 // The interesting case.
1437 break;
1438 }
1439
1440 // Read a record.
1441 Record.clear();
1442 StringRef Blob;
1443 Expected<unsigned> MaybeRecord =
1444 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1445 if (!MaybeRecord)
1446 return MaybeRecord.takeError();
1447 switch (MaybeRecord.get()) {
1448 default: // Default behavior: ignore.
1449 break;
1450
1451 case SM_SLOC_FILE_ENTRY:
1454 // Once we hit one of the source location entries, we're done.
1455 return llvm::Error::success();
1456 }
1457 }
1458}
1459
1462 BitstreamCursor &Cursor = F->SLocEntryCursor;
1463 SavedStreamPosition SavedPosition(Cursor);
1464 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1465 F->SLocEntryOffsets[Index]))
1466 return std::move(Err);
1467
1468 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1469 if (!MaybeEntry)
1470 return MaybeEntry.takeError();
1471
1472 llvm::BitstreamEntry Entry = MaybeEntry.get();
1473 if (Entry.Kind != llvm::BitstreamEntry::Record)
1474 return llvm::createStringError(
1475 std::errc::illegal_byte_sequence,
1476 "incorrectly-formatted source location entry in AST file");
1477
1479 StringRef Blob;
1480 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1481 if (!MaybeSLOC)
1482 return MaybeSLOC.takeError();
1483
1484 switch (MaybeSLOC.get()) {
1485 default:
1486 return llvm::createStringError(
1487 std::errc::illegal_byte_sequence,
1488 "incorrectly-formatted source location entry in AST file");
1489 case SM_SLOC_FILE_ENTRY:
1492 return F->SLocEntryBaseOffset + Record[0];
1493 }
1494}
1495
1497 auto SLocMapI =
1498 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1499 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1500 "Corrupted global sloc offset map");
1501 ModuleFile *F = SLocMapI->second;
1502
1503 bool Invalid = false;
1504
1505 auto It = llvm::upper_bound(
1506 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1507 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1508 int ID = F->SLocEntryBaseID + LocalIndex;
1509 std::size_t Index = -ID - 2;
1510 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1511 assert(!SourceMgr.SLocEntryLoaded[Index]);
1512 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1513 if (!MaybeEntryOffset) {
1514 Error(MaybeEntryOffset.takeError());
1515 Invalid = true;
1516 return true;
1517 }
1518 SourceMgr.LoadedSLocEntryTable[Index] =
1519 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1520 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1521 }
1522 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1523 });
1524
1525 if (Invalid)
1526 return 0;
1527
1528 // The iterator points to the first entry with start offset greater than the
1529 // offset of interest. The previous entry must contain the offset of interest.
1530 return F->SLocEntryBaseID + *std::prev(It);
1531}
1532
1534 if (ID == 0)
1535 return false;
1536
1537 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1538 Error("source location entry ID out-of-range for AST file");
1539 return true;
1540 }
1541
1542 // Local helper to read the (possibly-compressed) buffer data following the
1543 // entry record.
1544 auto ReadBuffer = [this](
1545 BitstreamCursor &SLocEntryCursor,
1546 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1548 StringRef Blob;
1549 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1550 if (!MaybeCode) {
1551 Error(MaybeCode.takeError());
1552 return nullptr;
1553 }
1554 unsigned Code = MaybeCode.get();
1555
1556 Expected<unsigned> MaybeRecCode =
1557 SLocEntryCursor.readRecord(Code, Record, &Blob);
1558 if (!MaybeRecCode) {
1559 Error(MaybeRecCode.takeError());
1560 return nullptr;
1561 }
1562 unsigned RecCode = MaybeRecCode.get();
1563
1564 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1565 // Inspect the first byte to differentiate zlib (\x78) and zstd
1566 // (little-endian 0xFD2FB528).
1567 const llvm::compression::Format F =
1568 Blob.size() > 0 && Blob.data()[0] == 0x78
1569 ? llvm::compression::Format::Zlib
1570 : llvm::compression::Format::Zstd;
1571 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1572 Error(Reason);
1573 return nullptr;
1574 }
1575 SmallVector<uint8_t, 0> Decompressed;
1576 if (llvm::Error E = llvm::compression::decompress(
1577 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1578 Error("could not decompress embedded file contents: " +
1579 llvm::toString(std::move(E)));
1580 return nullptr;
1581 }
1582 return llvm::MemoryBuffer::getMemBufferCopy(
1583 llvm::toStringRef(Decompressed), Name);
1584 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1585 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1586 } else {
1587 Error("AST record has invalid code");
1588 return nullptr;
1589 }
1590 };
1591
1592 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1593 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1595 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1596 Error(std::move(Err));
1597 return true;
1598 }
1599
1600 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1602
1603 ++NumSLocEntriesRead;
1604 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1605 if (!MaybeEntry) {
1606 Error(MaybeEntry.takeError());
1607 return true;
1608 }
1609 llvm::BitstreamEntry Entry = MaybeEntry.get();
1610
1611 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1612 Error("incorrectly-formatted source location entry in AST file");
1613 return true;
1614 }
1615
1617 StringRef Blob;
1618 Expected<unsigned> MaybeSLOC =
1619 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1620 if (!MaybeSLOC) {
1621 Error(MaybeSLOC.takeError());
1622 return true;
1623 }
1624 switch (MaybeSLOC.get()) {
1625 default:
1626 Error("incorrectly-formatted source location entry in AST file");
1627 return true;
1628
1629 case SM_SLOC_FILE_ENTRY: {
1630 // We will detect whether a file changed and return 'Failure' for it, but
1631 // we will also try to fail gracefully by setting up the SLocEntry.
1632 unsigned InputID = Record[4];
1633 InputFile IF = getInputFile(*F, InputID);
1635 bool OverriddenBuffer = IF.isOverridden();
1636
1637 // Note that we only check if a File was returned. If it was out-of-date
1638 // we have complained but we will continue creating a FileID to recover
1639 // gracefully.
1640 if (!File)
1641 return true;
1642
1643 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1644 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1645 // This is the module's main file.
1646 IncludeLoc = getImportLocation(F);
1647 }
1649 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1650 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1651 BaseOffset + Record[0]);
1652 SrcMgr::FileInfo &FileInfo =
1653 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1654 FileInfo.NumCreatedFIDs = Record[5];
1655 if (Record[3])
1656 FileInfo.setHasLineDirectives();
1657
1658 unsigned NumFileDecls = Record[7];
1659 if (NumFileDecls && ContextObj) {
1660 const LocalDeclID *FirstDecl = F->FileSortedDecls + Record[6];
1661 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1662 FileDeclIDs[FID] =
1663 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1664 }
1665
1666 const SrcMgr::ContentCache &ContentCache =
1667 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1668 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1669 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1670 !ContentCache.getBufferIfLoaded()) {
1671 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1672 if (!Buffer)
1673 return true;
1674 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1675 }
1676
1677 break;
1678 }
1679
1680 case SM_SLOC_BUFFER_ENTRY: {
1681 const char *Name = Blob.data();
1682 unsigned Offset = Record[0];
1684 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1685 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1686 if (IncludeLoc.isInvalid() && F->isModule()) {
1687 IncludeLoc = getImportLocation(F);
1688 }
1689
1690 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1691 if (!Buffer)
1692 return true;
1693 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1694 BaseOffset + Offset, IncludeLoc);
1695 if (Record[3]) {
1696 auto &FileInfo =
1697 const_cast<SrcMgr::FileInfo &>(SourceMgr.getSLocEntry(FID).getFile());
1698 FileInfo.setHasLineDirectives();
1699 }
1700 break;
1701 }
1702
1705 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1706 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1707 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1708 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1709 Record[5], Record[4], ID,
1710 BaseOffset + Record[0]);
1711 break;
1712 }
1713 }
1714
1715 return false;
1716}
1717
1718std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1719 if (ID == 0)
1720 return std::make_pair(SourceLocation(), "");
1721
1722 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1723 Error("source location entry ID out-of-range for AST file");
1724 return std::make_pair(SourceLocation(), "");
1725 }
1726
1727 // Find which module file this entry lands in.
1728 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1729 if (!M->isModule())
1730 return std::make_pair(SourceLocation(), "");
1731
1732 // FIXME: Can we map this down to a particular submodule? That would be
1733 // ideal.
1734 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1735}
1736
1737/// Find the location where the module F is imported.
1738SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1739 if (F->ImportLoc.isValid())
1740 return F->ImportLoc;
1741
1742 // Otherwise we have a PCH. It's considered to be "imported" at the first
1743 // location of its includer.
1744 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1745 // Main file is the importer.
1746 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1747 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1748 }
1749 return F->ImportedBy[0]->FirstLoc;
1750}
1751
1752/// Enter a subblock of the specified BlockID with the specified cursor. Read
1753/// the abbreviations that are at the top of the block and then leave the cursor
1754/// pointing into the block.
1755llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1756 unsigned BlockID,
1757 uint64_t *StartOfBlockOffset) {
1758 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1759 return Err;
1760
1761 if (StartOfBlockOffset)
1762 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1763
1764 while (true) {
1765 uint64_t Offset = Cursor.GetCurrentBitNo();
1766 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1767 if (!MaybeCode)
1768 return MaybeCode.takeError();
1769 unsigned Code = MaybeCode.get();
1770
1771 // We expect all abbrevs to be at the start of the block.
1772 if (Code != llvm::bitc::DEFINE_ABBREV) {
1773 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1774 return Err;
1775 return llvm::Error::success();
1776 }
1777 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1778 return Err;
1779 }
1780}
1781
1783 unsigned &Idx) {
1784 Token Tok;
1785 Tok.startToken();
1786 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1787 Tok.setKind((tok::TokenKind)Record[Idx++]);
1788 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1789
1790 if (Tok.isAnnotation()) {
1791 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1792 switch (Tok.getKind()) {
1793 case tok::annot_pragma_loop_hint: {
1794 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1795 Info->PragmaName = ReadToken(M, Record, Idx);
1796 Info->Option = ReadToken(M, Record, Idx);
1797 unsigned NumTokens = Record[Idx++];
1799 Toks.reserve(NumTokens);
1800 for (unsigned I = 0; I < NumTokens; ++I)
1801 Toks.push_back(ReadToken(M, Record, Idx));
1802 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1803 Tok.setAnnotationValue(static_cast<void *>(Info));
1804 break;
1805 }
1806 case tok::annot_pragma_pack: {
1807 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1808 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1809 auto SlotLabel = ReadString(Record, Idx);
1810 Info->SlotLabel =
1811 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1812 Info->Alignment = ReadToken(M, Record, Idx);
1813 Tok.setAnnotationValue(static_cast<void *>(Info));
1814 break;
1815 }
1816 // Some annotation tokens do not use the PtrData field.
1817 case tok::annot_pragma_openmp:
1818 case tok::annot_pragma_openmp_end:
1819 case tok::annot_pragma_unused:
1820 case tok::annot_pragma_openacc:
1821 case tok::annot_pragma_openacc_end:
1822 break;
1823 default:
1824 llvm_unreachable("missing deserialization code for annotation token");
1825 }
1826 } else {
1827 Tok.setLength(Record[Idx++]);
1828 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1829 Tok.setIdentifierInfo(II);
1830 }
1831 return Tok;
1832}
1833
1835 BitstreamCursor &Stream = F.MacroCursor;
1836
1837 // Keep track of where we are in the stream, then jump back there
1838 // after reading this macro.
1839 SavedStreamPosition SavedPosition(Stream);
1840
1841 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1842 // FIXME this drops errors on the floor.
1843 consumeError(std::move(Err));
1844 return nullptr;
1845 }
1848 MacroInfo *Macro = nullptr;
1849 llvm::MutableArrayRef<Token> MacroTokens;
1850
1851 while (true) {
1852 // Advance to the next record, but if we get to the end of the block, don't
1853 // pop it (removing all the abbreviations from the cursor) since we want to
1854 // be able to reseek within the block and read entries.
1855 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1857 Stream.advanceSkippingSubblocks(Flags);
1858 if (!MaybeEntry) {
1859 Error(MaybeEntry.takeError());
1860 return Macro;
1861 }
1862 llvm::BitstreamEntry Entry = MaybeEntry.get();
1863
1864 switch (Entry.Kind) {
1865 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1866 case llvm::BitstreamEntry::Error:
1867 Error("malformed block record in AST file");
1868 return Macro;
1869 case llvm::BitstreamEntry::EndBlock:
1870 return Macro;
1871 case llvm::BitstreamEntry::Record:
1872 // The interesting case.
1873 break;
1874 }
1875
1876 // Read a record.
1877 Record.clear();
1879 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1880 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1881 else {
1882 Error(MaybeRecType.takeError());
1883 return Macro;
1884 }
1885 switch (RecType) {
1886 case PP_MODULE_MACRO:
1888 return Macro;
1889
1892 // If we already have a macro, that means that we've hit the end
1893 // of the definition of the macro we were looking for. We're
1894 // done.
1895 if (Macro)
1896 return Macro;
1897
1898 unsigned NextIndex = 1; // Skip identifier ID.
1899 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1900 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1901 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1902 MI->setIsUsed(Record[NextIndex++]);
1903 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1904 MacroTokens = MI->allocateTokens(Record[NextIndex++],
1905 PP.getPreprocessorAllocator());
1906 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1907 // Decode function-like macro info.
1908 bool isC99VarArgs = Record[NextIndex++];
1909 bool isGNUVarArgs = Record[NextIndex++];
1910 bool hasCommaPasting = Record[NextIndex++];
1911 MacroParams.clear();
1912 unsigned NumArgs = Record[NextIndex++];
1913 for (unsigned i = 0; i != NumArgs; ++i)
1914 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1915
1916 // Install function-like macro info.
1917 MI->setIsFunctionLike();
1918 if (isC99VarArgs) MI->setIsC99Varargs();
1919 if (isGNUVarArgs) MI->setIsGNUVarargs();
1920 if (hasCommaPasting) MI->setHasCommaPasting();
1921 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1922 }
1923
1924 // Remember that we saw this macro last so that we add the tokens that
1925 // form its body to it.
1926 Macro = MI;
1927
1928 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1929 Record[NextIndex]) {
1930 // We have a macro definition. Register the association
1932 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1933 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1934 PreprocessingRecord::PPEntityID PPID =
1935 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1936 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1937 PPRec.getPreprocessedEntity(PPID));
1938 if (PPDef)
1939 PPRec.RegisterMacroDefinition(Macro, PPDef);
1940 }
1941
1942 ++NumMacrosRead;
1943 break;
1944 }
1945
1946 case PP_TOKEN: {
1947 // If we see a TOKEN before a PP_MACRO_*, then the file is
1948 // erroneous, just pretend we didn't see this.
1949 if (!Macro) break;
1950 if (MacroTokens.empty()) {
1951 Error("unexpected number of macro tokens for a macro in AST file");
1952 return Macro;
1953 }
1954
1955 unsigned Idx = 0;
1956 MacroTokens[0] = ReadToken(F, Record, Idx);
1957 MacroTokens = MacroTokens.drop_front();
1958 break;
1959 }
1960 }
1961 }
1962}
1963
1966 unsigned LocalID) const {
1967 if (!M.ModuleOffsetMap.empty())
1968 ReadModuleOffsetMap(M);
1969
1972 assert(I != M.PreprocessedEntityRemap.end()
1973 && "Invalid index into preprocessed entity index remap");
1974
1975 return LocalID + I->second;
1976}
1977
1978const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
1979 FileManager &FileMgr = Reader.getFileManager();
1980 if (!Key.Imported) {
1981 if (auto File = FileMgr.getFile(Key.Filename))
1982 return *File;
1983 return nullptr;
1984 }
1985
1986 std::string Resolved = std::string(Key.Filename);
1987 Reader.ResolveImportedPath(M, Resolved);
1988 if (auto File = FileMgr.getFile(Resolved))
1989 return *File;
1990 return nullptr;
1991}
1992
1993unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1994 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1995}
1996
1998HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
1999 internal_key_type ikey = {ekey.getSize(),
2000 M.HasTimestamps ? ekey.getModificationTime() : 0,
2001 ekey.getName(), /*Imported*/ false};
2002 return ikey;
2003}
2004
2005bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2006 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2007 return false;
2008
2009 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2010 return true;
2011
2012 // Determine whether the actual files are equivalent.
2013 const FileEntry *FEA = getFile(a);
2014 const FileEntry *FEB = getFile(b);
2015 return FEA && FEA == FEB;
2016}
2017
2018std::pair<unsigned, unsigned>
2019HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2020 return readULEBKeyDataLength(d);
2021}
2022
2024HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2025 using namespace llvm::support;
2026
2027 internal_key_type ikey;
2028 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2029 ikey.ModTime =
2030 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2031 ikey.Filename = (const char *)d;
2032 ikey.Imported = true;
2033 return ikey;
2034}
2035
2037HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2038 unsigned DataLen) {
2039 using namespace llvm::support;
2040
2041 const unsigned char *End = d + DataLen;
2042 HeaderFileInfo HFI;
2043 unsigned Flags = *d++;
2044
2045 bool Included = (Flags >> 6) & 0x01;
2046 if (Included)
2047 if (const FileEntry *FE = getFile(key))
2048 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2049 // deserialize this header file info again.
2050 Reader.getPreprocessor().getIncludedFiles().insert(FE);
2051
2052 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2053 HFI.isImport |= (Flags >> 5) & 0x01;
2054 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2055 HFI.DirInfo = (Flags >> 1) & 0x07;
2056 HFI.IndexHeaderMapHeader = Flags & 0x01;
2057 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
2058 M, endian::readNext<uint32_t, llvm::endianness::little>(d));
2059 if (unsigned FrameworkOffset =
2060 endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2061 // The framework offset is 1 greater than the actual offset,
2062 // since 0 is used as an indicator for "no framework name".
2063 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2064 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
2065 }
2066
2067 assert((End - d) % 4 == 0 &&
2068 "Wrong data length in HeaderFileInfo deserialization");
2069 while (d != End) {
2070 uint32_t LocalSMID =
2071 endian::readNext<uint32_t, llvm::endianness::little>(d);
2072 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2073 LocalSMID >>= 3;
2074
2075 // This header is part of a module. Associate it with the module to enable
2076 // implicit module import.
2077 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2078 Module *Mod = Reader.getSubmodule(GlobalSMID);
2079 FileManager &FileMgr = Reader.getFileManager();
2080 ModuleMap &ModMap =
2081 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2082
2083 std::string Filename = std::string(key.Filename);
2084 if (key.Imported)
2085 Reader.ResolveImportedPath(M, Filename);
2086 if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
2087 // FIXME: NameAsWritten
2088 Module::Header H = {std::string(key.Filename), "", *FE};
2089 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2090 }
2091 HFI.mergeModuleMembership(HeaderRole);
2092 }
2093
2094 // This HeaderFileInfo was externally loaded.
2095 HFI.External = true;
2096 HFI.IsValid = true;
2097 return HFI;
2098}
2099
2101 uint32_t MacroDirectivesOffset) {
2102 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2103 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2104}
2105
2107 // Note that we are loading defined macros.
2108 Deserializing Macros(this);
2109
2110 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2111 BitstreamCursor &MacroCursor = I.MacroCursor;
2112
2113 // If there was no preprocessor block, skip this file.
2114 if (MacroCursor.getBitcodeBytes().empty())
2115 continue;
2116
2117 BitstreamCursor Cursor = MacroCursor;
2118 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2119 Error(std::move(Err));
2120 return;
2121 }
2122
2124 while (true) {
2125 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2126 if (!MaybeE) {
2127 Error(MaybeE.takeError());
2128 return;
2129 }
2130 llvm::BitstreamEntry E = MaybeE.get();
2131
2132 switch (E.Kind) {
2133 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2134 case llvm::BitstreamEntry::Error:
2135 Error("malformed block record in AST file");
2136 return;
2137 case llvm::BitstreamEntry::EndBlock:
2138 goto NextCursor;
2139
2140 case llvm::BitstreamEntry::Record: {
2141 Record.clear();
2142 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2143 if (!MaybeRecord) {
2144 Error(MaybeRecord.takeError());
2145 return;
2146 }
2147 switch (MaybeRecord.get()) {
2148 default: // Default behavior: ignore.
2149 break;
2150
2153 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2154 if (II->isOutOfDate())
2155 updateOutOfDateIdentifier(*II);
2156 break;
2157 }
2158
2159 case PP_TOKEN:
2160 // Ignore tokens.
2161 break;
2162 }
2163 break;
2164 }
2165 }
2166 }
2167 NextCursor: ;
2168 }
2169}
2170
2171namespace {
2172
2173 /// Visitor class used to look up identifirs in an AST file.
2174 class IdentifierLookupVisitor {
2175 StringRef Name;
2176 unsigned NameHash;
2177 unsigned PriorGeneration;
2178 unsigned &NumIdentifierLookups;
2179 unsigned &NumIdentifierLookupHits;
2180 IdentifierInfo *Found = nullptr;
2181
2182 public:
2183 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2184 unsigned &NumIdentifierLookups,
2185 unsigned &NumIdentifierLookupHits)
2186 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2187 PriorGeneration(PriorGeneration),
2188 NumIdentifierLookups(NumIdentifierLookups),
2189 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2190
2191 bool operator()(ModuleFile &M) {
2192 // If we've already searched this module file, skip it now.
2193 if (M.Generation <= PriorGeneration)
2194 return true;
2195
2198 if (!IdTable)
2199 return false;
2200
2201 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2202 Found);
2203 ++NumIdentifierLookups;
2204 ASTIdentifierLookupTable::iterator Pos =
2205 IdTable->find_hashed(Name, NameHash, &Trait);
2206 if (Pos == IdTable->end())
2207 return false;
2208
2209 // Dereferencing the iterator has the effect of building the
2210 // IdentifierInfo node and populating it with the various
2211 // declarations it needs.
2212 ++NumIdentifierLookupHits;
2213 Found = *Pos;
2214 return true;
2215 }
2216
2217 // Retrieve the identifier info found within the module
2218 // files.
2219 IdentifierInfo *getIdentifierInfo() const { return Found; }
2220 };
2221
2222} // namespace
2223
2225 // Note that we are loading an identifier.
2226 Deserializing AnIdentifier(this);
2227
2228 unsigned PriorGeneration = 0;
2229 if (getContext().getLangOpts().Modules)
2230 PriorGeneration = IdentifierGeneration[&II];
2231
2232 // If there is a global index, look there first to determine which modules
2233 // provably do not have any results for this identifier.
2235 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2236 if (!loadGlobalIndex()) {
2237 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2238 HitsPtr = &Hits;
2239 }
2240 }
2241
2242 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2243 NumIdentifierLookups,
2244 NumIdentifierLookupHits);
2245 ModuleMgr.visit(Visitor, HitsPtr);
2246 markIdentifierUpToDate(&II);
2247}
2248
2250 if (!II)
2251 return;
2252
2253 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2254
2255 // Update the generation for this identifier.
2256 if (getContext().getLangOpts().Modules)
2257 IdentifierGeneration[II] = getGeneration();
2258}
2259
2261 const PendingMacroInfo &PMInfo) {
2262 ModuleFile &M = *PMInfo.M;
2263
2264 BitstreamCursor &Cursor = M.MacroCursor;
2265 SavedStreamPosition SavedPosition(Cursor);
2266 if (llvm::Error Err =
2267 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2268 Error(std::move(Err));
2269 return;
2270 }
2271
2272 struct ModuleMacroRecord {
2273 SubmoduleID SubModID;
2274 MacroInfo *MI;
2276 };
2278
2279 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2280 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2281 // macro histroy.
2283 while (true) {
2285 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2286 if (!MaybeEntry) {
2287 Error(MaybeEntry.takeError());
2288 return;
2289 }
2290 llvm::BitstreamEntry Entry = MaybeEntry.get();
2291
2292 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2293 Error("malformed block record in AST file");
2294 return;
2295 }
2296
2297 Record.clear();
2298 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2299 if (!MaybePP) {
2300 Error(MaybePP.takeError());
2301 return;
2302 }
2303 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2305 break;
2306
2307 case PP_MODULE_MACRO: {
2308 ModuleMacros.push_back(ModuleMacroRecord());
2309 auto &Info = ModuleMacros.back();
2310 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2311 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2312 for (int I = 2, N = Record.size(); I != N; ++I)
2313 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2314 continue;
2315 }
2316
2317 default:
2318 Error("malformed block record in AST file");
2319 return;
2320 }
2321
2322 // We found the macro directive history; that's the last record
2323 // for this macro.
2324 break;
2325 }
2326
2327 // Module macros are listed in reverse dependency order.
2328 {
2329 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2331 for (auto &MMR : ModuleMacros) {
2332 Overrides.clear();
2333 for (unsigned ModID : MMR.Overrides) {
2334 Module *Mod = getSubmodule(ModID);
2335 auto *Macro = PP.getModuleMacro(Mod, II);
2336 assert(Macro && "missing definition for overridden macro");
2337 Overrides.push_back(Macro);
2338 }
2339
2340 bool Inserted = false;
2341 Module *Owner = getSubmodule(MMR.SubModID);
2342 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2343 }
2344 }
2345
2346 // Don't read the directive history for a module; we don't have anywhere
2347 // to put it.
2348 if (M.isModule())
2349 return;
2350
2351 // Deserialize the macro directives history in reverse source-order.
2352 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2353 unsigned Idx = 0, N = Record.size();
2354 while (Idx < N) {
2355 MacroDirective *MD = nullptr;
2356 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2358 switch (K) {
2360 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2361 MD = PP.AllocateDefMacroDirective(MI, Loc);
2362 break;
2363 }
2365 MD = PP.AllocateUndefMacroDirective(Loc);
2366 break;
2368 bool isPublic = Record[Idx++];
2369 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2370 break;
2371 }
2372
2373 if (!Latest)
2374 Latest = MD;
2375 if (Earliest)
2376 Earliest->setPrevious(MD);
2377 Earliest = MD;
2378 }
2379
2380 if (Latest)
2381 PP.setLoadedMacroDirective(II, Earliest, Latest);
2382}
2383
2384bool ASTReader::shouldDisableValidationForFile(
2385 const serialization::ModuleFile &M) const {
2386 if (DisableValidationKind == DisableValidationForModuleKind::None)
2387 return false;
2388
2389 // If a PCH is loaded and validation is disabled for PCH then disable
2390 // validation for the PCH and the modules it loads.
2391 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2392
2393 switch (K) {
2394 case MK_MainFile:
2395 case MK_Preamble:
2396 case MK_PCH:
2397 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2398 case MK_ImplicitModule:
2399 case MK_ExplicitModule:
2400 case MK_PrebuiltModule:
2401 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2402 }
2403
2404 return false;
2405}
2406
2407InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2408 // If this ID is bogus, just return an empty input file.
2409 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2410 return InputFileInfo();
2411
2412 // If we've already loaded this input file, return it.
2413 if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2414 return F.InputFileInfosLoaded[ID - 1];
2415
2416 // Go find this input file.
2417 BitstreamCursor &Cursor = F.InputFilesCursor;
2418 SavedStreamPosition SavedPosition(Cursor);
2419 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2420 F.InputFileOffsets[ID - 1])) {
2421 // FIXME this drops errors on the floor.
2422 consumeError(std::move(Err));
2423 }
2424
2425 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2426 if (!MaybeCode) {
2427 // FIXME this drops errors on the floor.
2428 consumeError(MaybeCode.takeError());
2429 }
2430 unsigned Code = MaybeCode.get();
2431 RecordData Record;
2432 StringRef Blob;
2433
2434 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2435 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2436 "invalid record type for input file");
2437 else {
2438 // FIXME this drops errors on the floor.
2439 consumeError(Maybe.takeError());
2440 }
2441
2442 assert(Record[0] == ID && "Bogus stored ID or offset");
2443 InputFileInfo R;
2444 R.StoredSize = static_cast<off_t>(Record[1]);
2445 R.StoredTime = static_cast<time_t>(Record[2]);
2446 R.Overridden = static_cast<bool>(Record[3]);
2447 R.Transient = static_cast<bool>(Record[4]);
2448 R.TopLevel = static_cast<bool>(Record[5]);
2449 R.ModuleMap = static_cast<bool>(Record[6]);
2450 std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
2451 uint16_t AsRequestedLength = Record[7];
2452
2453 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2454 std::string Name = Blob.substr(AsRequestedLength).str();
2455
2456 ResolveImportedPath(F, NameAsRequested);
2457 ResolveImportedPath(F, Name);
2458
2459 if (Name.empty())
2460 Name = NameAsRequested;
2461
2462 return std::make_pair(std::move(NameAsRequested), std::move(Name));
2463 }();
2464
2465 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2466 if (!MaybeEntry) // FIXME this drops errors on the floor.
2467 consumeError(MaybeEntry.takeError());
2468 llvm::BitstreamEntry Entry = MaybeEntry.get();
2469 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2470 "expected record type for input file hash");
2471
2472 Record.clear();
2473 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2474 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2475 "invalid record type for input file hash");
2476 else {
2477 // FIXME this drops errors on the floor.
2478 consumeError(Maybe.takeError());
2479 }
2480 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2481 static_cast<uint64_t>(Record[0]);
2482
2483 // Note that we've loaded this input file info.
2484 F.InputFileInfosLoaded[ID - 1] = R;
2485 return R;
2486}
2487
2488static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2489InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2490 // If this ID is bogus, just return an empty input file.
2491 if (ID == 0 || ID > F.InputFilesLoaded.size())
2492 return InputFile();
2493
2494 // If we've already loaded this input file, return it.
2495 if (F.InputFilesLoaded[ID-1].getFile())
2496 return F.InputFilesLoaded[ID-1];
2497
2498 if (F.InputFilesLoaded[ID-1].isNotFound())
2499 return InputFile();
2500
2501 // Go find this input file.
2502 BitstreamCursor &Cursor = F.InputFilesCursor;
2503 SavedStreamPosition SavedPosition(Cursor);
2504 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2505 F.InputFileOffsets[ID - 1])) {
2506 // FIXME this drops errors on the floor.
2507 consumeError(std::move(Err));
2508 }
2509
2510 InputFileInfo FI = getInputFileInfo(F, ID);
2511 off_t StoredSize = FI.StoredSize;
2512 time_t StoredTime = FI.StoredTime;
2513 bool Overridden = FI.Overridden;
2514 bool Transient = FI.Transient;
2515 StringRef Filename = FI.FilenameAsRequested;
2516 uint64_t StoredContentHash = FI.ContentHash;
2517
2518 // For standard C++ modules, we don't need to check the inputs.
2519 bool SkipChecks = F.StandardCXXModule;
2520
2521 const HeaderSearchOptions &HSOpts =
2522 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2523
2524 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2525 // modules.
2527 SkipChecks = false;
2528 Overridden = false;
2529 }
2530
2531 auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);
2532
2533 // For an overridden file, create a virtual file with the stored
2534 // size/timestamp.
2535 if ((Overridden || Transient || SkipChecks) && !File)
2536 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2537
2538 if (!File) {
2539 if (Complain) {
2540 std::string ErrorStr = "could not find file '";
2541 ErrorStr += Filename;
2542 ErrorStr += "' referenced by AST file '";
2543 ErrorStr += F.FileName;
2544 ErrorStr += "'";
2545 Error(ErrorStr);
2546 }
2547 // Record that we didn't find the file.
2549 return InputFile();
2550 }
2551
2552 // Check if there was a request to override the contents of the file
2553 // that was part of the precompiled header. Overriding such a file
2554 // can lead to problems when lexing using the source locations from the
2555 // PCH.
2556 SourceManager &SM = getSourceManager();
2557 // FIXME: Reject if the overrides are different.
2558 if ((!Overridden && !Transient) && !SkipChecks &&
2559 SM.isFileOverridden(*File)) {
2560 if (Complain)
2561 Error(diag::err_fe_pch_file_overridden, Filename);
2562
2563 // After emitting the diagnostic, bypass the overriding file to recover
2564 // (this creates a separate FileEntry).
2565 File = SM.bypassFileContentsOverride(*File);
2566 if (!File) {
2568 return InputFile();
2569 }
2570 }
2571
2572 struct Change {
2573 enum ModificationKind {
2574 Size,
2575 ModTime,
2576 Content,
2577 None,
2578 } Kind;
2579 std::optional<int64_t> Old = std::nullopt;
2580 std::optional<int64_t> New = std::nullopt;
2581 };
2582 auto HasInputContentChanged = [&](Change OriginalChange) {
2583 assert(ValidateASTInputFilesContent &&
2584 "We should only check the content of the inputs with "
2585 "ValidateASTInputFilesContent enabled.");
2586
2587 if (StoredContentHash == static_cast<uint64_t>(llvm::hash_code(-1)))
2588 return OriginalChange;
2589
2590 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2591 if (!MemBuffOrError) {
2592 if (!Complain)
2593 return OriginalChange;
2594 std::string ErrorStr = "could not get buffer for file '";
2595 ErrorStr += File->getName();
2596 ErrorStr += "'";
2597 Error(ErrorStr);
2598 return OriginalChange;
2599 }
2600
2601 // FIXME: hash_value is not guaranteed to be stable!
2602 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2603 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2604 return Change{Change::None};
2605
2606 return Change{Change::Content};
2607 };
2608 auto HasInputFileChanged = [&]() {
2609 if (StoredSize != File->getSize())
2610 return Change{Change::Size, StoredSize, File->getSize()};
2611 if (!shouldDisableValidationForFile(F) && StoredTime &&
2612 StoredTime != File->getModificationTime()) {
2613 Change MTimeChange = {Change::ModTime, StoredTime,
2614 File->getModificationTime()};
2615
2616 // In case the modification time changes but not the content,
2617 // accept the cached file as legit.
2618 if (ValidateASTInputFilesContent)
2619 return HasInputContentChanged(MTimeChange);
2620
2621 return MTimeChange;
2622 }
2623 return Change{Change::None};
2624 };
2625
2626 bool IsOutOfDate = false;
2627 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2628 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2629 // enabled, it is better to check the contents of the inputs. Since we can't
2630 // get correct modified time information for inputs from overriden inputs.
2631 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2632 F.StandardCXXModule && FileChange.Kind == Change::None)
2633 FileChange = HasInputContentChanged(FileChange);
2634
2635 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2636 // it is better to check the content of the input files because we cannot rely
2637 // on the file modification time, which will be the same (zero) for these
2638 // files.
2639 if (!StoredTime && ValidateASTInputFilesContent &&
2640 FileChange.Kind == Change::None)
2641 FileChange = HasInputContentChanged(FileChange);
2642
2643 // For an overridden file, there is nothing to validate.
2644 if (!Overridden && FileChange.Kind != Change::None) {
2645 if (Complain && !Diags.isDiagnosticInFlight()) {
2646 // Build a list of the PCH imports that got us here (in reverse).
2647 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2648 while (!ImportStack.back()->ImportedBy.empty())
2649 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2650
2651 // The top-level PCH is stale.
2652 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2653 Diag(diag::err_fe_ast_file_modified)
2654 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2655 << TopLevelPCHName << FileChange.Kind
2656 << (FileChange.Old && FileChange.New)
2657 << llvm::itostr(FileChange.Old.value_or(0))
2658 << llvm::itostr(FileChange.New.value_or(0));
2659
2660 // Print the import stack.
2661 if (ImportStack.size() > 1) {
2662 Diag(diag::note_pch_required_by)
2663 << Filename << ImportStack[0]->FileName;
2664 for (unsigned I = 1; I < ImportStack.size(); ++I)
2665 Diag(diag::note_pch_required_by)
2666 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2667 }
2668
2669 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2670 }
2671
2672 IsOutOfDate = true;
2673 }
2674 // FIXME: If the file is overridden and we've already opened it,
2675 // issue an error (or split it into a separate FileEntry).
2676
2677 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2678
2679 // Note that we've loaded this input file.
2680 F.InputFilesLoaded[ID-1] = IF;
2681 return IF;
2682}
2683
2684/// If we are loading a relocatable PCH or module file, and the filename
2685/// is not an absolute path, add the system or module root to the beginning of
2686/// the file name.
2688 // Resolve relative to the base directory, if we have one.
2689 if (!M.BaseDirectory.empty())
2690 return ResolveImportedPath(Filename, M.BaseDirectory);
2691}
2692
2693void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2694 if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||
2695 Filename == "<built-in>" || Filename == "<command line>")
2696 return;
2697
2698 SmallString<128> Buffer;
2699 llvm::sys::path::append(Buffer, Prefix, Filename);
2700 Filename.assign(Buffer.begin(), Buffer.end());
2701}
2702
2703static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2704 switch (ARR) {
2705 case ASTReader::Failure: return true;
2706 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2707 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2710 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2711 case ASTReader::HadErrors: return true;
2712 case ASTReader::Success: return false;
2713 }
2714
2715 llvm_unreachable("unknown ASTReadResult");
2716}
2717
2718ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2719 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2720 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2721 std::string &SuggestedPredefines) {
2722 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2723 // FIXME this drops errors on the floor.
2724 consumeError(std::move(Err));
2725 return Failure;
2726 }
2727
2728 // Read all of the records in the options block.
2729 RecordData Record;
2730 ASTReadResult Result = Success;
2731 while (true) {
2732 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2733 if (!MaybeEntry) {
2734 // FIXME this drops errors on the floor.
2735 consumeError(MaybeEntry.takeError());
2736 return Failure;
2737 }
2738 llvm::BitstreamEntry Entry = MaybeEntry.get();
2739
2740 switch (Entry.Kind) {
2741 case llvm::BitstreamEntry::Error:
2742 case llvm::BitstreamEntry::SubBlock:
2743 return Failure;
2744
2745 case llvm::BitstreamEntry::EndBlock:
2746 return Result;
2747
2748 case llvm::BitstreamEntry::Record:
2749 // The interesting case.
2750 break;
2751 }
2752
2753 // Read and process a record.
2754 Record.clear();
2755 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2756 if (!MaybeRecordType) {
2757 // FIXME this drops errors on the floor.
2758 consumeError(MaybeRecordType.takeError());
2759 return Failure;
2760 }
2761 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2762 case LANGUAGE_OPTIONS: {
2763 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2764 if (ParseLanguageOptions(Record, Complain, Listener,
2765 AllowCompatibleConfigurationMismatch))
2766 Result = ConfigurationMismatch;
2767 break;
2768 }
2769
2770 case TARGET_OPTIONS: {
2771 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2772 if (ParseTargetOptions(Record, Complain, Listener,
2773 AllowCompatibleConfigurationMismatch))
2774 Result = ConfigurationMismatch;
2775 break;
2776 }
2777
2778 case FILE_SYSTEM_OPTIONS: {
2779 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2780 if (!AllowCompatibleConfigurationMismatch &&
2781 ParseFileSystemOptions(Record, Complain, Listener))
2782 Result = ConfigurationMismatch;
2783 break;
2784 }
2785
2786 case HEADER_SEARCH_OPTIONS: {
2787 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2788 if (!AllowCompatibleConfigurationMismatch &&
2789 ParseHeaderSearchOptions(Record, Complain, Listener))
2790 Result = ConfigurationMismatch;
2791 break;
2792 }
2793
2795 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2796 if (!AllowCompatibleConfigurationMismatch &&
2797 ParsePreprocessorOptions(Record, Complain, Listener,
2798 SuggestedPredefines))
2799 Result = ConfigurationMismatch;
2800 break;
2801 }
2802 }
2803}
2804
2806ASTReader::ReadControlBlock(ModuleFile &F,
2808 const ModuleFile *ImportedBy,
2809 unsigned ClientLoadCapabilities) {
2810 BitstreamCursor &Stream = F.Stream;
2811
2812 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2813 Error(std::move(Err));
2814 return Failure;
2815 }
2816
2817 // Lambda to read the unhashed control block the first time it's called.
2818 //
2819 // For PCM files, the unhashed control block cannot be read until after the
2820 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2821 // need to look ahead before reading the IMPORTS record. For consistency,
2822 // this block is always read somehow (see BitstreamEntry::EndBlock).
2823 bool HasReadUnhashedControlBlock = false;
2824 auto readUnhashedControlBlockOnce = [&]() {
2825 if (!HasReadUnhashedControlBlock) {
2826 HasReadUnhashedControlBlock = true;
2827 if (ASTReadResult Result =
2828 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2829 return Result;
2830 }
2831 return Success;
2832 };
2833
2834 bool DisableValidation = shouldDisableValidationForFile(F);
2835
2836 // Read all of the records and blocks in the control block.
2837 RecordData Record;
2838 unsigned NumInputs = 0;
2839 unsigned NumUserInputs = 0;
2840 StringRef BaseDirectoryAsWritten;
2841 while (true) {
2842 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2843 if (!MaybeEntry) {
2844 Error(MaybeEntry.takeError());
2845 return Failure;
2846 }
2847 llvm::BitstreamEntry Entry = MaybeEntry.get();
2848
2849 switch (Entry.Kind) {
2850 case llvm::BitstreamEntry::Error:
2851 Error("malformed block record in AST file");
2852 return Failure;
2853 case llvm::BitstreamEntry::EndBlock: {
2854 // Validate the module before returning. This call catches an AST with
2855 // no module name and no imports.
2856 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2857 return Result;
2858
2859 // Validate input files.
2860 const HeaderSearchOptions &HSOpts =
2861 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2862
2863 // All user input files reside at the index range [0, NumUserInputs), and
2864 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2865 // loaded module files, ignore missing inputs.
2866 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2867 F.Kind != MK_PrebuiltModule) {
2868 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2869
2870 // If we are reading a module, we will create a verification timestamp,
2871 // so we verify all input files. Otherwise, verify only user input
2872 // files.
2873
2874 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2878 N = NumUserInputs;
2879
2880 for (unsigned I = 0; I < N; ++I) {
2881 InputFile IF = getInputFile(F, I+1, Complain);
2882 if (!IF.getFile() || IF.isOutOfDate())
2883 return OutOfDate;
2884 }
2885 }
2886
2887 if (Listener)
2888 Listener->visitModuleFile(F.FileName, F.Kind);
2889
2890 if (Listener && Listener->needsInputFileVisitation()) {
2891 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2892 : NumUserInputs;
2893 for (unsigned I = 0; I < N; ++I) {
2894 bool IsSystem = I >= NumUserInputs;
2895 InputFileInfo FI = getInputFileInfo(F, I + 1);
2896 Listener->visitInputFile(
2897 FI.FilenameAsRequested, IsSystem, FI.Overridden,
2899 }
2900 }
2901
2902 return Success;
2903 }
2904
2905 case llvm::BitstreamEntry::SubBlock:
2906 switch (Entry.ID) {
2908 F.InputFilesCursor = Stream;
2909 if (llvm::Error Err = Stream.SkipBlock()) {
2910 Error(std::move(Err));
2911 return Failure;
2912 }
2913 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2914 Error("malformed block record in AST file");
2915 return Failure;
2916 }
2917 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
2918 continue;
2919
2920 case OPTIONS_BLOCK_ID:
2921 // If we're reading the first module for this group, check its options
2922 // are compatible with ours. For modules it imports, no further checking
2923 // is required, because we checked them when we built it.
2924 if (Listener && !ImportedBy) {
2925 // Should we allow the configuration of the module file to differ from
2926 // the configuration of the current translation unit in a compatible
2927 // way?
2928 //
2929 // FIXME: Allow this for files explicitly specified with -include-pch.
2930 bool AllowCompatibleConfigurationMismatch =
2932
2933 ASTReadResult Result =
2934 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2935 AllowCompatibleConfigurationMismatch, *Listener,
2936 SuggestedPredefines);
2937 if (Result == Failure) {
2938 Error("malformed block record in AST file");
2939 return Result;
2940 }
2941
2942 if (DisableValidation ||
2943 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2944 Result = Success;
2945
2946 // If we can't load the module, exit early since we likely
2947 // will rebuild the module anyway. The stream may be in the
2948 // middle of a block.
2949 if (Result != Success)
2950 return Result;
2951 } else if (llvm::Error Err = Stream.SkipBlock()) {
2952 Error(std::move(Err));
2953 return Failure;
2954 }
2955 continue;
2956
2957 default:
2958 if (llvm::Error Err = Stream.SkipBlock()) {
2959 Error(std::move(Err));
2960 return Failure;
2961 }
2962 continue;
2963 }
2964
2965 case llvm::BitstreamEntry::Record:
2966 // The interesting case.
2967 break;
2968 }
2969
2970 // Read and process a record.
2971 Record.clear();
2972 StringRef Blob;
2973 Expected<unsigned> MaybeRecordType =
2974 Stream.readRecord(Entry.ID, Record, &Blob);
2975 if (!MaybeRecordType) {
2976 Error(MaybeRecordType.takeError());
2977 return Failure;
2978 }
2979 switch ((ControlRecordTypes)MaybeRecordType.get()) {
2980 case METADATA: {
2981 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2982 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2983 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2984 : diag::err_pch_version_too_new);
2985 return VersionMismatch;
2986 }
2987
2988 bool hasErrors = Record[7];
2989 if (hasErrors && !DisableValidation) {
2990 // If requested by the caller and the module hasn't already been read
2991 // or compiled, mark modules on error as out-of-date.
2992 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2993 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2994 return OutOfDate;
2995
2996 if (!AllowASTWithCompilerErrors) {
2997 Diag(diag::err_pch_with_compiler_errors);
2998 return HadErrors;
2999 }
3000 }
3001 if (hasErrors) {
3002 Diags.ErrorOccurred = true;
3003 Diags.UncompilableErrorOccurred = true;
3004 Diags.UnrecoverableErrorOccurred = true;
3005 }
3006
3007 F.RelocatablePCH = Record[4];
3008 // Relative paths in a relocatable PCH are relative to our sysroot.
3009 if (F.RelocatablePCH)
3010 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3011
3013
3014 F.HasTimestamps = Record[6];
3015
3016 const std::string &CurBranch = getClangFullRepositoryVersion();
3017 StringRef ASTBranch = Blob;
3018 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3019 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3020 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
3021 return VersionMismatch;
3022 }
3023 break;
3024 }
3025
3026 case IMPORTS: {
3027 // Validate the AST before processing any imports (otherwise, untangling
3028 // them can be error-prone and expensive). A module will have a name and
3029 // will already have been validated, but this catches the PCH case.
3030 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3031 return Result;
3032
3033 // Load each of the imported PCH files.
3034 unsigned Idx = 0, N = Record.size();
3035 while (Idx < N) {
3036 // Read information about the AST file.
3037 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3038 // Whether we're importing a standard c++ module.
3039 bool IsImportingStdCXXModule = Record[Idx++];
3040 // The import location will be the local one for now; we will adjust
3041 // all import locations of module imports after the global source
3042 // location info are setup, in ReadAST.
3043 auto [ImportLoc, ImportModuleFileIndex] =
3044 ReadUntranslatedSourceLocation(Record[Idx++]);
3045 // The import location must belong to the current module file itself.
3046 assert(ImportModuleFileIndex == 0);
3047 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;
3048 time_t StoredModTime =
3049 !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;
3050
3051 ASTFileSignature StoredSignature;
3052 if (!IsImportingStdCXXModule) {
3053 auto FirstSignatureByte = Record.begin() + Idx;
3054 StoredSignature = ASTFileSignature::create(
3055 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
3057 }
3058
3059 std::string ImportedName = ReadString(Record, Idx);
3060 std::string ImportedFile;
3061
3062 // For prebuilt and explicit modules first consult the file map for
3063 // an override. Note that here we don't search prebuilt module
3064 // directories if we're not importing standard c++ module, only the
3065 // explicit name to file mappings. Also, we will still verify the
3066 // size/signature making sure it is essentially the same file but
3067 // perhaps in a different location.
3068 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3069 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3070 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3071
3072 // For C++20 Modules, we won't record the path to the imported modules
3073 // in the BMI
3074 if (!IsImportingStdCXXModule) {
3075 if (ImportedFile.empty()) {
3076 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3077 // ModuleCache as when writing.
3078 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
3079 } else
3080 SkipPath(Record, Idx);
3081 } else if (ImportedFile.empty()) {
3082 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3083 return Missing;
3084 }
3085
3086 // If our client can't cope with us being out of date, we can't cope with
3087 // our dependency being missing.
3088 unsigned Capabilities = ClientLoadCapabilities;
3089 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3090 Capabilities &= ~ARR_Missing;
3091
3092 // Load the AST file.
3093 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3094 Loaded, StoredSize, StoredModTime,
3095 StoredSignature, Capabilities);
3096
3097 // If we diagnosed a problem, produce a backtrace.
3098 bool recompilingFinalized =
3099 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3100 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3101 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3102 Diag(diag::note_module_file_imported_by)
3103 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3104 if (recompilingFinalized)
3105 Diag(diag::note_module_file_conflict);
3106
3107 switch (Result) {
3108 case Failure: return Failure;
3109 // If we have to ignore the dependency, we'll have to ignore this too.
3110 case Missing:
3111 case OutOfDate: return OutOfDate;
3112 case VersionMismatch: return VersionMismatch;
3113 case ConfigurationMismatch: return ConfigurationMismatch;
3114 case HadErrors: return HadErrors;
3115 case Success: break;
3116 }
3117 }
3118 break;
3119 }
3120
3121 case ORIGINAL_FILE:
3122 F.OriginalSourceFileID = FileID::get(Record[0]);
3123 F.ActualOriginalSourceFileName = std::string(Blob);
3125 ResolveImportedPath(F, F.OriginalSourceFileName);
3126 break;
3127
3128 case ORIGINAL_FILE_ID:
3129 F.OriginalSourceFileID = FileID::get(Record[0]);
3130 break;
3131
3132 case MODULE_NAME:
3133 F.ModuleName = std::string(Blob);
3134 Diag(diag::remark_module_import)
3135 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3136 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3137 if (Listener)
3138 Listener->ReadModuleName(F.ModuleName);
3139
3140 // Validate the AST as soon as we have a name so we can exit early on
3141 // failure.
3142 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3143 return Result;
3144
3145 break;
3146
3147 case MODULE_DIRECTORY: {
3148 // Save the BaseDirectory as written in the PCM for computing the module
3149 // filename for the ModuleCache.
3150 BaseDirectoryAsWritten = Blob;
3151 assert(!F.ModuleName.empty() &&
3152 "MODULE_DIRECTORY found before MODULE_NAME");
3153 F.BaseDirectory = std::string(Blob);
3154 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3155 break;
3156 // If we've already loaded a module map file covering this module, we may
3157 // have a better path for it (relative to the current build).
3158 Module *M = PP.getHeaderSearchInfo().lookupModule(
3159 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3160 /*AllowExtraModuleMapSearch*/ true);
3161 if (M && M->Directory) {
3162 // If we're implicitly loading a module, the base directory can't
3163 // change between the build and use.
3164 // Don't emit module relocation error if we have -fno-validate-pch
3165 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3168 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3169 if (!BuildDir || *BuildDir != M->Directory) {
3170 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3171 Diag(diag::err_imported_module_relocated)
3172 << F.ModuleName << Blob << M->Directory->getName();
3173 return OutOfDate;
3174 }
3175 }
3176 F.BaseDirectory = std::string(M->Directory->getName());
3177 }
3178 break;
3179 }
3180
3181 case MODULE_MAP_FILE:
3182 if (ASTReadResult Result =
3183 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3184 return Result;
3185 break;
3186
3187 case INPUT_FILE_OFFSETS:
3188 NumInputs = Record[0];
3189 NumUserInputs = Record[1];
3191 (const llvm::support::unaligned_uint64_t *)Blob.data();
3192 F.InputFilesLoaded.resize(NumInputs);
3193 F.InputFileInfosLoaded.resize(NumInputs);
3194 F.NumUserInputFiles = NumUserInputs;
3195 break;
3196 }
3197 }
3198}
3199
3200llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3201 unsigned ClientLoadCapabilities) {
3202 BitstreamCursor &Stream = F.Stream;
3203
3204 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3205 return Err;
3206 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3207
3208 // Read all of the records and blocks for the AST file.
3209 RecordData Record;
3210 while (true) {
3211 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3212 if (!MaybeEntry)
3213 return MaybeEntry.takeError();
3214 llvm::BitstreamEntry Entry = MaybeEntry.get();
3215
3216 switch (Entry.Kind) {
3217 case llvm::BitstreamEntry::Error:
3218 return llvm::createStringError(
3219 std::errc::illegal_byte_sequence,
3220 "error at end of module block in AST file");
3221 case llvm::BitstreamEntry::EndBlock:
3222 // Outside of C++, we do not store a lookup map for the translation unit.
3223 // Instead, mark it as needing a lookup map to be built if this module
3224 // contains any declarations lexically within it (which it always does!).
3225 // This usually has no cost, since we very rarely need the lookup map for
3226 // the translation unit outside C++.
3227 if (ASTContext *Ctx = ContextObj) {
3228 DeclContext *DC = Ctx->getTranslationUnitDecl();
3229 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3231 }
3232
3233 return llvm::Error::success();
3234 case llvm::BitstreamEntry::SubBlock:
3235 switch (Entry.ID) {
3236 case DECLTYPES_BLOCK_ID:
3237 // We lazily load the decls block, but we want to set up the
3238 // DeclsCursor cursor to point into it. Clone our current bitcode
3239 // cursor to it, enter the block and read the abbrevs in that block.
3240 // With the main cursor, we just skip over it.
3241 F.DeclsCursor = Stream;
3242 if (llvm::Error Err = Stream.SkipBlock())
3243 return Err;
3244 if (llvm::Error Err = ReadBlockAbbrevs(
3246 return Err;
3247 break;
3248
3250 F.MacroCursor = Stream;
3251 if (!PP.getExternalSource())
3252 PP.setExternalSource(this);
3253
3254 if (llvm::Error Err = Stream.SkipBlock())
3255 return Err;
3256 if (llvm::Error Err =
3257 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3258 return Err;
3259 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3260 break;
3261
3263 F.PreprocessorDetailCursor = Stream;
3264
3265 if (llvm::Error Err = Stream.SkipBlock()) {
3266 return Err;
3267 }
3268 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3270 return Err;
3272 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3273
3274 if (!PP.getPreprocessingRecord())
3275 PP.createPreprocessingRecord();
3276 if (!PP.getPreprocessingRecord()->getExternalSource())
3277 PP.getPreprocessingRecord()->SetExternalSource(*this);
3278 break;
3279
3281 if (llvm::Error Err = ReadSourceManagerBlock(F))
3282 return Err;
3283 break;
3284
3285 case SUBMODULE_BLOCK_ID:
3286 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3287 return Err;
3288 break;
3289
3290 case COMMENTS_BLOCK_ID: {
3291 BitstreamCursor C = Stream;
3292
3293 if (llvm::Error Err = Stream.SkipBlock())
3294 return Err;
3295 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3296 return Err;
3297 CommentsCursors.push_back(std::make_pair(C, &F));
3298 break;
3299 }
3300
3301 default:
3302 if (llvm::Error Err = Stream.SkipBlock())
3303 return Err;
3304 break;
3305 }
3306 continue;
3307
3308 case llvm::BitstreamEntry::Record:
3309 // The interesting case.
3310 break;
3311 }
3312
3313 // Read and process a record.
3314 Record.clear();
3315 StringRef Blob;
3316 Expected<unsigned> MaybeRecordType =
3317 Stream.readRecord(Entry.ID, Record, &Blob);
3318 if (!MaybeRecordType)
3319 return MaybeRecordType.takeError();
3320 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3321
3322 // If we're not loading an AST context, we don't care about most records.
3323 if (!ContextObj) {
3324 switch (RecordType) {
3325 case IDENTIFIER_TABLE:
3326 case IDENTIFIER_OFFSET:
3328 case STATISTICS:
3331 case PP_COUNTER_VALUE:
3333 case MODULE_OFFSET_MAP:
3337 case IMPORTED_MODULES:
3338 case MACRO_OFFSET:
3339 break;
3340 default:
3341 continue;
3342 }
3343 }
3344
3345 switch (RecordType) {
3346 default: // Default behavior: ignore.
3347 break;
3348
3349 case TYPE_OFFSET: {
3350 if (F.LocalNumTypes != 0)
3351 return llvm::createStringError(
3352 std::errc::illegal_byte_sequence,
3353 "duplicate TYPE_OFFSET record in AST file");
3354 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3355 F.LocalNumTypes = Record[0];
3356 unsigned LocalBaseTypeIndex = Record[1];
3357 F.BaseTypeIndex = getTotalNumTypes();
3358
3359 if (F.LocalNumTypes > 0) {
3360 // Introduce the global -> local mapping for types within this module.
3361 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3362
3363 // Introduce the local -> global mapping for types within this module.
3365 std::make_pair(LocalBaseTypeIndex,
3366 F.BaseTypeIndex - LocalBaseTypeIndex));
3367
3368 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3369 }
3370 break;
3371 }
3372
3373 case DECL_OFFSET: {
3374 if (F.LocalNumDecls != 0)
3375 return llvm::createStringError(
3376 std::errc::illegal_byte_sequence,
3377 "duplicate DECL_OFFSET record in AST file");
3378 F.DeclOffsets = (const DeclOffset *)Blob.data();
3379 F.LocalNumDecls = Record[0];
3380 unsigned LocalBaseDeclID = Record[1];
3381 F.BaseDeclID = getTotalNumDecls();
3382
3383 if (F.LocalNumDecls > 0) {
3384 // Introduce the global -> local mapping for declarations within this
3385 // module.
3386 GlobalDeclMap.insert(std::make_pair(
3387 GlobalDeclID(getTotalNumDecls() + NUM_PREDEF_DECL_IDS), &F));
3388
3389 // Introduce the local -> global mapping for declarations within this
3390 // module.
3392 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3393
3394 // Introduce the global -> local mapping for declarations within this
3395 // module.
3396 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3397
3398 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3399 }
3400 break;
3401 }
3402
3403 case TU_UPDATE_LEXICAL: {
3404 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3405 LexicalContents Contents(
3406 reinterpret_cast<const unalighed_decl_id_t *>(Blob.data()),
3407 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3408 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3410 break;
3411 }
3412
3413 case UPDATE_VISIBLE: {
3414 unsigned Idx = 0;
3415 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3416 auto *Data = (const unsigned char*)Blob.data();
3417 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3418 // If we've already loaded the decl, perform the updates when we finish
3419 // loading this block.
3420 if (Decl *D = GetExistingDecl(ID))
3421 PendingUpdateRecords.push_back(
3422 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3423 break;
3424 }
3425
3426 case IDENTIFIER_TABLE:
3428 reinterpret_cast<const unsigned char *>(Blob.data());
3429 if (Record[0]) {
3430 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3432 F.IdentifierTableData + sizeof(uint32_t),
3434 ASTIdentifierLookupTrait(*this, F));
3435
3436 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3437 }
3438 break;
3439
3440 case IDENTIFIER_OFFSET: {
3441 if (F.LocalNumIdentifiers != 0)
3442 return llvm::createStringError(
3443 std::errc::illegal_byte_sequence,
3444 "duplicate IDENTIFIER_OFFSET record in AST file");
3445 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3447 unsigned LocalBaseIdentifierID = Record[1];
3448 F.BaseIdentifierID = getTotalNumIdentifiers();
3449
3450 if (F.LocalNumIdentifiers > 0) {
3451 // Introduce the global -> local mapping for identifiers within this
3452 // module.
3453 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3454 &F));
3455
3456 // Introduce the local -> global mapping for identifiers within this
3457 // module.
3459 std::make_pair(LocalBaseIdentifierID,
3460 F.BaseIdentifierID - LocalBaseIdentifierID));
3461
3462 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3464 }
3465 break;
3466 }
3467
3469 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3470 break;
3471
3473 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3474 // about "interesting" decls (for instance, if we're building a module).
3475 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3476 EagerlyDeserializedDecls.push_back(
3477 getGlobalDeclID(F, LocalDeclID(Record[I])));
3478 break;
3479
3481 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3482 // them (ie: if we're not codegenerating this module).
3483 if (F.Kind == MK_MainFile ||
3484 getContext().getLangOpts().BuildingPCHWithObjectFile)
3485 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3486 EagerlyDeserializedDecls.push_back(
3487 getGlobalDeclID(F, LocalDeclID(Record[I])));
3488 break;
3489
3490 case SPECIAL_TYPES:
3491 if (SpecialTypes.empty()) {
3492 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3493 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3494 break;
3495 }
3496
3497 if (SpecialTypes.size() != Record.size())
3498 return llvm::createStringError(std::errc::illegal_byte_sequence,
3499 "invalid special-types record");
3500
3501 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3502 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3503 if (!SpecialTypes[I])
3504 SpecialTypes[I] = ID;
3505 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3506 // merge step?
3507 }
3508 break;
3509
3510 case STATISTICS:
3511 TotalNumStatements += Record[0];
3512 TotalNumMacros += Record[1];
3513 TotalLexicalDeclContexts += Record[2];
3514 TotalVisibleDeclContexts += Record[3];
3515 break;
3516
3518 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3519 UnusedFileScopedDecls.push_back(
3520 getGlobalDeclID(F, LocalDeclID(Record[I])));
3521 break;
3522
3523 case DELEGATING_CTORS:
3524 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3525 DelegatingCtorDecls.push_back(
3526 getGlobalDeclID(F, LocalDeclID(Record[I])));
3527 break;
3528
3530 if (Record.size() % 3 != 0)
3531 return llvm::createStringError(std::errc::illegal_byte_sequence,
3532 "invalid weak identifiers record");
3533
3534 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3535 // files. This isn't the way to do it :)
3536 WeakUndeclaredIdentifiers.clear();
3537
3538 // Translate the weak, undeclared identifiers into global IDs.
3539 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3540 WeakUndeclaredIdentifiers.push_back(
3541 getGlobalIdentifierID(F, Record[I++]));
3542 WeakUndeclaredIdentifiers.push_back(
3543 getGlobalIdentifierID(F, Record[I++]));
3544 WeakUndeclaredIdentifiers.push_back(
3545 ReadSourceLocation(F, Record, I).getRawEncoding());
3546 }
3547 break;
3548
3549 case SELECTOR_OFFSETS: {
3550 F.SelectorOffsets = (const uint32_t *)Blob.data();
3552 unsigned LocalBaseSelectorID = Record[1];
3553 F.BaseSelectorID = getTotalNumSelectors();
3554
3555 if (F.LocalNumSelectors > 0) {
3556 // Introduce the global -> local mapping for selectors within this
3557 // module.
3558 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3559
3560 // Introduce the local -> global mapping for selectors within this
3561 // module.
3563 std::make_pair(LocalBaseSelectorID,
3564 F.BaseSelectorID - LocalBaseSelectorID));
3565
3566 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3567 }
3568 break;
3569 }
3570
3571 case METHOD_POOL:
3572 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3573 if (Record[0])
3575 = ASTSelectorLookupTable::Create(
3578 ASTSelectorLookupTrait(*this, F));
3579 TotalNumMethodPoolEntries += Record[1];
3580 break;
3581
3583 if (!Record.empty()) {
3584 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3585 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3586 Record[Idx++]));
3587 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3588 getRawEncoding());
3589 }
3590 }
3591 break;
3592
3593 case PP_ASSUME_NONNULL_LOC: {
3594 unsigned Idx = 0;
3595 if (!Record.empty())
3596 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3597 ReadSourceLocation(F, Record, Idx));
3598 break;
3599 }
3600
3602 if (!Record.empty()) {
3603 unsigned Idx = 0, End = Record.size() - 1;
3604 bool ReachedEOFWhileSkipping = Record[Idx++];
3605 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3606 if (ReachedEOFWhileSkipping) {
3607 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3608 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3609 bool FoundNonSkipPortion = Record[Idx++];
3610 bool FoundElse = Record[Idx++];
3611 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3612 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3613 FoundElse, ElseLoc);
3614 }
3615 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3616 while (Idx < End) {
3617 auto Loc = ReadSourceLocation(F, Record, Idx);
3618 bool WasSkipping = Record[Idx++];
3619 bool FoundNonSkip = Record[Idx++];
3620 bool FoundElse = Record[Idx++];
3621 ConditionalStack.push_back(
3622 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3623 }
3624 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3625 }
3626 break;
3627
3628 case PP_COUNTER_VALUE:
3629 if (!Record.empty() && Listener)
3630 Listener->ReadCounter(F, Record[0]);
3631 break;
3632
3633 case FILE_SORTED_DECLS:
3634 F.FileSortedDecls = (const LocalDeclID *)Blob.data();
3636 break;
3637
3639 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3641 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3643 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3644 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3645 SLocSpaceSize);
3646 if (!F.SLocEntryBaseID) {
3647 if (!Diags.isDiagnosticInFlight()) {
3648 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3649 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3650 }
3651 return llvm::createStringError(std::errc::invalid_argument,
3652 "ran out of source locations");
3653 }
3654 // Make our entry in the range map. BaseID is negative and growing, so
3655 // we invert it. Because we invert it, though, we need the other end of
3656 // the range.
3657 unsigned RangeStart =
3659 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3661
3662 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3663 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3664 GlobalSLocOffsetMap.insert(
3665 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3666 - SLocSpaceSize,&F));
3667
3668 TotalNumSLocEntries += F.LocalNumSLocEntries;
3669 break;
3670 }
3671
3672 case MODULE_OFFSET_MAP:
3673 F.ModuleOffsetMap = Blob;
3674 break;
3675
3677 ParseLineTable(F, Record);
3678 break;
3679
3680 case EXT_VECTOR_DECLS:
3681 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3682 ExtVectorDecls.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3683 break;
3684
3685 case VTABLE_USES:
3686 if (Record.size() % 3 != 0)
3687 return llvm::createStringError(std::errc::illegal_byte_sequence,
3688 "Invalid VTABLE_USES record");
3689
3690 // Later tables overwrite earlier ones.
3691 // FIXME: Modules will have some trouble with this. This is clearly not
3692 // the right way to do this.
3693 VTableUses.clear();
3694
3695 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3696 VTableUses.push_back(
3697 {getGlobalDeclID(F, LocalDeclID(Record[Idx++])),
3698 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
3699 (bool)Record[Idx++]});
3700 }
3701 break;
3702
3704
3705 if (Record.size() % 2 != 0)
3706 return llvm::createStringError(
3707 std::errc::illegal_byte_sequence,
3708 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3709
3710 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3711 PendingInstantiations.push_back(
3712 {getGlobalDeclID(F, LocalDeclID(Record[I++])),
3713 ReadSourceLocation(F, Record, I).getRawEncoding()});
3714 }
3715 break;
3716
3717 case SEMA_DECL_REFS:
3718 if (Record.size() != 3)
3719 return llvm::createStringError(std::errc::illegal_byte_sequence,
3720 "Invalid SEMA_DECL_REFS block");
3721 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3722 SemaDeclRefs.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3723 break;
3724
3725 case PPD_ENTITIES_OFFSETS: {
3726 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3727 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3728 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3729
3730 unsigned LocalBasePreprocessedEntityID = Record[0];
3731
3732 unsigned StartingID;
3733 if (!PP.getPreprocessingRecord())
3734 PP.createPreprocessingRecord();
3735 if (!PP.getPreprocessingRecord()->getExternalSource())
3736 PP.getPreprocessingRecord()->SetExternalSource(*this);
3737 StartingID
3738 = PP.getPreprocessingRecord()
3739 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3740 F.BasePreprocessedEntityID = StartingID;
3741
3742 if (F.NumPreprocessedEntities > 0) {
3743 // Introduce the global -> local mapping for preprocessed entities in
3744 // this module.
3745 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3746
3747 // Introduce the local -> global mapping for preprocessed entities in
3748 // this module.
3750 std::make_pair(LocalBasePreprocessedEntityID,
3751 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3752 }
3753
3754 break;
3755 }
3756
3757 case PPD_SKIPPED_RANGES: {
3758 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3759 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3760 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3761
3762 if (!PP.getPreprocessingRecord())
3763 PP.createPreprocessingRecord();
3764 if (!PP.getPreprocessingRecord()->getExternalSource())
3765 PP.getPreprocessingRecord()->SetExternalSource(*this);
3766 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3767 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3768
3770 GlobalSkippedRangeMap.insert(
3771 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3772 break;
3773 }
3774
3776 if (Record.size() % 2 != 0)
3777 return llvm::createStringError(
3778 std::errc::illegal_byte_sequence,
3779 "invalid DECL_UPDATE_OFFSETS block in AST file");
3780 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3781 GlobalDeclID ID = getGlobalDeclID(F, LocalDeclID(Record[I]));
3782 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3783
3784 // If we've already loaded the decl, perform the updates when we finish
3785 // loading this block.
3786 if (Decl *D = GetExistingDecl(ID))
3787 PendingUpdateRecords.push_back(
3788 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3789 }
3790 break;
3791
3793 if (Record.size() % 3 != 0)
3794 return llvm::createStringError(
3795 std::errc::illegal_byte_sequence,
3796 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3797 "file");
3798 for (unsigned I = 0, N = Record.size(); I != N; I += 3) {
3799 GlobalDeclID ID = getGlobalDeclID(F, LocalDeclID(Record[I]));
3800
3801 uint64_t BaseOffset = F.DeclsBlockStartOffset;
3802 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
3803 uint64_t LexicalOffset = Record[I + 1] ? BaseOffset + Record[I + 1] : 0;
3804 uint64_t VisibleOffset = Record[I + 2] ? BaseOffset + Record[I + 2] : 0;
3805
3806 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};
3807
3808 assert(!GetExistingDecl(ID) &&
3809 "We shouldn't load the namespace in the front of delayed "
3810 "namespace lexical and visible block");
3811 }
3812 break;
3813 }
3814
3816 if (F.LocalNumObjCCategoriesInMap != 0)
3817 return llvm::createStringError(
3818 std::errc::illegal_byte_sequence,
3819 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3820
3822 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3823 break;
3824
3825 case OBJC_CATEGORIES:
3826 F.ObjCCategories.swap(Record);
3827 break;
3828
3830 // Later tables overwrite earlier ones.
3831 // FIXME: Modules will have trouble with this.
3832 CUDASpecialDeclRefs.clear();
3833 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3834 CUDASpecialDeclRefs.push_back(
3835 getGlobalDeclID(F, LocalDeclID(Record[I])));
3836 break;
3837
3839 F.HeaderFileInfoTableData = Blob.data();
3841 if (Record[0]) {
3843 = HeaderFileInfoLookupTable::Create(
3844 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3845 (const unsigned char *)F.HeaderFileInfoTableData,
3846 HeaderFileInfoTrait(*this, F,
3847 &PP.getHeaderSearchInfo(),
3848 Blob.data() + Record[2]));
3849
3850 PP.getHeaderSearchInfo().SetExternalSource(this);
3851 if (!PP.getHeaderSearchInfo().getExternalLookup())
3852 PP.getHeaderSearchInfo().SetExternalLookup(this);
3853 }
3854 break;
3855
3856 case FP_PRAGMA_OPTIONS:
3857 // Later tables overwrite earlier ones.
3858 FPPragmaOptions.swap(Record);
3859 break;
3860
3861 case OPENCL_EXTENSIONS:
3862 for (unsigned I = 0, E = Record.size(); I != E; ) {
3863 auto Name = ReadString(Record, I);
3864 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3865 OptInfo.Supported = Record[I++] != 0;
3866 OptInfo.Enabled = Record[I++] != 0;
3867 OptInfo.WithPragma = Record[I++] != 0;
3868 OptInfo.Avail = Record[I++];
3869 OptInfo.Core = Record[I++];
3870 OptInfo.Opt = Record[I++];
3871 }
3872 break;
3873
3875 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3876 TentativeDefinitions.push_back(
3877 getGlobalDeclID(F, LocalDeclID(Record[I])));
3878 break;
3879
3880 case KNOWN_NAMESPACES:
3881 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3882 KnownNamespaces.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3883 break;
3884
3885 case UNDEFINED_BUT_USED:
3886 if (Record.size() % 2 != 0)
3887 return llvm::createStringError(std::errc::illegal_byte_sequence,
3888 "invalid undefined-but-used record");
3889 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3890 UndefinedButUsed.push_back(
3891 {getGlobalDeclID(F, LocalDeclID(Record[I++])),
3892 ReadSourceLocation(F, Record, I).getRawEncoding()});
3893 }
3894 break;
3895
3897 for (unsigned I = 0, N = Record.size(); I != N;) {
3898 DelayedDeleteExprs.push_back(
3899 getGlobalDeclID(F, LocalDeclID(Record[I++])).get());
3900 const uint64_t Count = Record[I++];
3901 DelayedDeleteExprs.push_back(Count);
3902 for (uint64_t C = 0; C < Count; ++C) {
3903 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3904 bool IsArrayForm = Record[I++] == 1;
3905 DelayedDeleteExprs.push_back(IsArrayForm);
3906 }
3907 }
3908 break;
3909
3910 case IMPORTED_MODULES:
3911 if (!F.isModule()) {
3912 // If we aren't loading a module (which has its own exports), make
3913 // all of the imported modules visible.
3914 // FIXME: Deal with macros-only imports.
3915 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3916 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3917 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3918 if (GlobalID) {
3919 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3920 if (DeserializationListener)
3921 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3922 }
3923 }
3924 }
3925 break;
3926
3927 case MACRO_OFFSET: {
3928 if (F.LocalNumMacros != 0)
3929 return llvm::createStringError(
3930 std::errc::illegal_byte_sequence,
3931 "duplicate MACRO_OFFSET record in AST file");
3932 F.MacroOffsets = (const uint32_t *)Blob.data();
3933 F.LocalNumMacros = Record[0];
3934 unsigned LocalBaseMacroID = Record[1];
3936 F.BaseMacroID = getTotalNumMacros();
3937
3938 if (F.LocalNumMacros > 0) {
3939 // Introduce the global -> local mapping for macros within this module.
3940 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3941
3942 // Introduce the local -> global mapping for macros within this module.
3944 std::make_pair(LocalBaseMacroID,
3945 F.BaseMacroID - LocalBaseMacroID));
3946
3947 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3948 }
3949 break;
3950 }
3951
3953 LateParsedTemplates.emplace_back(
3954 std::piecewise_construct, std::forward_as_tuple(&F),
3955 std::forward_as_tuple(Record.begin(), Record.end()));
3956 break;
3957
3959 if (Record.size() != 1)
3960 return llvm::createStringError(std::errc::illegal_byte_sequence,
3961 "invalid pragma optimize record");
3962 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3963 break;
3964
3966 if (Record.size() != 1)
3967 return llvm::createStringError(std::errc::illegal_byte_sequence,
3968 "invalid pragma ms_struct record");
3969 PragmaMSStructState = Record[0];
3970 break;
3971
3973 if (Record.size() != 2)
3974 return llvm::createStringError(
3975 std::errc::illegal_byte_sequence,
3976 "invalid pragma pointers to members record");
3977 PragmaMSPointersToMembersState = Record[0];
3978 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3979 break;
3980
3982 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3983 UnusedLocalTypedefNameCandidates.push_back(
3984 getGlobalDeclID(F, LocalDeclID(Record[I])));
3985 break;
3986
3988 if (Record.size() != 1)
3989 return llvm::createStringError(std::errc::illegal_byte_sequence,
3990 "invalid cuda pragma options record");
3991 ForceHostDeviceDepth = Record[0];
3992 break;
3993
3995 if (Record.size() < 3)
3996 return llvm::createStringError(std::errc::illegal_byte_sequence,
3997 "invalid pragma pack record");
3998 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3999 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4000 unsigned NumStackEntries = Record[2];
4001 unsigned Idx = 3;
4002 // Reset the stack when importing a new module.
4003 PragmaAlignPackStack.clear();
4004 for (unsigned I = 0; I < NumStackEntries; ++I) {
4005 PragmaAlignPackStackEntry Entry;
4006 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4007 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4008 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4009 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4010 Entry.SlotLabel = PragmaAlignPackStrings.back();
4011 PragmaAlignPackStack.push_back(Entry);
4012 }
4013 break;
4014 }
4015
4017 if (Record.size() < 3)
4018 return llvm::createStringError(std::errc::illegal_byte_sequence,
4019 "invalid pragma float control record");
4020 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4021 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4022 unsigned NumStackEntries = Record[2];
4023 unsigned Idx = 3;
4024 // Reset the stack when importing a new module.
4025 FpPragmaStack.clear();
4026 for (unsigned I = 0; I < NumStackEntries; ++I) {
4027 FpPragmaStackEntry Entry;
4028 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4029 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4030 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4031 FpPragmaStrings.push_back(ReadString(Record, Idx));
4032 Entry.SlotLabel = FpPragmaStrings.back();
4033 FpPragmaStack.push_back(Entry);
4034 }
4035 break;
4036 }
4037
4039 for (unsigned I = 0, N = Record.size(); I != N; ++I)
4040 DeclsToCheckForDeferredDiags.insert(
4041 getGlobalDeclID(F, LocalDeclID(Record[I])));
4042 break;
4043 }
4044 }
4045}
4046
4047void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4048 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4049
4050 // Additional remapping information.
4051 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4052 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4053 F.ModuleOffsetMap = StringRef();
4054
4056 RemapBuilder IdentifierRemap(F.IdentifierRemap);
4057 RemapBuilder MacroRemap(F.MacroRemap);
4058 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4059 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4060 RemapBuilder SelectorRemap(F.SelectorRemap);
4061 RemapBuilder DeclRemap(F.DeclRemap);
4062 RemapBuilder TypeRemap(F.TypeRemap);
4063
4064 auto &ImportedModuleVector = F.DependentModules;
4065 assert(ImportedModuleVector.empty());
4066
4067 while (Data < DataEnd) {
4068 // FIXME: Looking up dependency modules by filename is horrible. Let's
4069 // start fixing this with prebuilt, explicit and implicit modules and see
4070 // how it goes...
4071 using namespace llvm::support;
4072 ModuleKind Kind = static_cast<ModuleKind>(
4073 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4074 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4075 StringRef Name = StringRef((const char*)Data, Len);
4076 Data += Len;
4079 ? ModuleMgr.lookupByModuleName(Name)
4080 : ModuleMgr.lookupByFileName(Name));
4081 if (!OM) {
4082 std::string Msg = "refers to unknown module, cannot find ";
4083 Msg.append(std::string(Name));
4084 Error(Msg);
4085 return;
4086 }
4087
4088 ImportedModuleVector.push_back(OM);
4089
4090 uint32_t IdentifierIDOffset =
4091 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4092 uint32_t MacroIDOffset =
4093 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4094 uint32_t PreprocessedEntityIDOffset =
4095 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4096 uint32_t SubmoduleIDOffset =
4097 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4098 uint32_t SelectorIDOffset =
4099 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4100 uint32_t DeclIDOffset =
4101 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4102 uint32_t TypeIndexOffset =
4103 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4104
4105 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4106 RemapBuilder &Remap) {
4107 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4108 if (Offset != None)
4109 Remap.insert(std::make_pair(Offset,
4110 static_cast<int>(BaseOffset - Offset)));
4111 };
4112
4113 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
4114 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4115 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4116 PreprocessedEntityRemap);
4117 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4118 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4119 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
4120 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
4121
4122 // Global -> local mappings.
4123 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
4124 }
4125}
4126
4128ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4129 const ModuleFile *ImportedBy,
4130 unsigned ClientLoadCapabilities) {
4131 unsigned Idx = 0;
4132 F.ModuleMapPath = ReadPath(F, Record, Idx);
4133
4134 // Try to resolve ModuleName in the current header search context and
4135 // verify that it is found in the same module map file as we saved. If the
4136 // top-level AST file is a main file, skip this check because there is no
4137 // usable header search context.
4138 assert(!F.ModuleName.empty() &&
4139 "MODULE_NAME should come before MODULE_MAP_FILE");
4140 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4141 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4142 // An implicitly-loaded module file should have its module listed in some
4143 // module map file that we've already loaded.
4144 Module *M =
4145 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4146 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4147 OptionalFileEntryRef ModMap =
4148 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4149 // Don't emit module relocation error if we have -fno-validate-pch
4150 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4152 !ModMap) {
4153 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4154 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4155 // This module was defined by an imported (explicit) module.
4156 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4157 << ASTFE->getName();
4158 } else {
4159 // This module was built with a different module map.
4160 Diag(diag::err_imported_module_not_found)
4161 << F.ModuleName << F.FileName
4162 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4163 << !ImportedBy;
4164 // In case it was imported by a PCH, there's a chance the user is
4165 // just missing to include the search path to the directory containing
4166 // the modulemap.
4167 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4168 Diag(diag::note_imported_by_pch_module_not_found)
4169 << llvm::sys::path::parent_path(F.ModuleMapPath);
4170 }
4171 }
4172 return OutOfDate;
4173 }
4174
4175 assert(M && M->Name == F.ModuleName && "found module with different name");
4176
4177 // Check the primary module map file.
4178 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4179 if (!StoredModMap || *StoredModMap != ModMap) {
4180 assert(ModMap && "found module is missing module map file");
4181 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4182 "top-level import should be verified");
4183 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4184 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4185 Diag(diag::err_imported_module_modmap_changed)
4186 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4187 << ModMap->getName() << F.ModuleMapPath << NotImported;
4188 return OutOfDate;
4189 }
4190
4191 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4192 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4193 // FIXME: we should use input files rather than storing names.
4194 std::string Filename = ReadPath(F, Record, Idx);
4195 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4196 if (!SF) {
4197 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4198 Error("could not find file '" + Filename +"' referenced by AST file");
4199 return OutOfDate;
4200 }
4201 AdditionalStoredMaps.insert(*SF);
4202 }
4203
4204 // Check any additional module map files (e.g. module.private.modulemap)
4205 // that are not in the pcm.
4206 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4207 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4208 // Remove files that match
4209 // Note: SmallPtrSet::erase is really remove
4210 if (!AdditionalStoredMaps.erase(ModMap)) {
4211 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4212 Diag(diag::err_module_different_modmap)
4213 << F.ModuleName << /*new*/0 << ModMap.getName();
4214 return OutOfDate;
4215 }
4216 }
4217 }
4218
4219 // Check any additional module map files that are in the pcm, but not
4220 // found in header search. Cases that match are already removed.
4221 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4222 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4223 Diag(diag::err_module_different_modmap)
4224 << F.ModuleName << /*not new*/1 << ModMap.getName();
4225 return OutOfDate;
4226 }
4227 }
4228
4229 if (Listener)
4230 Listener->ReadModuleMapFile(F.ModuleMapPath);
4231 return Success;
4232}
4233
4234/// Move the given method to the back of the global list of methods.
4236 // Find the entry for this selector in the method pool.
4238 S.ObjC().MethodPool.find(Method->getSelector());
4239 if (Known == S.ObjC().MethodPool.end())
4240 return;
4241
4242 // Retrieve the appropriate method list.
4243 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4244 : Known->second.second;
4245 bool Found = false;
4246 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4247 if (!Found) {
4248 if (List->getMethod() == Method) {
4249 Found = true;
4250 } else {
4251 // Keep searching.
4252 continue;
4253 }
4254 }
4255
4256 if (List->getNext())
4257 List->setMethod(List->getNext()->getMethod());
4258 else
4259 List->setMethod(Method);
4260 }
4261}
4262
4264 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4265 for (Decl *D : Names) {
4266 bool wasHidden = !D->isUnconditionallyVisible();
4267 D->setVisibleDespiteOwningModule();
4268
4269 if (wasHidden && SemaObj) {
4270 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4271 moveMethodToBackOfGlobalList(*SemaObj, Method);
4272 }
4273 }
4274 }
4275}
4276
4278 Module::NameVisibilityKind NameVisibility,
4279 SourceLocation ImportLoc) {
4282 Stack.push_back(Mod);
4283 while (!Stack.empty()) {
4284 Mod = Stack.pop_back_val();
4285
4286 if (NameVisibility <= Mod->NameVisibility) {
4287 // This module already has this level of visibility (or greater), so
4288 // there is nothing more to do.
4289 continue;
4290 }
4291
4292 if (Mod->isUnimportable()) {
4293 // Modules that aren't importable cannot be made visible.
4294 continue;
4295 }
4296
4297 // Update the module's name visibility.
4298 Mod->NameVisibility = NameVisibility;
4299
4300 // If we've already deserialized any names from this module,
4301 // mark them as visible.
4302 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4303 if (Hidden != HiddenNamesMap.end()) {
4304 auto HiddenNames = std::move(*Hidden);
4305 HiddenNamesMap.erase(Hidden);
4306 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4307 assert(!HiddenNamesMap.contains(Mod) &&
4308 "making names visible added hidden names");
4309 }
4310
4311 // Push any exported modules onto the stack to be marked as visible.
4313 Mod->getExportedModules(Exports);
4315 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4316 Module *Exported = *I;
4317 if (Visited.insert(Exported).second)
4318 Stack.push_back(Exported);
4319 }
4320 }
4321}
4322
4323/// We've merged the definition \p MergedDef into the existing definition
4324/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4325/// visible.
4327 NamedDecl *MergedDef) {
4328 if (!Def->isUnconditionallyVisible()) {
4329 // If MergedDef is visible or becomes visible, make the definition visible.
4330 if (MergedDef->isUnconditionallyVisible())
4332 else {
4333 getContext().mergeDefinitionIntoModule(
4334 Def, MergedDef->getImportedOwningModule(),
4335 /*NotifyListeners*/ false);
4336 PendingMergedDefinitionsToDeduplicate.insert(Def);
4337 }
4338 }
4339}
4340
4342 if (GlobalIndex)
4343 return false;
4344
4345 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4346 !PP.getLangOpts().Modules)
4347 return true;
4348
4349 // Try to load the global index.
4350 TriedLoadingGlobalIndex = true;
4351 StringRef ModuleCachePath
4352 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4353 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4354 GlobalModuleIndex::readIndex(ModuleCachePath);
4355 if (llvm::Error Err = std::move(Result.second)) {
4356 assert(!Result.first);
4357 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4358 return true;
4359 }
4360
4361 GlobalIndex.reset(Result.first);
4362 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4363 return false;
4364}
4365
4367 return PP.getLangOpts().Modules && UseGlobalIndex &&
4368 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4369}
4370
4372 // Overwrite the timestamp file contents so that file's mtime changes.
4373 std::string TimestampFilename = MF.getTimestampFilename();
4374 std::error_code EC;
4375 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4376 llvm::sys::fs::OF_TextWithCRLF);
4377 if (EC)
4378 return;
4379 OS << "Timestamp file\n";
4380 OS.close();
4381 OS.clear_error(); // Avoid triggering a fatal error.
4382}
4383
4384/// Given a cursor at the start of an AST file, scan ahead and drop the
4385/// cursor into the start of the given block ID, returning false on success and
4386/// true on failure.
4387static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4388 while (true) {
4389 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4390 if (!MaybeEntry) {
4391 // FIXME this drops errors on the floor.
4392 consumeError(MaybeEntry.takeError());
4393 return true;
4394 }
4395 llvm::BitstreamEntry Entry = MaybeEntry.get();
4396
4397 switch (Entry.Kind) {
4398 case llvm::BitstreamEntry::Error:
4399 case llvm::BitstreamEntry::EndBlock:
4400 return true;
4401
4402 case llvm::BitstreamEntry::Record:
4403 // Ignore top-level records.
4404 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4405 break;
4406 else {
4407 // FIXME this drops errors on the floor.
4408 consumeError(Skipped.takeError());
4409 return true;
4410 }
4411
4412 case llvm::BitstreamEntry::SubBlock:
4413 if (Entry.ID == BlockID) {
4414 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4415 // FIXME this drops the error on the floor.
4416 consumeError(std::move(Err));
4417 return true;
4418 }
4419 // Found it!
4420 return false;
4421 }
4422
4423 if (llvm::Error Err = Cursor.SkipBlock()) {
4424 // FIXME this drops the error on the floor.
4425 consumeError(std::move(Err));
4426 return true;
4427 }
4428 }
4429 }
4430}
4431
4433 SourceLocation ImportLoc,
4434 unsigned ClientLoadCapabilities,
4435 ModuleFile **NewLoadedModuleFile) {
4436 llvm::TimeTraceScope scope("ReadAST", FileName);
4437
4438 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4440 CurrentDeserializingModuleKind, Type);
4441
4442 // Defer any pending actions until we get to the end of reading the AST file.
4443 Deserializing AnASTFile(this);
4444
4445 // Bump the generation number.
4446 unsigned PreviousGeneration = 0;
4447 if (ContextObj)
4448 PreviousGeneration = incrementGeneration(*ContextObj);
4449
4450 unsigned NumModules = ModuleMgr.size();
4452 if (ASTReadResult ReadResult =
4453 ReadASTCore(FileName, Type, ImportLoc,
4454 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4455 ClientLoadCapabilities)) {
4456 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4457
4458 // If we find that any modules are unusable, the global index is going
4459 // to be out-of-date. Just remove it.
4460 GlobalIndex.reset();
4461 ModuleMgr.setGlobalIndex(nullptr);
4462 return ReadResult;
4463 }
4464
4465 if (NewLoadedModuleFile && !Loaded.empty())
4466 *NewLoadedModuleFile = Loaded.back().Mod;
4467
4468 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4469 // remove modules from this point. Various fields are updated during reading
4470 // the AST block and removing the modules would result in dangling pointers.
4471 // They are generally only incidentally dereferenced, ie. a binary search
4472 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4473 // be dereferenced but it wouldn't actually be used.
4474
4475 // Load the AST blocks of all of the modules that we loaded. We can still
4476 // hit errors parsing the ASTs at this point.
4477 for (ImportedModule &M : Loaded) {
4478 ModuleFile &F = *M.Mod;
4479 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4480
4481 // Read the AST block.
4482 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4483 Error(std::move(Err));
4484 return Failure;
4485 }
4486
4487 // The AST block should always have a definition for the main module.
4488 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4489 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4490 return Failure;
4491 }
4492
4493 // Read the extension blocks.
4495 if (llvm::Error Err = ReadExtensionBlock(F)) {
4496 Error(std::move(Err));
4497 return Failure;
4498 }
4499 }
4500
4501 // Once read, set the ModuleFile bit base offset and update the size in
4502 // bits of all files we've seen.
4503 F.GlobalBitOffset = TotalModulesSizeInBits;
4504 TotalModulesSizeInBits += F.SizeInBits;
4505 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4506 }
4507
4508 // Preload source locations and interesting indentifiers.
4509 for (ImportedModule &M : Loaded) {
4510 ModuleFile &F = *M.Mod;
4511
4512 // Map the original source file ID into the ID space of the current
4513 // compilation.
4515 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4516
4517 for (auto Offset : F.PreloadIdentifierOffsets) {
4518 const unsigned char *Data = F.IdentifierTableData + Offset;
4519
4520 ASTIdentifierLookupTrait Trait(*this, F);
4521 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4522 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4523
4524 IdentifierInfo *II;
4525 if (!PP.getLangOpts().CPlusPlus) {
4526 // Identifiers present in both the module file and the importing
4527 // instance are marked out-of-date so that they can be deserialized
4528 // on next use via ASTReader::updateOutOfDateIdentifier().
4529 // Identifiers present in the module file but not in the importing
4530 // instance are ignored for now, preventing growth of the identifier
4531 // table. They will be deserialized on first use via ASTReader::get().
4532 auto It = PP.getIdentifierTable().find(Key);
4533 if (It == PP.getIdentifierTable().end())
4534 continue;
4535 II = It->second;
4536 } else {
4537 // With C++ modules, not many identifiers are considered interesting.
4538 // All identifiers in the module file can be placed into the identifier
4539 // table of the importing instance and marked as out-of-date. This makes
4540 // ASTReader::get() a no-op, and deserialization will take place on
4541 // first/next use via ASTReader::updateOutOfDateIdentifier().
4542 II = &PP.getIdentifierTable().getOwn(Key);
4543 }
4544
4545 II->setOutOfDate(true);
4546
4547 // Mark this identifier as being from an AST file so that we can track
4548 // whether we need to serialize it.
4549 markIdentifierFromAST(*this, *II);
4550
4551 // Associate the ID with the identifier so that the writer can reuse it.
4552 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4553 SetIdentifierInfo(ID, II);
4554 }
4555 }
4556
4557 // Builtins and library builtins have already been initialized. Mark all
4558 // identifiers as out-of-date, so that they are deserialized on first use.
4559 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4560 for (auto &Id : PP.getIdentifierTable())
4561 Id.second->setOutOfDate(true);
4562
4563 // Mark selectors as out of date.
4564 for (const auto &Sel : SelectorGeneration)
4565 SelectorOutOfDate[Sel.first] = true;
4566
4567 // Setup the import locations and notify the module manager that we've
4568 // committed to these module files.
4569 for (ImportedModule &M : Loaded) {
4570 ModuleFile &F = *M.Mod;
4571
4572 ModuleMgr.moduleFileAccepted(&F);
4573
4574 // Set the import location.
4575 F.DirectImportLoc = ImportLoc;
4576 // FIXME: We assume that locations from PCH / preamble do not need
4577 // any translation.
4578 if (!M.ImportedBy)
4579 F.ImportLoc = M.ImportLoc;
4580 else
4581 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4582 }
4583
4584 // Resolve any unresolved module exports.
4585 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4586 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4587 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4588 Module *ResolvedMod = getSubmodule(GlobalID);
4589
4590 switch (Unresolved.Kind) {
4591 case UnresolvedModuleRef::Conflict:
4592 if (ResolvedMod) {
4593 Module::Conflict Conflict;
4594 Conflict.Other = ResolvedMod;
4595 Conflict.Message = Unresolved.String.str();
4596 Unresolved.Mod->Conflicts.push_back(Conflict);
4597 }
4598 continue;
4599
4600 case UnresolvedModuleRef::Import:
4601 if (ResolvedMod)
4602 Unresolved.Mod->Imports.insert(ResolvedMod);
4603 continue;
4604
4605 case UnresolvedModuleRef::Affecting:
4606 if (ResolvedMod)
4607 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4608 continue;
4609
4610 case UnresolvedModuleRef::Export:
4611 if (ResolvedMod || Unresolved.IsWildcard)
4612 Unresolved.Mod->Exports.push_back(
4613 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4614 continue;
4615 }
4616 }
4617 UnresolvedModuleRefs.clear();
4618
4619 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4620 // Might be unnecessary as use declarations are only used to build the
4621 // module itself.
4622
4623 if (ContextObj)
4624 InitializeContext();
4625
4626 if (SemaObj)
4627 UpdateSema();
4628
4629 if (DeserializationListener)
4630 DeserializationListener->ReaderInitialized(this);
4631
4632 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4633 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4634 // If this AST file is a precompiled preamble, then set the
4635 // preamble file ID of the source manager to the file source file
4636 // from which the preamble was built.
4637 if (Type == MK_Preamble) {
4638 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4639 } else if (Type == MK_MainFile) {
4640 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4641 }
4642 }
4643
4644 // For any Objective-C class definitions we have already loaded, make sure
4645 // that we load any additional categories.
4646 if (ContextObj) {
4647 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4648 loadObjCCategories(GlobalDeclID(ObjCClassesLoaded[I]->getGlobalID()),
4649 ObjCClassesLoaded[I], PreviousGeneration);
4650 }
4651 }
4652
4653 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4655 // Now we are certain that the module and all modules it depends on are
4656 // up-to-date. For implicitly-built module files, ensure the corresponding
4657 // timestamp files are up-to-date in this build session.
4658 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4659 ImportedModule &M = Loaded[I];
4660 if (M.Mod->Kind == MK_ImplicitModule &&
4661 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4662 updateModuleTimestamp(*M.Mod);
4663 }
4664 }
4665
4666 return Success;
4667}
4668
4669static ASTFileSignature readASTFileSignature(StringRef PCH);
4670
4671/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4672static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4673 // FIXME checking magic headers is done in other places such as
4674 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4675 // always done the same. Unify it all with a helper.
4676 if (!Stream.canSkipToPos(4))
4677 return llvm::createStringError(std::errc::illegal_byte_sequence,
4678 "file too small to contain AST file magic");
4679 for (unsigned C : {'C', 'P', 'C', 'H'})
4680 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4681 if (Res.get() != C)
4682 return llvm::createStringError(
4683 std::errc::illegal_byte_sequence,
4684 "file doesn't start with AST file magic");
4685 } else
4686 return Res.takeError();
4687 return llvm::Error::success();
4688}
4689
4691 switch (Kind) {
4692 case MK_PCH:
4693 return 0; // PCH
4694 case MK_ImplicitModule:
4695 case MK_ExplicitModule:
4696 case MK_PrebuiltModule:
4697 return 1; // module
4698 case MK_MainFile:
4699 case MK_Preamble:
4700 return 2; // main source file
4701 }
4702 llvm_unreachable("unknown module kind");
4703}
4704
4706ASTReader::ReadASTCore(StringRef FileName,
4708 SourceLocation ImportLoc,
4709 ModuleFile *ImportedBy,
4711 off_t ExpectedSize, time_t ExpectedModTime,
4712 ASTFileSignature ExpectedSignature,
4713 unsigned ClientLoadCapabilities) {
4714 ModuleFile *M;
4715 std::string ErrorStr;
4717 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4718 getGeneration(), ExpectedSize, ExpectedModTime,
4719 ExpectedSignature, readASTFileSignature,
4720 M, ErrorStr);
4721
4722 switch (AddResult) {
4724 Diag(diag::remark_module_import)
4725 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4726 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4727 return Success;
4728
4730 // Load module file below.
4731 break;
4732
4734 // The module file was missing; if the client can handle that, return
4735 // it.
4736 if (ClientLoadCapabilities & ARR_Missing)
4737 return Missing;
4738
4739 // Otherwise, return an error.
4740 Diag(diag::err_ast_file_not_found)
4741 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4742 << ErrorStr;
4743 return Failure;
4744
4746 // We couldn't load the module file because it is out-of-date. If the
4747 // client can handle out-of-date, return it.
4748 if (ClientLoadCapabilities & ARR_OutOfDate)
4749 return OutOfDate;
4750
4751 // Otherwise, return an error.
4752 Diag(diag::err_ast_file_out_of_date)
4753 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4754 << ErrorStr;
4755 return Failure;
4756 }
4757
4758 assert(M && "Missing module file");
4759
4760 bool ShouldFinalizePCM = false;
4761 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4762 auto &MC = getModuleManager().getModuleCache();
4763 if (ShouldFinalizePCM)
4764 MC.finalizePCM(FileName);
4765 else
4766 MC.tryToDropPCM(FileName);
4767 });
4768 ModuleFile &F = *M;
4769 BitstreamCursor &Stream = F.Stream;
4770 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4771 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4772
4773 // Sniff for the signature.
4774 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4775 Diag(diag::err_ast_file_invalid)
4776 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4777 return Failure;
4778 }
4779
4780 // This is used for compatibility with older PCH formats.
4781 bool HaveReadControlBlock = false;
4782 while (true) {
4783 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4784 if (!MaybeEntry) {
4785 Error(MaybeEntry.takeError());
4786 return Failure;
4787 }
4788 llvm::BitstreamEntry Entry = MaybeEntry.get();
4789
4790 switch (Entry.Kind) {
4791 case llvm::BitstreamEntry::Error:
4792 case llvm::BitstreamEntry::Record:
4793 case llvm::BitstreamEntry::EndBlock:
4794 Error("invalid record at top-level of AST file");
4795 return Failure;
4796
4797 case llvm::BitstreamEntry::SubBlock:
4798 break;
4799 }
4800
4801 switch (Entry.ID) {
4802 case CONTROL_BLOCK_ID:
4803 HaveReadControlBlock = true;
4804 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4805 case Success:
4806 // Check that we didn't try to load a non-module AST file as a module.
4807 //
4808 // FIXME: Should we also perform the converse check? Loading a module as
4809 // a PCH file sort of works, but it's a bit wonky.
4811 Type == MK_PrebuiltModule) &&
4812 F.ModuleName.empty()) {
4813 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4814 if (Result != OutOfDate ||
4815 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4816 Diag(diag::err_module_file_not_module) << FileName;
4817 return Result;
4818 }
4819 break;
4820
4821 case Failure: return Failure;
4822 case Missing: return Missing;
4823 case OutOfDate: return OutOfDate;
4824 case VersionMismatch: return VersionMismatch;
4825 case ConfigurationMismatch: return ConfigurationMismatch;
4826 case HadErrors: return HadErrors;
4827 }
4828 break;
4829
4830 case AST_BLOCK_ID:
4831 if (!HaveReadControlBlock) {
4832 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4833 Diag(diag::err_pch_version_too_old);
4834 return VersionMismatch;
4835 }
4836
4837 // Record that we've loaded this module.
4838 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4839 ShouldFinalizePCM = true;
4840 return Success;
4841
4842 default:
4843 if (llvm::Error Err = Stream.SkipBlock()) {
4844 Error(std::move(Err));
4845 return Failure;
4846 }
4847 break;
4848 }
4849 }
4850
4851 llvm_unreachable("unexpected break; expected return");
4852}
4853
4855ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4856 unsigned ClientLoadCapabilities) {
4857 const HeaderSearchOptions &HSOpts =
4858 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4859 bool AllowCompatibleConfigurationMismatch =
4861 bool DisableValidation = shouldDisableValidationForFile(F);
4862
4863 ASTReadResult Result = readUnhashedControlBlockImpl(
4864 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4865 Listener.get(),
4866 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4867
4868 // If F was directly imported by another module, it's implicitly validated by
4869 // the importing module.
4870 if (DisableValidation || WasImportedBy ||
4871 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4872 return Success;
4873
4874 if (Result == Failure) {
4875 Error("malformed block record in AST file");
4876 return Failure;
4877 }
4878
4879 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4880 // If this module has already been finalized in the ModuleCache, we're stuck
4881 // with it; we can only load a single version of each module.
4882 //
4883 // This can happen when a module is imported in two contexts: in one, as a
4884 // user module; in another, as a system module (due to an import from
4885 // another module marked with the [system] flag). It usually indicates a
4886 // bug in the module map: this module should also be marked with [system].
4887 //
4888 // If -Wno-system-headers (the default), and the first import is as a
4889 // system module, then validation will fail during the as-user import,
4890 // since -Werror flags won't have been validated. However, it's reasonable
4891 // to treat this consistently as a system module.
4892 //
4893 // If -Wsystem-headers, the PCM on disk was built with
4894 // -Wno-system-headers, and the first import is as a user module, then
4895 // validation will fail during the as-system import since the PCM on disk
4896 // doesn't guarantee that -Werror was respected. However, the -Werror
4897 // flags were checked during the initial as-user import.
4898 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4899 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4900 return Success;
4901 }
4902 }
4903
4904 return Result;
4905}
4906
4907ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4908 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4909 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4910 bool ValidateDiagnosticOptions) {
4911 // Initialize a stream.
4912 BitstreamCursor Stream(StreamData);
4913
4914 // Sniff for the signature.
4915 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4916 // FIXME this drops the error on the floor.
4917 consumeError(std::move(Err));
4918 return Failure;
4919 }
4920
4921 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4923 return Failure;
4924
4925 // Read all of the records in the options block.
4926 RecordData Record;
4927 ASTReadResult Result = Success;
4928 while (true) {
4929 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4930 if (!MaybeEntry) {
4931 // FIXME this drops the error on the floor.
4932 consumeError(MaybeEntry.takeError());
4933 return Failure;
4934 }
4935 llvm::BitstreamEntry Entry = MaybeEntry.get();
4936
4937 switch (Entry.Kind) {
4938 case llvm::BitstreamEntry::Error:
4939 case llvm::BitstreamEntry::SubBlock:
4940 return Failure;
4941
4942 case llvm::BitstreamEntry::EndBlock:
4943 return Result;
4944
4945 case llvm::BitstreamEntry::Record:
4946 // The interesting case.
4947 break;
4948 }
4949
4950 // Read and process a record.
4951 Record.clear();
4952 StringRef Blob;
4953 Expected<unsigned> MaybeRecordType =
4954 Stream.readRecord(Entry.ID, Record, &Blob);
4955 if (!MaybeRecordType) {
4956 // FIXME this drops the error.
4957 return Failure;
4958 }
4959 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4960 case SIGNATURE:
4961 if (F) {
4962 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
4964 "Dummy AST file signature not backpatched in ASTWriter.");
4965 }
4966 break;
4967 case AST_BLOCK_HASH:
4968 if (F) {
4969 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
4971 "Dummy AST block hash not backpatched in ASTWriter.");
4972 }
4973 break;
4974 case DIAGNOSTIC_OPTIONS: {
4975 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4976 if (Listener && ValidateDiagnosticOptions &&
4977 !AllowCompatibleConfigurationMismatch &&
4978 ParseDiagnosticOptions(Record, Complain, *Listener))
4979 Result = OutOfDate; // Don't return early. Read the signature.
4980 break;
4981 }
4982 case HEADER_SEARCH_PATHS: {
4983 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4984 if (Listener && !AllowCompatibleConfigurationMismatch &&
4985 ParseHeaderSearchPaths(Record, Complain, *Listener))
4986 Result = ConfigurationMismatch;
4987 break;
4988 }
4990 if (!F)
4991 break;
4992 if (F->PragmaDiagMappings.empty())
4993 F->PragmaDiagMappings.swap(Record);
4994 else
4995 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4996 Record.begin(), Record.end());
4997 break;
4999 if (F)
5000 F->SearchPathUsage = ReadBitVector(Record, Blob);
5001 break;
5002 case VFS_USAGE:
5003 if (F)
5004 F->VFSUsage = ReadBitVector(Record, Blob);
5005 break;
5006 }
5007 }
5008}
5009
5010/// Parse a record and blob containing module file extension metadata.
5013 StringRef Blob,
5014 ModuleFileExtensionMetadata &Metadata) {
5015 if (Record.size() < 4) return true;
5016
5017 Metadata.MajorVersion = Record[0];
5018 Metadata.MinorVersion = Record[1];
5019
5020 unsigned BlockNameLen = Record[2];
5021 unsigned UserInfoLen = Record[3];
5022
5023 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5024
5025 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5026 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5027 Blob.data() + BlockNameLen + UserInfoLen);
5028 return false;
5029}
5030
5031llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5032 BitstreamCursor &Stream = F.Stream;
5033
5034 RecordData Record;
5035 while (true) {
5036 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5037 if (!MaybeEntry)
5038 return MaybeEntry.takeError();
5039 llvm::BitstreamEntry Entry = MaybeEntry.get();
5040
5041 switch (Entry.Kind) {
5042 case llvm::BitstreamEntry::SubBlock:
5043 if (llvm::Error Err = Stream.SkipBlock())
5044 return Err;
5045 continue;
5046 case llvm::BitstreamEntry::EndBlock:
5047 return llvm::Error::success();
5048 case llvm::BitstreamEntry::Error:
5049 return llvm::createStringError(std::errc::illegal_byte_sequence,
5050 "malformed block record in AST file");
5051 case llvm::BitstreamEntry::Record:
5052 break;
5053 }
5054
5055 Record.clear();
5056 StringRef Blob;
5057 Expected<unsigned> MaybeRecCode =
5058 Stream.readRecord(Entry.ID, Record, &Blob);
5059 if (!MaybeRecCode)
5060 return MaybeRecCode.takeError();
5061 switch (MaybeRecCode.get()) {
5062 case EXTENSION_METADATA: {
5064 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5065 return llvm::createStringError(
5066 std::errc::illegal_byte_sequence,
5067 "malformed EXTENSION_METADATA in AST file");
5068
5069 // Find a module file extension with this block name.
5070 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5071 if (Known == ModuleFileExtensions.end()) break;
5072
5073 // Form a reader.
5074 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5075 F, Stream)) {
5076 F.ExtensionReaders.push_back(std::move(Reader));
5077 }
5078
5079 break;
5080 }
5081 }
5082 }
5083
5084 return llvm::Error::success();
5085}
5086
5088 assert(ContextObj && "no context to initialize");
5089 ASTContext &Context = *ContextObj;
5090
5091 // If there's a listener, notify them that we "read" the translation unit.
5092 if (DeserializationListener)
5093 DeserializationListener->DeclRead(
5095 Context.getTranslationUnitDecl());
5096
5097 // FIXME: Find a better way to deal with collisions between these
5098 // built-in types. Right now, we just ignore the problem.
5099
5100 // Load the special types.
5101 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5102 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5103 if (!Context.CFConstantStringTypeDecl)
5104 Context.setCFConstantStringType(GetType(String));
5105 }
5106
5107 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5108 QualType FileType = GetType(File);
5109 if (FileType.isNull()) {
5110 Error("FILE type is NULL");
5111 return;
5112 }
5113
5114 if (!Context.FILEDecl) {
5115 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5116 Context.setFILEDecl(Typedef->getDecl());
5117 else {
5118 const TagType *Tag = FileType->getAs<TagType>();
5119 if (!Tag) {
5120 Error("Invalid FILE type in AST file");
5121 return;
5122 }
5123 Context.setFILEDecl(Tag->getDecl());
5124 }
5125 }
5126 }
5127
5128 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5129 QualType Jmp_bufType = GetType(Jmp_buf);
5130 if (Jmp_bufType.isNull()) {
5131 Error("jmp_buf type is NULL");
5132 return;
5133 }
5134
5135 if (!Context.jmp_bufDecl) {
5136 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5137 Context.setjmp_bufDecl(Typedef->getDecl());
5138 else {
5139 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5140 if (!Tag) {
5141 Error("Invalid jmp_buf type in AST file");
5142 return;
5143 }
5144 Context.setjmp_bufDecl(Tag->getDecl());
5145 }
5146 }
5147 }
5148
5149 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5150 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5151 if (Sigjmp_bufType.isNull()) {
5152 Error("sigjmp_buf type is NULL");
5153 return;
5154 }
5155
5156 if (!Context.sigjmp_bufDecl) {
5157 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5158 Context.setsigjmp_bufDecl(Typedef->getDecl());
5159 else {
5160 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5161 assert(Tag && "Invalid sigjmp_buf type in AST file");
5162 Context.setsigjmp_bufDecl(Tag->getDecl());
5163 }
5164 }
5165 }
5166
5167 if (unsigned ObjCIdRedef
5168 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5169 if (Context.ObjCIdRedefinitionType.isNull())
5170 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5171 }
5172
5173 if (unsigned ObjCClassRedef
5174 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5175 if (Context.ObjCClassRedefinitionType.isNull())
5176 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5177 }
5178
5179 if (unsigned ObjCSelRedef
5180 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5181 if (Context.ObjCSelRedefinitionType.isNull())
5182 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5183 }
5184
5185 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5186 QualType Ucontext_tType = GetType(Ucontext_t);
5187 if (Ucontext_tType.isNull()) {
5188 Error("ucontext_t type is NULL");
5189 return;
5190 }
5191
5192 if (!Context.ucontext_tDecl) {
5193 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5194 Context.setucontext_tDecl(Typedef->getDecl());
5195 else {
5196 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5197 assert(Tag && "Invalid ucontext_t type in AST file");
5198 Context.setucontext_tDecl(Tag->getDecl());
5199 }
5200 }
5201 }
5202 }
5203
5204 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5205
5206 // If there were any CUDA special declarations, deserialize them.
5207 if (!CUDASpecialDeclRefs.empty()) {
5208 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5210 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5211 }
5212
5213 // Re-export any modules that were imported by a non-module AST file.
5214 // FIXME: This does not make macro-only imports visible again.
5215 for (auto &Import : PendingImportedModules) {
5216 if (Module *Imported = getSubmodule(Import.ID)) {
5217 makeModuleVisible(Imported, Module::AllVisible,
5218 /*ImportLoc=*/Import.ImportLoc);
5219 if (Import.ImportLoc.isValid())
5220 PP.makeModuleVisible(Imported, Import.ImportLoc);
5221 // This updates visibility for Preprocessor only. For Sema, which can be
5222 // nullptr here, we do the same later, in UpdateSema().
5223 }
5224 }
5225
5226 // Hand off these modules to Sema.
5227 PendingImportedModulesSema.append(PendingImportedModules);
5228 PendingImportedModules.clear();
5229}
5230
5232 // Nothing to do for now.
5233}
5234
5235/// Reads and return the signature record from \p PCH's control block, or
5236/// else returns 0.
5238 BitstreamCursor Stream(PCH);
5239 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5240 // FIXME this drops the error on the floor.
5241 consumeError(std::move(Err));
5242 return ASTFileSignature();
5243 }
5244
5245 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5247 return ASTFileSignature();
5248
5249 // Scan for SIGNATURE inside the diagnostic options block.
5251 while (true) {
5253 Stream.advanceSkippingSubblocks();
5254 if (!MaybeEntry) {
5255 // FIXME this drops the error on the floor.
5256 consumeError(MaybeEntry.takeError());
5257 return ASTFileSignature();
5258 }
5259 llvm::BitstreamEntry Entry = MaybeEntry.get();
5260
5261 if (Entry.Kind != llvm::BitstreamEntry::Record)
5262 return ASTFileSignature();
5263
5264 Record.clear();
5265 StringRef Blob;
5266 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5267 if (!MaybeRecord) {
5268 // FIXME this drops the error on the floor.
5269 consumeError(MaybeRecord.takeError());
5270 return ASTFileSignature();
5271 }
5272 if (SIGNATURE == MaybeRecord.get()) {
5273 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5274 assert(Signature != ASTFileSignature::createDummy() &&
5275 "Dummy AST file signature not backpatched in ASTWriter.");
5276 return Signature;
5277 }
5278 }
5279}
5280
5281/// Retrieve the name of the original source file name
5282/// directly from the AST file, without actually loading the AST
5283/// file.
5285 const std::string &ASTFileName, FileManager &FileMgr,
5286 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5287 // Open the AST file.
5288 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5289 /*RequiresNullTerminator=*/false);
5290 if (!Buffer) {
5291 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5292 << ASTFileName << Buffer.getError().message();
5293 return std::string();
5294 }
5295
5296 // Initialize the stream
5297 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5298
5299 // Sniff for the signature.
5300 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5301 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5302 return std::string();
5303 }
5304
5305 // Scan for the CONTROL_BLOCK_ID block.
5306 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5307 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5308 return std::string();
5309 }
5310
5311 // Scan for ORIGINAL_FILE inside the control block.
5313 while (true) {
5315 Stream.advanceSkippingSubblocks();
5316 if (!MaybeEntry) {
5317 // FIXME this drops errors on the floor.
5318 consumeError(MaybeEntry.takeError());
5319 return std::string();
5320 }
5321 llvm::BitstreamEntry Entry = MaybeEntry.get();
5322
5323 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5324 return std::string();
5325
5326 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5327 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5328 return std::string();
5329 }
5330
5331 Record.clear();
5332 StringRef Blob;
5333 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5334 if (!MaybeRecord) {
5335 // FIXME this drops the errors on the floor.
5336 consumeError(MaybeRecord.takeError());
5337 return std::string();
5338 }
5339 if (ORIGINAL_FILE == MaybeRecord.get())
5340 return Blob.str();
5341 }
5342}
5343
5344namespace {
5345
5346 class SimplePCHValidator : public ASTReaderListener {
5347 const LangOptions &ExistingLangOpts;
5348 const TargetOptions &ExistingTargetOpts;
5349 const PreprocessorOptions &ExistingPPOpts;
5350 std::string ExistingModuleCachePath;
5351 FileManager &FileMgr;
5352 bool StrictOptionMatches;
5353
5354 public:
5355 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5356 const TargetOptions &ExistingTargetOpts,
5357 const PreprocessorOptions &ExistingPPOpts,
5358 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5359 bool StrictOptionMatches)
5360 : ExistingLangOpts(ExistingLangOpts),
5361 ExistingTargetOpts(ExistingTargetOpts),
5362 ExistingPPOpts(ExistingPPOpts),
5363 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5364 StrictOptionMatches(StrictOptionMatches) {}
5365
5366 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5367 bool AllowCompatibleDifferences) override {
5368 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5369 AllowCompatibleDifferences);
5370 }
5371
5372 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5373 bool AllowCompatibleDifferences) override {
5374 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5375 AllowCompatibleDifferences);
5376 }
5377
5378 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5379 StringRef SpecificModuleCachePath,
5380 bool Complain) override {
5381 return checkModuleCachePath(
5382 FileMgr.getVirtualFileSystem(), SpecificModuleCachePath,
5383 ExistingModuleCachePath, nullptr, ExistingLangOpts, ExistingPPOpts);
5384 }
5385
5386 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5387 bool ReadMacros, bool Complain,
5388 std::string &SuggestedPredefines) override {
5390 PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,
5391 SuggestedPredefines, ExistingLangOpts,
5392 StrictOptionMatches ? OptionValidateStrictMatches
5394 }
5395 };
5396
5397} // namespace
5398
5400 StringRef Filename, FileManager &FileMgr,
5401 const InMemoryModuleCache &ModuleCache,
5402 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5403 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5404 unsigned ClientLoadCapabilities) {
5405 // Open the AST file.
5406 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5407 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5408 if (!Buffer) {
5409 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5410 // read again later, but we do not have the context here to determine if it
5411 // is safe to change the result of InMemoryModuleCache::getPCMState().
5412
5413 // FIXME: This allows use of the VFS; we do not allow use of the
5414 // VFS when actually loading a module.
5415 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5416 if (!BufferOrErr)
5417 return true;
5418 OwnedBuffer = std::move(*BufferOrErr);
5419 Buffer = OwnedBuffer.get();
5420 }
5421
5422 // Initialize the stream
5423 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5424 BitstreamCursor Stream(Bytes);
5425
5426 // Sniff for the signature.
5427 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5428 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5429 return true;
5430 }
5431
5432 // Scan for the CONTROL_BLOCK_ID block.
5434 return true;
5435
5436 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5437 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5438 bool NeedsImports = Listener.needsImportVisitation();
5439 BitstreamCursor InputFilesCursor;
5440 uint64_t InputFilesOffsetBase = 0;
5441
5443 std::string ModuleDir;
5444 bool DoneWithControlBlock = false;
5445 while (!DoneWithControlBlock) {
5446 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5447 if (!MaybeEntry) {
5448 // FIXME this drops the error on the floor.
5449 consumeError(MaybeEntry.takeError());
5450 return true;
5451 }
5452 llvm::BitstreamEntry Entry = MaybeEntry.get();
5453
5454 switch (Entry.Kind) {
5455 case llvm::BitstreamEntry::SubBlock: {
5456 switch (Entry.ID) {
5457 case OPTIONS_BLOCK_ID: {
5458 std::string IgnoredSuggestedPredefines;
5459 if (ReadOptionsBlock(Stream, ClientLoadCapabilities,
5460 /*AllowCompatibleConfigurationMismatch*/ false,
5461 Listener, IgnoredSuggestedPredefines) != Success)
5462 return true;
5463 break;
5464 }
5465
5467 InputFilesCursor = Stream;
5468 if (llvm::Error Err = Stream.SkipBlock()) {
5469 // FIXME this drops the error on the floor.
5470 consumeError(std::move(Err));
5471 return true;
5472 }
5473 if (NeedsInputFiles &&
5474 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5475 return true;
5476 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5477 break;
5478
5479 default:
5480 if (llvm::Error Err = Stream.SkipBlock()) {
5481 // FIXME this drops the error on the floor.
5482 consumeError(std::move(Err));
5483 return true;
5484 }
5485 break;
5486 }
5487
5488 continue;
5489 }
5490
5491 case llvm::BitstreamEntry::EndBlock:
5492 DoneWithControlBlock = true;
5493 break;
5494
5495 case llvm::BitstreamEntry::Error:
5496 return true;
5497
5498 case llvm::BitstreamEntry::Record:
5499 break;
5500 }
5501
5502 if (DoneWithControlBlock) break;
5503
5504 Record.clear();
5505 StringRef Blob;
5506 Expected<unsigned> MaybeRecCode =
5507 Stream.readRecord(Entry.ID, Record, &Blob);
5508 if (!MaybeRecCode) {
5509 // FIXME this drops the error.
5510 return Failure;
5511 }
5512 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5513 case METADATA:
5514 if (Record[0] != VERSION_MAJOR)
5515 return true;
5516 if (Listener.ReadFullVersionInformation(Blob))
5517 return true;
5518 break;
5519 case MODULE_NAME:
5520 Listener.ReadModuleName(Blob);
5521 break;
5522 case MODULE_DIRECTORY:
5523 ModuleDir = std::string(Blob);
5524 break;
5525 case MODULE_MAP_FILE: {
5526 unsigned Idx = 0;
5527 auto Path = ReadString(Record, Idx);
5528 ResolveImportedPath(Path, ModuleDir);
5529 Listener.ReadModuleMapFile(Path);
5530 break;
5531 }
5532 case INPUT_FILE_OFFSETS: {
5533 if (!NeedsInputFiles)
5534 break;
5535
5536 unsigned NumInputFiles = Record[0];
5537 unsigned NumUserFiles = Record[1];
5538 const llvm::support::unaligned_uint64_t *InputFileOffs =
5539 (const llvm::support::unaligned_uint64_t *)Blob.data();
5540 for (unsigned I = 0; I != NumInputFiles; ++I) {
5541 // Go find this input file.
5542 bool isSystemFile = I >= NumUserFiles;
5543
5544 if (isSystemFile && !NeedsSystemInputFiles)
5545 break; // the rest are system input files
5546
5547 BitstreamCursor &Cursor = InputFilesCursor;
5548 SavedStreamPosition SavedPosition(Cursor);
5549 if (llvm::Error Err =
5550 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5551 // FIXME this drops errors on the floor.
5552 consumeError(std::move(Err));
5553 }
5554
5555 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5556 if (!MaybeCode) {
5557 // FIXME this drops errors on the floor.
5558 consumeError(MaybeCode.takeError());
5559 }
5560 unsigned Code = MaybeCode.get();
5561
5563 StringRef Blob;
5564 bool shouldContinue = false;
5565 Expected<unsigned> MaybeRecordType =
5566 Cursor.readRecord(Code, Record, &Blob);
5567 if (!MaybeRecordType) {
5568 // FIXME this drops errors on the floor.
5569 consumeError(MaybeRecordType.takeError());
5570 }
5571 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5572 case INPUT_FILE_HASH:
5573 break;
5574 case INPUT_FILE:
5575 bool Overridden = static_cast<bool>(Record[3]);
5576 std::string Filename = std::string(Blob);
5577 ResolveImportedPath(Filename, ModuleDir);
5578 shouldContinue = Listener.visitInputFile(
5579 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5580 break;
5581 }
5582 if (!shouldContinue)
5583 break;
5584 }
5585 break;
5586 }
5587
5588 case IMPORTS: {
5589 if (!NeedsImports)
5590 break;
5591
5592 unsigned Idx = 0, N = Record.size();
5593 while (Idx < N) {
5594 // Read information about the AST file.
5595
5596 // Skip Kind
5597 Idx++;
5598 bool IsStandardCXXModule = Record[Idx++];
5599
5600 // Skip ImportLoc
5601 Idx++;
5602
5603 // In C++20 Modules, we don't record the path to imported
5604 // modules in the BMI files.
5605 if (IsStandardCXXModule) {
5606 std::string ModuleName = ReadString(Record, Idx);
5607 Listener.visitImport(ModuleName, /*Filename=*/"");
5608 continue;
5609 }
5610
5611 // Skip Size, ModTime and Signature
5612 Idx += 1 + 1 + ASTFileSignature::size;
5613 std::string ModuleName = ReadString(Record, Idx);
5614 std::string Filename = ReadString(Record, Idx);
5615 ResolveImportedPath(Filename, ModuleDir);
5616 Listener.visitImport(ModuleName, Filename);
5617 }
5618 break;
5619 }
5620
5621 default:
5622 // No other validation to perform.
5623 break;
5624 }
5625 }
5626
5627 // Look for module file extension blocks, if requested.
5628 if (FindModuleFileExtensions) {
5629 BitstreamCursor SavedStream = Stream;
5630 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5631 bool DoneWithExtensionBlock = false;
5632 while (!DoneWithExtensionBlock) {
5633 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5634 if (!MaybeEntry) {
5635 // FIXME this drops the error.
5636 return true;
5637 }
5638 llvm::BitstreamEntry Entry = MaybeEntry.get();
5639
5640 switch (Entry.Kind) {
5641 case llvm::BitstreamEntry::SubBlock:
5642 if (llvm::Error Err = Stream.SkipBlock()) {
5643 // FIXME this drops the error on the floor.
5644 consumeError(std::move(Err));
5645 return true;
5646 }
5647 continue;
5648
5649 case llvm::BitstreamEntry::EndBlock:
5650 DoneWithExtensionBlock = true;
5651 continue;
5652
5653 case llvm::BitstreamEntry::Error:
5654 return true;
5655
5656 case llvm::BitstreamEntry::Record:
5657 break;
5658 }
5659
5660 Record.clear();
5661 StringRef Blob;
5662 Expected<unsigned> MaybeRecCode =
5663 Stream.readRecord(Entry.ID, Record, &Blob);
5664 if (!MaybeRecCode) {
5665 // FIXME this drops the error.
5666 return true;
5667 }
5668 switch (MaybeRecCode.get()) {
5669 case EXTENSION_METADATA: {
5671 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5672 return true;
5673
5674 Listener.readModuleFileExtension(Metadata);
5675 break;
5676 }
5677 }
5678 }
5679 }
5680 Stream = SavedStream;
5681 }
5682
5683 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5684 if (readUnhashedControlBlockImpl(
5685 nullptr, Bytes, ClientLoadCapabilities,
5686 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5687 ValidateDiagnosticOptions) != Success)
5688 return true;
5689
5690 return false;
5691}
5692
5694 const InMemoryModuleCache &ModuleCache,
5695 const PCHContainerReader &PCHContainerRdr,
5696 const LangOptions &LangOpts,
5697 const TargetOptions &TargetOpts,
5698 const PreprocessorOptions &PPOpts,
5699 StringRef ExistingModuleCachePath,
5700 bool RequireStrictOptionMatches) {
5701 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5702 ExistingModuleCachePath, FileMgr,
5703 RequireStrictOptionMatches);
5704 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5705 PCHContainerRdr,
5706 /*FindModuleFileExtensions=*/false, validator,
5707 /*ValidateDiagnosticOptions=*/true);
5708}
5709
5710llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5711 unsigned ClientLoadCapabilities) {
5712 // Enter the submodule block.
5713 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5714 return Err;
5715
5716 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5717 bool First = true;
5718 Module *CurrentModule = nullptr;
5719 RecordData Record;
5720 while (true) {
5722 F.Stream.advanceSkippingSubblocks();
5723 if (!MaybeEntry)
5724 return MaybeEntry.takeError();
5725 llvm::BitstreamEntry Entry = MaybeEntry.get();
5726
5727 switch (Entry.Kind) {
5728 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5729 case llvm::BitstreamEntry::Error:
5730 return llvm::createStringError(std::errc::illegal_byte_sequence,
5731 "malformed block record in AST file");
5732 case llvm::BitstreamEntry::EndBlock:
5733 return llvm::Error::success();
5734 case llvm::BitstreamEntry::Record:
5735 // The interesting case.
5736 break;
5737 }
5738
5739 // Read a record.
5740 StringRef Blob;
5741 Record.clear();
5742 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5743 if (!MaybeKind)
5744 return MaybeKind.takeError();
5745 unsigned Kind = MaybeKind.get();
5746
5747 if ((Kind == SUBMODULE_METADATA) != First)
5748 return llvm::createStringError(
5749 std::errc::illegal_byte_sequence,
5750 "submodule metadata record should be at beginning of block");
5751 First = false;
5752
5753 // Submodule information is only valid if we have a current module.
5754 // FIXME: Should we error on these cases?
5755 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5756 Kind != SUBMODULE_DEFINITION)
5757 continue;
5758
5759 switch (Kind) {
5760 default: // Default behavior: ignore.
5761 break;
5762
5763 case SUBMODULE_DEFINITION: {
5764 if (Record.size() < 13)
5765 return llvm::createStringError(std::errc::illegal_byte_sequence,
5766 "malformed module definition");
5767
5768 StringRef Name = Blob;
5769 unsigned Idx = 0;
5770 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5771 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5773 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5774 bool IsFramework = Record[Idx++];
5775 bool IsExplicit = Record[Idx++];
5776 bool IsSystem = Record[Idx++];
5777 bool IsExternC = Record[Idx++];
5778 bool InferSubmodules = Record[Idx++];
5779 bool InferExplicitSubmodules = Record[Idx++];
5780 bool InferExportWildcard = Record[Idx++];
5781 bool ConfigMacrosExhaustive = Record[Idx++];
5782 bool ModuleMapIsPrivate = Record[Idx++];
5783 bool NamedModuleHasInit = Record[Idx++];
5784
5785 Module *ParentModule = nullptr;
5786 if (Parent)
5787 ParentModule = getSubmodule(Parent);
5788
5789 // Retrieve this (sub)module from the module map, creating it if
5790 // necessary.
5791 CurrentModule =
5792 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5793 .first;
5794
5795 // FIXME: Call ModMap.setInferredModuleAllowedBy()
5796
5797 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5798 if (GlobalIndex >= SubmodulesLoaded.size() ||
5799 SubmodulesLoaded[GlobalIndex])
5800 return llvm::createStringError(std::errc::invalid_argument,
5801 "too many submodules");
5802
5803 if (!ParentModule) {
5804 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5805 // Don't emit module relocation error if we have -fno-validate-pch
5806 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5808 CurFile != F.File) {
5809 auto ConflictError =
5810 PartialDiagnostic(diag::err_module_file_conflict,
5811 ContextObj->DiagAllocator)
5812 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5813 << F.File.getName();
5814 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5815 }
5816 }
5817
5818 F.DidReadTopLevelSubmodule = true;
5819 CurrentModule->setASTFile(F.File);
5820 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5821 }
5822
5823 CurrentModule->Kind = Kind;
5824 CurrentModule->DefinitionLoc = DefinitionLoc;
5825 CurrentModule->Signature = F.Signature;
5826 CurrentModule->IsFromModuleFile = true;
5827 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5828 CurrentModule->IsExternC = IsExternC;
5829 CurrentModule->InferSubmodules = InferSubmodules;
5830 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5831 CurrentModule->InferExportWildcard = InferExportWildcard;
5832 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5833 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5834 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5835 if (DeserializationListener)
5836 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5837
5838 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5839
5840 // Clear out data that will be replaced by what is in the module file.
5841 CurrentModule->LinkLibraries.clear();
5842 CurrentModule->ConfigMacros.clear();
5843 CurrentModule->UnresolvedConflicts.clear();
5844 CurrentModule->Conflicts.clear();
5845
5846 // The module is available unless it's missing a requirement; relevant
5847 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5848 // Missing headers that were present when the module was built do not
5849 // make it unavailable -- if we got this far, this must be an explicitly
5850 // imported module file.
5851 CurrentModule->Requirements.clear();
5852 CurrentModule->MissingHeaders.clear();
5853 CurrentModule->IsUnimportable =
5854 ParentModule && ParentModule->IsUnimportable;
5855 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5856 break;
5857 }
5858
5860 // FIXME: This doesn't work for framework modules as `Filename` is the
5861 // name as written in the module file and does not include
5862 // `Headers/`, so this path will never exist.
5863 std::string Filename = std::string(Blob);
5864 ResolveImportedPath(F, Filename);
5865 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5866 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5867 // FIXME: NameAsWritten
5868 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5869 }
5870 // Note that it's too late at this point to return out of date if the
5871 // name from the PCM doesn't match up with the one in the module map,
5872 // but also quite unlikely since we will have already checked the
5873 // modification time and size of the module map file itself.
5874 }
5875 break;
5876 }
5877
5878 case SUBMODULE_HEADER:
5881 // We lazily associate headers with their modules via the HeaderInfo table.
5882 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5883 // of complete filenames or remove it entirely.
5884 break;
5885
5888 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5889 // them here.
5890 break;
5891
5892 case SUBMODULE_TOPHEADER: {
5893 std::string HeaderName(Blob);
5894 ResolveImportedPath(F, HeaderName);
5895 CurrentModule->addTopHeaderFilename(HeaderName);
5896 break;
5897 }
5898
5900 // See comments in SUBMODULE_UMBRELLA_HEADER
5901 std::string Dirname = std::string(Blob);
5902 ResolveImportedPath(F, Dirname);
5903 if (auto Umbrella =
5904 PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5905 if (!CurrentModule->getUmbrellaDirAsWritten()) {
5906 // FIXME: NameAsWritten
5907 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5908 }
5909 }
5910 break;
5911 }
5912
5913 case SUBMODULE_METADATA: {
5914 F.BaseSubmoduleID = getTotalNumSubmodules();
5916 unsigned LocalBaseSubmoduleID = Record[1];
5917 if (F.LocalNumSubmodules > 0) {
5918 // Introduce the global -> local mapping for submodules within this
5919 // module.
5920 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5921
5922 // Introduce the local -> global mapping for submodules within this
5923 // module.
5925 std::make_pair(LocalBaseSubmoduleID,
5926 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5927
5928 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5929 }
5930 break;
5931 }
5932
5933 case SUBMODULE_IMPORTS:
5934 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5935 UnresolvedModuleRef Unresolved;
5936 Unresolved.File = &F;
5937 Unresolved.Mod = CurrentModule;
5938 Unresolved.ID = Record[Idx];
5939 Unresolved.Kind = UnresolvedModuleRef::Import;
5940 Unresolved.IsWildcard = false;
5941 UnresolvedModuleRefs.push_back(Unresolved);
5942 }
5943 break;
5944
5946 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5947 UnresolvedModuleRef Unresolved;
5948 Unresolved.File = &F;
5949 Unresolved.Mod = CurrentModule;
5950 Unresolved.ID = Record[Idx];
5951 Unresolved.Kind = UnresolvedModuleRef::Affecting;
5952 Unresolved.IsWildcard = false;
5953 UnresolvedModuleRefs.push_back(Unresolved);
5954 }
5955 break;
5956
5957 case SUBMODULE_EXPORTS:
5958 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5959 UnresolvedModuleRef Unresolved;
5960 Unresolved.File = &F;
5961 Unresolved.Mod = CurrentModule;
5962 Unresolved.ID = Record[Idx];
5963 Unresolved.Kind = UnresolvedModuleRef::Export;
5964 Unresolved.IsWildcard = Record[Idx + 1];
5965 UnresolvedModuleRefs.push_back(Unresolved);
5966 }
5967
5968 // Once we've loaded the set of exports, there's no reason to keep
5969 // the parsed, unresolved exports around.
5970 CurrentModule->UnresolvedExports.clear();
5971 break;
5972
5973 case SUBMODULE_REQUIRES:
5974 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5975 PP.getTargetInfo());
5976 break;
5977
5979 ModMap.resolveLinkAsDependencies(CurrentModule);
5980 CurrentModule->LinkLibraries.push_back(
5981 Module::LinkLibrary(std::string(Blob), Record[0]));
5982 break;
5983
5985 CurrentModule->ConfigMacros.push_back(Blob.str());
5986 break;
5987
5988 case SUBMODULE_CONFLICT: {
5989 UnresolvedModuleRef Unresolved;
5990 Unresolved.File = &F;
5991 Unresolved.Mod = CurrentModule;
5992 Unresolved.ID = Record[0];
5993 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5994 Unresolved.IsWildcard = false;
5995 Unresolved.String = Blob;
5996 UnresolvedModuleRefs.push_back(Unresolved);
5997 break;
5998 }
5999
6001 if (!ContextObj)
6002 break;
6004 for (auto &ID : Record)
6005 Inits.push_back(getGlobalDeclID(F, LocalDeclID(ID)));
6006 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6007 break;
6008 }
6009
6011 CurrentModule->ExportAsModule = Blob.str();
6012 ModMap.addLinkAsDependency(CurrentModule);
6013 break;
6014 }
6015 }
6016}
6017
6018/// Parse the record that corresponds to a LangOptions data
6019/// structure.
6020///
6021/// This routine parses the language options from the AST file and then gives
6022/// them to the AST listener if one is set.
6023///
6024/// \returns true if the listener deems the file unacceptable, false otherwise.
6025bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6026 bool Complain,
6027 ASTReaderListener &Listener,
6028 bool AllowCompatibleDifferences) {
6029 LangOptions LangOpts;
6030 unsigned Idx = 0;
6031#define LANGOPT(Name, Bits, Default, Description) \
6032 LangOpts.Name = Record[Idx++];
6033#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6034 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6035#include "clang/Basic/LangOptions.def"
6036#define SANITIZER(NAME, ID) \
6037 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6038#include "clang/Basic/Sanitizers.def"
6039
6040 for (unsigned N = Record[Idx++]; N; --N)
6041 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6042
6043 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6044 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6045 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6046
6047 LangOpts.CurrentModule = ReadString(Record, Idx);
6048
6049 // Comment options.
6050 for (unsigned N = Record[Idx++]; N; --N) {
6051 LangOpts.CommentOpts.BlockCommandNames.push_back(
6052 ReadString(Record, Idx));
6053 }
6054 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6055
6056 // OpenMP offloading options.
6057 for (unsigned N = Record[Idx++]; N; --N) {
6058 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6059 }
6060
6061 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6062
6063 return Listener.ReadLanguageOptions(LangOpts, Complain,
6064 AllowCompatibleDifferences);
6065}
6066
6067bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
6068 ASTReaderListener &Listener,
6069 bool AllowCompatibleDifferences) {
6070 unsigned Idx = 0;
6071 TargetOptions TargetOpts;
6072 TargetOpts.Triple = ReadString(Record, Idx);
6073 TargetOpts.CPU = ReadString(Record, Idx);
6074 TargetOpts.TuneCPU = ReadString(Record, Idx);
6075 TargetOpts.ABI = ReadString(Record, Idx);
6076 for (unsigned N = Record[Idx++]; N; --N) {
6077 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6078 }
6079 for (unsigned N = Record[Idx++]; N; --N) {
6080 TargetOpts.Features.push_back(ReadString(Record, Idx));
6081 }
6082
6083 return Listener.ReadTargetOptions(TargetOpts, Complain,
6084 AllowCompatibleDifferences);
6085}
6086
6087bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
6088 ASTReaderListener &Listener) {
6090 unsigned Idx = 0;
6091#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6092#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6093 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6094#include "clang/Basic/DiagnosticOptions.def"
6095
6096 for (unsigned N = Record[Idx++]; N; --N)
6097 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6098 for (unsigned N = Record[Idx++]; N; --N)
6099 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6100
6101 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
6102}
6103
6104bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6105 ASTReaderListener &Listener) {
6106 FileSystemOptions FSOpts;
6107 unsigned Idx = 0;
6108 FSOpts.WorkingDir = ReadString(Record, Idx);
6109 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6110}
6111
6112bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6113 bool Complain,
6114 ASTReaderListener &Listener) {
6115 HeaderSearchOptions HSOpts;
6116 unsigned Idx = 0;
6117 HSOpts.Sysroot = ReadString(Record, Idx);
6118
6119 HSOpts.ResourceDir = ReadString(Record, Idx);
6120 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6121 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6122 HSOpts.DisableModuleHash = Record[Idx++];
6123 HSOpts.ImplicitModuleMaps = Record[Idx++];
6124 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6125 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6126 HSOpts.UseBuiltinIncludes = Record[Idx++];
6127 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6128 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6129 HSOpts.UseLibcxx = Record[Idx++];
6130 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6131
6132 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
6133 Complain);
6134}
6135
6136bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6137 ASTReaderListener &Listener) {
6138 HeaderSearchOptions HSOpts;
6139 unsigned Idx = 0;
6140
6141 // Include entries.
6142 for (unsigned N = Record[Idx++]; N; --N) {
6143 std::string Path = ReadString(Record, Idx);
6145 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6146 bool IsFramework = Record[Idx++];
6147 bool IgnoreSysRoot = Record[Idx++];
6148 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6149 IgnoreSysRoot);
6150 }
6151
6152 // System header prefixes.
6153 for (unsigned N = Record[Idx++]; N; --N) {
6154 std::string Prefix = ReadString(Record, Idx);
6155 bool IsSystemHeader = Record[Idx++];
6156 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6157 }
6158
6159 // VFS overlay files.
6160 for (unsigned N = Record[Idx++]; N; --N) {
6161 std::string VFSOverlayFile = ReadString(Record, Idx);
6162 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6163 }
6164
6165 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6166}
6167
6168bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6169 bool Complain,
6170 ASTReaderListener &Listener,
6171 std::string &SuggestedPredefines) {
6172 PreprocessorOptions PPOpts;
6173 unsigned Idx = 0;
6174
6175 // Macro definitions/undefs
6176 bool ReadMacros = Record[Idx++];
6177 if (ReadMacros) {
6178 for (unsigned N = Record[Idx++]; N; --N) {
6179 std::string Macro = ReadString(Record, Idx);
6180 bool IsUndef = Record[Idx++];
6181 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6182 }
6183 }
6184
6185 // Includes
6186 for (unsigned N = Record[Idx++]; N; --N) {
6187 PPOpts.Includes.push_back(ReadString(Record, Idx));
6188 }
6189
6190 // Macro Includes
6191 for (unsigned N = Record[Idx++]; N; --N) {
6192 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6193 }
6194
6195 PPOpts.UsePredefines = Record[Idx++];
6196 PPOpts.DetailedRecord = Record[Idx++];
6197 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6199 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6200 SuggestedPredefines.clear();
6201 return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
6202 SuggestedPredefines);
6203}
6204
6205std::pair<ModuleFile *, unsigned>
6206ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6207 GlobalPreprocessedEntityMapType::iterator
6208 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6209 assert(I != GlobalPreprocessedEntityMap.end() &&
6210 "Corrupted global preprocessed entity map");
6211 ModuleFile *M = I->second;
6212 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6213 return std::make_pair(M, LocalIndex);
6214}
6215
6216llvm::iterator_range<PreprocessingRecord::iterator>
6217ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6218 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6219 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6221
6222 return llvm::make_range(PreprocessingRecord::iterator(),
6224}
6225
6226bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6227 unsigned int ClientLoadCapabilities) {
6228 return ClientLoadCapabilities & ARR_OutOfDate &&
6229 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6230}
6231
6232llvm::iterator_range<ASTReader::ModuleDeclIterator>
6234 return llvm::make_range(
6235 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6236 ModuleDeclIterator(this, &Mod,
6238}
6239
6241 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6242 assert(I != GlobalSkippedRangeMap.end() &&
6243 "Corrupted global skipped range map");
6244 ModuleFile *M = I->second;
6245 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6246 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6247 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6248 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6249 ReadSourceLocation(*M, RawRange.getEnd()));
6250 assert(Range.isValid());
6251 return Range;
6252}
6253
6255 PreprocessedEntityID PPID = Index+1;
6256 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6257 ModuleFile &M = *PPInfo.first;
6258 unsigned LocalIndex = PPInfo.second;
6259 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6260
6261 if (!PP.getPreprocessingRecord()) {
6262 Error("no preprocessing record");
6263 return nullptr;
6264 }
6265
6267 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6268 M.MacroOffsetsBase + PPOffs.getOffset())) {
6269 Error(std::move(Err));
6270 return nullptr;
6271 }
6272
6274 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6275 if (!MaybeEntry) {
6276 Error(MaybeEntry.takeError());
6277 return nullptr;
6278 }
6279 llvm::BitstreamEntry Entry = MaybeEntry.get();
6280
6281 if (Entry.Kind != llvm::BitstreamEntry::Record)
6282 return nullptr;
6283
6284 // Read the record.
6285 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6286 ReadSourceLocation(M, PPOffs.getEnd()));
6287 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6288 StringRef Blob;
6290 Expected<unsigned> MaybeRecType =
6291 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6292 if (!MaybeRecType) {
6293 Error(MaybeRecType.takeError());
6294 return nullptr;
6295 }
6296 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6297 case PPD_MACRO_EXPANSION: {
6298 bool isBuiltin = Record[0];
6299 IdentifierInfo *Name = nullptr;
6300 MacroDefinitionRecord *Def = nullptr;
6301 if (isBuiltin)
6302 Name = getLocalIdentifier(M, Record[1]);
6303 else {
6304 PreprocessedEntityID GlobalID =
6305 getGlobalPreprocessedEntityID(M, Record[1]);
6306 Def = cast<MacroDefinitionRecord>(
6307 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6308 }
6309
6310 MacroExpansion *ME;
6311 if (isBuiltin)
6312 ME = new (PPRec) MacroExpansion(Name, Range);
6313 else
6314 ME = new (PPRec) MacroExpansion(Def, Range);
6315
6316 return ME;
6317 }
6318
6319 case PPD_MACRO_DEFINITION: {
6320 // Decode the identifier info and then check again; if the macro is
6321 // still defined and associated with the identifier,
6322 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6323 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6324
6325 if (DeserializationListener)
6326 DeserializationListener->MacroDefinitionRead(PPID, MD);
6327
6328 return MD;
6329 }
6330
6332 const char *FullFileNameStart = Blob.data() + Record[0];
6333 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6335 if (!FullFileName.empty())
6336 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6337
6338 // FIXME: Stable encoding
6340 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6342 = new (PPRec) InclusionDirective(PPRec, Kind,
6343 StringRef(Blob.data(), Record[0]),
6344 Record[1], Record[3],
6345 File,
6346 Range);
6347 return ID;
6348 }
6349 }
6350
6351 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6352}
6353
6354/// Find the next module that contains entities and return the ID
6355/// of the first entry.
6356///
6357/// \param SLocMapI points at a chunk of a module that contains no
6358/// preprocessed entities or the entities it contains are not the ones we are
6359/// looking for.
6360PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6361 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6362 ++SLocMapI;
6363 for (GlobalSLocOffsetMapType::const_iterator
6364 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6365 ModuleFile &M = *SLocMapI->second;
6367 return M.BasePreprocessedEntityID;
6368 }
6369
6370 return getTotalNumPreprocessedEntities();
6371}
6372
6373namespace {
6374
6375struct PPEntityComp {
6376 const ASTReader &Reader;
6377 ModuleFile &M;
6378
6379 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6380
6381 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6382 SourceLocation LHS = getLoc(L);
6383 SourceLocation RHS = getLoc(R);
6384 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6385 }
6386
6387 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6388 SourceLocation LHS = getLoc(L);
6389 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6390 }
6391
6392 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6393 SourceLocation RHS = getLoc(R);
6394 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6395 }
6396
6397 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6398 return Reader.ReadSourceLocation(M, PPE.getBegin());
6399 }
6400};
6401
6402} // namespace
6403
6404PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6405 bool EndsAfter) const {
6406 if (SourceMgr.isLocalSourceLocation(Loc))
6407 return getTotalNumPreprocessedEntities();
6408
6409 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6410 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6411 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6412 "Corrupted global sloc offset map");
6413
6414 if (SLocMapI->second->NumPreprocessedEntities == 0)
6415 return findNextPreprocessedEntity(SLocMapI);
6416
6417 ModuleFile &M = *SLocMapI->second;
6418
6419 using pp_iterator = const PPEntityOffset *;
6420
6421 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6422 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6423
6424 size_t Count = M.NumPreprocessedEntities;
6425 size_t Half;
6426 pp_iterator First = pp_begin;
6427 pp_iterator PPI;
6428
6429 if (EndsAfter) {
6430 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6431 PPEntityComp(*this, M));
6432 } else {
6433 // Do a binary search manually instead of using std::lower_bound because
6434 // The end locations of entities may be unordered (when a macro expansion
6435 // is inside another macro argument), but for this case it is not important
6436 // whether we get the first macro expansion or its containing macro.
6437 while (Count > 0) {
6438 Half = Count / 2;
6439 PPI = First;
6440 std::advance(PPI, Half);
6441 if (SourceMgr.isBeforeInTranslationUnit(
6442 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6443 First = PPI;
6444 ++First;
6445 Count = Count - Half - 1;
6446 } else
6447 Count = Half;
6448 }
6449 }
6450
6451 if (PPI == pp_end)
6452 return findNextPreprocessedEntity(SLocMapI);
6453
6454 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6455}
6456
6457/// Returns a pair of [Begin, End) indices of preallocated
6458/// preprocessed entities that \arg Range encompasses.
6459std::pair<unsigned, unsigned>
6461 if (Range.isInvalid())
6462 return std::make_pair(0,0);
6463 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6464
6465 PreprocessedEntityID BeginID =
6466 findPreprocessedEntity(Range.getBegin(), false);
6467 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6468 return std::make_pair(BeginID, EndID);
6469}
6470
6471/// Optionally returns true or false if the preallocated preprocessed
6472/// entity with index \arg Index came from file \arg FID.
6473std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6474 FileID FID) {
6475 if (FID.isInvalid())
6476 return false;
6477
6478 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6479 ModuleFile &M = *PPInfo.first;
6480 unsigned LocalIndex = PPInfo.second;
6481 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6482
6483 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6484 if (Loc.isInvalid())
6485 return false;
6486
6487 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6488 return true;
6489 else
6490 return false;
6491}
6492
6493namespace {
6494
6495 /// Visitor used to search for information about a header file.
6496 class HeaderFileInfoVisitor {
6497 FileEntryRef FE;
6498 std::optional<HeaderFileInfo> HFI;
6499
6500 public:
6501 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6502
6503 bool operator()(ModuleFile &M) {
6506 if (!Table)
6507 return false;
6508
6509 // Look in the on-disk hash table for an entry for this file name.
6510 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6511 if (Pos == Table->end())
6512 return false;
6513
6514 HFI = *Pos;
6515 return true;
6516 }
6517
6518 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6519 };
6520
6521} // namespace
6522
6524 HeaderFileInfoVisitor Visitor(FE);
6525 ModuleMgr.visit(Visitor);
6526 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6527 return *HFI;
6528
6529 return HeaderFileInfo();
6530}
6531
6533 using DiagState = DiagnosticsEngine::DiagState;
6535
6536 for (ModuleFile &F : ModuleMgr) {
6537 unsigned Idx = 0;
6538 auto &Record = F.PragmaDiagMappings;
6539 if (Record.empty())
6540 continue;
6541
6542 DiagStates.clear();
6543
6544 auto ReadDiagState = [&](const DiagState &BasedOn,
6545 bool IncludeNonPragmaStates) {
6546 unsigned BackrefID = Record[Idx++];
6547 if (BackrefID != 0)
6548 return DiagStates[BackrefID - 1];
6549
6550 // A new DiagState was created here.
6551 Diag.DiagStates.push_back(BasedOn);
6552 DiagState *NewState = &Diag.DiagStates.back();
6553 DiagStates.push_back(NewState);
6554 unsigned Size = Record[Idx++];
6555 assert(Idx + Size * 2 <= Record.size() &&
6556 "Invalid data, not enough diag/map pairs");
6557 while (Size--) {
6558 unsigned DiagID = Record[Idx++];
6559 DiagnosticMapping NewMapping =
6561 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6562 continue;
6563
6564 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6565
6566 // If this mapping was specified as a warning but the severity was
6567 // upgraded due to diagnostic settings, simulate the current diagnostic
6568 // settings (and use a warning).
6569 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6571 NewMapping.setUpgradedFromWarning(false);
6572 }
6573
6574 Mapping = NewMapping;
6575 }
6576 return NewState;
6577 };
6578
6579 // Read the first state.
6580 DiagState *FirstState;
6581 if (F.Kind == MK_ImplicitModule) {
6582 // Implicitly-built modules are reused with different diagnostic
6583 // settings. Use the initial diagnostic state from Diag to simulate this
6584 // compilation's diagnostic settings.
6585 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6586 DiagStates.push_back(FirstState);
6587
6588 // Skip the initial diagnostic state from the serialized module.
6589 assert(Record[1] == 0 &&
6590 "Invalid data, unexpected backref in initial state");
6591 Idx = 3 + Record[2] * 2;
6592 assert(Idx < Record.size() &&
6593 "Invalid data, not enough state change pairs in initial state");
6594 } else if (F.isModule()) {
6595 // For an explicit module, preserve the flags from the module build
6596 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6597 // -Wblah flags.
6598 unsigned Flags = Record[Idx++];
6599 DiagState Initial;
6600 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6601 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6602 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6603 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6604 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6605 Initial.ExtBehavior = (diag::Severity)Flags;
6606 FirstState = ReadDiagState(Initial, true);
6607
6608 assert(F.OriginalSourceFileID.isValid());
6609
6610 // Set up the root buffer of the module to start with the initial
6611 // diagnostic state of the module itself, to cover files that contain no
6612 // explicit transitions (for which we did not serialize anything).
6613 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6614 .StateTransitions.push_back({FirstState, 0});
6615 } else {
6616 // For prefix ASTs, start with whatever the user configured on the
6617 // command line.
6618 Idx++; // Skip flags.
6619 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6620 }
6621
6622 // Read the state transitions.
6623 unsigned NumLocations = Record[Idx++];
6624 while (NumLocations--) {
6625 assert(Idx < Record.size() &&
6626 "Invalid data, missing pragma diagnostic states");
6627 FileID FID = ReadFileID(F, Record, Idx);
6628 assert(FID.isValid() && "invalid FileID for transition");
6629 unsigned Transitions = Record[Idx++];
6630
6631 // Note that we don't need to set up Parent/ParentOffset here, because
6632 // we won't be changing the diagnostic state within imported FileIDs
6633 // (other than perhaps appending to the main source file, which has no
6634 // parent).
6635 auto &F = Diag.DiagStatesByLoc.Files[FID];
6636 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6637 for (unsigned I = 0; I != Transitions; ++I) {
6638 unsigned Offset = Record[Idx++];
6639 auto *State = ReadDiagState(*FirstState, false);
6640 F.StateTransitions.push_back({State, Offset});
6641 }
6642 }
6643
6644 // Read the final state.
6645 assert(Idx < Record.size() &&
6646 "Invalid data, missing final pragma diagnostic state");
6647 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6648 auto *CurState = ReadDiagState(*FirstState, false);
6649
6650 if (!F.isModule()) {
6651 Diag.DiagStatesByLoc.CurDiagState = CurState;
6652 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6653
6654 // Preserve the property that the imaginary root file describes the
6655 // current state.
6656 FileID NullFile;
6657 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6658 if (T.empty())
6659 T.push_back({CurState, 0});
6660 else
6661 T[0].State = CurState;
6662 }
6663
6664 // Don't try to read these mappings again.
6665 Record.clear();
6666 }
6667}
6668
6669/// Get the correct cursor and offset for loading a type.
6670ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6671 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6672 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6673 ModuleFile *M = I->second;
6674 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
6676}
6677
6678static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6679 switch (code) {
6680#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6681 case TYPE_##CODE_ID: return Type::CLASS_ID;
6682#include "clang/Serialization/TypeBitCodes.def"
6683 default:
6684 return std::nullopt;
6685 }
6686}
6687
6688/// Read and return the type with the given index..
6689///
6690/// The index is the type ID, shifted and minus the number of predefs. This
6691/// routine actually reads the record corresponding to the type at the given
6692/// location. It is a helper routine for GetType, which deals with reading type
6693/// IDs.
6694QualType ASTReader::readTypeRecord(unsigned Index) {
6695 assert(ContextObj && "reading type with no AST context");
6696 ASTContext &Context = *ContextObj;
6697 RecordLocation Loc = TypeCursorForIndex(Index);
6698 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6699
6700 // Keep track of where we are in the stream, then jump back there
6701 // after reading this type.
6702 SavedStreamPosition SavedPosition(DeclsCursor);
6703
6704 ReadingKindTracker ReadingKind(Read_Type, *this);
6705
6706 // Note that we are loading a type record.
6707 Deserializing AType(this);
6708
6709 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6710 Error(std::move(Err));
6711 return QualType();
6712 }
6713 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6714 if (!RawCode) {
6715 Error(RawCode.takeError());
6716 return QualType();
6717 }
6718
6719 ASTRecordReader Record(*this, *Loc.F);
6720 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6721 if (!Code) {
6722 Error(Code.takeError());
6723 return QualType();
6724 }
6725 if (Code.get() == TYPE_EXT_QUAL) {
6726 QualType baseType = Record.readQualType();
6727 Qualifiers quals = Record.readQualifiers();
6728 return Context.getQualifiedType(baseType, quals);
6729 }
6730
6731 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6732 if (!maybeClass) {
6733 Error("Unexpected code for type");
6734 return QualType();
6735 }
6736
6738 return TypeReader.read(*maybeClass);
6739}
6740
6741namespace clang {
6742
6743class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6745
6746 ASTRecordReader &Reader;
6747 LocSeq *Seq;
6748
6749 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6750 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6751
6752 TypeSourceInfo *GetTypeSourceInfo() {
6753 return Reader.readTypeSourceInfo();
6754 }
6755
6756 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6757 return Reader.readNestedNameSpecifierLoc();
6758 }
6759
6760 Attr *ReadAttr() {
6761 return Reader.readAttr();
6762 }
6763
6764public:
6766 : Reader(Reader), Seq(Seq) {}
6767
6768 // We want compile-time assurance that we've enumerated all of
6769 // these, so unfortunately we have to declare them first, then
6770 // define them out-of-line.
6771#define ABSTRACT_TYPELOC(CLASS, PARENT)
6772#define TYPELOC(CLASS, PARENT) \
6773 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6774#include "clang/AST/TypeLocNodes.def"
6775
6776 void VisitFunctionTypeLoc(FunctionTypeLoc);
6777 void VisitArrayTypeLoc(ArrayTypeLoc);
6778};
6779
6780} // namespace clang
6781
6782void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6783 // nothing to do
6784}
6785
6786void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6787 TL.setBuiltinLoc(readSourceLocation());
6788 if (TL.needsExtraLocalData()) {
6789 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6790 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6791 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6792 TL.setModeAttr(Reader.readInt());
6793 }
6794}
6795
6796void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6797 TL.setNameLoc(readSourceLocation());
6798}
6799
6800void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6801 TL.setStarLoc(readSourceLocation());
6802}
6803
6804void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6805 // nothing to do
6806}
6807
6808void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6809 // nothing to do
6810}
6811
6812void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6813 // nothing to do
6814}
6815
6816void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6817 TL.setExpansionLoc(readSourceLocation());
6818}
6819
6820void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6821 TL.setCaretLoc(readSourceLocation());
6822}
6823
6824void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6825 TL.setAmpLoc(readSourceLocation());
6826}
6827
6828void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6829 TL.setAmpAmpLoc(readSourceLocation());
6830}
6831
6832void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6833 TL.setStarLoc(readSourceLocation());
6834 TL.setClassTInfo(GetTypeSourceInfo());
6835}
6836
6838 TL.setLBracketLoc(readSourceLocation());
6839 TL.setRBracketLoc(readSourceLocation());
6840 if (Reader.readBool())
6841 TL.setSizeExpr(Reader.readExpr());
6842 else
6843 TL.setSizeExpr(nullptr);
6844}
6845
6846void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6847 VisitArrayTypeLoc(TL);
6848}
6849
6850void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6851 VisitArrayTypeLoc(TL);
6852}
6853
6854void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6855 VisitArrayTypeLoc(TL);
6856}
6857
6858void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6860 VisitArrayTypeLoc(TL);
6861}
6862
6863void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6865
6866 TL.setAttrNameLoc(readSourceLocation());
6867 TL.setAttrOperandParensRange(readSourceRange());
6868 TL.setAttrExprOperand(Reader.readExpr());
6869}
6870
6871void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6873 TL.setNameLoc(readSourceLocation());
6874}
6875
6876void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6877 TL.setNameLoc(readSourceLocation());
6878}
6879
6880void TypeLocReader::VisitDependentVectorTypeLoc(
6882 TL.setNameLoc(readSourceLocation());
6883}
6884
6885void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6886 TL.setNameLoc(readSourceLocation());
6887}
6888
6889void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6890 TL.setAttrNameLoc(readSourceLocation());
6891 TL.setAttrOperandParensRange(readSourceRange());
6892 TL.setAttrRowOperand(Reader.readExpr());
6893 TL.setAttrColumnOperand(Reader.readExpr());
6894}
6895
6896void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6898 TL.setAttrNameLoc(readSourceLocation());
6899 TL.setAttrOperandParensRange(readSourceRange());
6900 TL.setAttrRowOperand(Reader.readExpr());
6901 TL.setAttrColumnOperand(Reader.readExpr());
6902}
6903
6905 TL.setLocalRangeBegin(readSourceLocation());
6906 TL.setLParenLoc(readSourceLocation());
6907 TL.setRParenLoc(readSourceLocation());
6908 TL.setExceptionSpecRange(readSourceRange());
6909 TL.setLocalRangeEnd(readSourceLocation());
6910 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6911 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6912 }
6913}
6914
6915void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6916 VisitFunctionTypeLoc(TL);
6917}
6918
6919void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6920 VisitFunctionTypeLoc(TL);
6921}
6922
6923void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6924 TL.setNameLoc(readSourceLocation());
6925}
6926
6927void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6928 TL.setNameLoc(readSourceLocation());
6929}
6930
6931void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6932 TL.setNameLoc(readSourceLocation());
6933}
6934
6935void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6936 TL.setTypeofLoc(readSourceLocation());
6937 TL.setLParenLoc(readSourceLocation());
6938 TL.setRParenLoc(readSourceLocation());
6939}
6940
6941void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6942 TL.setTypeofLoc(readSourceLocation());
6943 TL.setLParenLoc(readSourceLocation());
6944 TL.setRParenLoc(readSourceLocation());
6945 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6946}
6947
6948void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6949 TL.setDecltypeLoc(readSourceLocation());
6950 TL.setRParenLoc(readSourceLocation());
6951}
6952
6953void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6954 TL.setEllipsisLoc(readSourceLocation());
6955}
6956
6957void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6958 TL.setKWLoc(readSourceLocation());
6959 TL.setLParenLoc(readSourceLocation());
6960 TL.setRParenLoc(readSourceLocation());
6961 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6962}
6963
6965 auto NNS = readNestedNameSpecifierLoc();
6966 auto TemplateKWLoc = readSourceLocation();
6967 auto ConceptNameLoc = readDeclarationNameInfo();
6968 auto FoundDecl = readDeclAs<NamedDecl>();
6969 auto NamedConcept = readDeclAs<ConceptDecl>();
6970 auto *CR = ConceptReference::Create(
6971 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
6972 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
6973 return CR;
6974}
6975
6976void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6977 TL.setNameLoc(readSourceLocation());
6978 if (Reader.readBool())
6979 TL.setConceptReference(Reader.readConceptReference());
6980 if (Reader.readBool())
6981 TL.setRParenLoc(readSourceLocation());
6982}
6983
6984void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6986 TL.setTemplateNameLoc(readSourceLocation());
6987}
6988
6989void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6990 TL.setNameLoc(readSourceLocation());
6991}
6992
6993void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6994 TL.setNameLoc(readSourceLocation());
6995}
6996
6997void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6998 TL.setAttr(ReadAttr());
6999}
7000
7001void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7002 // Nothing to do
7003}
7004
7005void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7006 // Nothing to do.
7007}
7008
7009void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7010 TL.setNameLoc(readSourceLocation());
7011}
7012
7013void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7015 TL.setNameLoc(readSourceLocation());
7016}
7017
7018void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7020 TL.setNameLoc(readSourceLocation());
7021}
7022
7023void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7025 TL.setTemplateKeywordLoc(readSourceLocation());
7026 TL.setTemplateNameLoc(readSourceLocation());
7027 TL.setLAngleLoc(readSourceLocation());
7028 TL.setRAngleLoc(readSourceLocation());
7029 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7030 TL.setArgLocInfo(i,
7031 Reader.readTemplateArgumentLocInfo(
7032 TL.getTypePtr()->template_arguments()[i].getKind()));
7033}
7034
7035void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7036 TL.setLParenLoc(readSourceLocation());
7037 TL.setRParenLoc(readSourceLocation());
7038}
7039
7040void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7041 TL.setElaboratedKeywordLoc(readSourceLocation());
7042 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7043}
7044
7045void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7046 TL.setNameLoc(readSourceLocation());
7047}
7048
7049void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7050 TL.setElaboratedKeywordLoc(readSourceLocation());
7051 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7052 TL.setNameLoc(readSourceLocation());
7053}
7054
7055void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7057 TL.setElaboratedKeywordLoc(readSourceLocation());
7058 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7059 TL.setTemplateKeywordLoc(readSourceLocation());
7060 TL.setTemplateNameLoc(readSourceLocation());
7061 TL.setLAngleLoc(readSourceLocation());
7062 TL.setRAngleLoc(readSourceLocation());
7063 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7064 TL.setArgLocInfo(I,
7065 Reader.readTemplateArgumentLocInfo(
7066 TL.getTypePtr()->template_arguments()[I].getKind()));
7067}
7068
7069void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7070 TL.setEllipsisLoc(readSourceLocation());
7071}
7072
7073void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7074 TL.setNameLoc(readSourceLocation());
7075 TL.setNameEndLoc(readSourceLocation());
7076}
7077
7078void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7079 if (TL.getNumProtocols()) {
7080 TL.setProtocolLAngleLoc(readSourceLocation());
7081 TL.setProtocolRAngleLoc(readSourceLocation());
7082 }
7083 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7084 TL.setProtocolLoc(i, readSourceLocation());
7085}
7086
7087void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7088 TL.setHasBaseTypeAsWritten(Reader.readBool());
7089 TL.setTypeArgsLAngleLoc(readSourceLocation());
7090 TL.setTypeArgsRAngleLoc(readSourceLocation());
7091 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7092 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7093 TL.setProtocolLAngleLoc(readSourceLocation());
7094 TL.setProtocolRAngleLoc(readSourceLocation());
7095 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7096 TL.setProtocolLoc(i, readSourceLocation());
7097}
7098
7099void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7100 TL.setStarLoc(readSourceLocation());
7101}
7102
7103void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7104 TL.setKWLoc(readSourceLocation());
7105 TL.setLParenLoc(readSourceLocation());
7106 TL.setRParenLoc(readSourceLocation());
7107}
7108
7109void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7110 TL.setKWLoc(readSourceLocation());
7111}
7112
7113void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7114 TL.setNameLoc(readSourceLocation());
7115}
7116void TypeLocReader::VisitDependentBitIntTypeLoc(
7118 TL.setNameLoc(readSourceLocation());
7119}
7120
7122 LocSeq::State Seq(ParentSeq);
7123 TypeLocReader TLR(*this, Seq);
7124 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7125 TLR.Visit(TL);
7126}
7127
7129 QualType InfoTy = readType();
7130 if (InfoTy.isNull())
7131 return nullptr;
7132
7133 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7134 readTypeLoc(TInfo->getTypeLoc());
7135 return TInfo;
7136}
7137
7139 assert(ContextObj && "reading type with no AST context");
7140 ASTContext &Context = *ContextObj;
7141
7142 unsigned FastQuals = ID & Qualifiers::FastMask;
7143 unsigned Index = ID >> Qualifiers::FastWidth;
7144
7145 if (Index < NUM_PREDEF_TYPE_IDS) {
7146 QualType T;
7147 switch ((PredefinedTypeIDs)Index) {
7149 // We should never use this one.
7150 llvm_unreachable("Invalid predefined type");
7151 break;
7153 return QualType();
7155 T = Context.VoidTy;
7156 break;
7158 T = Context.BoolTy;
7159 break;
7162 // FIXME: Check that the signedness of CharTy is correct!
7163 T = Context.CharTy;
7164 break;
7166 T = Context.UnsignedCharTy;
7167 break;
7169 T = Context.UnsignedShortTy;
7170 break;
7172 T = Context.UnsignedIntTy;
7173 break;
7175 T = Context.UnsignedLongTy;
7176 break;
7178 T = Context.UnsignedLongLongTy;
7179 break;
7181 T = Context.UnsignedInt128Ty;
7182 break;
7184 T = Context.SignedCharTy;
7185 break;
7187 T = Context.WCharTy;
7188 break;
7190 T = Context.ShortTy;
7191 break;
7192 case PREDEF_TYPE_INT_ID:
7193 T = Context.IntTy;
7194 break;
7196 T = Context.LongTy;
7197 break;
7199 T = Context.LongLongTy;
7200 break;
7202 T = Context.Int128Ty;
7203 break;
7205 T = Context.BFloat16Ty;
7206 break;
7208 T = Context.HalfTy;
7209 break;
7211 T = Context.FloatTy;
7212 break;
7214 T = Context.DoubleTy;
7215 break;
7217 T = Context.LongDoubleTy;
7218 break;
7220 T = Context.ShortAccumTy;
7221 break;
7223 T = Context.AccumTy;
7224 break;
7226 T = Context.LongAccumTy;
7227 break;
7229 T = Context.UnsignedShortAccumTy;
7230 break;
7232 T = Context.UnsignedAccumTy;
7233 break;
7235 T = Context.UnsignedLongAccumTy;
7236 break;
7238 T = Context.ShortFractTy;
7239 break;
7241 T = Context.FractTy;
7242 break;
7244 T = Context.LongFractTy;
7245 break;
7247 T = Context.UnsignedShortFractTy;
7248 break;
7250 T = Context.UnsignedFractTy;
7251 break;
7253 T = Context.UnsignedLongFractTy;
7254 break;
7256 T = Context.SatShortAccumTy;
7257 break;
7259 T = Context.SatAccumTy;
7260 break;
7262 T = Context.SatLongAccumTy;
7263 break;
7265 T = Context.SatUnsignedShortAccumTy;
7266 break;
7268 T = Context.SatUnsignedAccumTy;
7269 break;
7271 T = Context.SatUnsignedLongAccumTy;
7272 break;
7274 T = Context.SatShortFractTy;
7275 break;
7277 T = Context.SatFractTy;
7278 break;
7280 T = Context.SatLongFractTy;
7281 break;
7283 T = Context.SatUnsignedShortFractTy;
7284 break;
7286 T = Context.SatUnsignedFractTy;
7287 break;
7289 T = Context.SatUnsignedLongFractTy;
7290 break;
7292 T = Context.Float16Ty;
7293 break;
7295 T = Context.Float128Ty;
7296 break;
7298 T = Context.Ibm128Ty;
7299 break;
7301 T = Context.OverloadTy;
7302 break;
7304 T = Context.UnresolvedTemplateTy;
7305 break;
7307 T = Context.BoundMemberTy;
7308 break;
7310 T = Context.PseudoObjectTy;
7311 break;
7313 T = Context.DependentTy;
7314 break;
7316 T = Context.UnknownAnyTy;
7317 break;
7319 T = Context.NullPtrTy;
7320 break;
7322 T = Context.Char8Ty;
7323 break;
7325 T = Context.Char16Ty;
7326 break;
7328 T = Context.Char32Ty;
7329 break;
7331 T = Context.ObjCBuiltinIdTy;
7332 break;
7334 T = Context.ObjCBuiltinClassTy;
7335 break;
7337 T = Context.ObjCBuiltinSelTy;
7338 break;
7339#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7340 case PREDEF_TYPE_##Id##_ID: \
7341 T = Context.SingletonId; \
7342 break;
7343#include "clang/Basic/OpenCLImageTypes.def"
7344#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7345 case PREDEF_TYPE_##Id##_ID: \
7346 T = Context.Id##Ty; \
7347 break;
7348#include "clang/Basic/OpenCLExtensionTypes.def"
7350 T = Context.OCLSamplerTy;
7351 break;
7353 T = Context.OCLEventTy;
7354 break;
7356 T = Context.OCLClkEventTy;
7357 break;
7359 T = Context.OCLQueueTy;
7360 break;
7362 T = Context.OCLReserveIDTy;
7363 break;
7365 T = Context.getAutoDeductType();
7366 break;
7368 T = Context.getAutoRRefDeductType();
7369 break;
7371 T = Context.ARCUnbridgedCastTy;
7372 break;
7374 T = Context.BuiltinFnTy;
7375 break;
7377 T = Context.IncompleteMatrixIdxTy;
7378 break;
7380 T = Context.ArraySectionTy;
7381 break;
7383 T = Context.OMPArrayShapingTy;
7384 break;
7386 T = Context.OMPIteratorTy;
7387 break;
7388#define SVE_TYPE(Name, Id, SingletonId) \
7389 case PREDEF_TYPE_##Id##_ID: \
7390 T = Context.SingletonId; \
7391 break;
7392#include "clang/Basic/AArch64SVEACLETypes.def"
7393#define PPC_VECTOR_TYPE(Name, Id, Size) \
7394 case PREDEF_TYPE_##Id##_ID: \
7395 T = Context.Id##Ty; \
7396 break;
7397#include "clang/Basic/PPCTypes.def"
7398#define RVV_TYPE(Name, Id, SingletonId) \
7399 case PREDEF_TYPE_##Id##_ID: \
7400 T = Context.SingletonId; \
7401 break;
7402#include "clang/Basic/RISCVVTypes.def"
7403#define WASM_TYPE(Name, Id, SingletonId) \
7404 case PREDEF_TYPE_##Id##_ID: \
7405 T = Context.SingletonId; \
7406 break;
7407#include "clang/Basic/WebAssemblyReferenceTypes.def"
7408 }
7409
7410 assert(!T.isNull() && "Unknown predefined type");
7411 return T.withFastQualifiers(FastQuals);
7412 }
7413
7414 Index -= NUM_PREDEF_TYPE_IDS;
7415 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7416 if (TypesLoaded[Index].isNull()) {
7417 TypesLoaded[Index] = readTypeRecord(Index);
7418 if (TypesLoaded[Index].isNull())
7419 return QualType();
7420
7421 TypesLoaded[Index]->setFromAST();
7422 if (DeserializationListener)
7423 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7424 TypesLoaded[Index]);
7425 }
7426
7427 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7428}
7429
7431 return GetType(getGlobalTypeID(F, LocalID));
7432}
7433
7435ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7436 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7437 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7438
7439 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7440 return LocalID;
7441
7442 if (!F.ModuleOffsetMap.empty())
7443 ReadModuleOffsetMap(F);
7444
7446 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7447 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7448
7449 unsigned GlobalIndex = LocalIndex + I->second;
7450 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7451}
7452
7455 switch (Kind) {
7457 return readExpr();
7459 return readTypeSourceInfo();
7461 NestedNameSpecifierLoc QualifierLoc =
7462 readNestedNameSpecifierLoc();
7463 SourceLocation TemplateNameLoc = readSourceLocation();
7464 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7465 TemplateNameLoc, SourceLocation());
7466 }
7468 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7469 SourceLocation TemplateNameLoc = readSourceLocation();
7470 SourceLocation EllipsisLoc = readSourceLocation();
7471 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7472 TemplateNameLoc, EllipsisLoc);
7473 }
7480 // FIXME: Is this right?
7481 return TemplateArgumentLocInfo();
7482 }
7483 llvm_unreachable("unexpected template argument loc");
7484}
7485
7487 TemplateArgument Arg = readTemplateArgument();
7488
7490 if (readBool()) // bool InfoHasSameExpr.
7492 }
7493 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7494}
7495
7498 Result.setLAngleLoc(readSourceLocation());
7499 Result.setRAngleLoc(readSourceLocation());
7500 unsigned NumArgsAsWritten = readInt();
7501 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7502 Result.addArgument(readTemplateArgumentLoc());
7503}
7504
7508 readTemplateArgumentListInfo(Result);
7509 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7510}
7511
7513
7515 if (NumCurrentElementsDeserializing) {
7516 // We arrange to not care about the complete redeclaration chain while we're
7517 // deserializing. Just remember that the AST has marked this one as complete
7518 // but that it's not actually complete yet, so we know we still need to
7519 // complete it later.
7520 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7521 return;
7522 }
7523
7524 if (!D->getDeclContext()) {
7525 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7526 return;
7527 }
7528
7529 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7530
7531 // If this is a named declaration, complete it by looking it up
7532 // within its context.
7533 //
7534 // FIXME: Merging a function definition should merge
7535 // all mergeable entities within it.
7536 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7537 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7538 if (!getContext().getLangOpts().CPlusPlus &&
7539 isa<TranslationUnitDecl>(DC)) {
7540 // Outside of C++, we don't have a lookup table for the TU, so update
7541 // the identifier instead. (For C++ modules, we don't store decls
7542 // in the serialized identifier table, so we do the lookup in the TU.)
7543 auto *II = Name.getAsIdentifierInfo();
7544 assert(II && "non-identifier name in C?");
7545 if (II->isOutOfDate())
7546 updateOutOfDateIdentifier(*II);
7547 } else
7548 DC->lookup(Name);
7549 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7550 // Find all declarations of this kind from the relevant context.
7551 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7552 auto *DC = cast<DeclContext>(DCDecl);
7554 FindExternalLexicalDecls(
7555 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7556 }
7557 }
7558 }
7559
7560 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7561 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7562 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7563 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7564 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7565 if (auto *Template = FD->getPrimaryTemplate())
7566 Template->LoadLazySpecializations();
7567 }
7568}
7569
7572 RecordLocation Loc = getLocalBitOffset(Offset);
7573 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7574 SavedStreamPosition SavedPosition(Cursor);
7575 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7576 Error(std::move(Err));
7577 return nullptr;
7578 }
7579 ReadingKindTracker ReadingKind(Read_Decl, *this);
7580 Deserializing D(this);
7581
7582 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7583 if (!MaybeCode) {
7584 Error(MaybeCode.takeError());
7585 return nullptr;
7586 }
7587 unsigned Code = MaybeCode.get();
7588
7589 ASTRecordReader Record(*this, *Loc.F);
7590 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7591 if (!MaybeRecCode) {
7592 Error(MaybeRecCode.takeError());
7593 return nullptr;
7594 }
7595 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7596 Error("malformed AST file: missing C++ ctor initializers");
7597 return nullptr;
7598 }
7599
7600 return Record.readCXXCtorInitializers();
7601}
7602
7604 assert(ContextObj && "reading base specifiers with no AST context");
7605 ASTContext &Context = *ContextObj;
7606
7607 RecordLocation Loc = getLocalBitOffset(Offset);
7608 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7609 SavedStreamPosition SavedPosition(Cursor);
7610 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7611 Error(std::move(Err));
7612 return nullptr;
7613 }
7614 ReadingKindTracker ReadingKind(Read_Decl, *this);
7615 Deserializing D(this);
7616
7617 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7618 if (!MaybeCode) {
7619 Error(MaybeCode.takeError());
7620 return nullptr;
7621 }
7622 unsigned Code = MaybeCode.get();
7623
7624 ASTRecordReader Record(*this, *Loc.F);
7625 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7626 if (!MaybeRecCode) {
7627 Error(MaybeCode.takeError());
7628 return nullptr;
7629 }
7630 unsigned RecCode = MaybeRecCode.get();
7631
7632 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7633 Error("malformed AST file: missing C++ base specifiers");
7634 return nullptr;
7635 }
7636
7637 unsigned NumBases = Record.readInt();
7638 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7639 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7640 for (unsigned I = 0; I != NumBases; ++I)
7641 Bases[I] = Record.readCXXBaseSpecifier();
7642 return Bases;
7643}
7644
7646 LocalDeclID LocalID) const {
7647 DeclID ID = LocalID.get();
7648 if (ID < NUM_PREDEF_DECL_IDS)
7649 return GlobalDeclID(ID);
7650
7651 if (!F.ModuleOffsetMap.empty())
7652 ReadModuleOffsetMap(F);
7653
7656 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7657
7658 return GlobalDeclID(ID + I->second);
7659}
7660
7662 // Predefined decls aren't from any module.
7663 if (ID.get() < NUM_PREDEF_DECL_IDS)
7664 return false;
7665
7666 return ID.get() - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7667 ID.get() - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7668}
7669
7671 if (!D->isFromASTFile())
7672 return nullptr;
7674 GlobalDeclMap.find(GlobalDeclID(D->getGlobalID()));
7675 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7676 return I->second;
7677}
7678
7680 if (ID.get() < NUM_PREDEF_DECL_IDS)
7681 return SourceLocation();
7682
7683 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7684
7685 if (Index > DeclsLoaded.size()) {
7686 Error("declaration ID out-of-range for AST file");
7687 return SourceLocation();
7688 }
7689
7690 if (Decl *D = DeclsLoaded[Index])
7691 return D->getLocation();
7692
7694 DeclCursorForID(ID, Loc);
7695 return Loc;
7696}
7697
7699 switch (ID) {
7701 return nullptr;
7702
7704 return Context.getTranslationUnitDecl();
7705
7707 return Context.getObjCIdDecl();
7708
7710 return Context.getObjCSelDecl();
7711
7713 return Context.getObjCClassDecl();
7714
7716 return Context.getObjCProtocolDecl();
7717
7719 return Context.getInt128Decl();
7720
7722 return Context.getUInt128Decl();
7723
7725 return Context.getObjCInstanceTypeDecl();
7726
7728 return Context.getBuiltinVaListDecl();
7729
7731 return Context.getVaListTagDecl();
7732
7734 return Context.getBuiltinMSVaListDecl();
7735
7737 return Context.getMSGuidTagDecl();
7738
7740 return Context.getExternCContextDecl();
7741
7743 return Context.getMakeIntegerSeqDecl();
7744
7746 return Context.getCFConstantStringDecl();
7747
7749 return Context.getCFConstantStringTagDecl();
7750
7752 return Context.getTypePackElementDecl();
7753 }
7754 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7755}
7756
7758 assert(ContextObj && "reading decl with no AST context");
7759 if (ID.get() < NUM_PREDEF_DECL_IDS) {
7760 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7761 if (D) {
7762 // Track that we have merged the declaration with ID \p ID into the
7763 // pre-existing predefined declaration \p D.
7764 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7765 if (Merged.empty())
7766 Merged.push_back(ID);
7767 }
7768 return D;
7769 }
7770
7771 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7772
7773 if (Index >= DeclsLoaded.size()) {
7774 assert(0 && "declaration ID out-of-range for AST file");
7775 Error("declaration ID out-of-range for AST file");
7776 return nullptr;
7777 }
7778
7779 return DeclsLoaded[Index];
7780}
7781
7783 if (ID.get() < NUM_PREDEF_DECL_IDS)
7784 return GetExistingDecl(ID);
7785
7786 unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7787
7788 if (Index >= DeclsLoaded.size()) {
7789 assert(0 && "declaration ID out-of-range for AST file");
7790 Error("declaration ID out-of-range for AST file");
7791 return nullptr;
7792 }
7793
7794 if (!DeclsLoaded[Index]) {
7795 ReadDeclRecord(ID);
7796 if (DeserializationListener)
7797 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7798 }
7799
7800 return DeclsLoaded[Index];
7801}
7802
7804 GlobalDeclID GlobalID) {
7805 DeclID ID = GlobalID.get();
7806 if (ID < NUM_PREDEF_DECL_IDS)
7807 return LocalDeclID(ID);
7808
7809 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7810 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7811 ModuleFile *Owner = I->second;
7812
7813 llvm::DenseMap<ModuleFile *, DeclID>::iterator Pos =
7814 M.GlobalToLocalDeclIDs.find(Owner);
7815 if (Pos == M.GlobalToLocalDeclIDs.end())
7816 return LocalDeclID();
7817
7818 return LocalDeclID(ID - Owner->BaseDeclID + Pos->second);
7819}
7820
7822 unsigned &Idx) {
7823 if (Idx >= Record.size()) {
7824 Error("Corrupted AST file");
7825 return GlobalDeclID(0);
7826 }
7827
7828 return getGlobalDeclID(F, LocalDeclID(Record[Idx++]));
7829}
7830
7831/// Resolve the offset of a statement into a statement.
7832///
7833/// This operation will read a new statement from the external
7834/// source each time it is called, and is meant to be used via a
7835/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7837 // Switch case IDs are per Decl.
7838 ClearSwitchCaseIDs();
7839
7840 // Offset here is a global offset across the entire chain.
7841 RecordLocation Loc = getLocalBitOffset(Offset);
7842 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7843 Error(std::move(Err));
7844 return nullptr;
7845 }
7846 assert(NumCurrentElementsDeserializing == 0 &&
7847 "should not be called while already deserializing");
7848 Deserializing D(this);
7849 return ReadStmtFromStream(*Loc.F);
7850}
7851
7853 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7854 SmallVectorImpl<Decl *> &Decls) {
7855 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7856
7857 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7858 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7859 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7860 auto K = (Decl::Kind)+LexicalDecls[I];
7861 if (!IsKindWeWant(K))
7862 continue;
7863
7864 auto ID = (DeclID) + LexicalDecls[I + 1];
7865
7866 // Don't add predefined declarations to the lexical context more
7867 // than once.
7868 if (ID < NUM_PREDEF_DECL_IDS) {
7869 if (PredefsVisited[ID])
7870 continue;
7871
7872 PredefsVisited[ID] = true;
7873 }
7874
7875 if (Decl *D = GetLocalDecl(*M, LocalDeclID(ID))) {
7876 assert(D->getKind() == K && "wrong kind for lexical decl");
7877 if (!DC->isDeclInLexicalTraversal(D))
7878 Decls.push_back(D);
7879 }
7880 }
7881 };
7882
7883 if (isa<TranslationUnitDecl>(DC)) {
7884 for (const auto &Lexical : TULexicalDecls)
7885 Visit(Lexical.first, Lexical.second);
7886 } else {
7887 auto I = LexicalDecls.find(DC);
7888 if (I != LexicalDecls.end())
7889 Visit(I->second.first, I->second.second);
7890 }
7891
7892 ++NumLexicalDeclContextsRead;
7893}
7894
7895namespace {
7896
7897class DeclIDComp {
7898 ASTReader &Reader;
7899 ModuleFile &Mod;
7900
7901public:
7902 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7903
7904 bool operator()(LocalDeclID L, LocalDeclID R) const {
7905 SourceLocation LHS = getLocation(L);
7906 SourceLocation RHS = getLocation(R);
7907 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7908 }
7909
7910 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7911 SourceLocation RHS = getLocation(R);
7912 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7913 }
7914
7915 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7916 SourceLocation LHS = getLocation(L);
7917 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7918 }
7919
7920 SourceLocation getLocation(LocalDeclID ID) const {
7921 return Reader.getSourceManager().getFileLoc(
7922 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7923 }
7924};
7925
7926} // namespace
7927
7929 unsigned Offset, unsigned Length,
7930 SmallVectorImpl<Decl *> &Decls) {
7931 SourceManager &SM = getSourceManager();
7932
7933 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7934 if (I == FileDeclIDs.end())
7935 return;
7936
7937 FileDeclsInfo &DInfo = I->second;
7938 if (DInfo.Decls.empty())
7939 return;
7940
7942 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7943 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7944
7945 DeclIDComp DIDComp(*this, *DInfo.Mod);
7947 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7948 if (BeginIt != DInfo.Decls.begin())
7949 --BeginIt;
7950
7951 // If we are pointing at a top-level decl inside an objc container, we need
7952 // to backtrack until we find it otherwise we will fail to report that the
7953 // region overlaps with an objc container.
7954 while (BeginIt != DInfo.Decls.begin() &&
7955 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7956 ->isTopLevelDeclInObjCContainer())
7957 --BeginIt;
7958
7960 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7961 if (EndIt != DInfo.Decls.end())
7962 ++EndIt;
7963
7964 for (ArrayRef<LocalDeclID>::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
7965 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7966}
7967
7968bool
7970 DeclarationName Name) {
7971 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7972 "DeclContext has no visible decls in storage");
7973 if (!Name)
7974 return false;
7975
7976 auto It = Lookups.find(DC);
7977 if (It == Lookups.end())
7978 return false;
7979
7980 Deserializing LookupResults(this);
7981
7982 // Load the list of declarations.
7985
7986 for (GlobalDeclID ID : It->second.Table.find(Name)) {
7987 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7988 if (ND->getDeclName() == Name && Found.insert(ND).second)
7989 Decls.push_back(ND);
7990 }
7991
7992 ++NumVisibleDeclContextsRead;
7993 SetExternalVisibleDeclsForName(DC, Name, Decls);
7994 return !Decls.empty();
7995}
7996
7998 if (!DC->hasExternalVisibleStorage())
7999 return;
8000
8001 auto It = Lookups.find(DC);
8002 assert(It != Lookups.end() &&
8003 "have external visible storage but no lookup tables");
8004
8005 DeclsMap Decls;
8006
8007 for (GlobalDeclID ID : It->second.Table.findAll()) {
8008 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8009 Decls[ND->getDeclName()].push_back(ND);
8010 }
8011
8012 ++NumVisibleDeclContextsRead;
8013
8014 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8015 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8016 }
8017 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8018}
8019
8022 auto I = Lookups.find(Primary);
8023 return I == Lookups.end() ? nullptr : &I->second;
8024}
8025
8026/// Under non-PCH compilation the consumer receives the objc methods
8027/// before receiving the implementation, and codegen depends on this.
8028/// We simulate this by deserializing and passing to consumer the methods of the
8029/// implementation before passing the deserialized implementation decl.
8031 ASTConsumer *Consumer) {
8032 assert(ImplD && Consumer);
8033
8034 for (auto *I : ImplD->methods())
8035 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8036
8037 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8038}
8039
8040void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8041 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8042 PassObjCImplDeclToConsumer(ImplD, Consumer);
8043 else
8044 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8045}
8046
8048 this->Consumer = Consumer;
8049
8050 if (Consumer)
8051 PassInterestingDeclsToConsumer();
8052
8053 if (DeserializationListener)
8054 DeserializationListener->ReaderInitialized(this);
8055}
8056
8058 std::fprintf(stderr, "*** AST File Statistics:\n");
8059
8060 unsigned NumTypesLoaded =
8061 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8062 unsigned NumDeclsLoaded =
8063 DeclsLoaded.size() -
8064 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8065 unsigned NumIdentifiersLoaded =
8066 IdentifiersLoaded.size() -
8067 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8068 unsigned NumMacrosLoaded =
8069 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8070 unsigned NumSelectorsLoaded =
8071 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8072
8073 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8074 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8075 NumSLocEntriesRead, TotalNumSLocEntries,
8076 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8077 if (!TypesLoaded.empty())
8078 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8079 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8080 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8081 if (!DeclsLoaded.empty())
8082 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8083 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8084 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8085 if (!IdentifiersLoaded.empty())
8086 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8087 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8088 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8089 if (!MacrosLoaded.empty())
8090 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8091 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8092 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8093 if (!SelectorsLoaded.empty())
8094 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8095 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8096 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8097 if (TotalNumStatements)
8098 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8099 NumStatementsRead, TotalNumStatements,
8100 ((float)NumStatementsRead/TotalNumStatements * 100));
8101 if (TotalNumMacros)
8102 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8103 NumMacrosRead, TotalNumMacros,
8104 ((float)NumMacrosRead/TotalNumMacros * 100));
8105 if (TotalLexicalDeclContexts)
8106 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8107 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8108 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8109 * 100));
8110 if (TotalVisibleDeclContexts)
8111 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8112 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8113 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8114 * 100));
8115 if (TotalNumMethodPoolEntries)
8116 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8117 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8118 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8119 * 100));
8120 if (NumMethodPoolLookups)
8121 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8122 NumMethodPoolHits, NumMethodPoolLookups,
8123 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8124 if (NumMethodPoolTableLookups)
8125 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8126 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8127 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8128 * 100.0));
8129 if (NumIdentifierLookupHits)
8130 std::fprintf(stderr,
8131 " %u / %u identifier table lookups succeeded (%f%%)\n",
8132 NumIdentifierLookupHits, NumIdentifierLookups,
8133 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8134
8135 if (GlobalIndex) {
8136 std::fprintf(stderr, "\n");
8137 GlobalIndex->printStats();
8138 }
8139
8140 std::fprintf(stderr, "\n");
8141 dump();
8142 std::fprintf(stderr, "\n");
8143}
8144
8145template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8146LLVM_DUMP_METHOD static void
8147dumpModuleIDMap(StringRef Name,
8148 const ContinuousRangeMap<Key, ModuleFile *,
8149 InitialCapacity> &Map) {
8150 if (Map.begin() == Map.end())
8151 return;
8152
8154
8155 llvm::errs() << Name << ":\n";
8156 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8157 I != IEnd; ++I) {
8158 uint64_t ID = 0;
8159 if constexpr (std::is_integral_v<Key>)
8160 ID = I->first;
8161 else /*GlobalDeclID*/
8162 ID = I->first.get();
8163 llvm::errs() << " " << ID << " -> " << I->second->FileName << "\n";
8164 }
8165}
8166
8167LLVM_DUMP_METHOD void ASTReader::dump() {
8168 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8169 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8170 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8171 dumpModuleIDMap("Global type map", GlobalTypeMap);
8172 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8173 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8174 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8175 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8176 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8177 dumpModuleIDMap("Global preprocessed entity map",
8178 GlobalPreprocessedEntityMap);
8179
8180 llvm::errs() << "\n*** PCH/Modules Loaded:";
8181 for (ModuleFile &M : ModuleMgr)
8182 M.dump();
8183}
8184
8185/// Return the amount of memory used by memory buffers, breaking down
8186/// by heap-backed versus mmap'ed memory.
8188 for (ModuleFile &I : ModuleMgr) {
8189 if (llvm::MemoryBuffer *buf = I.Buffer) {
8190 size_t bytes = buf->getBufferSize();
8191 switch (buf->getBufferKind()) {
8192 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8193 sizes.malloc_bytes += bytes;
8194 break;
8195 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8196 sizes.mmap_bytes += bytes;
8197 break;
8198 }
8199 }
8200 }
8201}
8202
8204 SemaObj = &S;
8205 S.addExternalSource(this);
8206
8207 // Makes sure any declarations that were deserialized "too early"
8208 // still get added to the identifier's declaration chains.
8209 for (GlobalDeclID ID : PreloadedDeclIDs) {
8210 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8211 pushExternalDeclIntoScope(D, D->getDeclName());
8212 }
8213 PreloadedDeclIDs.clear();
8214
8215 // FIXME: What happens if these are changed by a module import?
8216 if (!FPPragmaOptions.empty()) {
8217 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8218 FPOptionsOverride NewOverrides =
8219 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8220 SemaObj->CurFPFeatures =
8221 NewOverrides.applyOverrides(SemaObj->getLangOpts());
8222 }
8223
8224 SemaObj->OpenCLFeatures = OpenCLExtensions;
8225
8226 UpdateSema();
8227}
8228
8230 assert(SemaObj && "no Sema to update");
8231
8232 // Load the offsets of the declarations that Sema references.
8233 // They will be lazily deserialized when needed.
8234 if (!SemaDeclRefs.empty()) {
8235 assert(SemaDeclRefs.size() % 3 == 0);
8236 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8237 if (!SemaObj->StdNamespace)
8238 SemaObj->StdNamespace = SemaDeclRefs[I].get();
8239 if (!SemaObj->StdBadAlloc)
8240 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].get();
8241 if (!SemaObj->StdAlignValT)
8242 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].get();
8243 }
8244 SemaDeclRefs.clear();
8245 }
8246
8247 // Update the state of pragmas. Use the same API as if we had encountered the
8248 // pragma in the source.
8249 if(OptimizeOffPragmaLocation.isValid())
8250 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8251 if (PragmaMSStructState != -1)
8252 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8253 if (PointersToMembersPragmaLocation.isValid()) {
8254 SemaObj->ActOnPragmaMSPointersToMembers(
8256 PragmaMSPointersToMembersState,
8257 PointersToMembersPragmaLocation);
8258 }
8259 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8260
8261 if (PragmaAlignPackCurrentValue) {
8262 // The bottom of the stack might have a default value. It must be adjusted
8263 // to the current value to ensure that the packing state is preserved after
8264 // popping entries that were included/imported from a PCH/module.
8265 bool DropFirst = false;
8266 if (!PragmaAlignPackStack.empty() &&
8267 PragmaAlignPackStack.front().Location.isInvalid()) {
8268 assert(PragmaAlignPackStack.front().Value ==
8269 SemaObj->AlignPackStack.DefaultValue &&
8270 "Expected a default alignment value");
8271 SemaObj->AlignPackStack.Stack.emplace_back(
8272 PragmaAlignPackStack.front().SlotLabel,
8273 SemaObj->AlignPackStack.CurrentValue,
8274 SemaObj->AlignPackStack.CurrentPragmaLocation,
8275 PragmaAlignPackStack.front().PushLocation);
8276 DropFirst = true;
8277 }
8278 for (const auto &Entry :
8279 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8280 SemaObj->AlignPackStack.Stack.emplace_back(
8281 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8282 }
8283 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8284 assert(*PragmaAlignPackCurrentValue ==
8285 SemaObj->AlignPackStack.DefaultValue &&
8286 "Expected a default align and pack value");
8287 // Keep the current values.
8288 } else {
8289 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8290 SemaObj->AlignPackStack.CurrentPragmaLocation =
8291 PragmaAlignPackCurrentLocation;
8292 }
8293 }
8294 if (FpPragmaCurrentValue) {
8295 // The bottom of the stack might have a default value. It must be adjusted
8296 // to the current value to ensure that fp-pragma state is preserved after
8297 // popping entries that were included/imported from a PCH/module.
8298 bool DropFirst = false;
8299 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8300 assert(FpPragmaStack.front().Value ==
8301 SemaObj->FpPragmaStack.DefaultValue &&
8302 "Expected a default pragma float_control value");
8303 SemaObj->FpPragmaStack.Stack.emplace_back(
8304 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8305 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8306 FpPragmaStack.front().PushLocation);
8307 DropFirst = true;
8308 }
8309 for (const auto &Entry :
8310 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8311 SemaObj->FpPragmaStack.Stack.emplace_back(
8312 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8313 if (FpPragmaCurrentLocation.isInvalid()) {
8314 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8315 "Expected a default pragma float_control value");
8316 // Keep the current values.
8317 } else {
8318 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8319 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8320 }
8321 }
8322
8323 // For non-modular AST files, restore visiblity of modules.
8324 for (auto &Import : PendingImportedModulesSema) {
8325 if (Import.ImportLoc.isInvalid())
8326 continue;
8327 if (Module *Imported = getSubmodule(Import.ID)) {
8328 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8329 }
8330 }
8331 PendingImportedModulesSema.clear();
8332}
8333
8335 // Note that we are loading an identifier.
8336 Deserializing AnIdentifier(this);
8337
8338 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8339 NumIdentifierLookups,
8340 NumIdentifierLookupHits);
8341
8342 // We don't need to do identifier table lookups in C++ modules (we preload
8343 // all interesting declarations, and don't need to use the scope for name
8344 // lookups). Perform the lookup in PCH files, though, since we don't build
8345 // a complete initial identifier table if we're carrying on from a PCH.
8346 if (PP.getLangOpts().CPlusPlus) {
8347 for (auto *F : ModuleMgr.pch_modules())
8348 if (Visitor(*F))
8349 break;
8350 } else {
8351 // If there is a global index, look there first to determine which modules
8352 // provably do not have any results for this identifier.
8354 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8355 if (!loadGlobalIndex()) {
8356 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8357 HitsPtr = &Hits;
8358 }
8359 }
8360
8361 ModuleMgr.visit(Visitor, HitsPtr);
8362 }
8363
8364 IdentifierInfo *II = Visitor.getIdentifierInfo();
8365 markIdentifierUpToDate(II);
8366 return II;
8367}
8368
8369namespace clang {
8370
8371 /// An identifier-lookup iterator that enumerates all of the
8372 /// identifiers stored within a set of AST files.
8374 /// The AST reader whose identifiers are being enumerated.
8375 const ASTReader &Reader;
8376
8377 /// The current index into the chain of AST files stored in
8378 /// the AST reader.
8379 unsigned Index;
8380
8381 /// The current position within the identifier lookup table
8382 /// of the current AST file.
8383 ASTIdentifierLookupTable::key_iterator Current;
8384
8385 /// The end position within the identifier lookup table of
8386 /// the current AST file.
8387 ASTIdentifierLookupTable::key_iterator End;
8388
8389 /// Whether to skip any modules in the ASTReader.
8390 bool SkipModules;
8391
8392 public:
8393 explicit ASTIdentifierIterator(const ASTReader &Reader,
8394 bool SkipModules = false);
8395
8396 StringRef Next() override;
8397 };
8398
8399} // namespace clang
8400
8402 bool SkipModules)
8403 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8404}
8405
8407 while (Current == End) {
8408 // If we have exhausted all of our AST files, we're done.
8409 if (Index == 0)
8410 return StringRef();
8411
8412 --Index;
8413 ModuleFile &F = Reader.ModuleMgr[Index];
8414 if (SkipModules && F.isModule())
8415 continue;
8416
8417 ASTIdentifierLookupTable *IdTable =
8419 Current = IdTable->key_begin();
8420 End = IdTable->key_end();
8421 }
8422
8423 // We have any identifiers remaining in the current AST file; return
8424 // the next one.
8425 StringRef Result = *Current;
8426 ++Current;
8427 return Result;
8428}
8429
8430namespace {
8431
8432/// A utility for appending two IdentifierIterators.
8433class ChainedIdentifierIterator : public IdentifierIterator {
8434 std::unique_ptr<IdentifierIterator> Current;
8435 std::unique_ptr<IdentifierIterator> Queued;
8436
8437public:
8438 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8439 std::unique_ptr<IdentifierIterator> Second)
8440 : Current(std::move(First)), Queued(std::move(Second)) {}
8441
8442 StringRef Next() override {
8443 if (!Current)
8444 return StringRef();
8445
8446 StringRef result = Current->Next();
8447 if (!result.empty())
8448 return result;
8449
8450 // Try the queued iterator, which may itself be empty.
8451 Current.reset();
8452 std::swap(Current, Queued);
8453 return Next();
8454 }
8455};
8456
8457} // namespace
8458
8460 if (!loadGlobalIndex()) {
8461 std::unique_ptr<IdentifierIterator> ReaderIter(
8462 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8463 std::unique_ptr<IdentifierIterator> ModulesIter(
8464 GlobalIndex->createIdentifierIterator());
8465 return new ChainedIdentifierIterator(std::move(ReaderIter),
8466 std::move(ModulesIter));
8467 }
8468
8469 return new ASTIdentifierIterator(*this);
8470}
8471
8472namespace clang {
8473namespace serialization {
8474
8476 ASTReader &Reader;
8477 Selector Sel;
8478 unsigned PriorGeneration;
8479 unsigned InstanceBits = 0;
8480 unsigned FactoryBits = 0;
8481 bool InstanceHasMoreThanOneDecl = false;
8482 bool FactoryHasMoreThanOneDecl = false;
8483 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8484 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8485
8486 public:
8488 unsigned PriorGeneration)
8489 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8490
8492 if (!M.SelectorLookupTable)
8493 return false;
8494
8495 // If we've already searched this module file, skip it now.
8496 if (M.Generation <= PriorGeneration)
8497 return true;
8498
8499 ++Reader.NumMethodPoolTableLookups;
8500 ASTSelectorLookupTable *PoolTable
8502 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8503 if (Pos == PoolTable->end())
8504 return false;
8505
8506 ++Reader.NumMethodPoolTableHits;
8507 ++Reader.NumSelectorsRead;
8508 // FIXME: Not quite happy with the statistics here. We probably should
8509 // disable this tracking when called via LoadSelector.
8510 // Also, should entries without methods count as misses?
8511 ++Reader.NumMethodPoolEntriesRead;
8513 if (Reader.DeserializationListener)
8514 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8515
8516 // Append methods in the reverse order, so that later we can process them
8517 // in the order they appear in the source code by iterating through
8518 // the vector in the reverse order.
8519 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8520 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8521 InstanceBits = Data.InstanceBits;
8522 FactoryBits = Data.FactoryBits;
8523 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8524 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8525 return false;
8526 }
8527
8528 /// Retrieve the instance methods found by this visitor.
8530 return InstanceMethods;
8531 }
8532
8533 /// Retrieve the instance methods found by this visitor.
8535 return FactoryMethods;
8536 }
8537
8538 unsigned getInstanceBits() const { return InstanceBits; }
8539 unsigned getFactoryBits() const { return FactoryBits; }
8540
8542 return InstanceHasMoreThanOneDecl;
8543 }
8544
8545 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8546 };
8547
8548} // namespace serialization
8549} // namespace clang
8550
8551/// Add the given set of methods to the method list.
8553 ObjCMethodList &List) {
8554 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8555 S.ObjC().addMethodToGlobalList(&List, M);
8556}
8557
8559 // Get the selector generation and update it to the current generation.
8560 unsigned &Generation = SelectorGeneration[Sel];
8561 unsigned PriorGeneration = Generation;
8562 Generation = getGeneration();
8563 SelectorOutOfDate[Sel] = false;
8564
8565 // Search for methods defined with this selector.
8566 ++NumMethodPoolLookups;
8567 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8568 ModuleMgr.visit(Visitor);
8569
8570 if (Visitor.getInstanceMethods().empty() &&
8571 Visitor.getFactoryMethods().empty())
8572 return;
8573
8574 ++NumMethodPoolHits;
8575
8576 if (!getSema())
8577 return;
8578
8579 Sema &S = *getSema();
8581 S.ObjC()
8582 .MethodPool
8583 .insert(std::make_pair(Sel, SemaObjC::GlobalMethodPool::Lists()))
8584 .first;
8585
8586 Pos->second.first.setBits(Visitor.getInstanceBits());
8587 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8588 Pos->second.second.setBits(Visitor.getFactoryBits());
8589 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8590
8591 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8592 // when building a module we keep every method individually and may need to
8593 // update hasMoreThanOneDecl as we add the methods.
8594 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8595 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8596}
8597
8599 if (SelectorOutOfDate[Sel])
8600 ReadMethodPool(Sel);
8601}
8602
8605 Namespaces.clear();
8606
8607 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8608 if (NamespaceDecl *Namespace
8609 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8610 Namespaces.push_back(Namespace);
8611 }
8612}
8613
8615 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8616 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8617 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
8618 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
8620 Undefined.insert(std::make_pair(D, Loc));
8621 }
8622 UndefinedButUsed.clear();
8623}
8624
8626 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8627 Exprs) {
8628 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8629 FieldDecl *FD =
8630 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
8631 uint64_t Count = DelayedDeleteExprs[Idx++];
8632 for (uint64_t C = 0; C < Count; ++C) {
8633 SourceLocation DeleteLoc =
8634 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8635 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8636 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8637 }
8638 }
8639}
8640
8642 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8643 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8644 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8645 if (Var)
8646 TentativeDefs.push_back(Var);
8647 }
8648 TentativeDefinitions.clear();
8649}
8650
8653 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8655 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8656 if (D)
8657 Decls.push_back(D);
8658 }
8659 UnusedFileScopedDecls.clear();
8660}
8661
8664 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8666 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8667 if (D)
8668 Decls.push_back(D);
8669 }
8670 DelegatingCtorDecls.clear();
8671}
8672
8674 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8676 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8677 if (D)
8678 Decls.push_back(D);
8679 }
8680 ExtVectorDecls.clear();
8681}
8682
8685 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8686 ++I) {
8687 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8688 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8689 if (D)
8690 Decls.insert(D);
8691 }
8692 UnusedLocalTypedefNameCandidates.clear();
8693}
8694
8697 for (auto I : DeclsToCheckForDeferredDiags) {
8698 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8699 if (D)
8700 Decls.insert(D);
8701 }
8702 DeclsToCheckForDeferredDiags.clear();
8703}
8704
8706 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8707 if (ReferencedSelectorsData.empty())
8708 return;
8709
8710 // If there are @selector references added them to its pool. This is for
8711 // implementation of -Wselector.
8712 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8713 unsigned I = 0;
8714 while (I < DataSize) {
8715 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8716 SourceLocation SelLoc
8717 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8718 Sels.push_back(std::make_pair(Sel, SelLoc));
8719 }
8720 ReferencedSelectorsData.clear();
8721}
8722
8724 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8725 if (WeakUndeclaredIdentifiers.empty())
8726 return;
8727
8728 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8729 IdentifierInfo *WeakId
8730 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8731 IdentifierInfo *AliasId
8732 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8734 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8735 WeakInfo WI(AliasId, Loc);
8736 WeakIDs.push_back(std::make_pair(WeakId, WI));
8737 }
8738 WeakUndeclaredIdentifiers.clear();
8739}
8740
8742 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8744 VTableUse &TableInfo = VTableUses[Idx++];
8745 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
8746 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
8747 VT.DefinitionRequired = TableInfo.Used;
8748 VTables.push_back(VT);
8749 }
8750
8751 VTableUses.clear();
8752}
8753
8755 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8756 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8757 PendingInstantiation &Inst = PendingInstantiations[Idx++];
8758 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
8760
8761 Pending.push_back(std::make_pair(D, Loc));
8762 }
8763 PendingInstantiations.clear();
8764}
8765
8767 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8768 &LPTMap) {
8769 for (auto &LPT : LateParsedTemplates) {
8770 ModuleFile *FMod = LPT.first;
8771 RecordDataImpl &LateParsed = LPT.second;
8772 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8773 /* In loop */) {
8774 FunctionDecl *FD = cast<FunctionDecl>(
8775 GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++])));
8776
8777 auto LT = std::make_unique<LateParsedTemplate>();
8778 LT->D = GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++]));
8779 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8780
8782 assert(F && "No module");
8783
8784 unsigned TokN = LateParsed[Idx++];
8785 LT->Toks.reserve(TokN);
8786 for (unsigned T = 0; T < TokN; ++T)
8787 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8788
8789 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8790 }
8791 }
8792
8793 LateParsedTemplates.clear();
8794}
8795
8797 if (Lambda->getLambdaContextDecl()) {
8798 // Keep track of this lambda so it can be merged with another lambda that
8799 // is loaded later.
8800 LambdaDeclarationsForMerging.insert(
8802 Lambda->getLambdaIndexInContext()},
8803 const_cast<CXXRecordDecl *>(Lambda)});
8804 }
8805}
8806
8808 // It would be complicated to avoid reading the methods anyway. So don't.
8809 ReadMethodPool(Sel);
8810}
8811
8813 assert(ID && "Non-zero identifier ID required");
8814 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8815 IdentifiersLoaded[ID - 1] = II;
8816 if (DeserializationListener)
8817 DeserializationListener->IdentifierRead(ID, II);
8818}
8819
8820/// Set the globally-visible declarations associated with the given
8821/// identifier.
8822///
8823/// If the AST reader is currently in a state where the given declaration IDs
8824/// cannot safely be resolved, they are queued until it is safe to resolve
8825/// them.
8826///
8827/// \param II an IdentifierInfo that refers to one or more globally-visible
8828/// declarations.
8829///
8830/// \param DeclIDs the set of declaration IDs with the name @p II that are
8831/// visible at global scope.
8832///
8833/// \param Decls if non-null, this vector will be populated with the set of
8834/// deserialized declarations. These declarations will not be pushed into
8835/// scope.
8838 SmallVectorImpl<Decl *> *Decls) {
8839 if (NumCurrentElementsDeserializing && !Decls) {
8840 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8841 return;
8842 }
8843
8844 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8845 if (!SemaObj) {
8846 // Queue this declaration so that it will be added to the
8847 // translation unit scope and identifier's declaration chain
8848 // once a Sema object is known.
8849 PreloadedDeclIDs.push_back(DeclIDs[I]);
8850 continue;
8851 }
8852
8853 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8854
8855 // If we're simply supposed to record the declarations, do so now.
8856 if (Decls) {
8857 Decls->push_back(D);
8858 continue;
8859 }
8860
8861 // Introduce this declaration into the translation-unit scope
8862 // and add it to the declaration chain for this identifier, so
8863 // that (unqualified) name lookup will find it.
8864 pushExternalDeclIntoScope(D, II);
8865 }
8866}
8867
8869 if (ID == 0)
8870 return nullptr;
8871
8872 if (IdentifiersLoaded.empty()) {
8873 Error("no identifier table in AST file");
8874 return nullptr;
8875 }
8876
8877 ID -= 1;
8878 if (!IdentifiersLoaded[ID]) {
8879 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8880 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8881 ModuleFile *M = I->second;
8882 unsigned Index = ID - M->BaseIdentifierID;
8883 const unsigned char *Data =
8885
8886 ASTIdentifierLookupTrait Trait(*this, *M);
8887 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8888 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8889 auto &II = PP.getIdentifierTable().get(Key);
8890 IdentifiersLoaded[ID] = &II;
8891 markIdentifierFromAST(*this, II);
8892 if (DeserializationListener)
8893 DeserializationListener->IdentifierRead(ID + 1, &II);
8894 }
8895
8896 return IdentifiersLoaded[ID];
8897}
8898
8900 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8901}
8902
8904 if (LocalID < NUM_PREDEF_IDENT_IDS)
8905 return LocalID;
8906
8907 if (!M.ModuleOffsetMap.empty())
8908 ReadModuleOffsetMap(M);
8909
8912 assert(I != M.IdentifierRemap.end()
8913 && "Invalid index into identifier index remap");
8914
8915 return LocalID + I->second;
8916}
8917
8919 if (ID == 0)
8920 return nullptr;
8921
8922 if (MacrosLoaded.empty()) {
8923 Error("no macro table in AST file");
8924 return nullptr;
8925 }
8926
8928 if (!MacrosLoaded[ID]) {
8930 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8931 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8932 ModuleFile *M = I->second;
8933 unsigned Index = ID - M->BaseMacroID;
8934 MacrosLoaded[ID] =
8935 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8936
8937 if (DeserializationListener)
8938 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8939 MacrosLoaded[ID]);
8940 }
8941
8942 return MacrosLoaded[ID];
8943}
8944
8946 if (LocalID < NUM_PREDEF_MACRO_IDS)
8947 return LocalID;
8948
8949 if (!M.ModuleOffsetMap.empty())
8950 ReadModuleOffsetMap(M);
8951
8953 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8954 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8955
8956 return LocalID + I->second;
8957}
8958
8960ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
8961 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8962 return LocalID;
8963
8964 if (!M.ModuleOffsetMap.empty())
8965 ReadModuleOffsetMap(M);
8966
8969 assert(I != M.SubmoduleRemap.end()
8970 && "Invalid index into submodule index remap");
8971
8972 return LocalID + I->second;
8973}
8974
8976 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8977 assert(GlobalID == 0 && "Unhandled global submodule ID");
8978 return nullptr;
8979 }
8980
8981 if (GlobalID > SubmodulesLoaded.size()) {
8982 Error("submodule ID out of range in AST file");
8983 return nullptr;
8984 }
8985
8986 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8987}
8988
8990 return getSubmodule(ID);
8991}
8992
8994 if (ID & 1) {
8995 // It's a module, look it up by submodule ID.
8996 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
8997 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8998 } else {
8999 // It's a prefix (preamble, PCH, ...). Look it up by index.
9000 unsigned IndexFromEnd = ID >> 1;
9001 assert(IndexFromEnd && "got reference to unknown module file");
9002 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9003 }
9004}
9005
9007 if (!M)
9008 return 1;
9009
9010 // For a file representing a module, use the submodule ID of the top-level
9011 // module as the file ID. For any other kind of file, the number of such
9012 // files loaded beforehand will be the same on reload.
9013 // FIXME: Is this true even if we have an explicit module file and a PCH?
9014 if (M->isModule())
9015 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9016
9017 auto PCHModules = getModuleManager().pch_modules();
9018 auto I = llvm::find(PCHModules, M);
9019 assert(I != PCHModules.end() && "emitting reference to unknown file");
9020 return (I - PCHModules.end()) << 1;
9021}
9022
9023std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9024 if (Module *M = getSubmodule(ID))
9025 return ASTSourceDescriptor(*M);
9026
9027 // If there is only a single PCH, return it instead.
9028 // Chained PCH are not supported.
9029 const auto &PCHChain = ModuleMgr.pch_modules();
9030 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9031 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9032 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9033 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9034 return ASTSourceDescriptor(ModuleName,
9035 llvm::sys::path::parent_path(MF.FileName),
9036 FileName, MF.Signature);
9037 }
9038 return std::nullopt;
9039}
9040
9042 auto I = DefinitionSource.find(FD);
9043 if (I == DefinitionSource.end())
9044 return EK_ReplyHazy;
9045 return I->second ? EK_Never : EK_Always;
9046}
9047
9049 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9050}
9051
9053 if (ID == 0)
9054 return Selector();
9055
9056 if (ID > SelectorsLoaded.size()) {
9057 Error("selector ID out of range in AST file");
9058 return Selector();
9059 }
9060
9061 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9062 // Load this selector from the selector table.
9063 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9064 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9065 ModuleFile &M = *I->second;
9066 ASTSelectorLookupTrait Trait(*this, M);
9067 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9068 SelectorsLoaded[ID - 1] =
9069 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9070 if (DeserializationListener)
9071 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9072 }
9073
9074 return SelectorsLoaded[ID - 1];
9075}
9076
9078 return DecodeSelector(ID);
9079}
9080
9082 // ID 0 (the null selector) is considered an external selector.
9083 return getTotalNumSelectors() + 1;
9084}
9085
9087ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9088 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9089 return LocalID;
9090
9091 if (!M.ModuleOffsetMap.empty())
9092 ReadModuleOffsetMap(M);
9093
9096 assert(I != M.SelectorRemap.end()
9097 && "Invalid index into selector index remap");
9098
9099 return LocalID + I->second;
9100}
9101
9104 switch (Name.getNameKind()) {
9109
9112
9116
9123 break;
9124 }
9125 return DeclarationNameLoc();
9126}
9127
9129 DeclarationNameInfo NameInfo;
9130 NameInfo.setName(readDeclarationName());
9131 NameInfo.setLoc(readSourceLocation());
9132 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9133 return NameInfo;
9134}
9135
9137 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9138}
9139
9142 unsigned NumTPLists = readInt();
9143 Info.NumTemplParamLists = NumTPLists;
9144 if (NumTPLists) {
9145 Info.TemplParamLists =
9146 new (getContext()) TemplateParameterList *[NumTPLists];
9147 for (unsigned i = 0; i != NumTPLists; ++i)
9149 }
9150}
9151
9154 SourceLocation TemplateLoc = readSourceLocation();
9155 SourceLocation LAngleLoc = readSourceLocation();
9156 SourceLocation RAngleLoc = readSourceLocation();
9157
9158 unsigned NumParams = readInt();
9160 Params.reserve(NumParams);
9161 while (NumParams--)
9162 Params.push_back(readDeclAs<NamedDecl>());
9163
9164 bool HasRequiresClause = readBool();
9165 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9166
9168 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9169 return TemplateParams;
9170}
9171
9174 bool Canonicalize) {
9175 unsigned NumTemplateArgs = readInt();
9176 TemplArgs.reserve(NumTemplateArgs);
9177 while (NumTemplateArgs--)
9178 TemplArgs.push_back(readTemplateArgument(Canonicalize));
9179}
9180
9181/// Read a UnresolvedSet structure.
9183 unsigned NumDecls = readInt();
9184 Set.reserve(getContext(), NumDecls);
9185 while (NumDecls--) {
9186 GlobalDeclID ID = readDeclID();
9188 Set.addLazyDecl(getContext(), ID.get(), AS);
9189 }
9190}
9191
9194 bool isVirtual = readBool();
9195 bool isBaseOfClass = readBool();
9196 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9197 bool inheritConstructors = readBool();
9200 SourceLocation EllipsisLoc = readSourceLocation();
9201 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9202 EllipsisLoc);
9203 Result.setInheritConstructors(inheritConstructors);
9204 return Result;
9205}
9206
9209 ASTContext &Context = getContext();
9210 unsigned NumInitializers = readInt();
9211 assert(NumInitializers && "wrote ctor initializers but have no inits");
9212 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9213 for (unsigned i = 0; i != NumInitializers; ++i) {
9214 TypeSourceInfo *TInfo = nullptr;
9215 bool IsBaseVirtual = false;
9216 FieldDecl *Member = nullptr;
9217 IndirectFieldDecl *IndirectMember = nullptr;
9218
9220 switch (Type) {
9222 TInfo = readTypeSourceInfo();
9223 IsBaseVirtual = readBool();
9224 break;
9225
9227 TInfo = readTypeSourceInfo();
9228 break;
9229
9231 Member = readDeclAs<FieldDecl>();
9232 break;
9233
9235 IndirectMember = readDeclAs<IndirectFieldDecl>();
9236 break;
9237 }
9238
9239 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9240 Expr *Init = readExpr();
9241 SourceLocation LParenLoc = readSourceLocation();
9242 SourceLocation RParenLoc = readSourceLocation();
9243
9244 CXXCtorInitializer *BOMInit;
9246 BOMInit = new (Context)
9247 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9248 RParenLoc, MemberOrEllipsisLoc);
9250 BOMInit = new (Context)
9251 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9252 else if (Member)
9253 BOMInit = new (Context)
9254 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9255 Init, RParenLoc);
9256 else
9257 BOMInit = new (Context)
9258 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9259 LParenLoc, Init, RParenLoc);
9260
9261 if (/*IsWritten*/readBool()) {
9262 unsigned SourceOrder = readInt();
9263 BOMInit->setSourceOrder(SourceOrder);
9264 }
9265
9266 CtorInitializers[i] = BOMInit;
9267 }
9268
9269 return CtorInitializers;
9270}
9271
9274 ASTContext &Context = getContext();
9275 unsigned N = readInt();
9277 for (unsigned I = 0; I != N; ++I) {
9278 auto Kind = readNestedNameSpecifierKind();
9279 switch (Kind) {
9283 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9284 break;
9285 }
9286
9288 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9290 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9291 break;
9292 }
9293
9295 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9297 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9298 break;
9299 }
9300
9303 bool Template = readBool();
9305 if (!T)
9306 return NestedNameSpecifierLoc();
9307 SourceLocation ColonColonLoc = readSourceLocation();
9308
9309 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9310 Builder.Extend(Context,
9311 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9312 T->getTypeLoc(), ColonColonLoc);
9313 break;
9314 }
9315
9317 SourceLocation ColonColonLoc = readSourceLocation();
9318 Builder.MakeGlobal(Context, ColonColonLoc);
9319 break;
9320 }
9321
9323 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9325 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9326 break;
9327 }
9328 }
9329 }
9330
9331 return Builder.getWithLocInContext(Context);
9332}
9333
9335 unsigned &Idx, LocSeq *Seq) {
9338 return SourceRange(beg, end);
9339}
9340
9342 const StringRef Blob) {
9343 unsigned Count = Record[0];
9344 const char *Byte = Blob.data();
9345 llvm::BitVector Ret = llvm::BitVector(Count, false);
9346 for (unsigned I = 0; I < Count; ++Byte)
9347 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9348 if (*Byte & (1 << Bit))
9349 Ret[I] = true;
9350 return Ret;
9351}
9352
9353/// Read a floating-point value
9354llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9355 return llvm::APFloat(Sem, readAPInt());
9356}
9357
9358// Read a string
9359std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9360 unsigned Len = Record[Idx++];
9361 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9362 Idx += Len;
9363 return Result;
9364}
9365
9367 unsigned &Idx) {
9368 std::string Filename = ReadString(Record, Idx);
9370 return Filename;
9371}
9372
9373std::string ASTReader::ReadPath(StringRef BaseDirectory,
9374 const RecordData &Record, unsigned &Idx) {
9375 std::string Filename = ReadString(Record, Idx);
9376 if (!BaseDirectory.empty())
9377 ResolveImportedPath(Filename, BaseDirectory);
9378 return Filename;
9379}
9380
9382 unsigned &Idx) {
9383 unsigned Major = Record[Idx++];
9384 unsigned Minor = Record[Idx++];
9385 unsigned Subminor = Record[Idx++];
9386 if (Minor == 0)
9387 return VersionTuple(Major);
9388 if (Subminor == 0)
9389 return VersionTuple(Major, Minor - 1);
9390 return VersionTuple(Major, Minor - 1, Subminor - 1);
9391}
9392
9394 const RecordData &Record,
9395 unsigned &Idx) {
9396 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9398}
9399
9400DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9401 return Diag(CurrentImportLoc, DiagID);
9402}
9403
9405 return Diags.Report(Loc, DiagID);
9406}
9407
9408/// Retrieve the identifier table associated with the
9409/// preprocessor.
9411 return PP.getIdentifierTable();
9412}
9413
9414/// Record that the given ID maps to the given switch-case
9415/// statement.
9417 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9418 "Already have a SwitchCase with this ID");
9419 (*CurrSwitchCaseStmts)[ID] = SC;
9420}
9421
9422/// Retrieve the switch-case statement with the given ID.
9424 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9425 return (*CurrSwitchCaseStmts)[ID];
9426}
9427
9429 CurrSwitchCaseStmts->clear();
9430}
9431
9433 ASTContext &Context = getContext();
9434 std::vector<RawComment *> Comments;
9435 for (SmallVectorImpl<std::pair<BitstreamCursor,
9436 serialization::ModuleFile *>>::iterator
9437 I = CommentsCursors.begin(),
9438 E = CommentsCursors.end();
9439 I != E; ++I) {
9440 Comments.clear();
9441 BitstreamCursor &Cursor = I->first;
9442 serialization::ModuleFile &F = *I->second;
9443 SavedStreamPosition SavedPosition(Cursor);
9444
9446 while (true) {
9448 Cursor.advanceSkippingSubblocks(
9449 BitstreamCursor::AF_DontPopBlockAtEnd);
9450 if (!MaybeEntry) {
9451 Error(MaybeEntry.takeError());
9452 return;
9453 }
9454 llvm::BitstreamEntry Entry = MaybeEntry.get();
9455
9456 switch (Entry.Kind) {
9457 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9458 case llvm::BitstreamEntry::Error:
9459 Error("malformed block record in AST file");
9460 return;
9461 case llvm::BitstreamEntry::EndBlock:
9462 goto NextCursor;
9463 case llvm::BitstreamEntry::Record:
9464 // The interesting case.
9465 break;
9466 }
9467
9468 // Read a record.
9469 Record.clear();
9470 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9471 if (!MaybeComment) {
9472 Error(MaybeComment.takeError());
9473 return;
9474 }
9475 switch ((CommentRecordTypes)MaybeComment.get()) {
9476 case COMMENTS_RAW_COMMENT: {
9477 unsigned Idx = 0;
9478 SourceRange SR = ReadSourceRange(F, Record, Idx);
9481 bool IsTrailingComment = Record[Idx++];
9482 bool IsAlmostTrailingComment = Record[Idx++];
9483 Comments.push_back(new (Context) RawComment(
9484 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9485 break;
9486 }
9487 }
9488 }
9489 NextCursor:
9490 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9491 FileToOffsetToComment;
9492 for (RawComment *C : Comments) {
9493 SourceLocation CommentLoc = C->getBeginLoc();
9494 if (CommentLoc.isValid()) {
9495 std::pair<FileID, unsigned> Loc =
9496 SourceMgr.getDecomposedLoc(CommentLoc);
9497 if (Loc.first.isValid())
9498 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9499 }
9500 }
9501 }
9502}
9503
9505 serialization::ModuleFile &MF, bool IncludeSystem,
9506 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9507 bool IsSystem)>
9508 Visitor) {
9509 unsigned NumUserInputs = MF.NumUserInputFiles;
9510 unsigned NumInputs = MF.InputFilesLoaded.size();
9511 assert(NumUserInputs <= NumInputs);
9512 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9513 for (unsigned I = 0; I < N; ++I) {
9514 bool IsSystem = I >= NumUserInputs;
9515 InputFileInfo IFI = getInputFileInfo(MF, I+1);
9516 Visitor(IFI, IsSystem);
9517 }
9518}
9519
9521 bool IncludeSystem, bool Complain,
9522 llvm::function_ref<void(const serialization::InputFile &IF,
9523 bool isSystem)> Visitor) {
9524 unsigned NumUserInputs = MF.NumUserInputFiles;
9525 unsigned NumInputs = MF.InputFilesLoaded.size();
9526 assert(NumUserInputs <= NumInputs);
9527 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9528 for (unsigned I = 0; I < N; ++I) {
9529 bool IsSystem = I >= NumUserInputs;
9530 InputFile IF = getInputFile(MF, I+1, Complain);
9531 Visitor(IF, IsSystem);
9532 }
9533}
9534
9537 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9538 unsigned NumInputs = MF.InputFilesLoaded.size();
9539 for (unsigned I = 0; I < NumInputs; ++I) {
9540 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9541 if (IFI.TopLevel && IFI.ModuleMap)
9542 if (auto FE = getInputFile(MF, I + 1).getFile())
9543 Visitor(*FE);
9544 }
9545}
9546
9547void ASTReader::finishPendingActions() {
9548 while (
9549 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9550 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9551 !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9552 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9553 !PendingObjCExtensionIvarRedeclarations.empty()) {
9554 // If any identifiers with corresponding top-level declarations have
9555 // been loaded, load those declarations now.
9556 using TopLevelDeclsMap =
9557 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9558 TopLevelDeclsMap TopLevelDecls;
9559
9560 while (!PendingIdentifierInfos.empty()) {
9561 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9563 std::move(PendingIdentifierInfos.back().second);
9564 PendingIdentifierInfos.pop_back();
9565
9566 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9567 }
9568
9569 // Load each function type that we deferred loading because it was a
9570 // deduced type that might refer to a local type declared within itself.
9571 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9572 auto *FD = PendingDeducedFunctionTypes[I].first;
9573 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9574
9575 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
9576 // If we gave a function a deduced return type, remember that we need to
9577 // propagate that along the redeclaration chain.
9578 if (DT->isDeduced()) {
9579 PendingDeducedTypeUpdates.insert(
9580 {FD->getCanonicalDecl(), FD->getReturnType()});
9581 continue;
9582 }
9583
9584 // The function has undeduced DeduceType return type. We hope we can
9585 // find the deduced type by iterating the redecls in other modules
9586 // later.
9587 PendingUndeducedFunctionDecls.push_back(FD);
9588 continue;
9589 }
9590 }
9591 PendingDeducedFunctionTypes.clear();
9592
9593 // Load each variable type that we deferred loading because it was a
9594 // deduced type that might refer to a local type declared within itself.
9595 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9596 auto *VD = PendingDeducedVarTypes[I].first;
9597 VD->setType(GetType(PendingDeducedVarTypes[I].second));
9598 }
9599 PendingDeducedVarTypes.clear();
9600
9601 // For each decl chain that we wanted to complete while deserializing, mark
9602 // it as "still needs to be completed".
9603 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9604 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9605 }
9606 PendingIncompleteDeclChains.clear();
9607
9608 // Load pending declaration chains.
9609 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9610 loadPendingDeclChain(PendingDeclChains[I].first,
9611 PendingDeclChains[I].second);
9612 PendingDeclChains.clear();
9613
9614 // Make the most recent of the top-level declarations visible.
9615 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9616 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9617 IdentifierInfo *II = TLD->first;
9618 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9619 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9620 }
9621 }
9622
9623 // Load any pending macro definitions.
9624 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9625 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9627 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9628 // Initialize the macro history from chained-PCHs ahead of module imports.
9629 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9630 ++IDIdx) {
9631 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9632 if (!Info.M->isModule())
9633 resolvePendingMacro(II, Info);
9634 }
9635 // Handle module imports.
9636 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9637 ++IDIdx) {
9638 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9639 if (Info.M->isModule())
9640 resolvePendingMacro(II, Info);
9641 }
9642 }
9643 PendingMacroIDs.clear();
9644
9645 // Wire up the DeclContexts for Decls that we delayed setting until
9646 // recursive loading is completed.
9647 while (!PendingDeclContextInfos.empty()) {
9648 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9649 PendingDeclContextInfos.pop_front();
9650 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9651 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9652 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9653 }
9654
9655 // Perform any pending declaration updates.
9656 while (!PendingUpdateRecords.empty()) {
9657 auto Update = PendingUpdateRecords.pop_back_val();
9658 ReadingKindTracker ReadingKind(Read_Decl, *this);
9659 loadDeclUpdateRecords(Update);
9660 }
9661
9662 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9663 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9664 auto DuplicateIvars =
9665 PendingObjCExtensionIvarRedeclarations.back().second;
9666 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9668 ExtensionsPair.first->getASTContext(),
9669 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9670 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9671 /*Complain =*/false,
9672 /*ErrorOnTagTypeMismatch =*/true);
9673 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9674 // Merge redeclared ivars with their predecessors.
9675 for (auto IvarPair : DuplicateIvars) {
9676 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9677 // Change semantic DeclContext but keep the lexical one.
9678 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9679 Ivar->getLexicalDeclContext(),
9680 getContext());
9681 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9682 }
9683 // Invalidate duplicate extension and the cached ivar list.
9684 ExtensionsPair.first->setInvalidDecl();
9685 ExtensionsPair.second->getClassInterface()
9686 ->getDefinition()
9687 ->setIvarList(nullptr);
9688 } else {
9689 for (auto IvarPair : DuplicateIvars) {
9690 Diag(IvarPair.first->getLocation(),
9691 diag::err_duplicate_ivar_declaration)
9692 << IvarPair.first->getIdentifier();
9693 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9694 }
9695 }
9696 PendingObjCExtensionIvarRedeclarations.pop_back();
9697 }
9698 }
9699
9700 // At this point, all update records for loaded decls are in place, so any
9701 // fake class definitions should have become real.
9702 assert(PendingFakeDefinitionData.empty() &&
9703 "faked up a class definition but never saw the real one");
9704
9705 // If we deserialized any C++ or Objective-C class definitions, any
9706 // Objective-C protocol definitions, or any redeclarable templates, make sure
9707 // that all redeclarations point to the definitions. Note that this can only
9708 // happen now, after the redeclaration chains have been fully wired.
9709 for (Decl *D : PendingDefinitions) {
9710 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9711 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9712 // Make sure that the TagType points at the definition.
9713 const_cast<TagType*>(TagT)->decl = TD;
9714 }
9715
9716 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9717 for (auto *R = getMostRecentExistingDecl(RD); R;
9718 R = R->getPreviousDecl()) {
9719 assert((R == D) ==
9720 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9721 "declaration thinks it's the definition but it isn't");
9722 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9723 }
9724 }
9725
9726 continue;
9727 }
9728
9729 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9730 // Make sure that the ObjCInterfaceType points at the definition.
9731 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9732 ->Decl = ID;
9733
9734 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9735 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9736
9737 continue;
9738 }
9739
9740 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9741 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9742 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9743
9744 continue;
9745 }
9746
9747 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9748 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9749 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9750 }
9751 PendingDefinitions.clear();
9752
9753 // Load the bodies of any functions or methods we've encountered. We do
9754 // this now (delayed) so that we can be sure that the declaration chains
9755 // have been fully wired up (hasBody relies on this).
9756 // FIXME: We shouldn't require complete redeclaration chains here.
9757 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9758 PBEnd = PendingBodies.end();
9759 PB != PBEnd; ++PB) {
9760 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9761 // For a function defined inline within a class template, force the
9762 // canonical definition to be the one inside the canonical definition of
9763 // the template. This ensures that we instantiate from a correct view
9764 // of the template.
9765 //
9766 // Sadly we can't do this more generally: we can't be sure that all
9767 // copies of an arbitrary class definition will have the same members
9768 // defined (eg, some member functions may not be instantiated, and some
9769 // special members may or may not have been implicitly defined).
9770 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9771 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9772 continue;
9773
9774 // FIXME: Check for =delete/=default?
9775 const FunctionDecl *Defn = nullptr;
9776 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9777 FD->setLazyBody(PB->second);
9778 } else {
9779 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9780 mergeDefinitionVisibility(NonConstDefn, FD);
9781
9782 if (!FD->isLateTemplateParsed() &&
9783 !NonConstDefn->isLateTemplateParsed() &&
9784 // We only perform ODR checks for decls not in the explicit
9785 // global module fragment.
9786 !shouldSkipCheckingODR(FD) &&
9787 FD->getODRHash() != NonConstDefn->getODRHash()) {
9788 if (!isa<CXXMethodDecl>(FD)) {
9789 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9790 } else if (FD->getLexicalParent()->isFileContext() &&
9791 NonConstDefn->getLexicalParent()->isFileContext()) {
9792 // Only diagnose out-of-line method definitions. If they are
9793 // in class definitions, then an error will be generated when
9794 // processing the class bodies.
9795 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9796 }
9797 }
9798 }
9799 continue;
9800 }
9801
9802 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9803 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9804 MD->setLazyBody(PB->second);
9805 }
9806 PendingBodies.clear();
9807
9808 // Inform any classes that had members added that they now have more members.
9809 for (auto [RD, MD] : PendingAddedClassMembers) {
9810 RD->addedMember(MD);
9811 }
9812 PendingAddedClassMembers.clear();
9813
9814 // Do some cleanup.
9815 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9817 PendingMergedDefinitionsToDeduplicate.clear();
9818}
9819
9820void ASTReader::diagnoseOdrViolations() {
9821 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9822 PendingRecordOdrMergeFailures.empty() &&
9823 PendingFunctionOdrMergeFailures.empty() &&
9824 PendingEnumOdrMergeFailures.empty() &&
9825 PendingObjCInterfaceOdrMergeFailures.empty() &&
9826 PendingObjCProtocolOdrMergeFailures.empty())
9827 return;
9828
9829 // Trigger the import of the full definition of each class that had any
9830 // odr-merging problems, so we can produce better diagnostics for them.
9831 // These updates may in turn find and diagnose some ODR failures, so take
9832 // ownership of the set first.
9833 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9834 PendingOdrMergeFailures.clear();
9835 for (auto &Merge : OdrMergeFailures) {
9836 Merge.first->buildLookup();
9837 Merge.first->decls_begin();
9838 Merge.first->bases_begin();
9839 Merge.first->vbases_begin();
9840 for (auto &RecordPair : Merge.second) {
9841 auto *RD = RecordPair.first;
9842 RD->decls_begin();
9843 RD->bases_begin();
9844 RD->vbases_begin();
9845 }
9846 }
9847
9848 // Trigger the import of the full definition of each record in C/ObjC.
9849 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9850 PendingRecordOdrMergeFailures.clear();
9851 for (auto &Merge : RecordOdrMergeFailures) {
9852 Merge.first->decls_begin();
9853 for (auto &D : Merge.second)
9854 D->decls_begin();
9855 }
9856
9857 // Trigger the import of the full interface definition.
9858 auto ObjCInterfaceOdrMergeFailures =
9859 std::move(PendingObjCInterfaceOdrMergeFailures);
9860 PendingObjCInterfaceOdrMergeFailures.clear();
9861 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9862 Merge.first->decls_begin();
9863 for (auto &InterfacePair : Merge.second)
9864 InterfacePair.first->decls_begin();
9865 }
9866
9867 // Trigger the import of functions.
9868 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9869 PendingFunctionOdrMergeFailures.clear();
9870 for (auto &Merge : FunctionOdrMergeFailures) {
9871 Merge.first->buildLookup();
9872 Merge.first->decls_begin();
9873 Merge.first->getBody();
9874 for (auto &FD : Merge.second) {
9875 FD->buildLookup();
9876 FD->decls_begin();
9877 FD->getBody();
9878 }
9879 }
9880
9881 // Trigger the import of enums.
9882 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9883 PendingEnumOdrMergeFailures.clear();
9884 for (auto &Merge : EnumOdrMergeFailures) {
9885 Merge.first->decls_begin();
9886 for (auto &Enum : Merge.second) {
9887 Enum->decls_begin();
9888 }
9889 }
9890
9891 // Trigger the import of the full protocol definition.
9892 auto ObjCProtocolOdrMergeFailures =
9893 std::move(PendingObjCProtocolOdrMergeFailures);
9894 PendingObjCProtocolOdrMergeFailures.clear();
9895 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9896 Merge.first->decls_begin();
9897 for (auto &ProtocolPair : Merge.second)
9898 ProtocolPair.first->decls_begin();
9899 }
9900
9901 // For each declaration from a merged context, check that the canonical
9902 // definition of that context also contains a declaration of the same
9903 // entity.
9904 //
9905 // Caution: this loop does things that might invalidate iterators into
9906 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9907 while (!PendingOdrMergeChecks.empty()) {
9908 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9909
9910 // FIXME: Skip over implicit declarations for now. This matters for things
9911 // like implicitly-declared special member functions. This isn't entirely
9912 // correct; we can end up with multiple unmerged declarations of the same
9913 // implicit entity.
9914 if (D->isImplicit())
9915 continue;
9916
9917 DeclContext *CanonDef = D->getDeclContext();
9918
9919 bool Found = false;
9920 const Decl *DCanon = D->getCanonicalDecl();
9921
9922 for (auto *RI : D->redecls()) {
9923 if (RI->getLexicalDeclContext() == CanonDef) {
9924 Found = true;
9925 break;
9926 }
9927 }
9928 if (Found)
9929 continue;
9930
9931 // Quick check failed, time to do the slow thing. Note, we can't just
9932 // look up the name of D in CanonDef here, because the member that is
9933 // in CanonDef might not be found by name lookup (it might have been
9934 // replaced by a more recent declaration in the lookup table), and we
9935 // can't necessarily find it in the redeclaration chain because it might
9936 // be merely mergeable, not redeclarable.
9938 for (auto *CanonMember : CanonDef->decls()) {
9939 if (CanonMember->getCanonicalDecl() == DCanon) {
9940 // This can happen if the declaration is merely mergeable and not
9941 // actually redeclarable (we looked for redeclarations earlier).
9942 //
9943 // FIXME: We should be able to detect this more efficiently, without
9944 // pulling in all of the members of CanonDef.
9945 Found = true;
9946 break;
9947 }
9948 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9949 if (ND->getDeclName() == D->getDeclName())
9950 Candidates.push_back(ND);
9951 }
9952
9953 if (!Found) {
9954 // The AST doesn't like TagDecls becoming invalid after they've been
9955 // completed. We only really need to mark FieldDecls as invalid here.
9956 if (!isa<TagDecl>(D))
9957 D->setInvalidDecl();
9958
9959 // Ensure we don't accidentally recursively enter deserialization while
9960 // we're producing our diagnostic.
9961 Deserializing RecursionGuard(this);
9962
9963 std::string CanonDefModule =
9965 cast<Decl>(CanonDef));
9966 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9968 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9969
9970 if (Candidates.empty())
9971 Diag(cast<Decl>(CanonDef)->getLocation(),
9972 diag::note_module_odr_violation_no_possible_decls) << D;
9973 else {
9974 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9975 Diag(Candidates[I]->getLocation(),
9976 diag::note_module_odr_violation_possible_decl)
9977 << Candidates[I];
9978 }
9979
9980 DiagnosedOdrMergeFailures.insert(CanonDef);
9981 }
9982 }
9983
9984 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9985 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9986 ObjCInterfaceOdrMergeFailures.empty() &&
9987 ObjCProtocolOdrMergeFailures.empty())
9988 return;
9989
9990 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9991 getPreprocessor().getLangOpts());
9992
9993 // Issue any pending ODR-failure diagnostics.
9994 for (auto &Merge : OdrMergeFailures) {
9995 // If we've already pointed out a specific problem with this class, don't
9996 // bother issuing a general "something's different" diagnostic.
9997 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9998 continue;
9999
10000 bool Diagnosed = false;
10001 CXXRecordDecl *FirstRecord = Merge.first;
10002 for (auto &RecordPair : Merge.second) {
10003 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10004 RecordPair.second)) {
10005 Diagnosed = true;
10006 break;
10007 }
10008 }
10009
10010 if (!Diagnosed) {
10011 // All definitions are updates to the same declaration. This happens if a
10012 // module instantiates the declaration of a class template specialization
10013 // and two or more other modules instantiate its definition.
10014 //
10015 // FIXME: Indicate which modules had instantiations of this definition.
10016 // FIXME: How can this even happen?
10017 Diag(Merge.first->getLocation(),
10018 diag::err_module_odr_violation_different_instantiations)
10019 << Merge.first;
10020 }
10021 }
10022
10023 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10024 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10025 for (auto &Merge : RecordOdrMergeFailures) {
10026 // If we've already pointed out a specific problem with this class, don't
10027 // bother issuing a general "something's different" diagnostic.
10028 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10029 continue;
10030
10031 RecordDecl *FirstRecord = Merge.first;
10032 bool Diagnosed = false;
10033 for (auto *SecondRecord : Merge.second) {
10034 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10035 Diagnosed = true;
10036 break;
10037 }
10038 }
10039 (void)Diagnosed;
10040 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10041 }
10042
10043 // Issue ODR failures diagnostics for functions.
10044 for (auto &Merge : FunctionOdrMergeFailures) {
10045 FunctionDecl *FirstFunction = Merge.first;
10046 bool Diagnosed = false;
10047 for (auto &SecondFunction : Merge.second) {
10048 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10049 Diagnosed = true;
10050 break;
10051 }
10052 }
10053 (void)Diagnosed;
10054 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10055 }
10056
10057 // Issue ODR failures diagnostics for enums.
10058 for (auto &Merge : EnumOdrMergeFailures) {
10059 // If we've already pointed out a specific problem with this enum, don't
10060 // bother issuing a general "something's different" diagnostic.
10061 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10062 continue;
10063
10064 EnumDecl *FirstEnum = Merge.first;
10065 bool Diagnosed = false;
10066 for (auto &SecondEnum : Merge.second) {
10067 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10068 Diagnosed = true;
10069 break;
10070 }
10071 }
10072 (void)Diagnosed;
10073 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10074 }
10075
10076 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10077 // If we've already pointed out a specific problem with this interface,
10078 // don't bother issuing a general "something's different" diagnostic.
10079 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10080 continue;
10081
10082 bool Diagnosed = false;
10083 ObjCInterfaceDecl *FirstID = Merge.first;
10084 for (auto &InterfacePair : Merge.second) {
10085 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10086 InterfacePair.second)) {
10087 Diagnosed = true;
10088 break;
10089 }
10090 }
10091 (void)Diagnosed;
10092 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10093 }
10094
10095 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10096 // If we've already pointed out a specific problem with this protocol,
10097 // don't bother issuing a general "something's different" diagnostic.
10098 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10099 continue;
10100
10101 ObjCProtocolDecl *FirstProtocol = Merge.first;
10102 bool Diagnosed = false;
10103 for (auto &ProtocolPair : Merge.second) {
10104 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10105 ProtocolPair.second)) {
10106 Diagnosed = true;
10107 break;
10108 }
10109 }
10110 (void)Diagnosed;
10111 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10112 }
10113}
10114
10116 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10117 ReadTimer->startTimer();
10118}
10119
10121 assert(NumCurrentElementsDeserializing &&
10122 "FinishedDeserializing not paired with StartedDeserializing");
10123 if (NumCurrentElementsDeserializing == 1) {
10124 // We decrease NumCurrentElementsDeserializing only after pending actions
10125 // are finished, to avoid recursively re-calling finishPendingActions().
10126 finishPendingActions();
10127 }
10128 --NumCurrentElementsDeserializing;
10129
10130 if (NumCurrentElementsDeserializing == 0) {
10131 // Propagate exception specification and deduced type updates along
10132 // redeclaration chains.
10133 //
10134 // We do this now rather than in finishPendingActions because we want to
10135 // be able to walk the complete redeclaration chains of the updated decls.
10136 while (!PendingExceptionSpecUpdates.empty() ||
10137 !PendingDeducedTypeUpdates.empty()) {
10138 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10139 PendingExceptionSpecUpdates.clear();
10140 for (auto Update : ESUpdates) {
10141 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10142 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10143 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10144 if (auto *Listener = getContext().getASTMutationListener())
10145 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10146 for (auto *Redecl : Update.second->redecls())
10147 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10148 }
10149
10150 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10151 PendingDeducedTypeUpdates.clear();
10152 for (auto Update : DTUpdates) {
10153 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10154 // FIXME: If the return type is already deduced, check that it matches.
10156 Update.second);
10157 }
10158
10159 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10160 PendingUndeducedFunctionDecls.clear();
10161 // We hope we can find the deduced type for the functions by iterating
10162 // redeclarations in other modules.
10163 for (FunctionDecl *UndeducedFD : UDTUpdates)
10164 (void)UndeducedFD->getMostRecentDecl();
10165 }
10166
10167 if (ReadTimer)
10168 ReadTimer->stopTimer();
10169
10170 diagnoseOdrViolations();
10171
10172 // We are not in recursive loading, so it's safe to pass the "interesting"
10173 // decls to the consumer.
10174 if (Consumer)
10175 PassInterestingDeclsToConsumer();
10176 }
10177}
10178
10179void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10180 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10181 // Remove any fake results before adding any real ones.
10182 auto It = PendingFakeLookupResults.find(II);
10183 if (It != PendingFakeLookupResults.end()) {
10184 for (auto *ND : It->second)
10185 SemaObj->IdResolver.RemoveDecl(ND);
10186 // FIXME: this works around module+PCH performance issue.
10187 // Rather than erase the result from the map, which is O(n), just clear
10188 // the vector of NamedDecls.
10189 It->second.clear();
10190 }
10191 }
10192
10193 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10194 SemaObj->TUScope->AddDecl(D);
10195 } else if (SemaObj->TUScope) {
10196 // Adding the decl to IdResolver may have failed because it was already in
10197 // (even though it was not added in scope). If it is already in, make sure
10198 // it gets in the scope as well.
10199 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10200 SemaObj->TUScope->AddDecl(D);
10201 }
10202}
10203
10205 ASTContext *Context,
10206 const PCHContainerReader &PCHContainerRdr,
10207 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10208 StringRef isysroot,
10209 DisableValidationForModuleKind DisableValidationKind,
10210 bool AllowASTWithCompilerErrors,
10211 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10212 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10213 std::unique_ptr<llvm::Timer> ReadTimer)
10214 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10216 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10217 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10218 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10219 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10220 PCHContainerRdr, PP.getHeaderSearchInfo()),
10221 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10222 DisableValidationKind(DisableValidationKind),
10223 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10224 AllowConfigurationMismatch(AllowConfigurationMismatch),
10225 ValidateSystemInputs(ValidateSystemInputs),
10226 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10227 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10228 SourceMgr.setExternalSLocEntrySource(this);
10229
10230 for (const auto &Ext : Extensions) {
10231 auto BlockName = Ext->getExtensionMetadata().BlockName;
10232 auto Known = ModuleFileExtensions.find(BlockName);
10233 if (Known != ModuleFileExtensions.end()) {
10234 Diags.Report(diag::warn_duplicate_module_file_extension)
10235 << BlockName;
10236 continue;
10237 }
10238
10239 ModuleFileExtensions.insert({BlockName, Ext});
10240 }
10241}
10242
10244 if (OwnsDeserializationListener)
10245 delete DeserializationListener;
10246}
10247
10249 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10250}
10251
10253 unsigned AbbrevID) {
10254 Idx = 0;
10255 Record.clear();
10256 return Cursor.readRecord(AbbrevID, Record);
10257}
10258//===----------------------------------------------------------------------===//
10259//// OMPClauseReader implementation
10260////===----------------------------------------------------------------------===//
10261
10262// This has to be in namespace clang because it's friended by all
10263// of the OMP clauses.
10264namespace clang {
10265
10266class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10268 ASTContext &Context;
10269
10270public:
10272 : Record(Record), Context(Record.getContext()) {}
10273#define GEN_CLANG_CLAUSE_CLASS
10274#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10275#include "llvm/Frontend/OpenMP/OMP.inc"
10279};
10280
10281} // end namespace clang
10282
10284 return OMPClauseReader(*this).readClause();
10285}
10286
10288 OMPClause *C = nullptr;
10289 switch (llvm::omp::Clause(Record.readInt())) {
10290 case llvm::omp::OMPC_if:
10291 C = new (Context) OMPIfClause();
10292 break;
10293 case llvm::omp::OMPC_final:
10294 C = new (Context) OMPFinalClause();
10295 break;
10296 case llvm::omp::OMPC_num_threads:
10297 C = new (Context) OMPNumThreadsClause();
10298 break;
10299 case llvm::omp::OMPC_safelen:
10300 C = new (Context) OMPSafelenClause();
10301 break;
10302 case llvm::omp::OMPC_simdlen:
10303 C = new (Context) OMPSimdlenClause();
10304 break;
10305 case llvm::omp::OMPC_sizes: {
10306 unsigned NumSizes = Record.readInt();
10307 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10308 break;
10309 }
10310 case llvm::omp::OMPC_full:
10311 C = OMPFullClause::CreateEmpty(Context);
10312 break;
10313 case llvm::omp::OMPC_partial:
10315 break;
10316 case llvm::omp::OMPC_allocator:
10317 C = new (Context) OMPAllocatorClause();
10318 break;
10319 case llvm::omp::OMPC_collapse:
10320 C = new (Context) OMPCollapseClause();
10321 break;
10322 case llvm::omp::OMPC_default:
10323 C = new (Context) OMPDefaultClause();
10324 break;
10325 case llvm::omp::OMPC_proc_bind:
10326 C = new (Context) OMPProcBindClause();
10327 break;
10328 case llvm::omp::OMPC_schedule:
10329 C = new (Context) OMPScheduleClause();
10330 break;
10331 case llvm::omp::OMPC_ordered:
10332 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10333 break;
10334 case llvm::omp::OMPC_nowait:
10335 C = new (Context) OMPNowaitClause();
10336 break;
10337 case llvm::omp::OMPC_untied:
10338 C = new (Context) OMPUntiedClause();
10339 break;
10340 case llvm::omp::OMPC_mergeable:
10341 C = new (Context) OMPMergeableClause();
10342 break;
10343 case llvm::omp::OMPC_read:
10344 C = new (Context) OMPReadClause();
10345 break;
10346 case llvm::omp::OMPC_write:
10347 C = new (Context) OMPWriteClause();
10348 break;
10349 case llvm::omp::OMPC_update:
10350 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10351 break;
10352 case llvm::omp::OMPC_capture:
10353 C = new (Context) OMPCaptureClause();
10354 break;
10355 case llvm::omp::OMPC_compare:
10356 C = new (Context) OMPCompareClause();
10357 break;
10358 case llvm::omp::OMPC_fail:
10359 C = new (Context) OMPFailClause();
10360 break;
10361 case llvm::omp::OMPC_seq_cst:
10362 C = new (Context) OMPSeqCstClause();
10363 break;
10364 case llvm::omp::OMPC_acq_rel:
10365 C = new (Context) OMPAcqRelClause();
10366 break;
10367 case llvm::omp::OMPC_acquire:
10368 C = new (Context) OMPAcquireClause();
10369 break;
10370 case llvm::omp::OMPC_release:
10371 C = new (Context) OMPReleaseClause();
10372 break;
10373 case llvm::omp::OMPC_relaxed:
10374 C = new (Context) OMPRelaxedClause();
10375 break;
10376 case llvm::omp::OMPC_weak:
10377 C = new (Context) OMPWeakClause();
10378 break;
10379 case llvm::omp::OMPC_threads:
10380 C = new (Context) OMPThreadsClause();
10381 break;
10382 case llvm::omp::OMPC_simd:
10383 C = new (Context) OMPSIMDClause();
10384 break;
10385 case llvm::omp::OMPC_nogroup:
10386 C = new (Context) OMPNogroupClause();
10387 break;
10388 case llvm::omp::OMPC_unified_address:
10389 C = new (Context) OMPUnifiedAddressClause();
10390 break;
10391 case llvm::omp::OMPC_unified_shared_memory:
10392 C = new (Context) OMPUnifiedSharedMemoryClause();
10393 break;
10394 case llvm::omp::OMPC_reverse_offload:
10395 C = new (Context) OMPReverseOffloadClause();
10396 break;
10397 case llvm::omp::OMPC_dynamic_allocators:
10398 C = new (Context) OMPDynamicAllocatorsClause();
10399 break;
10400 case llvm::omp::OMPC_atomic_default_mem_order:
10401 C = new (Context) OMPAtomicDefaultMemOrderClause();
10402 break;
10403 case llvm::omp::OMPC_at:
10404 C = new (Context) OMPAtClause();
10405 break;
10406 case llvm::omp::OMPC_severity:
10407 C = new (Context) OMPSeverityClause();
10408 break;
10409 case llvm::omp::OMPC_message:
10410 C = new (Context) OMPMessageClause();
10411 break;
10412 case llvm::omp::OMPC_private:
10413 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10414 break;
10415 case llvm::omp::OMPC_firstprivate:
10416 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10417 break;
10418 case llvm::omp::OMPC_lastprivate:
10419 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10420 break;
10421 case llvm::omp::OMPC_shared:
10422 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10423 break;
10424 case llvm::omp::OMPC_reduction: {
10425 unsigned N = Record.readInt();
10426 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10427 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10428 break;
10429 }
10430 case llvm::omp::OMPC_task_reduction:
10431 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10432 break;
10433 case llvm::omp::OMPC_in_reduction:
10434 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10435 break;
10436 case llvm::omp::OMPC_linear:
10437 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10438 break;
10439 case llvm::omp::OMPC_aligned:
10440 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10441 break;
10442 case llvm::omp::OMPC_copyin:
10443 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10444 break;
10445 case llvm::omp::OMPC_copyprivate:
10446 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10447 break;
10448 case llvm::omp::OMPC_flush:
10449 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10450 break;
10451 case llvm::omp::OMPC_depobj:
10453 break;
10454 case llvm::omp::OMPC_depend: {
10455 unsigned NumVars = Record.readInt();
10456 unsigned NumLoops = Record.readInt();
10457 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10458 break;
10459 }
10460 case llvm::omp::OMPC_device:
10461 C = new (Context) OMPDeviceClause();
10462 break;
10463 case llvm::omp::OMPC_map: {
10465 Sizes.NumVars = Record.readInt();
10466 Sizes.NumUniqueDeclarations = Record.readInt();
10467 Sizes.NumComponentLists = Record.readInt();
10468 Sizes.NumComponents = Record.readInt();
10469 C = OMPMapClause::CreateEmpty(Context, Sizes);
10470 break;
10471 }
10472 case llvm::omp::OMPC_num_teams:
10473 C = new (Context) OMPNumTeamsClause();
10474 break;
10475 case llvm::omp::OMPC_thread_limit:
10476 C = new (Context) OMPThreadLimitClause();
10477 break;
10478 case llvm::omp::OMPC_priority:
10479 C = new (Context) OMPPriorityClause();
10480 break;
10481 case llvm::omp::OMPC_grainsize:
10482 C = new (Context) OMPGrainsizeClause();
10483 break;
10484 case llvm::omp::OMPC_num_tasks:
10485 C = new (Context) OMPNumTasksClause();
10486 break;
10487 case llvm::omp::OMPC_hint:
10488 C = new (Context) OMPHintClause();
10489 break;
10490 case llvm::omp::OMPC_dist_schedule:
10491 C = new (Context) OMPDistScheduleClause();
10492 break;
10493 case llvm::omp::OMPC_defaultmap:
10494 C = new (Context) OMPDefaultmapClause();
10495 break;
10496 case llvm::omp::OMPC_to: {
10498 Sizes.NumVars = Record.readInt();
10499 Sizes.NumUniqueDeclarations = Record.readInt();
10500 Sizes.NumComponentLists = Record.readInt();
10501 Sizes.NumComponents = Record.readInt();
10502 C = OMPToClause::CreateEmpty(Context, Sizes);
10503 break;
10504 }
10505 case llvm::omp::OMPC_from: {
10507 Sizes.NumVars = Record.readInt();
10508 Sizes.NumUniqueDeclarations = Record.readInt();
10509 Sizes.NumComponentLists = Record.readInt();
10510 Sizes.NumComponents = Record.readInt();
10511 C = OMPFromClause::CreateEmpty(Context, Sizes);
10512 break;
10513 }
10514 case llvm::omp::OMPC_use_device_ptr: {
10516 Sizes.NumVars = Record.readInt();
10517 Sizes.NumUniqueDeclarations = Record.readInt();
10518 Sizes.NumComponentLists = Record.readInt();
10519 Sizes.NumComponents = Record.readInt();
10520 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10521 break;
10522 }
10523 case llvm::omp::OMPC_use_device_addr: {
10525 Sizes.NumVars = Record.readInt();
10526 Sizes.NumUniqueDeclarations = Record.readInt();
10527 Sizes.NumComponentLists = Record.readInt();
10528 Sizes.NumComponents = Record.readInt();
10529 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10530 break;
10531 }
10532 case llvm::omp::OMPC_is_device_ptr: {
10534 Sizes.NumVars = Record.readInt();
10535 Sizes.NumUniqueDeclarations = Record.readInt();
10536 Sizes.NumComponentLists = Record.readInt();
10537 Sizes.NumComponents = Record.readInt();
10538 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10539 break;
10540 }
10541 case llvm::omp::OMPC_has_device_addr: {
10543 Sizes.NumVars = Record.readInt();
10544 Sizes.NumUniqueDeclarations = Record.readInt();
10545 Sizes.NumComponentLists = Record.readInt();
10546 Sizes.NumComponents = Record.readInt();
10547 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10548 break;
10549 }
10550 case llvm::omp::OMPC_allocate:
10551 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10552 break;
10553 case llvm::omp::OMPC_nontemporal:
10554 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10555 break;
10556 case llvm::omp::OMPC_inclusive:
10557 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10558 break;
10559 case llvm::omp::OMPC_exclusive:
10560 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10561 break;
10562 case llvm::omp::OMPC_order:
10563 C = new (Context) OMPOrderClause();
10564 break;
10565 case llvm::omp::OMPC_init:
10566 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10567 break;
10568 case llvm::omp::OMPC_use:
10569 C = new (Context) OMPUseClause();
10570 break;
10571 case llvm::omp::OMPC_destroy:
10572 C = new (Context) OMPDestroyClause();
10573 break;
10574 case llvm::omp::OMPC_novariants:
10575 C = new (Context) OMPNovariantsClause();
10576 break;
10577 case llvm::omp::OMPC_nocontext:
10578 C = new (Context) OMPNocontextClause();
10579 break;
10580 case llvm::omp::OMPC_detach:
10581 C = new (Context) OMPDetachClause();
10582 break;
10583 case llvm::omp::OMPC_uses_allocators:
10584 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10585 break;
10586 case llvm::omp::OMPC_affinity:
10587 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10588 break;
10589 case llvm::omp::OMPC_filter:
10590 C = new (Context) OMPFilterClause();
10591 break;
10592 case llvm::omp::OMPC_bind:
10593 C = OMPBindClause::CreateEmpty(Context);
10594 break;
10595 case llvm::omp::OMPC_align:
10596 C = new (Context) OMPAlignClause();
10597 break;
10598 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10599 C = new (Context) OMPXDynCGroupMemClause();
10600 break;
10601 case llvm::omp::OMPC_doacross: {
10602 unsigned NumVars = Record.readInt();
10603 unsigned NumLoops = Record.readInt();
10604 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10605 break;
10606 }
10607 case llvm::omp::OMPC_ompx_attribute:
10608 C = new (Context) OMPXAttributeClause();
10609 break;
10610 case llvm::omp::OMPC_ompx_bare:
10611 C = new (Context) OMPXBareClause();
10612 break;
10613#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10614 case llvm::omp::Enum: \
10615 break;
10616#include "llvm/Frontend/OpenMP/OMPKinds.def"
10617 default:
10618 break;
10619 }
10620 assert(C && "Unknown OMPClause type");
10621
10622 Visit(C);
10623 C->setLocStart(Record.readSourceLocation());
10624 C->setLocEnd(Record.readSourceLocation());
10625
10626 return C;
10627}
10628
10630 C->setPreInitStmt(Record.readSubStmt(),
10631 static_cast<OpenMPDirectiveKind>(Record.readInt()));
10632}
10633
10636 C->setPostUpdateExpr(Record.readSubExpr());
10637}
10638
10639void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10641 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10642 C->setNameModifierLoc(Record.readSourceLocation());
10643 C->setColonLoc(Record.readSourceLocation());
10644 C->setCondition(Record.readSubExpr());
10645 C->setLParenLoc(Record.readSourceLocation());
10646}
10647
10648void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10650 C->setCondition(Record.readSubExpr());
10651 C->setLParenLoc(Record.readSourceLocation());
10652}
10653
10654void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10656 C->setNumThreads(Record.readSubExpr());
10657 C->setLParenLoc(Record.readSourceLocation());
10658}
10659
10660void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10661 C->setSafelen(Record.readSubExpr());
10662 C->setLParenLoc(Record.readSourceLocation());
10663}
10664
10665void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10666 C->setSimdlen(Record.readSubExpr());
10667 C->setLParenLoc(Record.readSourceLocation());
10668}
10669
10670void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10671 for (Expr *&E : C->getSizesRefs())
10672 E = Record.readSubExpr();
10673 C->setLParenLoc(Record.readSourceLocation());
10674}
10675
10676void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10677
10678void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10679 C->setFactor(Record.readSubExpr());
10680 C->setLParenLoc(Record.readSourceLocation());
10681}
10682
10683void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10684 C->setAllocator(Record.readExpr());
10685 C->setLParenLoc(Record.readSourceLocation());
10686}
10687
10688void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10689 C->setNumForLoops(Record.readSubExpr());
10690 C->setLParenLoc(Record.readSourceLocation());
10691}
10692
10693void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10694 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10695 C->setLParenLoc(Record.readSourceLocation());
10696 C->setDefaultKindKwLoc(Record.readSourceLocation());
10697}
10698
10699void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10700 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10701 C->setLParenLoc(Record.readSourceLocation());
10702 C->setProcBindKindKwLoc(Record.readSourceLocation());
10703}
10704
10705void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10707 C->setScheduleKind(
10708 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10709 C->setFirstScheduleModifier(
10710 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10711 C->setSecondScheduleModifier(
10712 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10713 C->setChunkSize(Record.readSubExpr());
10714 C->setLParenLoc(Record.readSourceLocation());
10715 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10716 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10717 C->setScheduleKindLoc(Record.readSourceLocation());
10718 C->setCommaLoc(Record.readSourceLocation());
10719}
10720
10721void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10722 C->setNumForLoops(Record.readSubExpr());
10723 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10724 C->setLoopNumIterations(I, Record.readSubExpr());
10725 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10726 C->setLoopCounter(I, Record.readSubExpr());
10727 C->setLParenLoc(Record.readSourceLocation());
10728}
10729
10730void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10731 C->setEventHandler(Record.readSubExpr());
10732 C->setLParenLoc(Record.readSourceLocation());
10733}
10734
10735void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10736
10737void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10738
10739void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10740
10741void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10742
10743void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10744
10745void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10746 if (C->isExtended()) {
10747 C->setLParenLoc(Record.readSourceLocation());
10748 C->setArgumentLoc(Record.readSourceLocation());
10749 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10750 }
10751}
10752
10753void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10754
10755void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10756
10757// Read the parameter of fail clause. This will have been saved when
10758// OMPClauseWriter is called.
10759void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10760 C->setLParenLoc(Record.readSourceLocation());
10761 SourceLocation FailParameterLoc = Record.readSourceLocation();
10762 C->setFailParameterLoc(FailParameterLoc);
10763 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10764 C->setFailParameter(CKind);
10765}
10766
10767void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10768
10769void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10770
10771void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10772
10773void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10774
10775void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10776
10777void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
10778
10779void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10780
10781void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10782
10783void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10784
10785void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10786 unsigned NumVars = C->varlist_size();
10788 Vars.reserve(NumVars);
10789 for (unsigned I = 0; I != NumVars; ++I)
10790 Vars.push_back(Record.readSubExpr());
10791 C->setVarRefs(Vars);
10792 C->setIsTarget(Record.readBool());
10793 C->setIsTargetSync(Record.readBool());
10794 C->setLParenLoc(Record.readSourceLocation());
10795 C->setVarLoc(Record.readSourceLocation());
10796}
10797
10798void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10799 C->setInteropVar(Record.readSubExpr());
10800 C->setLParenLoc(Record.readSourceLocation());
10801 C->setVarLoc(Record.readSourceLocation());
10802}
10803
10804void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10805 C->setInteropVar(Record.readSubExpr());
10806 C->setLParenLoc(Record.readSourceLocation());
10807 C->setVarLoc(Record.readSourceLocation());
10808}
10809
10810void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10812 C->setCondition(Record.readSubExpr());
10813 C->setLParenLoc(Record.readSourceLocation());
10814}
10815
10816void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10818 C->setCondition(Record.readSubExpr());
10819 C->setLParenLoc(Record.readSourceLocation());
10820}
10821
10822void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10823
10824void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10826
10827void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10828
10829void
10830OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10831}
10832
10833void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10835 C->setAtomicDefaultMemOrderKind(
10836 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10837 C->setLParenLoc(Record.readSourceLocation());
10838 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10839}
10840
10841void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10842 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10843 C->setLParenLoc(Record.readSourceLocation());
10844 C->setAtKindKwLoc(Record.readSourceLocation());
10845}
10846
10847void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10848 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10849 C->setLParenLoc(Record.readSourceLocation());
10850 C->setSeverityKindKwLoc(Record.readSourceLocation());
10851}
10852
10853void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10854 C->setMessageString(Record.readSubExpr());
10855 C->setLParenLoc(Record.readSourceLocation());
10856}
10857
10858void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10859 C->setLParenLoc(Record.readSourceLocation());
10860 unsigned NumVars = C->varlist_size();
10862 Vars.reserve(NumVars);
10863 for (unsigned i = 0; i != NumVars; ++i)
10864 Vars.push_back(Record.readSubExpr());
10865 C->setVarRefs(Vars);
10866 Vars.clear();
10867 for (unsigned i = 0; i != NumVars; ++i)
10868 Vars.push_back(Record.readSubExpr());
10869 C->setPrivateCopies(Vars);
10870}
10871
10872void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10874 C->setLParenLoc(Record.readSourceLocation());
10875 unsigned NumVars = C->varlist_size();
10877 Vars.reserve(NumVars);
10878 for (unsigned i = 0; i != NumVars; ++i)
10879 Vars.push_back(Record.readSubExpr());
10880 C->setVarRefs(Vars);
10881 Vars.clear();
10882 for (unsigned i = 0; i != NumVars; ++i)
10883 Vars.push_back(Record.readSubExpr());
10884 C->setPrivateCopies(Vars);
10885 Vars.clear();
10886 for (unsigned i = 0; i != NumVars; ++i)
10887 Vars.push_back(Record.readSubExpr());
10888 C->setInits(Vars);
10889}
10890
10891void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10893 C->setLParenLoc(Record.readSourceLocation());
10894 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10895 C->setKindLoc(Record.readSourceLocation());
10896 C->setColonLoc(Record.readSourceLocation());
10897 unsigned NumVars = C->varlist_size();
10899 Vars.reserve(NumVars);
10900 for (unsigned i = 0; i != NumVars; ++i)
10901 Vars.push_back(Record.readSubExpr());
10902 C->setVarRefs(Vars);
10903 Vars.clear();
10904 for (unsigned i = 0; i != NumVars; ++i)
10905 Vars.push_back(Record.readSubExpr());
10906 C->setPrivateCopies(Vars);
10907 Vars.clear();
10908 for (unsigned i = 0; i != NumVars; ++i)
10909 Vars.push_back(Record.readSubExpr());
10910 C->setSourceExprs(Vars);
10911 Vars.clear();
10912 for (unsigned i = 0; i != NumVars; ++i)
10913 Vars.push_back(Record.readSubExpr());
10914 C->setDestinationExprs(Vars);
10915 Vars.clear();
10916 for (unsigned i = 0; i != NumVars; ++i)
10917 Vars.push_back(Record.readSubExpr());
10918 C->setAssignmentOps(Vars);
10919}
10920
10921void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10922 C->setLParenLoc(Record.readSourceLocation());
10923 unsigned NumVars = C->varlist_size();
10925 Vars.reserve(NumVars);
10926 for (unsigned i = 0; i != NumVars; ++i)
10927 Vars.push_back(Record.readSubExpr());
10928 C->setVarRefs(Vars);
10929}
10930
10931void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10933 C->setLParenLoc(Record.readSourceLocation());
10934 C->setModifierLoc(Record.readSourceLocation());
10935 C->setColonLoc(Record.readSourceLocation());
10936 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10937 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10938 C->setQualifierLoc(NNSL);
10939 C->setNameInfo(DNI);
10940
10941 unsigned NumVars = C->varlist_size();
10943 Vars.reserve(NumVars);
10944 for (unsigned i = 0; i != NumVars; ++i)
10945 Vars.push_back(Record.readSubExpr());
10946 C->setVarRefs(Vars);
10947 Vars.clear();
10948 for (unsigned i = 0; i != NumVars; ++i)
10949 Vars.push_back(Record.readSubExpr());
10950 C->setPrivates(Vars);
10951 Vars.clear();
10952 for (unsigned i = 0; i != NumVars; ++i)
10953 Vars.push_back(Record.readSubExpr());
10954 C->setLHSExprs(Vars);
10955 Vars.clear();
10956 for (unsigned i = 0; i != NumVars; ++i)
10957 Vars.push_back(Record.readSubExpr());
10958 C->setRHSExprs(Vars);
10959 Vars.clear();
10960 for (unsigned i = 0; i != NumVars; ++i)
10961 Vars.push_back(Record.readSubExpr());
10962 C->setReductionOps(Vars);
10963 if (C->getModifier() == OMPC_REDUCTION_inscan) {
10964 Vars.clear();
10965 for (unsigned i = 0; i != NumVars; ++i)
10966 Vars.push_back(Record.readSubExpr());
10967 C->setInscanCopyOps(Vars);
10968 Vars.clear();
10969 for (unsigned i = 0; i != NumVars; ++i)
10970 Vars.push_back(Record.readSubExpr());
10971 C->setInscanCopyArrayTemps(Vars);
10972 Vars.clear();
10973 for (unsigned i = 0; i != NumVars; ++i)
10974 Vars.push_back(Record.readSubExpr());
10975 C->setInscanCopyArrayElems(Vars);
10976 }
10977}
10978
10979void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10981 C->setLParenLoc(Record.readSourceLocation());
10982 C->setColonLoc(Record.readSourceLocation());
10983 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10984 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10985 C->setQualifierLoc(NNSL);
10986 C->setNameInfo(DNI);
10987
10988 unsigned NumVars = C->varlist_size();
10990 Vars.reserve(NumVars);
10991 for (unsigned I = 0; I != NumVars; ++I)
10992 Vars.push_back(Record.readSubExpr());
10993 C->setVarRefs(Vars);
10994 Vars.clear();
10995 for (unsigned I = 0; I != NumVars; ++I)
10996 Vars.push_back(Record.readSubExpr());
10997 C->setPrivates(Vars);
10998 Vars.clear();
10999 for (unsigned I = 0; I != NumVars; ++I)
11000 Vars.push_back(Record.readSubExpr());
11001 C->setLHSExprs(Vars);
11002 Vars.clear();
11003 for (unsigned I = 0; I != NumVars; ++I)
11004 Vars.push_back(Record.readSubExpr());
11005 C->setRHSExprs(Vars);
11006 Vars.clear();
11007 for (unsigned I = 0; I != NumVars; ++I)
11008 Vars.push_back(Record.readSubExpr());
11009 C->setReductionOps(Vars);
11010}
11011
11012void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11014 C->setLParenLoc(Record.readSourceLocation());
11015 C->setColonLoc(Record.readSourceLocation());
11016 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11017 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11018 C->setQualifierLoc(NNSL);
11019 C->setNameInfo(DNI);
11020
11021 unsigned NumVars = C->varlist_size();
11023 Vars.reserve(NumVars);
11024 for (unsigned I = 0; I != NumVars; ++I)
11025 Vars.push_back(Record.readSubExpr());
11026 C->setVarRefs(Vars);
11027 Vars.clear();
11028 for (unsigned I = 0; I != NumVars; ++I)
11029 Vars.push_back(Record.readSubExpr());
11030 C->setPrivates(Vars);
11031 Vars.clear();
11032 for (unsigned I = 0; I != NumVars; ++I)
11033 Vars.push_back(Record.readSubExpr());
11034 C->setLHSExprs(Vars);
11035 Vars.clear();
11036 for (unsigned I = 0; I != NumVars; ++I)
11037 Vars.push_back(Record.readSubExpr());
11038 C->setRHSExprs(Vars);
11039 Vars.clear();
11040 for (unsigned I = 0; I != NumVars; ++I)
11041 Vars.push_back(Record.readSubExpr());
11042 C->setReductionOps(Vars);
11043 Vars.clear();
11044 for (unsigned I = 0; I != NumVars; ++I)
11045 Vars.push_back(Record.readSubExpr());
11046 C->setTaskgroupDescriptors(Vars);
11047}
11048
11049void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11051 C->setLParenLoc(Record.readSourceLocation());
11052 C->setColonLoc(Record.readSourceLocation());
11053 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11054 C->setModifierLoc(Record.readSourceLocation());
11055 unsigned NumVars = C->varlist_size();
11057 Vars.reserve(NumVars);
11058 for (unsigned i = 0; i != NumVars; ++i)
11059 Vars.push_back(Record.readSubExpr());
11060 C->setVarRefs(Vars);
11061 Vars.clear();
11062 for (unsigned i = 0; i != NumVars; ++i)
11063 Vars.push_back(Record.readSubExpr());
11064 C->setPrivates(Vars);
11065 Vars.clear();
11066 for (unsigned i = 0; i != NumVars; ++i)
11067 Vars.push_back(Record.readSubExpr());
11068 C->setInits(Vars);
11069 Vars.clear();
11070 for (unsigned i = 0; i != NumVars; ++i)
11071 Vars.push_back(Record.readSubExpr());
11072 C->setUpdates(Vars);
11073 Vars.clear();
11074 for (unsigned i = 0; i != NumVars; ++i)
11075 Vars.push_back(Record.readSubExpr());
11076 C->setFinals(Vars);
11077 C->setStep(Record.readSubExpr());
11078 C->setCalcStep(Record.readSubExpr());
11079 Vars.clear();
11080 for (unsigned I = 0; I != NumVars + 1; ++I)
11081 Vars.push_back(Record.readSubExpr());
11082 C->setUsedExprs(Vars);
11083}
11084
11085void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11086 C->setLParenLoc(Record.readSourceLocation());
11087 C->setColonLoc(Record.readSourceLocation());
11088 unsigned NumVars = C->varlist_size();
11090 Vars.reserve(NumVars);
11091 for (unsigned i = 0; i != NumVars; ++i)
11092 Vars.push_back(Record.readSubExpr());
11093 C->setVarRefs(Vars);
11094 C->setAlignment(Record.readSubExpr());
11095}
11096
11097void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11098 C->setLParenLoc(Record.readSourceLocation());
11099 unsigned NumVars = C->varlist_size();
11101 Exprs.reserve(NumVars);
11102 for (unsigned i = 0; i != NumVars; ++i)
11103 Exprs.push_back(Record.readSubExpr());
11104 C->setVarRefs(Exprs);
11105 Exprs.clear();
11106 for (unsigned i = 0; i != NumVars; ++i)
11107 Exprs.push_back(Record.readSubExpr());
11108 C->setSourceExprs(Exprs);
11109 Exprs.clear();
11110 for (unsigned i = 0; i != NumVars; ++i)
11111 Exprs.push_back(Record.readSubExpr());
11112 C->setDestinationExprs(Exprs);
11113 Exprs.clear();
11114 for (unsigned i = 0; i != NumVars; ++i)
11115 Exprs.push_back(Record.readSubExpr());
11116 C->setAssignmentOps(Exprs);
11117}
11118
11119void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11120 C->setLParenLoc(Record.readSourceLocation());
11121 unsigned NumVars = C->varlist_size();
11123 Exprs.reserve(NumVars);
11124 for (unsigned i = 0; i != NumVars; ++i)
11125 Exprs.push_back(Record.readSubExpr());
11126 C->setVarRefs(Exprs);
11127 Exprs.clear();
11128 for (unsigned i = 0; i != NumVars; ++i)
11129 Exprs.push_back(Record.readSubExpr());
11130 C->setSourceExprs(Exprs);
11131 Exprs.clear();
11132 for (unsigned i = 0; i != NumVars; ++i)
11133 Exprs.push_back(Record.readSubExpr());
11134 C->setDestinationExprs(Exprs);
11135 Exprs.clear();
11136 for (unsigned i = 0; i != NumVars; ++i)
11137 Exprs.push_back(Record.readSubExpr());
11138 C->setAssignmentOps(Exprs);
11139}
11140
11141void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11142 C->setLParenLoc(Record.readSourceLocation());
11143 unsigned NumVars = C->varlist_size();
11145 Vars.reserve(NumVars);
11146 for (unsigned i = 0; i != NumVars; ++i)
11147 Vars.push_back(Record.readSubExpr());
11148 C->setVarRefs(Vars);
11149}
11150
11151void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11152 C->setDepobj(Record.readSubExpr());
11153 C->setLParenLoc(Record.readSourceLocation());
11154}
11155
11156void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11157 C->setLParenLoc(Record.readSourceLocation());
11158 C->setModifier(Record.readSubExpr());
11159 C->setDependencyKind(
11160 static_cast<OpenMPDependClauseKind>(Record.readInt()));
11161 C->setDependencyLoc(Record.readSourceLocation());
11162 C->setColonLoc(Record.readSourceLocation());
11163 C->setOmpAllMemoryLoc(Record.readSourceLocation());
11164 unsigned NumVars = C->varlist_size();
11166 Vars.reserve(NumVars);
11167 for (unsigned I = 0; I != NumVars; ++I)
11168 Vars.push_back(Record.readSubExpr());
11169 C->setVarRefs(Vars);
11170 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11171 C->setLoopData(I, Record.readSubExpr());
11172}
11173
11174void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11176 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11177 C->setDevice(Record.readSubExpr());
11178 C->setModifierLoc(Record.readSourceLocation());
11179 C->setLParenLoc(Record.readSourceLocation());
11180}
11181
11182void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11183 C->setLParenLoc(Record.readSourceLocation());
11184 bool HasIteratorModifier = false;
11185 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11186 C->setMapTypeModifier(
11187 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11188 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11189 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11190 HasIteratorModifier = true;
11191 }
11192 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11193 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11194 C->setMapType(
11195 static_cast<OpenMPMapClauseKind>(Record.readInt()));
11196 C->setMapLoc(Record.readSourceLocation());
11197 C->setColonLoc(Record.readSourceLocation());
11198 auto NumVars = C->varlist_size();
11199 auto UniqueDecls = C->getUniqueDeclarationsNum();
11200 auto TotalLists = C->getTotalComponentListNum();
11201 auto TotalComponents = C->getTotalComponentsNum();
11202
11204 Vars.reserve(NumVars);
11205 for (unsigned i = 0; i != NumVars; ++i)
11206 Vars.push_back(Record.readExpr());
11207 C->setVarRefs(Vars);
11208
11209 SmallVector<Expr *, 16> UDMappers;
11210 UDMappers.reserve(NumVars);
11211 for (unsigned I = 0; I < NumVars; ++I)
11212 UDMappers.push_back(Record.readExpr());
11213 C->setUDMapperRefs(UDMappers);
11214
11215 if (HasIteratorModifier)
11216 C->setIteratorModifier(Record.readExpr());
11217
11219 Decls.reserve(UniqueDecls);
11220 for (unsigned i = 0; i < UniqueDecls; ++i)
11221 Decls.push_back(Record.readDeclAs<ValueDecl>());
11222 C->setUniqueDecls(Decls);
11223
11224 SmallVector<unsigned, 16> ListsPerDecl;
11225 ListsPerDecl.reserve(UniqueDecls);
11226 for (unsigned i = 0; i < UniqueDecls; ++i)
11227 ListsPerDecl.push_back(Record.readInt());
11228 C->setDeclNumLists(ListsPerDecl);
11229
11230 SmallVector<unsigned, 32> ListSizes;
11231 ListSizes.reserve(TotalLists);
11232 for (unsigned i = 0; i < TotalLists; ++i)
11233 ListSizes.push_back(Record.readInt());
11234 C->setComponentListSizes(ListSizes);
11235
11237 Components.reserve(TotalComponents);
11238 for (unsigned i = 0; i < TotalComponents; ++i) {
11239 Expr *AssociatedExprPr = Record.readExpr();
11240 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11241 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11242 /*IsNonContiguous=*/false);
11243 }
11244 C->setComponents(Components, ListSizes);
11245}
11246
11247void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11248 C->setLParenLoc(Record.readSourceLocation());
11249 C->setColonLoc(Record.readSourceLocation());
11250 C->setAllocator(Record.readSubExpr());
11251 unsigned NumVars = C->varlist_size();
11253 Vars.reserve(NumVars);
11254 for (unsigned i = 0; i != NumVars; ++i)
11255 Vars.push_back(Record.readSubExpr());
11256 C->setVarRefs(Vars);
11257}
11258
11259void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11261 C->setNumTeams(Record.readSubExpr());
11262 C->setLParenLoc(Record.readSourceLocation());
11263}
11264
11265void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11267 C->setThreadLimit(Record.readSubExpr());
11268 C->setLParenLoc(Record.readSourceLocation());
11269}
11270
11271void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11273 C->setPriority(Record.readSubExpr());
11274 C->setLParenLoc(Record.readSourceLocation());
11275}
11276
11277void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11279 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11280 C->setGrainsize(Record.readSubExpr());
11281 C->setModifierLoc(Record.readSourceLocation());
11282 C->setLParenLoc(Record.readSourceLocation());
11283}
11284
11285void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11287 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11288 C->setNumTasks(Record.readSubExpr());
11289 C->setModifierLoc(Record.readSourceLocation());
11290 C->setLParenLoc(Record.readSourceLocation());
11291}
11292
11293void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11294 C->setHint(Record.readSubExpr());
11295 C->setLParenLoc(Record.readSourceLocation());
11296}
11297
11298void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11300 C->setDistScheduleKind(
11301 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11302 C->setChunkSize(Record.readSubExpr());
11303 C->setLParenLoc(Record.readSourceLocation());
11304 C->setDistScheduleKindLoc(Record.readSourceLocation());
11305 C->setCommaLoc(Record.readSourceLocation());
11306}
11307
11308void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11309 C->setDefaultmapKind(
11310 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11311 C->setDefaultmapModifier(
11312 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11313 C->setLParenLoc(Record.readSourceLocation());
11314 C->setDefaultmapModifierLoc(Record.readSourceLocation());
11315 C->setDefaultmapKindLoc(Record.readSourceLocation());
11316}
11317
11318void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11319 C->setLParenLoc(Record.readSourceLocation());
11320 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11321 C->setMotionModifier(
11322 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11323 C->setMotionModifierLoc(I, Record.readSourceLocation());
11324 }
11325 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11326 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11327 C->setColonLoc(Record.readSourceLocation());
11328 auto NumVars = C->varlist_size();
11329 auto UniqueDecls = C->getUniqueDeclarationsNum();
11330 auto TotalLists = C->getTotalComponentListNum();
11331 auto TotalComponents = C->getTotalComponentsNum();
11332
11334 Vars.reserve(NumVars);
11335 for (unsigned i = 0; i != NumVars; ++i)
11336 Vars.push_back(Record.readSubExpr());
11337 C->setVarRefs(Vars);
11338
11339 SmallVector<Expr *, 16> UDMappers;
11340 UDMappers.reserve(NumVars);
11341 for (unsigned I = 0; I < NumVars; ++I)
11342 UDMappers.push_back(Record.readSubExpr());
11343 C->setUDMapperRefs(UDMappers);
11344
11346 Decls.reserve(UniqueDecls);
11347 for (unsigned i = 0; i < UniqueDecls; ++i)
11348 Decls.push_back(Record.readDeclAs<ValueDecl>());
11349 C->setUniqueDecls(Decls);
11350
11351 SmallVector<unsigned, 16> ListsPerDecl;
11352 ListsPerDecl.reserve(UniqueDecls);
11353 for (unsigned i = 0; i < UniqueDecls; ++i)
11354 ListsPerDecl.push_back(Record.readInt());
11355 C->setDeclNumLists(ListsPerDecl);
11356
11357 SmallVector<unsigned, 32> ListSizes;
11358 ListSizes.reserve(TotalLists);
11359 for (unsigned i = 0; i < TotalLists; ++i)
11360 ListSizes.push_back(Record.readInt());
11361 C->setComponentListSizes(ListSizes);
11362
11364 Components.reserve(TotalComponents);
11365 for (unsigned i = 0; i < TotalComponents; ++i) {
11366 Expr *AssociatedExprPr = Record.readSubExpr();
11367 bool IsNonContiguous = Record.readBool();
11368 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11369 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11370 }
11371 C->setComponents(Components, ListSizes);
11372}
11373
11374void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11375 C->setLParenLoc(Record.readSourceLocation());
11376 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11377 C->setMotionModifier(
11378 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11379 C->setMotionModifierLoc(I, Record.readSourceLocation());
11380 }
11381 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11382 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11383 C->setColonLoc(Record.readSourceLocation());
11384 auto NumVars = C->varlist_size();
11385 auto UniqueDecls = C->getUniqueDeclarationsNum();
11386 auto TotalLists = C->getTotalComponentListNum();
11387 auto TotalComponents = C->getTotalComponentsNum();
11388
11390 Vars.reserve(NumVars);
11391 for (unsigned i = 0; i != NumVars; ++i)
11392 Vars.push_back(Record.readSubExpr());
11393 C->setVarRefs(Vars);
11394
11395 SmallVector<Expr *, 16> UDMappers;
11396 UDMappers.reserve(NumVars);
11397 for (unsigned I = 0; I < NumVars; ++I)
11398 UDMappers.push_back(Record.readSubExpr());
11399 C->setUDMapperRefs(UDMappers);
11400
11402 Decls.reserve(UniqueDecls);
11403 for (unsigned i = 0; i < UniqueDecls; ++i)
11404 Decls.push_back(Record.readDeclAs<ValueDecl>());
11405 C->setUniqueDecls(Decls);
11406
11407 SmallVector<unsigned, 16> ListsPerDecl;
11408 ListsPerDecl.reserve(UniqueDecls);
11409 for (unsigned i = 0; i < UniqueDecls; ++i)
11410 ListsPerDecl.push_back(Record.readInt());
11411 C->setDeclNumLists(ListsPerDecl);
11412
11413 SmallVector<unsigned, 32> ListSizes;
11414 ListSizes.reserve(TotalLists);
11415 for (unsigned i = 0; i < TotalLists; ++i)
11416 ListSizes.push_back(Record.readInt());
11417 C->setComponentListSizes(ListSizes);
11418
11420 Components.reserve(TotalComponents);
11421 for (unsigned i = 0; i < TotalComponents; ++i) {
11422 Expr *AssociatedExprPr = Record.readSubExpr();
11423 bool IsNonContiguous = Record.readBool();
11424 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11425 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11426 }
11427 C->setComponents(Components, ListSizes);
11428}
11429
11430void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11431 C->setLParenLoc(Record.readSourceLocation());
11432 auto NumVars = C->varlist_size();
11433 auto UniqueDecls = C->getUniqueDeclarationsNum();
11434 auto TotalLists = C->getTotalComponentListNum();
11435 auto TotalComponents = C->getTotalComponentsNum();
11436
11438 Vars.reserve(NumVars);
11439 for (unsigned i = 0; i != NumVars; ++i)
11440 Vars.push_back(Record.readSubExpr());
11441 C->setVarRefs(Vars);
11442 Vars.clear();
11443 for (unsigned i = 0; i != NumVars; ++i)
11444 Vars.push_back(Record.readSubExpr());
11445 C->setPrivateCopies(Vars);
11446 Vars.clear();
11447 for (unsigned i = 0; i != NumVars; ++i)
11448 Vars.push_back(Record.readSubExpr());
11449 C->setInits(Vars);
11450
11452 Decls.reserve(UniqueDecls);
11453 for (unsigned i = 0; i < UniqueDecls; ++i)
11454 Decls.push_back(Record.readDeclAs<ValueDecl>());
11455 C->setUniqueDecls(Decls);
11456
11457 SmallVector<unsigned, 16> ListsPerDecl;
11458 ListsPerDecl.reserve(UniqueDecls);
11459 for (unsigned i = 0; i < UniqueDecls; ++i)
11460 ListsPerDecl.push_back(Record.readInt());
11461 C->setDeclNumLists(ListsPerDecl);
11462
11463 SmallVector<unsigned, 32> ListSizes;
11464 ListSizes.reserve(TotalLists);
11465 for (unsigned i = 0; i < TotalLists; ++i)
11466 ListSizes.push_back(Record.readInt());
11467 C->setComponentListSizes(ListSizes);
11468
11470 Components.reserve(TotalComponents);
11471 for (unsigned i = 0; i < TotalComponents; ++i) {
11472 auto *AssociatedExprPr = Record.readSubExpr();
11473 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11474 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11475 /*IsNonContiguous=*/false);
11476 }
11477 C->setComponents(Components, ListSizes);
11478}
11479
11480void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11481 C->setLParenLoc(Record.readSourceLocation());
11482 auto NumVars = C->varlist_size();
11483 auto UniqueDecls = C->getUniqueDeclarationsNum();
11484 auto TotalLists = C->getTotalComponentListNum();
11485 auto TotalComponents = C->getTotalComponentsNum();
11486
11488 Vars.reserve(NumVars);
11489 for (unsigned i = 0; i != NumVars; ++i)
11490 Vars.push_back(Record.readSubExpr());
11491 C->setVarRefs(Vars);
11492
11494 Decls.reserve(UniqueDecls);
11495 for (unsigned i = 0; i < UniqueDecls; ++i)
11496 Decls.push_back(Record.readDeclAs<ValueDecl>());
11497 C->setUniqueDecls(Decls);
11498
11499 SmallVector<unsigned, 16> ListsPerDecl;
11500 ListsPerDecl.reserve(UniqueDecls);
11501 for (unsigned i = 0; i < UniqueDecls; ++i)
11502 ListsPerDecl.push_back(Record.readInt());
11503 C->setDeclNumLists(ListsPerDecl);
11504
11505 SmallVector<unsigned, 32> ListSizes;
11506 ListSizes.reserve(TotalLists);
11507 for (unsigned i = 0; i < TotalLists; ++i)
11508 ListSizes.push_back(Record.readInt());
11509 C->setComponentListSizes(ListSizes);
11510
11512 Components.reserve(TotalComponents);
11513 for (unsigned i = 0; i < TotalComponents; ++i) {
11514 Expr *AssociatedExpr = Record.readSubExpr();
11515 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11516 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11517 /*IsNonContiguous*/ false);
11518 }
11519 C->setComponents(Components, ListSizes);
11520}
11521
11522void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11523 C->setLParenLoc(Record.readSourceLocation());
11524 auto NumVars = C->varlist_size();
11525 auto UniqueDecls = C->getUniqueDeclarationsNum();
11526 auto TotalLists = C->getTotalComponentListNum();
11527 auto TotalComponents = C->getTotalComponentsNum();
11528
11530 Vars.reserve(NumVars);
11531 for (unsigned i = 0; i != NumVars; ++i)
11532 Vars.push_back(Record.readSubExpr());
11533 C->setVarRefs(Vars);
11534 Vars.clear();
11535
11537 Decls.reserve(UniqueDecls);
11538 for (unsigned i = 0; i < UniqueDecls; ++i)
11539 Decls.push_back(Record.readDeclAs<ValueDecl>());
11540 C->setUniqueDecls(Decls);
11541
11542 SmallVector<unsigned, 16> ListsPerDecl;
11543 ListsPerDecl.reserve(UniqueDecls);
11544 for (unsigned i = 0; i < UniqueDecls; ++i)
11545 ListsPerDecl.push_back(Record.readInt());
11546 C->setDeclNumLists(ListsPerDecl);
11547
11548 SmallVector<unsigned, 32> ListSizes;
11549 ListSizes.reserve(TotalLists);
11550 for (unsigned i = 0; i < TotalLists; ++i)
11551 ListSizes.push_back(Record.readInt());
11552 C->setComponentListSizes(ListSizes);
11553
11555 Components.reserve(TotalComponents);
11556 for (unsigned i = 0; i < TotalComponents; ++i) {
11557 Expr *AssociatedExpr = Record.readSubExpr();
11558 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11559 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11560 /*IsNonContiguous=*/false);
11561 }
11562 C->setComponents(Components, ListSizes);
11563}
11564
11565void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11566 C->setLParenLoc(Record.readSourceLocation());
11567 auto NumVars = C->varlist_size();
11568 auto UniqueDecls = C->getUniqueDeclarationsNum();
11569 auto TotalLists = C->getTotalComponentListNum();
11570 auto TotalComponents = C->getTotalComponentsNum();
11571
11573 Vars.reserve(NumVars);
11574 for (unsigned I = 0; I != NumVars; ++I)
11575 Vars.push_back(Record.readSubExpr());
11576 C->setVarRefs(Vars);
11577 Vars.clear();
11578
11580 Decls.reserve(UniqueDecls);
11581 for (unsigned I = 0; I < UniqueDecls; ++I)
11582 Decls.push_back(Record.readDeclAs<ValueDecl>());
11583 C->setUniqueDecls(Decls);
11584
11585 SmallVector<unsigned, 16> ListsPerDecl;
11586 ListsPerDecl.reserve(UniqueDecls);
11587 for (unsigned I = 0; I < UniqueDecls; ++I)
11588 ListsPerDecl.push_back(Record.readInt());
11589 C->setDeclNumLists(ListsPerDecl);
11590
11591 SmallVector<unsigned, 32> ListSizes;
11592 ListSizes.reserve(TotalLists);
11593 for (unsigned i = 0; i < TotalLists; ++i)
11594 ListSizes.push_back(Record.readInt());
11595 C->setComponentListSizes(ListSizes);
11596
11598 Components.reserve(TotalComponents);
11599 for (unsigned I = 0; I < TotalComponents; ++I) {
11600 Expr *AssociatedExpr = Record.readSubExpr();
11601 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11602 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11603 /*IsNonContiguous=*/false);
11604 }
11605 C->setComponents(Components, ListSizes);
11606}
11607
11608void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11609 C->setLParenLoc(Record.readSourceLocation());
11610 unsigned NumVars = C->varlist_size();
11612 Vars.reserve(NumVars);
11613 for (unsigned i = 0; i != NumVars; ++i)
11614 Vars.push_back(Record.readSubExpr());
11615 C->setVarRefs(Vars);
11616 Vars.clear();
11617 Vars.reserve(NumVars);
11618 for (unsigned i = 0; i != NumVars; ++i)
11619 Vars.push_back(Record.readSubExpr());
11620 C->setPrivateRefs(Vars);
11621}
11622
11623void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11624 C->setLParenLoc(Record.readSourceLocation());
11625 unsigned NumVars = C->varlist_size();
11627 Vars.reserve(NumVars);
11628 for (unsigned i = 0; i != NumVars; ++i)
11629 Vars.push_back(Record.readSubExpr());
11630 C->setVarRefs(Vars);
11631}
11632
11633void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11634 C->setLParenLoc(Record.readSourceLocation());
11635 unsigned NumVars = C->varlist_size();
11637 Vars.reserve(NumVars);
11638 for (unsigned i = 0; i != NumVars; ++i)
11639 Vars.push_back(Record.readSubExpr());
11640 C->setVarRefs(Vars);
11641}
11642
11643void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11644 C->setLParenLoc(Record.readSourceLocation());
11645 unsigned NumOfAllocators = C->getNumberOfAllocators();
11647 Data.reserve(NumOfAllocators);
11648 for (unsigned I = 0; I != NumOfAllocators; ++I) {
11649 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11650 D.Allocator = Record.readSubExpr();
11651 D.AllocatorTraits = Record.readSubExpr();
11652 D.LParenLoc = Record.readSourceLocation();
11653 D.RParenLoc = Record.readSourceLocation();
11654 }
11655 C->setAllocatorsData(Data);
11656}
11657
11658void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11659 C->setLParenLoc(Record.readSourceLocation());
11660 C->setModifier(Record.readSubExpr());
11661 C->setColonLoc(Record.readSourceLocation());
11662 unsigned NumOfLocators = C->varlist_size();
11663 SmallVector<Expr *, 4> Locators;
11664 Locators.reserve(NumOfLocators);
11665 for (unsigned I = 0; I != NumOfLocators; ++I)
11666 Locators.push_back(Record.readSubExpr());
11667 C->setVarRefs(Locators);
11668}
11669
11670void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11671 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11672 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11673 C->setLParenLoc(Record.readSourceLocation());
11674 C->setKindKwLoc(Record.readSourceLocation());
11675 C->setModifierKwLoc(Record.readSourceLocation());
11676}
11677
11678void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11680 C->setThreadID(Record.readSubExpr());
11681 C->setLParenLoc(Record.readSourceLocation());
11682}
11683
11684void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11685 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11686 C->setLParenLoc(Record.readSourceLocation());
11687 C->setBindKindLoc(Record.readSourceLocation());
11688}
11689
11690void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11691 C->setAlignment(Record.readExpr());
11692 C->setLParenLoc(Record.readSourceLocation());
11693}
11694
11695void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11697 C->setSize(Record.readSubExpr());
11698 C->setLParenLoc(Record.readSourceLocation());
11699}
11700
11701void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11702 C->setLParenLoc(Record.readSourceLocation());
11703 C->setDependenceType(
11704 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11705 C->setDependenceLoc(Record.readSourceLocation());
11706 C->setColonLoc(Record.readSourceLocation());
11707 unsigned NumVars = C->varlist_size();
11709 Vars.reserve(NumVars);
11710 for (unsigned I = 0; I != NumVars; ++I)
11711 Vars.push_back(Record.readSubExpr());
11712 C->setVarRefs(Vars);
11713 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11714 C->setLoopData(I, Record.readSubExpr());
11715}
11716
11717void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11718 AttrVec Attrs;
11719 Record.readAttributes(Attrs);
11720 C->setAttrs(Attrs);
11721 C->setLocStart(Record.readSourceLocation());
11722 C->setLParenLoc(Record.readSourceLocation());
11723 C->setLocEnd(Record.readSourceLocation());
11724}
11725
11726void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11727
11730 TI.Sets.resize(readUInt32());
11731 for (auto &Set : TI.Sets) {
11732 Set.Kind = readEnum<llvm::omp::TraitSet>();
11733 Set.Selectors.resize(readUInt32());
11734 for (auto &Selector : Set.Selectors) {
11735 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11736 Selector.ScoreOrCondition = nullptr;
11737 if (readBool())
11738 Selector.ScoreOrCondition = readExprRef();
11739 Selector.Properties.resize(readUInt32());
11740 for (auto &Property : Selector.Properties)
11741 Property.Kind = readEnum<llvm::omp::TraitProperty>();
11742 }
11743 }
11744 return &TI;
11745}
11746
11748 if (!Data)
11749 return;
11750 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11751 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11752 skipInts(3);
11753 }
11754 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11755 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11756 Clauses[I] = readOMPClause();
11757 Data->setClauses(Clauses);
11758 if (Data->hasAssociatedStmt())
11759 Data->setAssociatedStmt(readStmt());
11760 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11761 Data->getChildren()[I] = readStmt();
11762}
11763
11765 unsigned NumVars = readInt();
11767 for (unsigned I = 0; I < NumVars; ++I)
11768 VarList.push_back(readSubExpr());
11769 return VarList;
11770}
11771
11773 unsigned NumExprs = readInt();
11775 for (unsigned I = 0; I < NumExprs; ++I)
11776 ExprList.push_back(readSubExpr());
11777 return ExprList;
11778}
11779
11781 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
11784
11785 switch (ClauseKind) {
11787 SourceLocation LParenLoc = readSourceLocation();
11788 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
11789 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
11790 EndLoc);
11791 }
11792 case OpenACCClauseKind::If: {
11793 SourceLocation LParenLoc = readSourceLocation();
11794 Expr *CondExpr = readSubExpr();
11795 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
11796 EndLoc);
11797 }
11799 SourceLocation LParenLoc = readSourceLocation();
11800 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
11801 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
11802 CondExpr, EndLoc);
11803 }
11805 SourceLocation LParenLoc = readSourceLocation();
11806 unsigned NumClauses = readInt();
11808 for (unsigned I = 0; I < NumClauses; ++I)
11809 IntExprs.push_back(readSubExpr());
11810 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
11811 IntExprs, EndLoc);
11812 }
11814 SourceLocation LParenLoc = readSourceLocation();
11815 Expr *IntExpr = readSubExpr();
11816 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
11817 IntExpr, EndLoc);
11818 }
11820 SourceLocation LParenLoc = readSourceLocation();
11821 Expr *IntExpr = readSubExpr();
11822 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
11823 IntExpr, EndLoc);
11824 }
11826 SourceLocation LParenLoc = readSourceLocation();
11828 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
11829 VarList, EndLoc);
11830 }
11832 SourceLocation LParenLoc = readSourceLocation();
11834 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
11835 VarList, EndLoc);
11836 }
11838 SourceLocation LParenLoc = readSourceLocation();
11840 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
11841 VarList, EndLoc);
11842 }
11844 SourceLocation LParenLoc = readSourceLocation();
11846 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
11847 VarList, EndLoc);
11848 }
11850 SourceLocation LParenLoc = readSourceLocation();
11852 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
11853 VarList, EndLoc);
11854 }
11856 SourceLocation LParenLoc = readSourceLocation();
11858 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
11859 VarList, EndLoc);
11860 }
11864 SourceLocation LParenLoc = readSourceLocation();
11866 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
11867 LParenLoc, VarList, EndLoc);
11868 }
11872 SourceLocation LParenLoc = readSourceLocation();
11873 bool IsReadOnly = readBool();
11875 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
11876 LParenLoc, IsReadOnly, VarList, EndLoc);
11877 }
11881 SourceLocation LParenLoc = readSourceLocation();
11882 bool IsZero = readBool();
11884 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
11885 LParenLoc, IsZero, VarList, EndLoc);
11886 }
11890 SourceLocation LParenLoc = readSourceLocation();
11891 bool IsZero = readBool();
11893 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
11894 LParenLoc, IsZero, VarList, EndLoc);
11895 }
11897 SourceLocation LParenLoc = readSourceLocation();
11898 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
11899 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
11900 AsyncExpr, EndLoc);
11901 }
11903 SourceLocation LParenLoc = readSourceLocation();
11904 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
11905 SourceLocation QueuesLoc = readSourceLocation();
11907 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
11908 DevNumExpr, QueuesLoc, QueueIdExprs,
11909 EndLoc);
11910 }
11913 SourceLocation LParenLoc = readSourceLocation();
11915 unsigned NumArchs = readInt();
11916
11917 for (unsigned I = 0; I < NumArchs; ++I) {
11918 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
11920 Archs.emplace_back(Ident, Loc);
11921 }
11922
11923 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
11924 LParenLoc, Archs, EndLoc);
11925 }
11926
11950 llvm_unreachable("Clause serialization not yet implemented");
11951 }
11952 llvm_unreachable("Invalid Clause Kind");
11953}
11954
11957 for (unsigned I = 0; I < Clauses.size(); ++I)
11958 Clauses[I] = readOpenACCClause();
11959}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:4690
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8030
static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts)
Check that the specified and the existing module cache paths are equivalent.
Definition: ASTReader.cpp:837
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:4672
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:506
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:513
static void updateModuleTimestamp(ModuleFile &MF)
Definition: ASTReader.cpp:4371
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:612
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, 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:663
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain)
Definition: ASTReader.cpp:476
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4235
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:2703
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:991
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:5011
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:555
static Decl * getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID)
Definition: ASTReader.cpp:7698
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II)
Definition: ASTReader.cpp:1016
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:8552
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1003
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6678
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:887
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8147
OptionValidation
Definition: ASTReader.cpp:647
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:650
@ OptionValidateNone
Definition: ASTReader.cpp:648
@ OptionValidateContradictions
Definition: ASTReader.cpp:649
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
Definition: ASTReader.cpp:387
#define CHECK_TARGET_OPT(Field, Name)
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
Definition: ASTReader.cpp:280
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
Definition: ASTReader.cpp:5237
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:4387
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:874
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:127
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the 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:2975
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
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:45
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.
This file declares semantic analysis for CUDA constructs.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
const char * Data
Defines the clang::TargetOptions class.
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 b
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
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:182
CanQualType AccumTy
Definition: ASTContext.h:1104
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1123
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1122
CanQualType LongTy
Definition: ASTContext.h:1100
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1100
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1113
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:1106
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:1109
CanQualType ShortAccumTy
Definition: ASTContext.h:1104
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1204
CanQualType FloatTy
Definition: ASTContext.h:1103
CanQualType DoubleTy
Definition: ASTContext.h:1103
CanQualType SatLongAccumTy
Definition: ASTContext.h:1109
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1976
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1132
CanQualType Char16Ty
Definition: ASTContext.h:1098
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1954
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1108
CanQualType DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
CanQualType OMPIteratorTy
Definition: ASTContext.h:1132
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:805
CanQualType SatShortFractTy
Definition: ASTContext.h:1112
CanQualType Ibm128Ty
Definition: ASTContext.h:1103
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1110
CanQualType ArraySectionTy
Definition: ASTContext.h:1131
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1123
CanQualType BoolTy
Definition: ASTContext.h:1092
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1108
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1123
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1119
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1988
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1106
CanQualType ShortFractTy
Definition: ASTContext.h:1107
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1113
CanQualType CharTy
Definition: ASTContext.h:1093
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1100
CanQualType PseudoObjectTy
Definition: ASTContext.h:1122
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
CanQualType SignedCharTy
Definition: ASTContext.h:1100
CanQualType OverloadTy
Definition: ASTContext.h:1119
CanQualType OCLClkEventTy
Definition: ASTContext.h:1128
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:1110
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:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1128
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1108
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:718
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2138
CanQualType UnknownAnyTy
Definition: ASTContext.h:1120
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1129
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1114
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1421
CanQualType ShortTy
Definition: ASTContext.h:1100
CanQualType FractTy
Definition: ASTContext.h:1107
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1105
CanQualType Char32Ty
Definition: ASTContext.h:1099
CanQualType SatFractTy
Definition: ASTContext.h:1112
CanQualType SatLongFractTy
Definition: ASTContext.h:1112
CanQualType OCLQueueTy
Definition: ASTContext.h:1129
CanQualType LongFractTy
Definition: ASTContext.h:1107
CanQualType SatShortAccumTy
Definition: ASTContext.h:1109
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1116
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1130
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1964
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1111
CanQualType LongLongTy
Definition: ASTContext.h:1100
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
CanQualType WCharTy
Definition: ASTContext.h:1094
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:1039
CanQualType Char8Ty
Definition: ASTContext.h:1097
CanQualType HalfTy
Definition: ASTContext.h:1115
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1106
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1128
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:8373
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8401
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8406
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:174
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:127
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:218
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:142
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:230
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:189
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:161
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:152
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:244
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:132
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:241
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:213
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:237
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:122
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:209
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:126
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:222
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:202
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
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:6473
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6254
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2249
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.
Definition: ASTReader.cpp:9535
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:899
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:8960
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9041
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9410
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1773
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7661
friend class ASTIdentifierIterator
Definition: ASTReader.h:370
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1533
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9416
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9400
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2377
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9359
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8695
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8203
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1615
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1628
@ 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:1619
@ 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:1623
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8625
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:7928
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6240
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8167
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8903
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8796
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1834
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2411
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9048
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:7852
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9023
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8021
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9428
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2242
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:8836
void SetIdentifierInfo(unsigned ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8812
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4341
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9432
SourceManager & getSourceManager() const
Definition: ASTReader.h:1600
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7679
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:4277
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5231
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2389
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7571
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:9504
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:8047
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:7803
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2260
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:7969
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8641
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7512
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:1461
~ASTReader() override
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:7514
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:1755
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:1965
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:6460
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8334
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.
Definition: ASTReader.cpp:9520
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:8989
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6233
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7821
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7836
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9077
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1874
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8918
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:8614
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8662
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7138
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2100
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9334
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:7645
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:8723
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:7997
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8683
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:5399
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8673
void ResolveImportedPath(ModuleFile &M, std::string &Filename)
If we are loading a relocatable PCH or module file, and the filename is not an absolute path,...
Definition: ASTReader.cpp:2687
ModuleFile * getOwningModuleFile(const Decl *D)
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7670
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2384
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:1718
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8651
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8705
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9052
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:4432
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1781
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9366
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9006
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8868
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:384
@ Success
The control block was read successfully.
Definition: ASTReader.h:387
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:404
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:397
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:390
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:400
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:407
@ Missing
The AST file was missing.
Definition: ASTReader.h:393
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9381
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1782
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9423
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:8766
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8459
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8741
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:4366
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9081
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8598
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7757
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9341
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:8993
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8807
IdentifierInfo * getLocalIdentifier(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8899
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6532
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4263
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8229
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7782
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1930
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:1496
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:8754
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1777
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9393
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:8603
QualType getLocalType(ModuleFile &F, unsigned LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7430
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:8975
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8057
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:4326
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:9087
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:8558
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5087
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:7603
FileManager & getFileManager() const
Definition: ASTReader.h:1601
serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7435
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:5693
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:2224
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2106
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6523
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:8945
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:9354
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7486
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7121
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9182
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9172
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9140
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9103
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9193
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:9128
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7454
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:7128
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7496
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9136
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:9273
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:6964
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:9153
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:9208
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7506
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...
Definition: Module.h:874
Wrapper for source info for array parameter types.
Definition: TypeLoc.h:1617
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1567
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1575
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1587
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2638
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2630
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2622
Attr - This represents one attribute.
Definition: Attr.h:42
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:2201
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2195
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:925
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1320
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:2535
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2487
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
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:1685
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition: DeclCXX.h:1792
Represents a C++ temporary.
Definition: ExprCXX.h:1453
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1043
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:244
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:157
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:198
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:213
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:222
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:167
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:204
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:182
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:162
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:228
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:173
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:260
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:191
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:238
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:233
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:128
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:94
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
typename Representation::iterator iterator
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1786
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2649
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1922
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:2622
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2637
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1356
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2643
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:2663
DeclID get() const
Definition: DeclID.h:117
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:849
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.h:780
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:803
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
SourceLocation getLocation() const
Definition: DeclBase.h:445
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
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:770
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2087
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2302
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1773
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1794
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1892
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6523
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1864
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
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.
PartialDiagnosticAt & getDiagnostic()
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-header-in-module=... options used to override whether -Wsystem-headers is enable...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:562
bool getEnableAllWarnings() const
Definition: Diagnostic.h:664
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:195
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
bool getWarningsAsErrors() const
Definition: Diagnostic.h:672
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:781
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:557
StringRef getName() const
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
Represents an enum.
Definition: Decl.h:3868
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:915
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:978
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:985
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:879
Represents a member of a struct/union/class.
Definition: Decl.h:3058
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:348
off_t getSize() const
Definition: FileEntry.h:340
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
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:251
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
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:1971
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2302
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1448
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1464
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1472
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1456
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1486
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:450
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:3342
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1398
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:467
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:525
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:539
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:535
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:516
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:522
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...
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:1171
void setAttrRowOperand(Expr *e)
Definition: TypeLoc.h:1927
void setAttrColumnOperand(Expr *e)
Definition: TypeLoc.h:1933
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1942
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1921
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1350
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:69
std::pair< Module *, bool > findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Find a new module or submodule, or create it if it does not already exist.
Definition: ModuleMap.cpp:851
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:1201
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:1186
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:58
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:127
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1282
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:676
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:319
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:350
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:472
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition: Module.h:305
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition: Module.h:395
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:387
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:389
@ AllVisible
All of the names in this module are visible.
Definition: Module.h:391
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
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:285
ModuleKind Kind
The kind of this module.
Definition: Module.h:150
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition: Module.h:716
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition: Module.h:506
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition: Module.h:686
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:333
std::string Name
The name of this module.
Definition: Module.h:108
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:339
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:378
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:464
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:433
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition: Module.h:700
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Module.h:296
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:159
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition: Module.h:383
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:368
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:163
ASTFileSignature Signature
The module signature.
Definition: Module.h:169
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition: Module.h:360
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition: Module.cpp:402
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Module.h:485
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:320
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:412
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition: Module.h:692
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition: Module.h:179
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition: Module.h:316
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:355
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Module.h:681
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:497
This represents a decl that may have a name.
Definition: Decl.h:249
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
Represent a C++ namespace.
Definition: Decl.h:547
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 '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:388
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:432
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:354
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 'shedule', 'firstprivate' etc.
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.
Definition: OpenMPClause.h:977
This represents 'compare' clause in the '#pragma omp atomic' directive.
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:630
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.
Definition: OpenMPClause.h:879
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 'if' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:527
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 '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.
This represents 'num_threads' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:676
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.
Definition: OpenMPClause.h:907
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' 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:721
This represents 'schedule' clause in the '#pragma omp ...' directive.
This represents 'seq_cst' clause in the '#pragma omp atomic' directive.
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:756
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:788
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.
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:1091
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1101
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1113
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6952
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
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:1370
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1376
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:984
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:988
unsigned getNumProtocols() const
Definition: TypeLoc.h:1018
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:976
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition: TypeLoc.h:997
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1006
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1014
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:1046
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:1027
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
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)
This is the base type for all OpenACC Clauses.
Definition: OpenACCClause.h:24
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 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 OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static 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 OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, 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)
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:294
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:459
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:866
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:814
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:856
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:450
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:579
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2582
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2112
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Represents a parameter to a function.
Definition: Decl.h:1761
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2674
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
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:128
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:940
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
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:318
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:362
@ FastMask
The fast qualifier mask.
Definition: Type.h:365
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1412
Represents a struct/union/class.
Definition: Decl.h:4169
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:5549
void AddDecl(Decl *D)
Definition: Scope.h:345
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.
std::pair< iterator, bool > insert(std::pair< Selector, Lists > &&Val)
Definition: SemaObjC.h:195
iterator find(Selector Sel)
Definition: SemaObjC.h:194
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: SemaObjC.h:191
std::pair< ObjCMethodList, ObjCMethodList > Lists
Definition: SemaObjC.h:190
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:211
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:449
SemaObjC & ObjC()
Definition: Sema.h:997
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:819
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:557
IdentifierResolver IdResolver
Definition: Sema.h:2515
PragmaMsStackAction
Definition: Sema.h:1187
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:321
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:824
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.
Stmt - This represents one statement.
Definition: Stmt.h:84
DiagnosticStorage * getStorage() const
Retrieve storage for this particular diagnostic.
Definition: Diagnostic.h:1160
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:3585
TagDecl * getDecl() const
Definition: Type.cpp:4008
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:312
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:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6157
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:3167
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6837
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:6904
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6765
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:2061
A container of type source information.
Definition: Type.h:7330
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:1813
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8123
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2004
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:1996
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2012
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2146
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2140
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:2152
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2143
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:706
Represents a variable declaration or definition.
Definition: Decl.h:918
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1841
Captures information about a #pragma weak directive.
Definition: Weak.h:25
Source location and bit offset of a declaration.
Definition: ASTBitCodes.h:228
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2014
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1136
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition: ModuleFile.h:78
OptionalFileEntryRef getFile() const
Definition: ModuleFile.h:107
static InputFile getNotFound()
Definition: ModuleFile.h:101
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
const PPEntityOffset * PreprocessedEntityOffsets
Definition: ModuleFile.h:375
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition: ModuleFile.h:324
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
Definition: ModuleFile.h:458
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition: ModuleFile.h:438
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition: ModuleFile.h:240
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition: ModuleFile.h:230
StringRef Data
The serialized bitstream data for this file.
Definition: ModuleFile.h:216
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition: ModuleFile.h:478
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Definition: ModuleFile.h:373
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition: ModuleFile.h:285
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition: ModuleFile.h:311
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition: ModuleFile.h:370
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:498
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition: ModuleFile.h:481
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition: ModuleFile.h:341
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition: ModuleFile.h:255
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition: ModuleFile.h:328
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition: ModuleFile.h:301
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:445
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition: ModuleFile.h:320
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition: ModuleFile.h:292
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition: ModuleFile.h:249
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition: ModuleFile.h:258
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition: ModuleFile.h:423
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition: ModuleFile.h:509
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition: ModuleFile.h:394
SourceLocation ImportLoc
The source location where this module was first imported.
Definition: ModuleFile.h:233
ContinuousRangeMap< uint32_t, int, 2 > TypeRemap
Remapping table for type IDs in this module.
Definition: ModuleFile.h:501
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition: ModuleFile.h:296
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition: ModuleFile.h:334
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition: ModuleFile.h:162
FileEntryRef File
The file entry for the module file.
Definition: ModuleFile.h:179
llvm::SmallVector< ModuleFile *, 16 > DependentModules
List of modules which this modules dependent on.
Definition: ModuleFile.h:520
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition: ModuleFile.h:158
ContinuousRangeMap< uint32_t, int, 2 > IdentifierRemap
Remapping table for identifier IDs in this module.
Definition: ModuleFile.h:314
const LocalDeclID * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition: ModuleFile.h:473
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition: ModuleFile.h:366
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition: ModuleFile.h:261
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition: ModuleFile.h:403
SourceLocation FirstLoc
The first source location in this module.
Definition: ModuleFile.h:236
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:187
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition: ModuleFile.h:279
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition: ModuleFile.h:176
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:154
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition: ModuleFile.h:527
bool HasTimestamps
Whether timestamps are included in this module file.
Definition: ModuleFile.h:173
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition: ModuleFile.h:252
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition: ModuleFile.h:276
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition: ModuleFile.h:167
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition: ModuleFile.h:420
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition: ModuleFile.h:282
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition: ModuleFile.h:398
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition: ModuleFile.h:219
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition: ModuleFile.h:406
uint64_t SizeInBits
The size of this file, in bits.
Definition: ModuleFile.h:207
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition: ModuleFile.h:494
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition: ModuleFile.h:210
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition: ModuleFile.h:170
unsigned LocalNumTypes
The number of types in this AST file.
Definition: ModuleFile.h:490
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition: ModuleFile.h:381
std::string FileName
The file name of the module file.
Definition: ModuleFile.h:139
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition: ModuleFile.h:271
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition: ModuleFile.h:363
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition: ModuleFile.h:455
std::string getTimestampFilename() const
Definition: ModuleFile.h:147
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition: ModuleFile.h:357
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition: ModuleFile.h:183
unsigned LocalNumMacros
The number of macros in this AST file.
Definition: ModuleFile.h:337
ContinuousRangeMap< serialization::DeclID, int, 2 > DeclRemap
Remapping table for declaration IDs in this module.
Definition: ModuleFile.h:461
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition: ModuleFile.h:431
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:451
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition: ModuleFile.h:387
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition: ModuleFile.h:190
unsigned Generation
The generation of which this module file is a part.
Definition: ModuleFile.h:200
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition: ModuleFile.h:308
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition: ModuleFile.h:426
llvm::DenseMap< ModuleFile *, serialization::DeclID > GlobalToLocalDeclIDs
Mapping from the module files that this module file depends on to the base declaration ID for that mo...
Definition: ModuleFile.h:470
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
Definition: ModuleFile.h:354
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition: ModuleFile.h:348
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition: ModuleFile.h:213
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition: ModuleFile.h:409
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition: ModuleFile.h:193
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:448
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition: ModuleFile.h:506
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition: ModuleFile.h:379
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:416
ModuleKind Kind
The type of this module.
Definition: ModuleFile.h:136
std::string ModuleName
The name of the module.
Definition: ModuleFile.h:142
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition: ModuleFile.h:351
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition: ModuleFile.h:485
std::string BaseDirectory
The base directory of the module.
Definition: ModuleFile.h:145
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:47
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:187
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:203
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:204
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:210
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:222
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:223
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:8487
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8529
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8534
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:100
32 aligned uint64_t in the AST file.
Definition: ASTBitCodes.h:170
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:980
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:975
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:985
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1009
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1025
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:915
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:937
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:910
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:905
Trait class used to search the on-disk hash table containing all of the header search information.
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:843
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:1970
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1100
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1155
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1114
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:911
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:920
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:890
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:851
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1025
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:854
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:893
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:884
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:929
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:878
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:857
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:995
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:875
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:872
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:914
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:863
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:974
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:923
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:917
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:971
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:869
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:860
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:881
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:905
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:899
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:896
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:908
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:944
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:848
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:845
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:902
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
Definition: ASTBitCodes.h:1090
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:887
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:926
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:866
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:938
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1390
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1270
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1393
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1279
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1120
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1148
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1151
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1136
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1133
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1139
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1145
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1130
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1142
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:85
@ 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.
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:402
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:81
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:792
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:774
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:812
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:771
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:820
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:777
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:768
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:760
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:788
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:804
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:781
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:801
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:816
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:764
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:795
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:798
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:785
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:808
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:823
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:65
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:161
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:353
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:366
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:363
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:372
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:369
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:360
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:143
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:259
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:158
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:164
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:284
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:281
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:266
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:270
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:292
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:278
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:274
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:287
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:314
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:308
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:305
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:298
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:827
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:697
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:711
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:701
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:707
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:715
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:146
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:459
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:46
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:69
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:719
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:734
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:730
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:725
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:737
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:741
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:318
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:345
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:348
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:325
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:334
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:341
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:330
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:338
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:321
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:376
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:384
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:393
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:381
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:390
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:378
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:387
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:396
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:410
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:415
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:412
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:745
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:754
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:747
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:750
ModuleKind
Specifies the kind of module that has been loaded.
Definition: ModuleFile.h:42
@ MK_PCH
File is a PCH file treated as such.
Definition: ModuleFile.h:50
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition: ModuleFile.h:53
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition: ModuleFile.h:56
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition: ModuleFile.h:47
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition: ModuleFile.h:44
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition: ModuleFile.h:59
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:140
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:419
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:560
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:494
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:680
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:586
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:490
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:549
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:432
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:582
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:686
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:519
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:579
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:576
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:529
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:636
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:677
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:444
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:596
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:510
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:647
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:556
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:657
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:624
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:526
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:452
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:617
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:506
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:690
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:671
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:534
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:514
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:546
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:633
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:603
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:650
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:497
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:522
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:668
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:607
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:503
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:642
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:481
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:629
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:573
@ 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:600
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:570
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:538
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:674
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:471
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:543
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:639
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:592
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:653
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:130
uint32_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:62
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:284
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.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
Definition: OpenACCKinds.h:164
@ 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.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
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:24
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
Definition: OpenMPKinds.h:118
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
Definition: OpenMPKinds.h:171
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition: Warnings.cpp:44
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
Definition: OpenMPKinds.h:135
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
Definition: OpenMPKinds.h:186
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition: OpenMPKinds.h:38
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
Definition: OpenMPKinds.h:103
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
Definition: OpenMPKinds.h:219
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition: OpenMPKinds.h:87
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: DeclID.h:90
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition: DeclID.h:30
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: DeclID.h:80
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:35
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:83
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: DeclID.h:44
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: DeclID.h:68
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:56
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:47
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:53
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:41
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:50
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:62
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:65
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:77
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: DeclID.h:32
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:59
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:71
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:38
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:74
@ 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:200
OpenACCDefaultClauseKind
Definition: OpenACCKinds.h:462
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
Definition: OpenMPKinds.h:157
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition: OpenMPKinds.h:54
OpenMPGrainsizeClauseModifier
Definition: OpenMPKinds.h:206
OpenMPNumTasksClauseModifier
Definition: OpenMPKinds.h:212
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
Definition: OpenMPKinds.h:142
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
Definition: OpenMPKinds.h:99
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:91
PragmaMSStructKind
Definition: PragmaKinds.h:23
OpenMPDefaultmapClauseKind
OpenMP attributes for 'defaultmap' clause.
Definition: OpenMPKinds.h:110
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition: OpenMPKinds.h:62
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition: Specifiers.h:50
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
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:2481
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:127
@ Success
Template argument deduction was successful.
U cast(CodeGen::Address addr)
Definition: Address.h:291
@ None
The alignment was not explicit in code.
OpenMPDeviceClauseModifier
OpenMP modifiers for 'device' clause.
Definition: OpenMPKinds.h:47
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition: OpenMPKinds.h:78
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
Definition: OpenMPKinds.h:164
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition: OpenMPKinds.h:30
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition: OpenMPKinds.h:70
unsigned long uint64_t
Definition: Format.h:5428
#define true
Definition: stdbool.h:25
#define bool
Definition: stdbool.h:24
The signature of a module, which is a hash of the AST content.
Definition: Module.h:57
static constexpr size_t size
Definition: Module.h:60
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition: Module.h:75
static ASTFileSignature createDummy()
Definition: Module.h:85
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:4742
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:58
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:116
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:80
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:73
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:120
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:69
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:141
unsigned ControllingMacroID
The ID number of the controlling macro.
Definition: HeaderSearch.h:127
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:85
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:488
Module * Other
The module that this module conflicts with.
Definition: Module.h:490
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:493
Information about a header directive as found in the module map file.
Definition: Module.h:250
A library or framework to link against when an entity from this module is used.
Definition: Module.h:447
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.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
Expr * AllocatorTraits
Allocator traits.
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:743
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:757
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:744
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:750
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:1198
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
The input file info that has been loaded from an AST file.
Definition: ModuleFile.h:63
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1981