clang 20.0.0git
ASTReader.cpp
Go to the documentation of this file.
1//===- ASTReader.cpp - AST File Reader ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ASTCommon.h"
14#include "ASTReaderInternals.h"
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"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Module.h"
70#include "clang/Basic/Version.h"
73#include "clang/Lex/MacroInfo.h"
74#include "clang/Lex/ModuleMap.h"
78#include "clang/Lex/Token.h"
80#include "clang/Sema/Scope.h"
81#include "clang/Sema/Sema.h"
82#include "clang/Sema/SemaCUDA.h"
83#include "clang/Sema/SemaObjC.h"
84#include "clang/Sema/Weak.h"
96#include "llvm/ADT/APFloat.h"
97#include "llvm/ADT/APInt.h"
98#include "llvm/ADT/APSInt.h"
99#include "llvm/ADT/ArrayRef.h"
100#include "llvm/ADT/DenseMap.h"
101#include "llvm/ADT/FloatingPointMode.h"
102#include "llvm/ADT/FoldingSet.h"
103#include "llvm/ADT/Hashing.h"
104#include "llvm/ADT/IntrusiveRefCntPtr.h"
105#include "llvm/ADT/STLExtras.h"
106#include "llvm/ADT/ScopeExit.h"
107#include "llvm/ADT/SmallPtrSet.h"
108#include "llvm/ADT/SmallString.h"
109#include "llvm/ADT/SmallVector.h"
110#include "llvm/ADT/StringExtras.h"
111#include "llvm/ADT/StringMap.h"
112#include "llvm/ADT/StringRef.h"
113#include "llvm/ADT/iterator_range.h"
114#include "llvm/Bitstream/BitstreamReader.h"
115#include "llvm/Support/Casting.h"
116#include "llvm/Support/Compiler.h"
117#include "llvm/Support/Compression.h"
118#include "llvm/Support/DJB.h"
119#include "llvm/Support/Endian.h"
120#include "llvm/Support/Error.h"
121#include "llvm/Support/ErrorHandling.h"
122#include "llvm/Support/FileSystem.h"
123#include "llvm/Support/LEB128.h"
124#include "llvm/Support/MemoryBuffer.h"
125#include "llvm/Support/Path.h"
126#include "llvm/Support/SaveAndRestore.h"
127#include "llvm/Support/TimeProfiler.h"
128#include "llvm/Support/Timer.h"
129#include "llvm/Support/VersionTuple.h"
130#include "llvm/Support/raw_ostream.h"
131#include "llvm/TargetParser/Triple.h"
132#include <algorithm>
133#include <cassert>
134#include <cstddef>
135#include <cstdint>
136#include <cstdio>
137#include <ctime>
138#include <iterator>
139#include <limits>
140#include <map>
141#include <memory>
142#include <optional>
143#include <string>
144#include <system_error>
145#include <tuple>
146#include <utility>
147#include <vector>
148
149using namespace clang;
150using namespace clang::serialization;
151using namespace clang::serialization::reader;
152using llvm::BitstreamCursor;
153
154//===----------------------------------------------------------------------===//
155// ChainedASTReaderListener implementation
156//===----------------------------------------------------------------------===//
157
158bool
160 return First->ReadFullVersionInformation(FullVersion) ||
161 Second->ReadFullVersionInformation(FullVersion);
162}
163
165 First->ReadModuleName(ModuleName);
166 Second->ReadModuleName(ModuleName);
167}
168
169void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
170 First->ReadModuleMapFile(ModuleMapPath);
171 Second->ReadModuleMapFile(ModuleMapPath);
172}
173
174bool
176 bool Complain,
177 bool AllowCompatibleDifferences) {
178 return First->ReadLanguageOptions(LangOpts, Complain,
179 AllowCompatibleDifferences) ||
180 Second->ReadLanguageOptions(LangOpts, Complain,
181 AllowCompatibleDifferences);
182}
183
185 const TargetOptions &TargetOpts, bool Complain,
186 bool AllowCompatibleDifferences) {
187 return First->ReadTargetOptions(TargetOpts, Complain,
188 AllowCompatibleDifferences) ||
189 Second->ReadTargetOptions(TargetOpts, Complain,
190 AllowCompatibleDifferences);
191}
192
194 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
195 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
196 Second->ReadDiagnosticOptions(DiagOpts, Complain);
197}
198
199bool
201 bool Complain) {
202 return First->ReadFileSystemOptions(FSOpts, Complain) ||
203 Second->ReadFileSystemOptions(FSOpts, Complain);
204}
205
207 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
208 bool Complain) {
209 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
210 Complain) ||
211 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
212 Complain);
213}
214
216 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
217 std::string &SuggestedPredefines) {
218 return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
219 SuggestedPredefines) ||
220 Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
221 SuggestedPredefines);
222}
223
225 unsigned Value) {
226 First->ReadCounter(M, Value);
227 Second->ReadCounter(M, Value);
228}
229
231 return First->needsInputFileVisitation() ||
232 Second->needsInputFileVisitation();
233}
234
236 return First->needsSystemInputFileVisitation() ||
237 Second->needsSystemInputFileVisitation();
238}
239
241 ModuleKind Kind) {
242 First->visitModuleFile(Filename, Kind);
243 Second->visitModuleFile(Filename, Kind);
244}
245
247 bool isSystem,
248 bool isOverridden,
249 bool isExplicitModule) {
250 bool Continue = false;
251 if (First->needsInputFileVisitation() &&
252 (!isSystem || First->needsSystemInputFileVisitation()))
253 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
254 isExplicitModule);
255 if (Second->needsInputFileVisitation() &&
256 (!isSystem || Second->needsSystemInputFileVisitation()))
257 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
258 isExplicitModule);
259 return Continue;
260}
261
263 const ModuleFileExtensionMetadata &Metadata) {
264 First->readModuleFileExtension(Metadata);
265 Second->readModuleFileExtension(Metadata);
266}
267
268//===----------------------------------------------------------------------===//
269// PCH validator implementation
270//===----------------------------------------------------------------------===//
271
273
274/// Compare the given set of language options against an existing set of
275/// language options.
276///
277/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
278/// \param AllowCompatibleDifferences If true, differences between compatible
279/// language options will be permitted.
280///
281/// \returns true if the languagae options mis-match, false otherwise.
282static bool checkLanguageOptions(const LangOptions &LangOpts,
283 const LangOptions &ExistingLangOpts,
284 DiagnosticsEngine *Diags,
285 bool AllowCompatibleDifferences = true) {
286#define LANGOPT(Name, Bits, Default, Description) \
287 if (ExistingLangOpts.Name != LangOpts.Name) { \
288 if (Diags) { \
289 if (Bits == 1) \
290 Diags->Report(diag::err_pch_langopt_mismatch) \
291 << Description << LangOpts.Name << ExistingLangOpts.Name; \
292 else \
293 Diags->Report(diag::err_pch_langopt_value_mismatch) \
294 << Description; \
295 } \
296 return true; \
297 }
298
299#define VALUE_LANGOPT(Name, Bits, Default, Description) \
300 if (ExistingLangOpts.Name != LangOpts.Name) { \
301 if (Diags) \
302 Diags->Report(diag::err_pch_langopt_value_mismatch) \
303 << Description; \
304 return true; \
305 }
306
307#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
308 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
309 if (Diags) \
310 Diags->Report(diag::err_pch_langopt_value_mismatch) \
311 << Description; \
312 return true; \
313 }
314
315#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
316 if (!AllowCompatibleDifferences) \
317 LANGOPT(Name, Bits, Default, Description)
318
319#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
320 if (!AllowCompatibleDifferences) \
321 ENUM_LANGOPT(Name, Bits, Default, Description)
322
323#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
324 if (!AllowCompatibleDifferences) \
325 VALUE_LANGOPT(Name, Bits, Default, Description)
326
327#define BENIGN_LANGOPT(Name, Bits, Default, Description)
328#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
329#define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
330#include "clang/Basic/LangOptions.def"
331
332 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
333 if (Diags)
334 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
335 return true;
336 }
337
338 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
339 if (Diags)
340 Diags->Report(diag::err_pch_langopt_value_mismatch)
341 << "target Objective-C runtime";
342 return true;
343 }
344
345 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
347 if (Diags)
348 Diags->Report(diag::err_pch_langopt_value_mismatch)
349 << "block command names";
350 return true;
351 }
352
353 // Sanitizer feature mismatches are treated as compatible differences. If
354 // compatible differences aren't allowed, we still only want to check for
355 // mismatches of non-modular sanitizers (the only ones which can affect AST
356 // generation).
357 if (!AllowCompatibleDifferences) {
358 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
359 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
360 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
361 ExistingSanitizers.clear(ModularSanitizers);
362 ImportedSanitizers.clear(ModularSanitizers);
363 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
364 const std::string Flag = "-fsanitize=";
365 if (Diags) {
366#define SANITIZER(NAME, ID) \
367 { \
368 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
369 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
370 if (InExistingModule != InImportedModule) \
371 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
372 << InExistingModule << (Flag + NAME); \
373 }
374#include "clang/Basic/Sanitizers.def"
375 }
376 return true;
377 }
378 }
379
380 return false;
381}
382
383/// Compare the given set of target options against an existing set of
384/// target options.
385///
386/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
387///
388/// \returns true if the target options mis-match, false otherwise.
389static bool checkTargetOptions(const TargetOptions &TargetOpts,
390 const TargetOptions &ExistingTargetOpts,
391 DiagnosticsEngine *Diags,
392 bool AllowCompatibleDifferences = true) {
393#define CHECK_TARGET_OPT(Field, Name) \
394 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
395 if (Diags) \
396 Diags->Report(diag::err_pch_targetopt_mismatch) \
397 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
398 return true; \
399 }
400
401 // The triple and ABI must match exactly.
402 CHECK_TARGET_OPT(Triple, "target");
403 CHECK_TARGET_OPT(ABI, "target ABI");
404
405 // We can tolerate different CPUs in many cases, notably when one CPU
406 // supports a strict superset of another. When allowing compatible
407 // differences skip this check.
408 if (!AllowCompatibleDifferences) {
409 CHECK_TARGET_OPT(CPU, "target CPU");
410 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
411 }
412
413#undef CHECK_TARGET_OPT
414
415 // Compare feature sets.
416 SmallVector<StringRef, 4> ExistingFeatures(
417 ExistingTargetOpts.FeaturesAsWritten.begin(),
418 ExistingTargetOpts.FeaturesAsWritten.end());
419 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
420 TargetOpts.FeaturesAsWritten.end());
421 llvm::sort(ExistingFeatures);
422 llvm::sort(ReadFeatures);
423
424 // We compute the set difference in both directions explicitly so that we can
425 // diagnose the differences differently.
426 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
427 std::set_difference(
428 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
429 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
430 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
431 ExistingFeatures.begin(), ExistingFeatures.end(),
432 std::back_inserter(UnmatchedReadFeatures));
433
434 // If we are allowing compatible differences and the read feature set is
435 // a strict subset of the existing feature set, there is nothing to diagnose.
436 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
437 return false;
438
439 if (Diags) {
440 for (StringRef Feature : UnmatchedReadFeatures)
441 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
442 << /* is-existing-feature */ false << Feature;
443 for (StringRef Feature : UnmatchedExistingFeatures)
444 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
445 << /* is-existing-feature */ true << Feature;
446 }
447
448 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
449}
450
451bool
453 bool Complain,
454 bool AllowCompatibleDifferences) {
455 const LangOptions &ExistingLangOpts = PP.getLangOpts();
456 return checkLanguageOptions(LangOpts, ExistingLangOpts,
457 Complain ? &Reader.Diags : nullptr,
458 AllowCompatibleDifferences);
459}
460
462 bool Complain,
463 bool AllowCompatibleDifferences) {
464 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
465 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
466 Complain ? &Reader.Diags : nullptr,
467 AllowCompatibleDifferences);
468}
469
470namespace {
471
472using MacroDefinitionsMap =
473 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
474using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
475
476} // namespace
477
479 DiagnosticsEngine &Diags,
480 bool Complain) {
481 using Level = DiagnosticsEngine::Level;
482
483 // Check current mappings for new -Werror mappings, and the stored mappings
484 // for cases that were explicitly mapped to *not* be errors that are now
485 // errors because of options like -Werror.
486 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
487
488 for (DiagnosticsEngine *MappingSource : MappingSources) {
489 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
490 diag::kind DiagID = DiagIDMappingPair.first;
491 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
492 if (CurLevel < DiagnosticsEngine::Error)
493 continue; // not significant
494 Level StoredLevel =
495 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
496 if (StoredLevel < DiagnosticsEngine::Error) {
497 if (Complain)
498 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
499 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
500 return true;
501 }
502 }
503 }
504
505 return false;
506}
507
510 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
511 return true;
512 return Ext >= diag::Severity::Error;
513}
514
516 DiagnosticsEngine &Diags, bool IsSystem,
517 bool SystemHeaderWarningsInModule,
518 bool Complain) {
519 // Top-level options
520 if (IsSystem) {
521 if (Diags.getSuppressSystemWarnings())
522 return false;
523 // If -Wsystem-headers was not enabled before, and it was not explicit,
524 // be conservative
525 if (StoredDiags.getSuppressSystemWarnings() &&
526 !SystemHeaderWarningsInModule) {
527 if (Complain)
528 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
529 return true;
530 }
531 }
532
533 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
534 if (Complain)
535 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
536 return true;
537 }
538
539 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
540 !StoredDiags.getEnableAllWarnings()) {
541 if (Complain)
542 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
543 return true;
544 }
545
546 if (isExtHandlingFromDiagsError(Diags) &&
547 !isExtHandlingFromDiagsError(StoredDiags)) {
548 if (Complain)
549 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
550 return true;
551 }
552
553 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
554}
555
556/// Return the top import module if it is implicit, nullptr otherwise.
558 Preprocessor &PP) {
559 // If the original import came from a file explicitly generated by the user,
560 // don't check the diagnostic mappings.
561 // FIXME: currently this is approximated by checking whether this is not a
562 // module import of an implicitly-loaded module file.
563 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
564 // the transitive closure of its imports, since unrelated modules cannot be
565 // imported until after this module finishes validation.
566 ModuleFile *TopImport = &*ModuleMgr.rbegin();
567 while (!TopImport->ImportedBy.empty())
568 TopImport = TopImport->ImportedBy[0];
569 if (TopImport->Kind != MK_ImplicitModule)
570 return nullptr;
571
572 StringRef ModuleName = TopImport->ModuleName;
573 assert(!ModuleName.empty() && "diagnostic options read before module name");
574
575 Module *M =
576 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
577 assert(M && "missing module");
578 return M;
579}
580
582 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
583 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
586 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
587 // This should never fail, because we would have processed these options
588 // before writing them to an ASTFile.
589 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
590
591 ModuleManager &ModuleMgr = Reader.getModuleManager();
592 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
593
594 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
595 if (!TopM)
596 return false;
597
598 Module *Importer = PP.getCurrentModule();
599
600 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
601 bool SystemHeaderWarningsInModule =
602 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
603 Importer->Name);
604
605 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
606 // contains the union of their flags.
607 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
608 SystemHeaderWarningsInModule, Complain);
609}
610
611/// Collect the macro definitions provided by the given preprocessor
612/// options.
613static void
615 MacroDefinitionsMap &Macros,
616 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
617 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
618 StringRef Macro = PPOpts.Macros[I].first;
619 bool IsUndef = PPOpts.Macros[I].second;
620
621 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
622 StringRef MacroName = MacroPair.first;
623 StringRef MacroBody = MacroPair.second;
624
625 // For an #undef'd macro, we only care about the name.
626 if (IsUndef) {
627 if (MacroNames && !Macros.count(MacroName))
628 MacroNames->push_back(MacroName);
629
630 Macros[MacroName] = std::make_pair("", true);
631 continue;
632 }
633
634 // For a #define'd macro, figure out the actual definition.
635 if (MacroName.size() == Macro.size())
636 MacroBody = "1";
637 else {
638 // Note: GCC drops anything following an end-of-line character.
639 StringRef::size_type End = MacroBody.find_first_of("\n\r");
640 MacroBody = MacroBody.substr(0, End);
641 }
642
643 if (MacroNames && !Macros.count(MacroName))
644 MacroNames->push_back(MacroName);
645 Macros[MacroName] = std::make_pair(MacroBody, false);
646 }
647}
648
653};
654
655/// Check the preprocessor options deserialized from the control block
656/// against the preprocessor options in an existing preprocessor.
657///
658/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
659/// \param Validation If set to OptionValidateNone, ignore differences in
660/// preprocessor options. If set to OptionValidateContradictions,
661/// require that options passed both in the AST file and on the command
662/// line (-D or -U) match, but tolerate options missing in one or the
663/// other. If set to OptionValidateContradictions, require that there
664/// are no differences in the options between the two.
666 const PreprocessorOptions &PPOpts,
667 const PreprocessorOptions &ExistingPPOpts, bool ReadMacros,
668 DiagnosticsEngine *Diags, FileManager &FileMgr,
669 std::string &SuggestedPredefines, const LangOptions &LangOpts,
671 if (ReadMacros) {
672 // Check macro definitions.
673 MacroDefinitionsMap ASTFileMacros;
674 collectMacroDefinitions(PPOpts, ASTFileMacros);
675 MacroDefinitionsMap ExistingMacros;
676 SmallVector<StringRef, 4> ExistingMacroNames;
677 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
678 &ExistingMacroNames);
679
680 // Use a line marker to enter the <command line> file, as the defines and
681 // undefines here will have come from the command line.
682 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
683
684 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
685 // Dig out the macro definition in the existing preprocessor options.
686 StringRef MacroName = ExistingMacroNames[I];
687 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
688
689 // Check whether we know anything about this macro name or not.
690 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
691 ASTFileMacros.find(MacroName);
692 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
693 if (Validation == OptionValidateStrictMatches) {
694 // If strict matches are requested, don't tolerate any extra defines
695 // on the command line that are missing in the AST file.
696 if (Diags) {
697 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
698 }
699 return true;
700 }
701 // FIXME: Check whether this identifier was referenced anywhere in the
702 // AST file. If so, we should reject the AST file. Unfortunately, this
703 // information isn't in the control block. What shall we do about it?
704
705 if (Existing.second) {
706 SuggestedPredefines += "#undef ";
707 SuggestedPredefines += MacroName.str();
708 SuggestedPredefines += '\n';
709 } else {
710 SuggestedPredefines += "#define ";
711 SuggestedPredefines += MacroName.str();
712 SuggestedPredefines += ' ';
713 SuggestedPredefines += Existing.first.str();
714 SuggestedPredefines += '\n';
715 }
716 continue;
717 }
718
719 // If the macro was defined in one but undef'd in the other, we have a
720 // conflict.
721 if (Existing.second != Known->second.second) {
722 if (Diags) {
723 Diags->Report(diag::err_pch_macro_def_undef)
724 << MacroName << Known->second.second;
725 }
726 return true;
727 }
728
729 // If the macro was #undef'd in both, or if the macro bodies are
730 // identical, it's fine.
731 if (Existing.second || Existing.first == Known->second.first) {
732 ASTFileMacros.erase(Known);
733 continue;
734 }
735
736 // The macro bodies differ; complain.
737 if (Diags) {
738 Diags->Report(diag::err_pch_macro_def_conflict)
739 << MacroName << Known->second.first << Existing.first;
740 }
741 return true;
742 }
743
744 // Leave the <command line> file and return to <built-in>.
745 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
746
747 if (Validation == OptionValidateStrictMatches) {
748 // If strict matches are requested, don't tolerate any extra defines in
749 // the AST file that are missing on the command line.
750 for (const auto &MacroName : ASTFileMacros.keys()) {
751 if (Diags) {
752 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
753 }
754 return true;
755 }
756 }
757 }
758
759 // Check whether we're using predefines.
760 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
761 Validation != OptionValidateNone) {
762 if (Diags) {
763 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
764 }
765 return true;
766 }
767
768 // Detailed record is important since it is used for the module cache hash.
769 if (LangOpts.Modules &&
770 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
771 Validation != OptionValidateNone) {
772 if (Diags) {
773 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
774 }
775 return true;
776 }
777
778 // Compute the #include and #include_macros lines we need.
779 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
780 StringRef File = ExistingPPOpts.Includes[I];
781
782 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
783 !ExistingPPOpts.PCHThroughHeader.empty()) {
784 // In case the through header is an include, we must add all the includes
785 // to the predefines so the start point can be determined.
786 SuggestedPredefines += "#include \"";
787 SuggestedPredefines += File;
788 SuggestedPredefines += "\"\n";
789 continue;
790 }
791
792 if (File == ExistingPPOpts.ImplicitPCHInclude)
793 continue;
794
795 if (llvm::is_contained(PPOpts.Includes, File))
796 continue;
797
798 SuggestedPredefines += "#include \"";
799 SuggestedPredefines += File;
800 SuggestedPredefines += "\"\n";
801 }
802
803 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
804 StringRef File = ExistingPPOpts.MacroIncludes[I];
805 if (llvm::is_contained(PPOpts.MacroIncludes, File))
806 continue;
807
808 SuggestedPredefines += "#__include_macros \"";
809 SuggestedPredefines += File;
810 SuggestedPredefines += "\"\n##\n";
811 }
812
813 return false;
814}
815
817 bool ReadMacros, bool Complain,
818 std::string &SuggestedPredefines) {
819 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
820
822 PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr,
823 PP.getFileManager(), SuggestedPredefines, PP.getLangOpts());
824}
825
827 const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
828 std::string &SuggestedPredefines) {
829 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros,
830 nullptr, PP.getFileManager(),
831 SuggestedPredefines, PP.getLangOpts(),
833}
834
835/// Check that the specified and the existing module cache paths are equivalent.
836///
837/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
838/// \returns true when the module cache paths differ.
839static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
840 StringRef SpecificModuleCachePath,
841 StringRef ExistingModuleCachePath,
842 DiagnosticsEngine *Diags,
843 const LangOptions &LangOpts,
844 const PreprocessorOptions &PPOpts) {
845 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
846 SpecificModuleCachePath == ExistingModuleCachePath)
847 return false;
848 auto EqualOrErr =
849 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
850 if (EqualOrErr && *EqualOrErr)
851 return false;
852 if (Diags)
853 Diags->Report(diag::err_pch_modulecache_mismatch)
854 << SpecificModuleCachePath << ExistingModuleCachePath;
855 return true;
856}
857
859 StringRef SpecificModuleCachePath,
860 bool Complain) {
862 SpecificModuleCachePath,
864 Complain ? &Reader.Diags : nullptr,
866}
867
870}
871
872//===----------------------------------------------------------------------===//
873// AST reader implementation
874//===----------------------------------------------------------------------===//
875
876static uint64_t readULEB(const unsigned char *&P) {
877 unsigned Length = 0;
878 const char *Error = nullptr;
879
880 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
881 if (Error)
882 llvm::report_fatal_error(Error);
883 P += Length;
884 return Val;
885}
886
887/// Read ULEB-encoded key length and data length.
888static std::pair<unsigned, unsigned>
889readULEBKeyDataLength(const unsigned char *&P) {
890 unsigned KeyLen = readULEB(P);
891 if ((unsigned)KeyLen != KeyLen)
892 llvm::report_fatal_error("key too large");
893
894 unsigned DataLen = readULEB(P);
895 if ((unsigned)DataLen != DataLen)
896 llvm::report_fatal_error("data too large");
897
898 return std::make_pair(KeyLen, DataLen);
899}
900
902 bool TakeOwnership) {
903 DeserializationListener = Listener;
904 OwnsDeserializationListener = TakeOwnership;
905}
906
908 return serialization::ComputeHash(Sel);
909}
910
913#ifndef NDEBUG
914 if (!MF.ModuleOffsetMap.empty())
915 Reader.ReadModuleOffsetMap(MF);
916
917 unsigned ModuleFileIndex = ID.getModuleFileIndex();
918 unsigned LocalDeclID = ID.getLocalDeclIndex();
919
920 assert(ModuleFileIndex <= MF.TransitiveImports.size());
921
922 ModuleFile *OwningModuleFile =
923 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
924 assert(OwningModuleFile);
925
926 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
927
928 if (!ModuleFileIndex)
929 LocalNumDecls += NUM_PREDEF_DECL_IDS;
930
931 assert(LocalDeclID < LocalNumDecls);
932#endif
933 (void)Reader;
934 (void)MF;
935 return ID;
936}
937
939 unsigned ModuleFileIndex, unsigned LocalDeclID) {
940 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
941 return LocalDeclID::get(Reader, MF, Value);
942}
943
944std::pair<unsigned, unsigned>
946 return readULEBKeyDataLength(d);
947}
948
950ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
951 using namespace llvm::support;
952
953 SelectorTable &SelTable = Reader.getContext().Selectors;
954 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
955 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
956 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
957 if (N == 0)
958 return SelTable.getNullarySelector(FirstII);
959 else if (N == 1)
960 return SelTable.getUnarySelector(FirstII);
961
963 Args.push_back(FirstII);
964 for (unsigned I = 1; I != N; ++I)
965 Args.push_back(Reader.getLocalIdentifier(
966 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
967
968 return SelTable.getSelector(N, Args.data());
969}
970
973 unsigned DataLen) {
974 using namespace llvm::support;
975
977
978 Result.ID = Reader.getGlobalSelectorID(
979 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
980 unsigned FullInstanceBits =
981 endian::readNext<uint16_t, llvm::endianness::little>(d);
982 unsigned FullFactoryBits =
983 endian::readNext<uint16_t, llvm::endianness::little>(d);
984 Result.InstanceBits = FullInstanceBits & 0x3;
985 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
986 Result.FactoryBits = FullFactoryBits & 0x3;
987 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
988 unsigned NumInstanceMethods = FullInstanceBits >> 3;
989 unsigned NumFactoryMethods = FullFactoryBits >> 3;
990
991 // Load instance methods
992 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
993 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
995 Reader, F,
996 endian::readNext<DeclID, llvm::endianness::little>(d))))
997 Result.Instance.push_back(Method);
998 }
999
1000 // Load factory methods
1001 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1002 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1004 Reader, F,
1005 endian::readNext<DeclID, llvm::endianness::little>(d))))
1006 Result.Factory.push_back(Method);
1007 }
1008
1009 return Result;
1010}
1011
1013 return llvm::djbHash(a);
1014}
1015
1016std::pair<unsigned, unsigned>
1018 return readULEBKeyDataLength(d);
1019}
1020
1022ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1023 assert(n >= 2 && d[n-1] == '\0');
1024 return StringRef((const char*) d, n-1);
1025}
1026
1027/// Whether the given identifier is "interesting".
1028static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1029 bool IsModule) {
1030 bool IsInteresting =
1031 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1033 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1034 return II.hadMacroDefinition() || II.isPoisoned() ||
1035 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1036 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1037 II.getFETokenInfo());
1038}
1039
1040static bool readBit(unsigned &Bits) {
1041 bool Value = Bits & 0x1;
1042 Bits >>= 1;
1043 return Value;
1044}
1045
1047 using namespace llvm::support;
1048
1049 IdentifierID RawID =
1050 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1051 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1052}
1053
1055 if (!II.isFromAST()) {
1056 II.setIsFromAST();
1057 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1058 if (isInterestingIdentifier(Reader, II, IsModule))
1060 }
1061}
1062
1064 const unsigned char* d,
1065 unsigned DataLen) {
1066 using namespace llvm::support;
1067
1068 IdentifierID RawID =
1069 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1070 bool IsInteresting = RawID & 0x01;
1071
1072 DataLen -= sizeof(IdentifierID);
1073
1074 // Wipe out the "is interesting" bit.
1075 RawID = RawID >> 1;
1076
1077 // Build the IdentifierInfo and link the identifier ID with it.
1078 IdentifierInfo *II = KnownII;
1079 if (!II) {
1080 II = &Reader.getIdentifierTable().getOwn(k);
1081 KnownII = II;
1082 }
1083 markIdentifierFromAST(Reader, *II);
1084 Reader.markIdentifierUpToDate(II);
1085
1086 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1087 if (!IsInteresting) {
1088 // For uninteresting identifiers, there's nothing else to do. Just notify
1089 // the reader that we've finished loading this identifier.
1090 Reader.SetIdentifierInfo(ID, II);
1091 return II;
1092 }
1093
1094 unsigned ObjCOrBuiltinID =
1095 endian::readNext<uint16_t, llvm::endianness::little>(d);
1096 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1097 bool CPlusPlusOperatorKeyword = readBit(Bits);
1098 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1099 bool Poisoned = readBit(Bits);
1100 bool ExtensionToken = readBit(Bits);
1101 bool HadMacroDefinition = readBit(Bits);
1102
1103 assert(Bits == 0 && "Extra bits in the identifier?");
1104 DataLen -= sizeof(uint16_t) * 2;
1105
1106 // Set or check the various bits in the IdentifierInfo structure.
1107 // Token IDs are read-only.
1108 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1110 if (!F.isModule())
1111 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1112 assert(II->isExtensionToken() == ExtensionToken &&
1113 "Incorrect extension token flag");
1114 (void)ExtensionToken;
1115 if (Poisoned)
1116 II->setIsPoisoned(true);
1117 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1118 "Incorrect C++ operator keyword flag");
1119 (void)CPlusPlusOperatorKeyword;
1120
1121 // If this identifier is a macro, deserialize the macro
1122 // definition.
1123 if (HadMacroDefinition) {
1124 uint32_t MacroDirectivesOffset =
1125 endian::readNext<uint32_t, llvm::endianness::little>(d);
1126 DataLen -= 4;
1127
1128 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1129 }
1130
1131 Reader.SetIdentifierInfo(ID, II);
1132
1133 // Read all of the declarations visible at global scope with this
1134 // name.
1135 if (DataLen > 0) {
1137 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1138 DeclIDs.push_back(Reader.getGlobalDeclID(
1140 Reader, F,
1141 endian::readNext<DeclID, llvm::endianness::little>(d))));
1142 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1143 }
1144
1145 return II;
1146}
1147
1149 : Kind(Name.getNameKind()) {
1150 switch (Kind) {
1152 Data = (uint64_t)Name.getAsIdentifierInfo();
1153 break;
1157 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1158 break;
1160 Data = Name.getCXXOverloadedOperator();
1161 break;
1163 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1164 break;
1166 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1167 ->getDeclName().getAsIdentifierInfo();
1168 break;
1173 Data = 0;
1174 break;
1175 }
1176}
1177
1179 llvm::FoldingSetNodeID ID;
1180 ID.AddInteger(Kind);
1181
1182 switch (Kind) {
1186 ID.AddString(((IdentifierInfo*)Data)->getName());
1187 break;
1191 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1192 break;
1194 ID.AddInteger((OverloadedOperatorKind)Data);
1195 break;
1200 break;
1201 }
1202
1203 return ID.computeStableHash();
1204}
1205
1206ModuleFile *
1207ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1208 using namespace llvm::support;
1209
1210 uint32_t ModuleFileID =
1211 endian::readNext<uint32_t, llvm::endianness::little>(d);
1212 return Reader.getLocalModuleFile(F, ModuleFileID);
1213}
1214
1215std::pair<unsigned, unsigned>
1216ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1217 return readULEBKeyDataLength(d);
1218}
1219
1221ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1222 using namespace llvm::support;
1223
1224 auto Kind = (DeclarationName::NameKind)*d++;
1225 uint64_t Data;
1226 switch (Kind) {
1230 Data = (uint64_t)Reader.getLocalIdentifier(
1231 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1232 break;
1236 Data = (uint64_t)Reader
1237 .getLocalSelector(
1238 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1239 .getAsOpaquePtr();
1240 break;
1242 Data = *d++; // OverloadedOperatorKind
1243 break;
1248 Data = 0;
1249 break;
1250 }
1251
1252 return DeclarationNameKey(Kind, Data);
1253}
1254
1255void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1256 const unsigned char *d,
1257 unsigned DataLen,
1258 data_type_builder &Val) {
1259 using namespace llvm::support;
1260
1261 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1263 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1264 Val.insert(Reader.getGlobalDeclID(F, ID));
1265 }
1266}
1267
1268bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1269 BitstreamCursor &Cursor,
1270 uint64_t Offset,
1271 DeclContext *DC) {
1272 assert(Offset != 0);
1273
1274 SavedStreamPosition SavedPosition(Cursor);
1275 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1276 Error(std::move(Err));
1277 return true;
1278 }
1279
1280 RecordData Record;
1281 StringRef Blob;
1282 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1283 if (!MaybeCode) {
1284 Error(MaybeCode.takeError());
1285 return true;
1286 }
1287 unsigned Code = MaybeCode.get();
1288
1289 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1290 if (!MaybeRecCode) {
1291 Error(MaybeRecCode.takeError());
1292 return true;
1293 }
1294 unsigned RecCode = MaybeRecCode.get();
1295 if (RecCode != DECL_CONTEXT_LEXICAL) {
1296 Error("Expected lexical block");
1297 return true;
1298 }
1299
1300 assert(!isa<TranslationUnitDecl>(DC) &&
1301 "expected a TU_UPDATE_LEXICAL record for TU");
1302 // If we are handling a C++ class template instantiation, we can see multiple
1303 // lexical updates for the same record. It's important that we select only one
1304 // of them, so that field numbering works properly. Just pick the first one we
1305 // see.
1306 auto &Lex = LexicalDecls[DC];
1307 if (!Lex.first) {
1308 Lex = std::make_pair(
1309 &M, llvm::ArrayRef(
1310 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1311 Blob.size() / sizeof(DeclID)));
1312 }
1314 return false;
1315}
1316
1317bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1318 BitstreamCursor &Cursor,
1319 uint64_t Offset,
1320 GlobalDeclID ID) {
1321 assert(Offset != 0);
1322
1323 SavedStreamPosition SavedPosition(Cursor);
1324 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1325 Error(std::move(Err));
1326 return true;
1327 }
1328
1329 RecordData Record;
1330 StringRef Blob;
1331 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1332 if (!MaybeCode) {
1333 Error(MaybeCode.takeError());
1334 return true;
1335 }
1336 unsigned Code = MaybeCode.get();
1337
1338 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1339 if (!MaybeRecCode) {
1340 Error(MaybeRecCode.takeError());
1341 return true;
1342 }
1343 unsigned RecCode = MaybeRecCode.get();
1344 if (RecCode != DECL_CONTEXT_VISIBLE) {
1345 Error("Expected visible lookup table block");
1346 return true;
1347 }
1348
1349 // We can't safely determine the primary context yet, so delay attaching the
1350 // lookup table until we're done with recursive deserialization.
1351 auto *Data = (const unsigned char*)Blob.data();
1352 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1353 return false;
1354}
1355
1356void ASTReader::Error(StringRef Msg) const {
1357 Error(diag::err_fe_pch_malformed, Msg);
1358 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1359 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1360 Diag(diag::note_module_cache_path)
1361 << PP.getHeaderSearchInfo().getModuleCachePath();
1362 }
1363}
1364
1365void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1366 StringRef Arg3) const {
1367 if (Diags.isDiagnosticInFlight())
1368 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1369 else
1370 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1371}
1372
1373void ASTReader::Error(llvm::Error &&Err) const {
1374 llvm::Error RemainingErr =
1375 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1376 auto Diag = E.getDiagnostic().second;
1377
1378 // Ideally we'd just emit it, but have to handle a possible in-flight
1379 // diagnostic. Note that the location is currently ignored as well.
1380 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1381 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1382 StringRef Arg1, Arg2, Arg3;
1383 switch (NumArgs) {
1384 case 3:
1385 Arg3 = Diag.getStringArg(2);
1386 [[fallthrough]];
1387 case 2:
1388 Arg2 = Diag.getStringArg(1);
1389 [[fallthrough]];
1390 case 1:
1391 Arg1 = Diag.getStringArg(0);
1392 }
1393 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1394 });
1395 if (RemainingErr)
1396 Error(toString(std::move(RemainingErr)));
1397}
1398
1399//===----------------------------------------------------------------------===//
1400// Source Manager Deserialization
1401//===----------------------------------------------------------------------===//
1402
1403/// Read the line table in the source manager block.
1404void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1405 unsigned Idx = 0;
1406 LineTableInfo &LineTable = SourceMgr.getLineTable();
1407
1408 // Parse the file names
1409 std::map<int, int> FileIDs;
1410 FileIDs[-1] = -1; // For unspecified filenames.
1411 for (unsigned I = 0; Record[Idx]; ++I) {
1412 // Extract the file name
1413 auto Filename = ReadPath(F, Record, Idx);
1414 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1415 }
1416 ++Idx;
1417
1418 // Parse the line entries
1419 std::vector<LineEntry> Entries;
1420 while (Idx < Record.size()) {
1421 FileID FID = ReadFileID(F, Record, Idx);
1422
1423 // Extract the line entries
1424 unsigned NumEntries = Record[Idx++];
1425 assert(NumEntries && "no line entries for file ID");
1426 Entries.clear();
1427 Entries.reserve(NumEntries);
1428 for (unsigned I = 0; I != NumEntries; ++I) {
1429 unsigned FileOffset = Record[Idx++];
1430 unsigned LineNo = Record[Idx++];
1431 int FilenameID = FileIDs[Record[Idx++]];
1434 unsigned IncludeOffset = Record[Idx++];
1435 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1436 FileKind, IncludeOffset));
1437 }
1438 LineTable.AddEntry(FID, Entries);
1439 }
1440}
1441
1442/// Read a source manager block
1443llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1444 using namespace SrcMgr;
1445
1446 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1447
1448 // Set the source-location entry cursor to the current position in
1449 // the stream. This cursor will be used to read the contents of the
1450 // source manager block initially, and then lazily read
1451 // source-location entries as needed.
1452 SLocEntryCursor = F.Stream;
1453
1454 // The stream itself is going to skip over the source manager block.
1455 if (llvm::Error Err = F.Stream.SkipBlock())
1456 return Err;
1457
1458 // Enter the source manager block.
1459 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1460 return Err;
1461 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1462
1463 RecordData Record;
1464 while (true) {
1466 SLocEntryCursor.advanceSkippingSubblocks();
1467 if (!MaybeE)
1468 return MaybeE.takeError();
1469 llvm::BitstreamEntry E = MaybeE.get();
1470
1471 switch (E.Kind) {
1472 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1473 case llvm::BitstreamEntry::Error:
1474 return llvm::createStringError(std::errc::illegal_byte_sequence,
1475 "malformed block record in AST file");
1476 case llvm::BitstreamEntry::EndBlock:
1477 return llvm::Error::success();
1478 case llvm::BitstreamEntry::Record:
1479 // The interesting case.
1480 break;
1481 }
1482
1483 // Read a record.
1484 Record.clear();
1485 StringRef Blob;
1486 Expected<unsigned> MaybeRecord =
1487 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1488 if (!MaybeRecord)
1489 return MaybeRecord.takeError();
1490 switch (MaybeRecord.get()) {
1491 default: // Default behavior: ignore.
1492 break;
1493
1494 case SM_SLOC_FILE_ENTRY:
1497 // Once we hit one of the source location entries, we're done.
1498 return llvm::Error::success();
1499 }
1500 }
1501}
1502
1505 BitstreamCursor &Cursor = F->SLocEntryCursor;
1506 SavedStreamPosition SavedPosition(Cursor);
1507 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1508 F->SLocEntryOffsets[Index]))
1509 return std::move(Err);
1510
1511 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1512 if (!MaybeEntry)
1513 return MaybeEntry.takeError();
1514
1515 llvm::BitstreamEntry Entry = MaybeEntry.get();
1516 if (Entry.Kind != llvm::BitstreamEntry::Record)
1517 return llvm::createStringError(
1518 std::errc::illegal_byte_sequence,
1519 "incorrectly-formatted source location entry in AST file");
1520
1522 StringRef Blob;
1523 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1524 if (!MaybeSLOC)
1525 return MaybeSLOC.takeError();
1526
1527 switch (MaybeSLOC.get()) {
1528 default:
1529 return llvm::createStringError(
1530 std::errc::illegal_byte_sequence,
1531 "incorrectly-formatted source location entry in AST file");
1532 case SM_SLOC_FILE_ENTRY:
1535 return F->SLocEntryBaseOffset + Record[0];
1536 }
1537}
1538
1540 auto SLocMapI =
1541 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1542 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1543 "Corrupted global sloc offset map");
1544 ModuleFile *F = SLocMapI->second;
1545
1546 bool Invalid = false;
1547
1548 auto It = llvm::upper_bound(
1549 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1550 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1551 int ID = F->SLocEntryBaseID + LocalIndex;
1552 std::size_t Index = -ID - 2;
1553 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1554 assert(!SourceMgr.SLocEntryLoaded[Index]);
1555 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1556 if (!MaybeEntryOffset) {
1557 Error(MaybeEntryOffset.takeError());
1558 Invalid = true;
1559 return true;
1560 }
1561 SourceMgr.LoadedSLocEntryTable[Index] =
1562 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1563 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1564 }
1565 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1566 });
1567
1568 if (Invalid)
1569 return 0;
1570
1571 // The iterator points to the first entry with start offset greater than the
1572 // offset of interest. The previous entry must contain the offset of interest.
1573 return F->SLocEntryBaseID + *std::prev(It);
1574}
1575
1577 if (ID == 0)
1578 return false;
1579
1580 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1581 Error("source location entry ID out-of-range for AST file");
1582 return true;
1583 }
1584
1585 // Local helper to read the (possibly-compressed) buffer data following the
1586 // entry record.
1587 auto ReadBuffer = [this](
1588 BitstreamCursor &SLocEntryCursor,
1589 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1591 StringRef Blob;
1592 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1593 if (!MaybeCode) {
1594 Error(MaybeCode.takeError());
1595 return nullptr;
1596 }
1597 unsigned Code = MaybeCode.get();
1598
1599 Expected<unsigned> MaybeRecCode =
1600 SLocEntryCursor.readRecord(Code, Record, &Blob);
1601 if (!MaybeRecCode) {
1602 Error(MaybeRecCode.takeError());
1603 return nullptr;
1604 }
1605 unsigned RecCode = MaybeRecCode.get();
1606
1607 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1608 // Inspect the first byte to differentiate zlib (\x78) and zstd
1609 // (little-endian 0xFD2FB528).
1610 const llvm::compression::Format F =
1611 Blob.size() > 0 && Blob.data()[0] == 0x78
1612 ? llvm::compression::Format::Zlib
1613 : llvm::compression::Format::Zstd;
1614 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1615 Error(Reason);
1616 return nullptr;
1617 }
1618 SmallVector<uint8_t, 0> Decompressed;
1619 if (llvm::Error E = llvm::compression::decompress(
1620 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1621 Error("could not decompress embedded file contents: " +
1622 llvm::toString(std::move(E)));
1623 return nullptr;
1624 }
1625 return llvm::MemoryBuffer::getMemBufferCopy(
1626 llvm::toStringRef(Decompressed), Name);
1627 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1628 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1629 } else {
1630 Error("AST record has invalid code");
1631 return nullptr;
1632 }
1633 };
1634
1635 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1636 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1638 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1639 Error(std::move(Err));
1640 return true;
1641 }
1642
1643 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1645
1646 ++NumSLocEntriesRead;
1647 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1648 if (!MaybeEntry) {
1649 Error(MaybeEntry.takeError());
1650 return true;
1651 }
1652 llvm::BitstreamEntry Entry = MaybeEntry.get();
1653
1654 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1655 Error("incorrectly-formatted source location entry in AST file");
1656 return true;
1657 }
1658
1660 StringRef Blob;
1661 Expected<unsigned> MaybeSLOC =
1662 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1663 if (!MaybeSLOC) {
1664 Error(MaybeSLOC.takeError());
1665 return true;
1666 }
1667 switch (MaybeSLOC.get()) {
1668 default:
1669 Error("incorrectly-formatted source location entry in AST file");
1670 return true;
1671
1672 case SM_SLOC_FILE_ENTRY: {
1673 // We will detect whether a file changed and return 'Failure' for it, but
1674 // we will also try to fail gracefully by setting up the SLocEntry.
1675 unsigned InputID = Record[4];
1676 InputFile IF = getInputFile(*F, InputID);
1678 bool OverriddenBuffer = IF.isOverridden();
1679
1680 // Note that we only check if a File was returned. If it was out-of-date
1681 // we have complained but we will continue creating a FileID to recover
1682 // gracefully.
1683 if (!File)
1684 return true;
1685
1686 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1687 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1688 // This is the module's main file.
1689 IncludeLoc = getImportLocation(F);
1690 }
1692 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1693 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1694 BaseOffset + Record[0]);
1695 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1696 FileInfo.NumCreatedFIDs = Record[5];
1697 if (Record[3])
1698 FileInfo.setHasLineDirectives();
1699
1700 unsigned NumFileDecls = Record[7];
1701 if (NumFileDecls && ContextObj) {
1702 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1703 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1704 FileDeclIDs[FID] =
1705 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1706 }
1707
1708 const SrcMgr::ContentCache &ContentCache =
1709 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1710 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1711 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1712 !ContentCache.getBufferIfLoaded()) {
1713 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1714 if (!Buffer)
1715 return true;
1716 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1717 }
1718
1719 break;
1720 }
1721
1722 case SM_SLOC_BUFFER_ENTRY: {
1723 const char *Name = Blob.data();
1724 unsigned Offset = Record[0];
1726 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1727 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1728 if (IncludeLoc.isInvalid() && F->isModule()) {
1729 IncludeLoc = getImportLocation(F);
1730 }
1731
1732 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1733 if (!Buffer)
1734 return true;
1735 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1736 BaseOffset + Offset, IncludeLoc);
1737 if (Record[3]) {
1738 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1739 FileInfo.setHasLineDirectives();
1740 }
1741 break;
1742 }
1743
1746 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1747 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1748 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1749 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1750 Record[5], Record[4], ID,
1751 BaseOffset + Record[0]);
1752 break;
1753 }
1754 }
1755
1756 return false;
1757}
1758
1759std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1760 if (ID == 0)
1761 return std::make_pair(SourceLocation(), "");
1762
1763 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1764 Error("source location entry ID out-of-range for AST file");
1765 return std::make_pair(SourceLocation(), "");
1766 }
1767
1768 // Find which module file this entry lands in.
1769 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1770 if (!M->isModule())
1771 return std::make_pair(SourceLocation(), "");
1772
1773 // FIXME: Can we map this down to a particular submodule? That would be
1774 // ideal.
1775 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1776}
1777
1778/// Find the location where the module F is imported.
1779SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1780 if (F->ImportLoc.isValid())
1781 return F->ImportLoc;
1782
1783 // Otherwise we have a PCH. It's considered to be "imported" at the first
1784 // location of its includer.
1785 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1786 // Main file is the importer.
1787 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1788 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1789 }
1790 return F->ImportedBy[0]->FirstLoc;
1791}
1792
1793/// Enter a subblock of the specified BlockID with the specified cursor. Read
1794/// the abbreviations that are at the top of the block and then leave the cursor
1795/// pointing into the block.
1796llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1797 unsigned BlockID,
1798 uint64_t *StartOfBlockOffset) {
1799 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1800 return Err;
1801
1802 if (StartOfBlockOffset)
1803 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1804
1805 while (true) {
1806 uint64_t Offset = Cursor.GetCurrentBitNo();
1807 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1808 if (!MaybeCode)
1809 return MaybeCode.takeError();
1810 unsigned Code = MaybeCode.get();
1811
1812 // We expect all abbrevs to be at the start of the block.
1813 if (Code != llvm::bitc::DEFINE_ABBREV) {
1814 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1815 return Err;
1816 return llvm::Error::success();
1817 }
1818 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1819 return Err;
1820 }
1821}
1822
1824 unsigned &Idx) {
1825 Token Tok;
1826 Tok.startToken();
1827 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1828 Tok.setKind((tok::TokenKind)Record[Idx++]);
1829 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1830
1831 if (Tok.isAnnotation()) {
1832 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1833 switch (Tok.getKind()) {
1834 case tok::annot_pragma_loop_hint: {
1835 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1836 Info->PragmaName = ReadToken(M, Record, Idx);
1837 Info->Option = ReadToken(M, Record, Idx);
1838 unsigned NumTokens = Record[Idx++];
1840 Toks.reserve(NumTokens);
1841 for (unsigned I = 0; I < NumTokens; ++I)
1842 Toks.push_back(ReadToken(M, Record, Idx));
1843 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1844 Tok.setAnnotationValue(static_cast<void *>(Info));
1845 break;
1846 }
1847 case tok::annot_pragma_pack: {
1848 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1849 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1850 auto SlotLabel = ReadString(Record, Idx);
1851 Info->SlotLabel =
1852 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1853 Info->Alignment = ReadToken(M, Record, Idx);
1854 Tok.setAnnotationValue(static_cast<void *>(Info));
1855 break;
1856 }
1857 // Some annotation tokens do not use the PtrData field.
1858 case tok::annot_pragma_openmp:
1859 case tok::annot_pragma_openmp_end:
1860 case tok::annot_pragma_unused:
1861 case tok::annot_pragma_openacc:
1862 case tok::annot_pragma_openacc_end:
1863 break;
1864 default:
1865 llvm_unreachable("missing deserialization code for annotation token");
1866 }
1867 } else {
1868 Tok.setLength(Record[Idx++]);
1869 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1870 Tok.setIdentifierInfo(II);
1871 }
1872 return Tok;
1873}
1874
1876 BitstreamCursor &Stream = F.MacroCursor;
1877
1878 // Keep track of where we are in the stream, then jump back there
1879 // after reading this macro.
1880 SavedStreamPosition SavedPosition(Stream);
1881
1882 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1883 // FIXME this drops errors on the floor.
1884 consumeError(std::move(Err));
1885 return nullptr;
1886 }
1889 MacroInfo *Macro = nullptr;
1890 llvm::MutableArrayRef<Token> MacroTokens;
1891
1892 while (true) {
1893 // Advance to the next record, but if we get to the end of the block, don't
1894 // pop it (removing all the abbreviations from the cursor) since we want to
1895 // be able to reseek within the block and read entries.
1896 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1898 Stream.advanceSkippingSubblocks(Flags);
1899 if (!MaybeEntry) {
1900 Error(MaybeEntry.takeError());
1901 return Macro;
1902 }
1903 llvm::BitstreamEntry Entry = MaybeEntry.get();
1904
1905 switch (Entry.Kind) {
1906 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1907 case llvm::BitstreamEntry::Error:
1908 Error("malformed block record in AST file");
1909 return Macro;
1910 case llvm::BitstreamEntry::EndBlock:
1911 return Macro;
1912 case llvm::BitstreamEntry::Record:
1913 // The interesting case.
1914 break;
1915 }
1916
1917 // Read a record.
1918 Record.clear();
1920 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1921 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1922 else {
1923 Error(MaybeRecType.takeError());
1924 return Macro;
1925 }
1926 switch (RecType) {
1927 case PP_MODULE_MACRO:
1929 return Macro;
1930
1933 // If we already have a macro, that means that we've hit the end
1934 // of the definition of the macro we were looking for. We're
1935 // done.
1936 if (Macro)
1937 return Macro;
1938
1939 unsigned NextIndex = 1; // Skip identifier ID.
1940 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1941 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1942 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1943 MI->setIsUsed(Record[NextIndex++]);
1944 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1945 MacroTokens = MI->allocateTokens(Record[NextIndex++],
1946 PP.getPreprocessorAllocator());
1947 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1948 // Decode function-like macro info.
1949 bool isC99VarArgs = Record[NextIndex++];
1950 bool isGNUVarArgs = Record[NextIndex++];
1951 bool hasCommaPasting = Record[NextIndex++];
1952 MacroParams.clear();
1953 unsigned NumArgs = Record[NextIndex++];
1954 for (unsigned i = 0; i != NumArgs; ++i)
1955 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1956
1957 // Install function-like macro info.
1958 MI->setIsFunctionLike();
1959 if (isC99VarArgs) MI->setIsC99Varargs();
1960 if (isGNUVarArgs) MI->setIsGNUVarargs();
1961 if (hasCommaPasting) MI->setHasCommaPasting();
1962 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1963 }
1964
1965 // Remember that we saw this macro last so that we add the tokens that
1966 // form its body to it.
1967 Macro = MI;
1968
1969 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1970 Record[NextIndex]) {
1971 // We have a macro definition. Register the association
1973 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1974 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1975 PreprocessingRecord::PPEntityID PPID =
1976 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1977 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1978 PPRec.getPreprocessedEntity(PPID));
1979 if (PPDef)
1980 PPRec.RegisterMacroDefinition(Macro, PPDef);
1981 }
1982
1983 ++NumMacrosRead;
1984 break;
1985 }
1986
1987 case PP_TOKEN: {
1988 // If we see a TOKEN before a PP_MACRO_*, then the file is
1989 // erroneous, just pretend we didn't see this.
1990 if (!Macro) break;
1991 if (MacroTokens.empty()) {
1992 Error("unexpected number of macro tokens for a macro in AST file");
1993 return Macro;
1994 }
1995
1996 unsigned Idx = 0;
1997 MacroTokens[0] = ReadToken(F, Record, Idx);
1998 MacroTokens = MacroTokens.drop_front();
1999 break;
2000 }
2001 }
2002 }
2003}
2004
2007 unsigned LocalID) const {
2008 if (!M.ModuleOffsetMap.empty())
2009 ReadModuleOffsetMap(M);
2010
2013 assert(I != M.PreprocessedEntityRemap.end()
2014 && "Invalid index into preprocessed entity index remap");
2015
2016 return LocalID + I->second;
2017}
2018
2019const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2020 FileManager &FileMgr = Reader.getFileManager();
2021 if (!Key.Imported) {
2022 if (auto File = FileMgr.getFile(Key.Filename))
2023 return *File;
2024 return nullptr;
2025 }
2026
2027 std::string Resolved = std::string(Key.Filename);
2028 Reader.ResolveImportedPath(M, Resolved);
2029 if (auto File = FileMgr.getFile(Resolved))
2030 return *File;
2031 return nullptr;
2032}
2033
2034unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
2035 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2036 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2037 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2038 return llvm::xxh3_64bits(buf);
2039}
2040
2042HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
2043 internal_key_type ikey = {ekey.getSize(),
2044 M.HasTimestamps ? ekey.getModificationTime() : 0,
2045 ekey.getName(), /*Imported*/ false};
2046 return ikey;
2047}
2048
2049bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2050 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2051 return false;
2052
2053 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2054 return true;
2055
2056 // Determine whether the actual files are equivalent.
2057 const FileEntry *FEA = getFile(a);
2058 const FileEntry *FEB = getFile(b);
2059 return FEA && FEA == FEB;
2060}
2061
2062std::pair<unsigned, unsigned>
2063HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2064 return readULEBKeyDataLength(d);
2065}
2066
2068HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2069 using namespace llvm::support;
2070
2071 internal_key_type ikey;
2072 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2073 ikey.ModTime =
2074 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2075 ikey.Filename = (const char *)d;
2076 ikey.Imported = true;
2077 return ikey;
2078}
2079
2081HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2082 unsigned DataLen) {
2083 using namespace llvm::support;
2084
2085 const unsigned char *End = d + DataLen;
2086 HeaderFileInfo HFI;
2087 unsigned Flags = *d++;
2088
2089 bool Included = (Flags >> 6) & 0x01;
2090 if (Included)
2091 if (const FileEntry *FE = getFile(key))
2092 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2093 // deserialize this header file info again.
2094 Reader.getPreprocessor().getIncludedFiles().insert(FE);
2095
2096 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2097 HFI.isImport |= (Flags >> 5) & 0x01;
2098 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2099 HFI.DirInfo = (Flags >> 1) & 0x07;
2100 HFI.IndexHeaderMapHeader = Flags & 0x01;
2101 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2102 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2103 if (unsigned FrameworkOffset =
2104 endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2105 // The framework offset is 1 greater than the actual offset,
2106 // since 0 is used as an indicator for "no framework name".
2107 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2108 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
2109 }
2110
2111 assert((End - d) % 4 == 0 &&
2112 "Wrong data length in HeaderFileInfo deserialization");
2113 while (d != End) {
2114 uint32_t LocalSMID =
2115 endian::readNext<uint32_t, llvm::endianness::little>(d);
2116 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2117 LocalSMID >>= 3;
2118
2119 // This header is part of a module. Associate it with the module to enable
2120 // implicit module import.
2121 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2122 Module *Mod = Reader.getSubmodule(GlobalSMID);
2123 FileManager &FileMgr = Reader.getFileManager();
2124 ModuleMap &ModMap =
2125 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2126
2127 std::string Filename = std::string(key.Filename);
2128 if (key.Imported)
2129 Reader.ResolveImportedPath(M, Filename);
2130 if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
2131 // FIXME: NameAsWritten
2132 Module::Header H = {std::string(key.Filename), "", *FE};
2133 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2134 }
2135 HFI.mergeModuleMembership(HeaderRole);
2136 }
2137
2138 // This HeaderFileInfo was externally loaded.
2139 HFI.External = true;
2140 HFI.IsValid = true;
2141 return HFI;
2142}
2143
2145 uint32_t MacroDirectivesOffset) {
2146 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2147 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2148}
2149
2151 // Note that we are loading defined macros.
2152 Deserializing Macros(this);
2153
2154 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2155 BitstreamCursor &MacroCursor = I.MacroCursor;
2156
2157 // If there was no preprocessor block, skip this file.
2158 if (MacroCursor.getBitcodeBytes().empty())
2159 continue;
2160
2161 BitstreamCursor Cursor = MacroCursor;
2162 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2163 Error(std::move(Err));
2164 return;
2165 }
2166
2168 while (true) {
2169 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2170 if (!MaybeE) {
2171 Error(MaybeE.takeError());
2172 return;
2173 }
2174 llvm::BitstreamEntry E = MaybeE.get();
2175
2176 switch (E.Kind) {
2177 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2178 case llvm::BitstreamEntry::Error:
2179 Error("malformed block record in AST file");
2180 return;
2181 case llvm::BitstreamEntry::EndBlock:
2182 goto NextCursor;
2183
2184 case llvm::BitstreamEntry::Record: {
2185 Record.clear();
2186 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2187 if (!MaybeRecord) {
2188 Error(MaybeRecord.takeError());
2189 return;
2190 }
2191 switch (MaybeRecord.get()) {
2192 default: // Default behavior: ignore.
2193 break;
2194
2197 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2198 if (II->isOutOfDate())
2199 updateOutOfDateIdentifier(*II);
2200 break;
2201 }
2202
2203 case PP_TOKEN:
2204 // Ignore tokens.
2205 break;
2206 }
2207 break;
2208 }
2209 }
2210 }
2211 NextCursor: ;
2212 }
2213}
2214
2215namespace {
2216
2217 /// Visitor class used to look up identifirs in an AST file.
2218 class IdentifierLookupVisitor {
2219 StringRef Name;
2220 unsigned NameHash;
2221 unsigned PriorGeneration;
2222 unsigned &NumIdentifierLookups;
2223 unsigned &NumIdentifierLookupHits;
2224 IdentifierInfo *Found = nullptr;
2225
2226 public:
2227 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2228 unsigned &NumIdentifierLookups,
2229 unsigned &NumIdentifierLookupHits)
2230 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2231 PriorGeneration(PriorGeneration),
2232 NumIdentifierLookups(NumIdentifierLookups),
2233 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2234
2235 bool operator()(ModuleFile &M) {
2236 // If we've already searched this module file, skip it now.
2237 if (M.Generation <= PriorGeneration)
2238 return true;
2239
2242 if (!IdTable)
2243 return false;
2244
2245 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2246 Found);
2247 ++NumIdentifierLookups;
2248 ASTIdentifierLookupTable::iterator Pos =
2249 IdTable->find_hashed(Name, NameHash, &Trait);
2250 if (Pos == IdTable->end())
2251 return false;
2252
2253 // Dereferencing the iterator has the effect of building the
2254 // IdentifierInfo node and populating it with the various
2255 // declarations it needs.
2256 ++NumIdentifierLookupHits;
2257 Found = *Pos;
2258 return true;
2259 }
2260
2261 // Retrieve the identifier info found within the module
2262 // files.
2263 IdentifierInfo *getIdentifierInfo() const { return Found; }
2264 };
2265
2266} // namespace
2267
2269 // Note that we are loading an identifier.
2270 Deserializing AnIdentifier(this);
2271
2272 unsigned PriorGeneration = 0;
2273 if (getContext().getLangOpts().Modules)
2274 PriorGeneration = IdentifierGeneration[&II];
2275
2276 // If there is a global index, look there first to determine which modules
2277 // provably do not have any results for this identifier.
2279 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2280 if (!loadGlobalIndex()) {
2281 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2282 HitsPtr = &Hits;
2283 }
2284 }
2285
2286 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2287 NumIdentifierLookups,
2288 NumIdentifierLookupHits);
2289 ModuleMgr.visit(Visitor, HitsPtr);
2290 markIdentifierUpToDate(&II);
2291}
2292
2294 if (!II)
2295 return;
2296
2297 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2298
2299 // Update the generation for this identifier.
2300 if (getContext().getLangOpts().Modules)
2301 IdentifierGeneration[II] = getGeneration();
2302}
2303
2305 const PendingMacroInfo &PMInfo) {
2306 ModuleFile &M = *PMInfo.M;
2307
2308 BitstreamCursor &Cursor = M.MacroCursor;
2309 SavedStreamPosition SavedPosition(Cursor);
2310 if (llvm::Error Err =
2311 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2312 Error(std::move(Err));
2313 return;
2314 }
2315
2316 struct ModuleMacroRecord {
2317 SubmoduleID SubModID;
2318 MacroInfo *MI;
2320 };
2322
2323 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2324 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2325 // macro histroy.
2327 while (true) {
2329 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2330 if (!MaybeEntry) {
2331 Error(MaybeEntry.takeError());
2332 return;
2333 }
2334 llvm::BitstreamEntry Entry = MaybeEntry.get();
2335
2336 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2337 Error("malformed block record in AST file");
2338 return;
2339 }
2340
2341 Record.clear();
2342 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2343 if (!MaybePP) {
2344 Error(MaybePP.takeError());
2345 return;
2346 }
2347 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2349 break;
2350
2351 case PP_MODULE_MACRO: {
2352 ModuleMacros.push_back(ModuleMacroRecord());
2353 auto &Info = ModuleMacros.back();
2354 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2355 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2356 for (int I = 2, N = Record.size(); I != N; ++I)
2357 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2358 continue;
2359 }
2360
2361 default:
2362 Error("malformed block record in AST file");
2363 return;
2364 }
2365
2366 // We found the macro directive history; that's the last record
2367 // for this macro.
2368 break;
2369 }
2370
2371 // Module macros are listed in reverse dependency order.
2372 {
2373 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2375 for (auto &MMR : ModuleMacros) {
2376 Overrides.clear();
2377 for (unsigned ModID : MMR.Overrides) {
2378 Module *Mod = getSubmodule(ModID);
2379 auto *Macro = PP.getModuleMacro(Mod, II);
2380 assert(Macro && "missing definition for overridden macro");
2381 Overrides.push_back(Macro);
2382 }
2383
2384 bool Inserted = false;
2385 Module *Owner = getSubmodule(MMR.SubModID);
2386 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2387 }
2388 }
2389
2390 // Don't read the directive history for a module; we don't have anywhere
2391 // to put it.
2392 if (M.isModule())
2393 return;
2394
2395 // Deserialize the macro directives history in reverse source-order.
2396 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2397 unsigned Idx = 0, N = Record.size();
2398 while (Idx < N) {
2399 MacroDirective *MD = nullptr;
2400 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2402 switch (K) {
2404 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2405 MD = PP.AllocateDefMacroDirective(MI, Loc);
2406 break;
2407 }
2409 MD = PP.AllocateUndefMacroDirective(Loc);
2410 break;
2412 bool isPublic = Record[Idx++];
2413 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2414 break;
2415 }
2416
2417 if (!Latest)
2418 Latest = MD;
2419 if (Earliest)
2420 Earliest->setPrevious(MD);
2421 Earliest = MD;
2422 }
2423
2424 if (Latest)
2425 PP.setLoadedMacroDirective(II, Earliest, Latest);
2426}
2427
2428bool ASTReader::shouldDisableValidationForFile(
2429 const serialization::ModuleFile &M) const {
2430 if (DisableValidationKind == DisableValidationForModuleKind::None)
2431 return false;
2432
2433 // If a PCH is loaded and validation is disabled for PCH then disable
2434 // validation for the PCH and the modules it loads.
2435 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2436
2437 switch (K) {
2438 case MK_MainFile:
2439 case MK_Preamble:
2440 case MK_PCH:
2441 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2442 case MK_ImplicitModule:
2443 case MK_ExplicitModule:
2444 case MK_PrebuiltModule:
2445 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2446 }
2447
2448 return false;
2449}
2450
2451InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2452 // If this ID is bogus, just return an empty input file.
2453 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2454 return InputFileInfo();
2455
2456 // If we've already loaded this input file, return it.
2457 if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2458 return F.InputFileInfosLoaded[ID - 1];
2459
2460 // Go find this input file.
2461 BitstreamCursor &Cursor = F.InputFilesCursor;
2462 SavedStreamPosition SavedPosition(Cursor);
2463 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2464 F.InputFileOffsets[ID - 1])) {
2465 // FIXME this drops errors on the floor.
2466 consumeError(std::move(Err));
2467 }
2468
2469 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2470 if (!MaybeCode) {
2471 // FIXME this drops errors on the floor.
2472 consumeError(MaybeCode.takeError());
2473 }
2474 unsigned Code = MaybeCode.get();
2475 RecordData Record;
2476 StringRef Blob;
2477
2478 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2479 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2480 "invalid record type for input file");
2481 else {
2482 // FIXME this drops errors on the floor.
2483 consumeError(Maybe.takeError());
2484 }
2485
2486 assert(Record[0] == ID && "Bogus stored ID or offset");
2487 InputFileInfo R;
2488 R.StoredSize = static_cast<off_t>(Record[1]);
2489 R.StoredTime = static_cast<time_t>(Record[2]);
2490 R.Overridden = static_cast<bool>(Record[3]);
2491 R.Transient = static_cast<bool>(Record[4]);
2492 R.TopLevel = static_cast<bool>(Record[5]);
2493 R.ModuleMap = static_cast<bool>(Record[6]);
2494 std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
2495 uint16_t AsRequestedLength = Record[7];
2496
2497 std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2498 std::string Name = Blob.substr(AsRequestedLength).str();
2499
2500 ResolveImportedPath(F, NameAsRequested);
2501 ResolveImportedPath(F, Name);
2502
2503 if (Name.empty())
2504 Name = NameAsRequested;
2505
2506 return std::make_pair(std::move(NameAsRequested), std::move(Name));
2507 }();
2508
2509 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2510 if (!MaybeEntry) // FIXME this drops errors on the floor.
2511 consumeError(MaybeEntry.takeError());
2512 llvm::BitstreamEntry Entry = MaybeEntry.get();
2513 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2514 "expected record type for input file hash");
2515
2516 Record.clear();
2517 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2518 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2519 "invalid record type for input file hash");
2520 else {
2521 // FIXME this drops errors on the floor.
2522 consumeError(Maybe.takeError());
2523 }
2524 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2525 static_cast<uint64_t>(Record[0]);
2526
2527 // Note that we've loaded this input file info.
2528 F.InputFileInfosLoaded[ID - 1] = R;
2529 return R;
2530}
2531
2532static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2533InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2534 // If this ID is bogus, just return an empty input file.
2535 if (ID == 0 || ID > F.InputFilesLoaded.size())
2536 return InputFile();
2537
2538 // If we've already loaded this input file, return it.
2539 if (F.InputFilesLoaded[ID-1].getFile())
2540 return F.InputFilesLoaded[ID-1];
2541
2542 if (F.InputFilesLoaded[ID-1].isNotFound())
2543 return InputFile();
2544
2545 // Go find this input file.
2546 BitstreamCursor &Cursor = F.InputFilesCursor;
2547 SavedStreamPosition SavedPosition(Cursor);
2548 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2549 F.InputFileOffsets[ID - 1])) {
2550 // FIXME this drops errors on the floor.
2551 consumeError(std::move(Err));
2552 }
2553
2554 InputFileInfo FI = getInputFileInfo(F, ID);
2555 off_t StoredSize = FI.StoredSize;
2556 time_t StoredTime = FI.StoredTime;
2557 bool Overridden = FI.Overridden;
2558 bool Transient = FI.Transient;
2559 StringRef Filename = FI.FilenameAsRequested;
2560 uint64_t StoredContentHash = FI.ContentHash;
2561
2562 // For standard C++ modules, we don't need to check the inputs.
2563 bool SkipChecks = F.StandardCXXModule;
2564
2565 const HeaderSearchOptions &HSOpts =
2566 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2567
2568 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2569 // modules.
2571 SkipChecks = false;
2572 Overridden = false;
2573 }
2574
2575 auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);
2576
2577 // For an overridden file, create a virtual file with the stored
2578 // size/timestamp.
2579 if ((Overridden || Transient || SkipChecks) && !File)
2580 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2581
2582 if (!File) {
2583 if (Complain) {
2584 std::string ErrorStr = "could not find file '";
2585 ErrorStr += Filename;
2586 ErrorStr += "' referenced by AST file '";
2587 ErrorStr += F.FileName;
2588 ErrorStr += "'";
2589 Error(ErrorStr);
2590 }
2591 // Record that we didn't find the file.
2593 return InputFile();
2594 }
2595
2596 // Check if there was a request to override the contents of the file
2597 // that was part of the precompiled header. Overriding such a file
2598 // can lead to problems when lexing using the source locations from the
2599 // PCH.
2600 SourceManager &SM = getSourceManager();
2601 // FIXME: Reject if the overrides are different.
2602 if ((!Overridden && !Transient) && !SkipChecks &&
2603 SM.isFileOverridden(*File)) {
2604 if (Complain)
2605 Error(diag::err_fe_pch_file_overridden, Filename);
2606
2607 // After emitting the diagnostic, bypass the overriding file to recover
2608 // (this creates a separate FileEntry).
2609 File = SM.bypassFileContentsOverride(*File);
2610 if (!File) {
2612 return InputFile();
2613 }
2614 }
2615
2616 struct Change {
2617 enum ModificationKind {
2618 Size,
2619 ModTime,
2620 Content,
2621 None,
2622 } Kind;
2623 std::optional<int64_t> Old = std::nullopt;
2624 std::optional<int64_t> New = std::nullopt;
2625 };
2626 auto HasInputContentChanged = [&](Change OriginalChange) {
2627 assert(ValidateASTInputFilesContent &&
2628 "We should only check the content of the inputs with "
2629 "ValidateASTInputFilesContent enabled.");
2630
2631 if (StoredContentHash == 0)
2632 return OriginalChange;
2633
2634 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2635 if (!MemBuffOrError) {
2636 if (!Complain)
2637 return OriginalChange;
2638 std::string ErrorStr = "could not get buffer for file '";
2639 ErrorStr += File->getName();
2640 ErrorStr += "'";
2641 Error(ErrorStr);
2642 return OriginalChange;
2643 }
2644
2645 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2646 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2647 return Change{Change::None};
2648
2649 return Change{Change::Content};
2650 };
2651 auto HasInputFileChanged = [&]() {
2652 if (StoredSize != File->getSize())
2653 return Change{Change::Size, StoredSize, File->getSize()};
2654 if (!shouldDisableValidationForFile(F) && StoredTime &&
2655 StoredTime != File->getModificationTime()) {
2656 Change MTimeChange = {Change::ModTime, StoredTime,
2657 File->getModificationTime()};
2658
2659 // In case the modification time changes but not the content,
2660 // accept the cached file as legit.
2661 if (ValidateASTInputFilesContent)
2662 return HasInputContentChanged(MTimeChange);
2663
2664 return MTimeChange;
2665 }
2666 return Change{Change::None};
2667 };
2668
2669 bool IsOutOfDate = false;
2670 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2671 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2672 // enabled, it is better to check the contents of the inputs. Since we can't
2673 // get correct modified time information for inputs from overriden inputs.
2674 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2675 F.StandardCXXModule && FileChange.Kind == Change::None)
2676 FileChange = HasInputContentChanged(FileChange);
2677
2678 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2679 // it is better to check the content of the input files because we cannot rely
2680 // on the file modification time, which will be the same (zero) for these
2681 // files.
2682 if (!StoredTime && ValidateASTInputFilesContent &&
2683 FileChange.Kind == Change::None)
2684 FileChange = HasInputContentChanged(FileChange);
2685
2686 // For an overridden file, there is nothing to validate.
2687 if (!Overridden && FileChange.Kind != Change::None) {
2688 if (Complain && !Diags.isDiagnosticInFlight()) {
2689 // Build a list of the PCH imports that got us here (in reverse).
2690 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2691 while (!ImportStack.back()->ImportedBy.empty())
2692 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2693
2694 // The top-level PCH is stale.
2695 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2696 Diag(diag::err_fe_ast_file_modified)
2697 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2698 << TopLevelPCHName << FileChange.Kind
2699 << (FileChange.Old && FileChange.New)
2700 << llvm::itostr(FileChange.Old.value_or(0))
2701 << llvm::itostr(FileChange.New.value_or(0));
2702
2703 // Print the import stack.
2704 if (ImportStack.size() > 1) {
2705 Diag(diag::note_pch_required_by)
2706 << Filename << ImportStack[0]->FileName;
2707 for (unsigned I = 1; I < ImportStack.size(); ++I)
2708 Diag(diag::note_pch_required_by)
2709 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2710 }
2711
2712 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2713 }
2714
2715 IsOutOfDate = true;
2716 }
2717 // FIXME: If the file is overridden and we've already opened it,
2718 // issue an error (or split it into a separate FileEntry).
2719
2720 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2721
2722 // Note that we've loaded this input file.
2723 F.InputFilesLoaded[ID-1] = IF;
2724 return IF;
2725}
2726
2727/// If we are loading a relocatable PCH or module file, and the filename
2728/// is not an absolute path, add the system or module root to the beginning of
2729/// the file name.
2731 // Resolve relative to the base directory, if we have one.
2732 if (!M.BaseDirectory.empty())
2733 return ResolveImportedPath(Filename, M.BaseDirectory);
2734}
2735
2736void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2737 if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||
2738 Filename == "<built-in>" || Filename == "<command line>")
2739 return;
2740
2741 SmallString<128> Buffer;
2742 llvm::sys::path::append(Buffer, Prefix, Filename);
2743 Filename.assign(Buffer.begin(), Buffer.end());
2744}
2745
2746static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2747 switch (ARR) {
2748 case ASTReader::Failure: return true;
2749 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2750 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2753 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2754 case ASTReader::HadErrors: return true;
2755 case ASTReader::Success: return false;
2756 }
2757
2758 llvm_unreachable("unknown ASTReadResult");
2759}
2760
2761ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2762 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2763 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2764 std::string &SuggestedPredefines) {
2765 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2766 // FIXME this drops errors on the floor.
2767 consumeError(std::move(Err));
2768 return Failure;
2769 }
2770
2771 // Read all of the records in the options block.
2772 RecordData Record;
2773 ASTReadResult Result = Success;
2774 while (true) {
2775 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2776 if (!MaybeEntry) {
2777 // FIXME this drops errors on the floor.
2778 consumeError(MaybeEntry.takeError());
2779 return Failure;
2780 }
2781 llvm::BitstreamEntry Entry = MaybeEntry.get();
2782
2783 switch (Entry.Kind) {
2784 case llvm::BitstreamEntry::Error:
2785 case llvm::BitstreamEntry::SubBlock:
2786 return Failure;
2787
2788 case llvm::BitstreamEntry::EndBlock:
2789 return Result;
2790
2791 case llvm::BitstreamEntry::Record:
2792 // The interesting case.
2793 break;
2794 }
2795
2796 // Read and process a record.
2797 Record.clear();
2798 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2799 if (!MaybeRecordType) {
2800 // FIXME this drops errors on the floor.
2801 consumeError(MaybeRecordType.takeError());
2802 return Failure;
2803 }
2804 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2805 case LANGUAGE_OPTIONS: {
2806 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2807 if (ParseLanguageOptions(Record, Complain, Listener,
2808 AllowCompatibleConfigurationMismatch))
2809 Result = ConfigurationMismatch;
2810 break;
2811 }
2812
2813 case TARGET_OPTIONS: {
2814 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2815 if (ParseTargetOptions(Record, Complain, Listener,
2816 AllowCompatibleConfigurationMismatch))
2817 Result = ConfigurationMismatch;
2818 break;
2819 }
2820
2821 case FILE_SYSTEM_OPTIONS: {
2822 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2823 if (!AllowCompatibleConfigurationMismatch &&
2824 ParseFileSystemOptions(Record, Complain, Listener))
2825 Result = ConfigurationMismatch;
2826 break;
2827 }
2828
2829 case HEADER_SEARCH_OPTIONS: {
2830 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2831 if (!AllowCompatibleConfigurationMismatch &&
2832 ParseHeaderSearchOptions(Record, Complain, Listener))
2833 Result = ConfigurationMismatch;
2834 break;
2835 }
2836
2838 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2839 if (!AllowCompatibleConfigurationMismatch &&
2840 ParsePreprocessorOptions(Record, Complain, Listener,
2841 SuggestedPredefines))
2842 Result = ConfigurationMismatch;
2843 break;
2844 }
2845 }
2846}
2847
2849ASTReader::ReadControlBlock(ModuleFile &F,
2851 const ModuleFile *ImportedBy,
2852 unsigned ClientLoadCapabilities) {
2853 BitstreamCursor &Stream = F.Stream;
2854
2855 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2856 Error(std::move(Err));
2857 return Failure;
2858 }
2859
2860 // Lambda to read the unhashed control block the first time it's called.
2861 //
2862 // For PCM files, the unhashed control block cannot be read until after the
2863 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2864 // need to look ahead before reading the IMPORTS record. For consistency,
2865 // this block is always read somehow (see BitstreamEntry::EndBlock).
2866 bool HasReadUnhashedControlBlock = false;
2867 auto readUnhashedControlBlockOnce = [&]() {
2868 if (!HasReadUnhashedControlBlock) {
2869 HasReadUnhashedControlBlock = true;
2870 if (ASTReadResult Result =
2871 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2872 return Result;
2873 }
2874 return Success;
2875 };
2876
2877 bool DisableValidation = shouldDisableValidationForFile(F);
2878
2879 // Read all of the records and blocks in the control block.
2880 RecordData Record;
2881 unsigned NumInputs = 0;
2882 unsigned NumUserInputs = 0;
2883 StringRef BaseDirectoryAsWritten;
2884 while (true) {
2885 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2886 if (!MaybeEntry) {
2887 Error(MaybeEntry.takeError());
2888 return Failure;
2889 }
2890 llvm::BitstreamEntry Entry = MaybeEntry.get();
2891
2892 switch (Entry.Kind) {
2893 case llvm::BitstreamEntry::Error:
2894 Error("malformed block record in AST file");
2895 return Failure;
2896 case llvm::BitstreamEntry::EndBlock: {
2897 // Validate the module before returning. This call catches an AST with
2898 // no module name and no imports.
2899 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2900 return Result;
2901
2902 // Validate input files.
2903 const HeaderSearchOptions &HSOpts =
2904 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2905
2906 // All user input files reside at the index range [0, NumUserInputs), and
2907 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2908 // loaded module files, ignore missing inputs.
2909 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2910 F.Kind != MK_PrebuiltModule) {
2911 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2912
2913 // If we are reading a module, we will create a verification timestamp,
2914 // so we verify all input files. Otherwise, verify only user input
2915 // files.
2916
2917 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2921 N = NumUserInputs;
2922
2923 for (unsigned I = 0; I < N; ++I) {
2924 InputFile IF = getInputFile(F, I+1, Complain);
2925 if (!IF.getFile() || IF.isOutOfDate())
2926 return OutOfDate;
2927 }
2928 }
2929
2930 if (Listener)
2931 Listener->visitModuleFile(F.FileName, F.Kind);
2932
2933 if (Listener && Listener->needsInputFileVisitation()) {
2934 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2935 : NumUserInputs;
2936 for (unsigned I = 0; I < N; ++I) {
2937 bool IsSystem = I >= NumUserInputs;
2938 InputFileInfo FI = getInputFileInfo(F, I + 1);
2939 Listener->visitInputFile(
2940 FI.FilenameAsRequested, IsSystem, FI.Overridden,
2942 }
2943 }
2944
2945 return Success;
2946 }
2947
2948 case llvm::BitstreamEntry::SubBlock:
2949 switch (Entry.ID) {
2951 F.InputFilesCursor = Stream;
2952 if (llvm::Error Err = Stream.SkipBlock()) {
2953 Error(std::move(Err));
2954 return Failure;
2955 }
2956 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2957 Error("malformed block record in AST file");
2958 return Failure;
2959 }
2960 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
2961 continue;
2962
2963 case OPTIONS_BLOCK_ID:
2964 // If we're reading the first module for this group, check its options
2965 // are compatible with ours. For modules it imports, no further checking
2966 // is required, because we checked them when we built it.
2967 if (Listener && !ImportedBy) {
2968 // Should we allow the configuration of the module file to differ from
2969 // the configuration of the current translation unit in a compatible
2970 // way?
2971 //
2972 // FIXME: Allow this for files explicitly specified with -include-pch.
2973 bool AllowCompatibleConfigurationMismatch =
2975
2976 ASTReadResult Result =
2977 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2978 AllowCompatibleConfigurationMismatch, *Listener,
2979 SuggestedPredefines);
2980 if (Result == Failure) {
2981 Error("malformed block record in AST file");
2982 return Result;
2983 }
2984
2985 if (DisableValidation ||
2986 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2987 Result = Success;
2988
2989 // If we can't load the module, exit early since we likely
2990 // will rebuild the module anyway. The stream may be in the
2991 // middle of a block.
2992 if (Result != Success)
2993 return Result;
2994 } else if (llvm::Error Err = Stream.SkipBlock()) {
2995 Error(std::move(Err));
2996 return Failure;
2997 }
2998 continue;
2999
3000 default:
3001 if (llvm::Error Err = Stream.SkipBlock()) {
3002 Error(std::move(Err));
3003 return Failure;
3004 }
3005 continue;
3006 }
3007
3008 case llvm::BitstreamEntry::Record:
3009 // The interesting case.
3010 break;
3011 }
3012
3013 // Read and process a record.
3014 Record.clear();
3015 StringRef Blob;
3016 Expected<unsigned> MaybeRecordType =
3017 Stream.readRecord(Entry.ID, Record, &Blob);
3018 if (!MaybeRecordType) {
3019 Error(MaybeRecordType.takeError());
3020 return Failure;
3021 }
3022 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3023 case METADATA: {
3024 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3025 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3026 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
3027 : diag::err_pch_version_too_new);
3028 return VersionMismatch;
3029 }
3030
3031 bool hasErrors = Record[7];
3032 if (hasErrors && !DisableValidation) {
3033 // If requested by the caller and the module hasn't already been read
3034 // or compiled, mark modules on error as out-of-date.
3035 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3036 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3037 return OutOfDate;
3038
3039 if (!AllowASTWithCompilerErrors) {
3040 Diag(diag::err_pch_with_compiler_errors);
3041 return HadErrors;
3042 }
3043 }
3044 if (hasErrors) {
3045 Diags.ErrorOccurred = true;
3046 Diags.UncompilableErrorOccurred = true;
3047 Diags.UnrecoverableErrorOccurred = true;
3048 }
3049
3050 F.RelocatablePCH = Record[4];
3051 // Relative paths in a relocatable PCH are relative to our sysroot.
3052 if (F.RelocatablePCH)
3053 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3054
3056
3057 F.HasTimestamps = Record[6];
3058
3059 const std::string &CurBranch = getClangFullRepositoryVersion();
3060 StringRef ASTBranch = Blob;
3061 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3062 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3063 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
3064 return VersionMismatch;
3065 }
3066 break;
3067 }
3068
3069 case IMPORTS: {
3070 // Validate the AST before processing any imports (otherwise, untangling
3071 // them can be error-prone and expensive). A module will have a name and
3072 // will already have been validated, but this catches the PCH case.
3073 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3074 return Result;
3075
3076 // Load each of the imported PCH files.
3077 unsigned Idx = 0, N = Record.size();
3078 while (Idx < N) {
3079 // Read information about the AST file.
3080 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3081 // Whether we're importing a standard c++ module.
3082 bool IsImportingStdCXXModule = Record[Idx++];
3083 // The import location will be the local one for now; we will adjust
3084 // all import locations of module imports after the global source
3085 // location info are setup, in ReadAST.
3086 auto [ImportLoc, ImportModuleFileIndex] =
3087 ReadUntranslatedSourceLocation(Record[Idx++]);
3088 // The import location must belong to the current module file itself.
3089 assert(ImportModuleFileIndex == 0);
3090 off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;
3091 time_t StoredModTime =
3092 !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;
3093
3094 ASTFileSignature StoredSignature;
3095 if (!IsImportingStdCXXModule) {
3096 auto FirstSignatureByte = Record.begin() + Idx;
3097 StoredSignature = ASTFileSignature::create(
3098 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
3100 }
3101
3102 std::string ImportedName = ReadString(Record, Idx);
3103 std::string ImportedFile;
3104
3105 // For prebuilt and explicit modules first consult the file map for
3106 // an override. Note that here we don't search prebuilt module
3107 // directories if we're not importing standard c++ module, only the
3108 // explicit name to file mappings. Also, we will still verify the
3109 // size/signature making sure it is essentially the same file but
3110 // perhaps in a different location.
3111 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3112 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3113 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3114
3115 // For C++20 Modules, we won't record the path to the imported modules
3116 // in the BMI
3117 if (!IsImportingStdCXXModule) {
3118 if (ImportedFile.empty()) {
3119 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3120 // ModuleCache as when writing.
3121 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
3122 } else
3123 SkipPath(Record, Idx);
3124 } else if (ImportedFile.empty()) {
3125 Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3126 return Missing;
3127 }
3128
3129 // If our client can't cope with us being out of date, we can't cope with
3130 // our dependency being missing.
3131 unsigned Capabilities = ClientLoadCapabilities;
3132 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3133 Capabilities &= ~ARR_Missing;
3134
3135 // Load the AST file.
3136 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3137 Loaded, StoredSize, StoredModTime,
3138 StoredSignature, Capabilities);
3139
3140 // If we diagnosed a problem, produce a backtrace.
3141 bool recompilingFinalized =
3142 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3143 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3144 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3145 Diag(diag::note_module_file_imported_by)
3146 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3147 if (recompilingFinalized)
3148 Diag(diag::note_module_file_conflict);
3149
3150 switch (Result) {
3151 case Failure: return Failure;
3152 // If we have to ignore the dependency, we'll have to ignore this too.
3153 case Missing:
3154 case OutOfDate: return OutOfDate;
3155 case VersionMismatch: return VersionMismatch;
3156 case ConfigurationMismatch: return ConfigurationMismatch;
3157 case HadErrors: return HadErrors;
3158 case Success: break;
3159 }
3160 }
3161 break;
3162 }
3163
3164 case ORIGINAL_FILE:
3165 F.OriginalSourceFileID = FileID::get(Record[0]);
3166 F.ActualOriginalSourceFileName = std::string(Blob);
3168 ResolveImportedPath(F, F.OriginalSourceFileName);
3169 break;
3170
3171 case ORIGINAL_FILE_ID:
3172 F.OriginalSourceFileID = FileID::get(Record[0]);
3173 break;
3174
3175 case MODULE_NAME:
3176 F.ModuleName = std::string(Blob);
3177 Diag(diag::remark_module_import)
3178 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3179 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3180 if (Listener)
3181 Listener->ReadModuleName(F.ModuleName);
3182
3183 // Validate the AST as soon as we have a name so we can exit early on
3184 // failure.
3185 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3186 return Result;
3187
3188 break;
3189
3190 case MODULE_DIRECTORY: {
3191 // Save the BaseDirectory as written in the PCM for computing the module
3192 // filename for the ModuleCache.
3193 BaseDirectoryAsWritten = Blob;
3194 assert(!F.ModuleName.empty() &&
3195 "MODULE_DIRECTORY found before MODULE_NAME");
3196 F.BaseDirectory = std::string(Blob);
3197 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3198 break;
3199 // If we've already loaded a module map file covering this module, we may
3200 // have a better path for it (relative to the current build).
3201 Module *M = PP.getHeaderSearchInfo().lookupModule(
3202 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3203 /*AllowExtraModuleMapSearch*/ true);
3204 if (M && M->Directory) {
3205 // If we're implicitly loading a module, the base directory can't
3206 // change between the build and use.
3207 // Don't emit module relocation error if we have -fno-validate-pch
3208 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3211 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3212 if (!BuildDir || *BuildDir != M->Directory) {
3213 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3214 Diag(diag::err_imported_module_relocated)
3215 << F.ModuleName << Blob << M->Directory->getName();
3216 return OutOfDate;
3217 }
3218 }
3219 F.BaseDirectory = std::string(M->Directory->getName());
3220 }
3221 break;
3222 }
3223
3224 case MODULE_MAP_FILE:
3225 if (ASTReadResult Result =
3226 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3227 return Result;
3228 break;
3229
3230 case INPUT_FILE_OFFSETS:
3231 NumInputs = Record[0];
3232 NumUserInputs = Record[1];
3234 (const llvm::support::unaligned_uint64_t *)Blob.data();
3235 F.InputFilesLoaded.resize(NumInputs);
3236 F.InputFileInfosLoaded.resize(NumInputs);
3237 F.NumUserInputFiles = NumUserInputs;
3238 break;
3239 }
3240 }
3241}
3242
3243llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3244 unsigned ClientLoadCapabilities) {
3245 BitstreamCursor &Stream = F.Stream;
3246
3247 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3248 return Err;
3249 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3250
3251 // Read all of the records and blocks for the AST file.
3252 RecordData Record;
3253 while (true) {
3254 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3255 if (!MaybeEntry)
3256 return MaybeEntry.takeError();
3257 llvm::BitstreamEntry Entry = MaybeEntry.get();
3258
3259 switch (Entry.Kind) {
3260 case llvm::BitstreamEntry::Error:
3261 return llvm::createStringError(
3262 std::errc::illegal_byte_sequence,
3263 "error at end of module block in AST file");
3264 case llvm::BitstreamEntry::EndBlock:
3265 // Outside of C++, we do not store a lookup map for the translation unit.
3266 // Instead, mark it as needing a lookup map to be built if this module
3267 // contains any declarations lexically within it (which it always does!).
3268 // This usually has no cost, since we very rarely need the lookup map for
3269 // the translation unit outside C++.
3270 if (ASTContext *Ctx = ContextObj) {
3271 DeclContext *DC = Ctx->getTranslationUnitDecl();
3272 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3274 }
3275
3276 return llvm::Error::success();
3277 case llvm::BitstreamEntry::SubBlock:
3278 switch (Entry.ID) {
3279 case DECLTYPES_BLOCK_ID:
3280 // We lazily load the decls block, but we want to set up the
3281 // DeclsCursor cursor to point into it. Clone our current bitcode
3282 // cursor to it, enter the block and read the abbrevs in that block.
3283 // With the main cursor, we just skip over it.
3284 F.DeclsCursor = Stream;
3285 if (llvm::Error Err = Stream.SkipBlock())
3286 return Err;
3287 if (llvm::Error Err = ReadBlockAbbrevs(
3289 return Err;
3290 break;
3291
3293 F.MacroCursor = Stream;
3294 if (!PP.getExternalSource())
3295 PP.setExternalSource(this);
3296
3297 if (llvm::Error Err = Stream.SkipBlock())
3298 return Err;
3299 if (llvm::Error Err =
3300 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3301 return Err;
3302 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3303 break;
3304
3306 F.PreprocessorDetailCursor = Stream;
3307
3308 if (llvm::Error Err = Stream.SkipBlock()) {
3309 return Err;
3310 }
3311 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3313 return Err;
3315 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3316
3317 if (!PP.getPreprocessingRecord())
3318 PP.createPreprocessingRecord();
3319 if (!PP.getPreprocessingRecord()->getExternalSource())
3320 PP.getPreprocessingRecord()->SetExternalSource(*this);
3321 break;
3322
3324 if (llvm::Error Err = ReadSourceManagerBlock(F))
3325 return Err;
3326 break;
3327
3328 case SUBMODULE_BLOCK_ID:
3329 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3330 return Err;
3331 break;
3332
3333 case COMMENTS_BLOCK_ID: {
3334 BitstreamCursor C = Stream;
3335
3336 if (llvm::Error Err = Stream.SkipBlock())
3337 return Err;
3338 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3339 return Err;
3340 CommentsCursors.push_back(std::make_pair(C, &F));
3341 break;
3342 }
3343
3344 default:
3345 if (llvm::Error Err = Stream.SkipBlock())
3346 return Err;
3347 break;
3348 }
3349 continue;
3350
3351 case llvm::BitstreamEntry::Record:
3352 // The interesting case.
3353 break;
3354 }
3355
3356 // Read and process a record.
3357 Record.clear();
3358 StringRef Blob;
3359 Expected<unsigned> MaybeRecordType =
3360 Stream.readRecord(Entry.ID, Record, &Blob);
3361 if (!MaybeRecordType)
3362 return MaybeRecordType.takeError();
3363 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3364
3365 // If we're not loading an AST context, we don't care about most records.
3366 if (!ContextObj) {
3367 switch (RecordType) {
3368 case IDENTIFIER_TABLE:
3369 case IDENTIFIER_OFFSET:
3371 case STATISTICS:
3374 case PP_COUNTER_VALUE:
3376 case MODULE_OFFSET_MAP:
3380 case IMPORTED_MODULES:
3381 case MACRO_OFFSET:
3382 break;
3383 default:
3384 continue;
3385 }
3386 }
3387
3388 switch (RecordType) {
3389 default: // Default behavior: ignore.
3390 break;
3391
3392 case TYPE_OFFSET: {
3393 if (F.LocalNumTypes != 0)
3394 return llvm::createStringError(
3395 std::errc::illegal_byte_sequence,
3396 "duplicate TYPE_OFFSET record in AST file");
3397 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3398 F.LocalNumTypes = Record[0];
3399 F.BaseTypeIndex = getTotalNumTypes();
3400
3401 if (F.LocalNumTypes > 0)
3402 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3403
3404 break;
3405 }
3406
3407 case DECL_OFFSET: {
3408 if (F.LocalNumDecls != 0)
3409 return llvm::createStringError(
3410 std::errc::illegal_byte_sequence,
3411 "duplicate DECL_OFFSET record in AST file");
3412 F.DeclOffsets = (const DeclOffset *)Blob.data();
3413 F.LocalNumDecls = Record[0];
3414 F.BaseDeclIndex = getTotalNumDecls();
3415
3416 if (F.LocalNumDecls > 0)
3417 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3418
3419 break;
3420 }
3421
3422 case TU_UPDATE_LEXICAL: {
3423 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3424 LexicalContents Contents(
3425 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3426 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3427 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3429 break;
3430 }
3431
3432 case UPDATE_VISIBLE: {
3433 unsigned Idx = 0;
3434 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3435 auto *Data = (const unsigned char*)Blob.data();
3436 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3437 // If we've already loaded the decl, perform the updates when we finish
3438 // loading this block.
3439 if (Decl *D = GetExistingDecl(ID))
3440 PendingUpdateRecords.push_back(
3441 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3442 break;
3443 }
3444
3445 case IDENTIFIER_TABLE:
3447 reinterpret_cast<const unsigned char *>(Blob.data());
3448 if (Record[0]) {
3449 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3451 F.IdentifierTableData + sizeof(uint32_t),
3453 ASTIdentifierLookupTrait(*this, F));
3454
3455 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3456 }
3457 break;
3458
3459 case IDENTIFIER_OFFSET: {
3460 if (F.LocalNumIdentifiers != 0)
3461 return llvm::createStringError(
3462 std::errc::illegal_byte_sequence,
3463 "duplicate IDENTIFIER_OFFSET record in AST file");
3464 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3466 F.BaseIdentifierID = getTotalNumIdentifiers();
3467
3468 if (F.LocalNumIdentifiers > 0)
3469 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3471 break;
3472 }
3473
3475 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3476 break;
3477
3479 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3480 // about "interesting" decls (for instance, if we're building a module).
3481 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3482 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3483 break;
3484
3486 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3487 // them (ie: if we're not codegenerating this module).
3488 if (F.Kind == MK_MainFile ||
3489 getContext().getLangOpts().BuildingPCHWithObjectFile)
3490 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3491 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3492 break;
3493
3494 case SPECIAL_TYPES:
3495 if (SpecialTypes.empty()) {
3496 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3497 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3498 break;
3499 }
3500
3501 if (SpecialTypes.size() != Record.size())
3502 return llvm::createStringError(std::errc::illegal_byte_sequence,
3503 "invalid special-types record");
3504
3505 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3506 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3507 if (!SpecialTypes[I])
3508 SpecialTypes[I] = ID;
3509 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3510 // merge step?
3511 }
3512 break;
3513
3514 case STATISTICS:
3515 TotalNumStatements += Record[0];
3516 TotalNumMacros += Record[1];
3517 TotalLexicalDeclContexts += Record[2];
3518 TotalVisibleDeclContexts += Record[3];
3519 break;
3520
3522 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3523 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3524 break;
3525
3526 case DELEGATING_CTORS:
3527 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3528 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3529 break;
3530
3532 if (Record.size() % 3 != 0)
3533 return llvm::createStringError(std::errc::illegal_byte_sequence,
3534 "invalid weak identifiers record");
3535
3536 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3537 // files. This isn't the way to do it :)
3538 WeakUndeclaredIdentifiers.clear();
3539
3540 // Translate the weak, undeclared identifiers into global IDs.
3541 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3542 WeakUndeclaredIdentifiers.push_back(
3543 getGlobalIdentifierID(F, Record[I++]));
3544 WeakUndeclaredIdentifiers.push_back(
3545 getGlobalIdentifierID(F, Record[I++]));
3546 WeakUndeclaredIdentifiers.push_back(
3547 ReadSourceLocation(F, Record, I).getRawEncoding());
3548 }
3549 break;
3550
3551 case SELECTOR_OFFSETS: {
3552 F.SelectorOffsets = (const uint32_t *)Blob.data();
3554 unsigned LocalBaseSelectorID = Record[1];
3555 F.BaseSelectorID = getTotalNumSelectors();
3556
3557 if (F.LocalNumSelectors > 0) {
3558 // Introduce the global -> local mapping for selectors within this
3559 // module.
3560 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3561
3562 // Introduce the local -> global mapping for selectors within this
3563 // module.
3565 std::make_pair(LocalBaseSelectorID,
3566 F.BaseSelectorID - LocalBaseSelectorID));
3567
3568 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3569 }
3570 break;
3571 }
3572
3573 case METHOD_POOL:
3574 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3575 if (Record[0])
3577 = ASTSelectorLookupTable::Create(
3580 ASTSelectorLookupTrait(*this, F));
3581 TotalNumMethodPoolEntries += Record[1];
3582 break;
3583
3585 if (!Record.empty()) {
3586 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3587 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3588 Record[Idx++]));
3589 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3590 getRawEncoding());
3591 }
3592 }
3593 break;
3594
3595 case PP_ASSUME_NONNULL_LOC: {
3596 unsigned Idx = 0;
3597 if (!Record.empty())
3598 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3599 ReadSourceLocation(F, Record, Idx));
3600 break;
3601 }
3602
3604 if (!Record.empty()) {
3606 unsigned Idx = 0;
3607 while (Idx < Record.size())
3608 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
3609 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
3610 }
3611 break;
3612 }
3613
3615 if (!Record.empty()) {
3616 unsigned Idx = 0, End = Record.size() - 1;
3617 bool ReachedEOFWhileSkipping = Record[Idx++];
3618 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3619 if (ReachedEOFWhileSkipping) {
3620 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3621 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3622 bool FoundNonSkipPortion = Record[Idx++];
3623 bool FoundElse = Record[Idx++];
3624 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3625 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3626 FoundElse, ElseLoc);
3627 }
3628 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3629 while (Idx < End) {
3630 auto Loc = ReadSourceLocation(F, Record, Idx);
3631 bool WasSkipping = Record[Idx++];
3632 bool FoundNonSkip = Record[Idx++];
3633 bool FoundElse = Record[Idx++];
3634 ConditionalStack.push_back(
3635 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3636 }
3637 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3638 }
3639 break;
3640
3641 case PP_COUNTER_VALUE:
3642 if (!Record.empty() && Listener)
3643 Listener->ReadCounter(F, Record[0]);
3644 break;
3645
3646 case FILE_SORTED_DECLS:
3647 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
3649 break;
3650
3652 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3654 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3656 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3657 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3658 SLocSpaceSize);
3659 if (!F.SLocEntryBaseID) {
3660 if (!Diags.isDiagnosticInFlight()) {
3661 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3662 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3663 }
3664 return llvm::createStringError(std::errc::invalid_argument,
3665 "ran out of source locations");
3666 }
3667 // Make our entry in the range map. BaseID is negative and growing, so
3668 // we invert it. Because we invert it, though, we need the other end of
3669 // the range.
3670 unsigned RangeStart =
3672 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3674
3675 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3676 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3677 GlobalSLocOffsetMap.insert(
3678 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3679 - SLocSpaceSize,&F));
3680
3681 TotalNumSLocEntries += F.LocalNumSLocEntries;
3682 break;
3683 }
3684
3685 case MODULE_OFFSET_MAP:
3686 F.ModuleOffsetMap = Blob;
3687 break;
3688
3690 ParseLineTable(F, Record);
3691 break;
3692
3693 case EXT_VECTOR_DECLS:
3694 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3695 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
3696 break;
3697
3698 case VTABLE_USES:
3699 if (Record.size() % 3 != 0)
3700 return llvm::createStringError(std::errc::illegal_byte_sequence,
3701 "Invalid VTABLE_USES record");
3702
3703 // Later tables overwrite earlier ones.
3704 // FIXME: Modules will have some trouble with this. This is clearly not
3705 // the right way to do this.
3706 VTableUses.clear();
3707
3708 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3709 VTableUses.push_back(
3710 {ReadDeclID(F, Record, Idx),
3711 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
3712 (bool)Record[Idx++]});
3713 }
3714 break;
3715
3717
3718 if (Record.size() % 2 != 0)
3719 return llvm::createStringError(
3720 std::errc::illegal_byte_sequence,
3721 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3722
3723 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3724 PendingInstantiations.push_back(
3725 {ReadDeclID(F, Record, I),
3726 ReadSourceLocation(F, Record, I).getRawEncoding()});
3727 }
3728 break;
3729
3730 case SEMA_DECL_REFS:
3731 if (Record.size() != 3)
3732 return llvm::createStringError(std::errc::illegal_byte_sequence,
3733 "Invalid SEMA_DECL_REFS block");
3734 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3735 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
3736 break;
3737
3738 case PPD_ENTITIES_OFFSETS: {
3739 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3740 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3741 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3742
3743 unsigned LocalBasePreprocessedEntityID = Record[0];
3744
3745 unsigned StartingID;
3746 if (!PP.getPreprocessingRecord())
3747 PP.createPreprocessingRecord();
3748 if (!PP.getPreprocessingRecord()->getExternalSource())
3749 PP.getPreprocessingRecord()->SetExternalSource(*this);
3750 StartingID
3751 = PP.getPreprocessingRecord()
3752 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3753 F.BasePreprocessedEntityID = StartingID;
3754
3755 if (F.NumPreprocessedEntities > 0) {
3756 // Introduce the global -> local mapping for preprocessed entities in
3757 // this module.
3758 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3759
3760 // Introduce the local -> global mapping for preprocessed entities in
3761 // this module.
3763 std::make_pair(LocalBasePreprocessedEntityID,
3764 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3765 }
3766
3767 break;
3768 }
3769
3770 case PPD_SKIPPED_RANGES: {
3771 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3772 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3773 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3774
3775 if (!PP.getPreprocessingRecord())
3776 PP.createPreprocessingRecord();
3777 if (!PP.getPreprocessingRecord()->getExternalSource())
3778 PP.getPreprocessingRecord()->SetExternalSource(*this);
3779 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3780 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3781
3783 GlobalSkippedRangeMap.insert(
3784 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3785 break;
3786 }
3787
3789 if (Record.size() % 2 != 0)
3790 return llvm::createStringError(
3791 std::errc::illegal_byte_sequence,
3792 "invalid DECL_UPDATE_OFFSETS block in AST file");
3793 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3794 GlobalDeclID ID = ReadDeclID(F, Record, I);
3795 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
3796
3797 // If we've already loaded the decl, perform the updates when we finish
3798 // loading this block.
3799 if (Decl *D = GetExistingDecl(ID))
3800 PendingUpdateRecords.push_back(
3801 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3802 }
3803 break;
3804
3806 if (Record.size() % 3 != 0)
3807 return llvm::createStringError(
3808 std::errc::illegal_byte_sequence,
3809 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3810 "file");
3811 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
3812 GlobalDeclID ID = ReadDeclID(F, Record, I);
3813
3814 uint64_t BaseOffset = F.DeclsBlockStartOffset;
3815 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
3816 uint64_t LocalLexicalOffset = Record[I++];
3817 uint64_t LexicalOffset =
3818 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
3819 uint64_t LocalVisibleOffset = Record[I++];
3820 uint64_t VisibleOffset =
3821 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
3822
3823 DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};
3824
3825 assert(!GetExistingDecl(ID) &&
3826 "We shouldn't load the namespace in the front of delayed "
3827 "namespace lexical and visible block");
3828 }
3829 break;
3830 }
3831
3833 if (F.LocalNumObjCCategoriesInMap != 0)
3834 return llvm::createStringError(
3835 std::errc::illegal_byte_sequence,
3836 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3837
3839 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3840 break;
3841
3842 case OBJC_CATEGORIES:
3843 F.ObjCCategories.swap(Record);
3844 break;
3845
3847 // Later tables overwrite earlier ones.
3848 // FIXME: Modules will have trouble with this.
3849 CUDASpecialDeclRefs.clear();
3850 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3851 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
3852 break;
3853
3855 F.HeaderFileInfoTableData = Blob.data();
3857 if (Record[0]) {
3859 = HeaderFileInfoLookupTable::Create(
3860 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3861 (const unsigned char *)F.HeaderFileInfoTableData,
3862 HeaderFileInfoTrait(*this, F,
3863 &PP.getHeaderSearchInfo(),
3864 Blob.data() + Record[2]));
3865
3866 PP.getHeaderSearchInfo().SetExternalSource(this);
3867 if (!PP.getHeaderSearchInfo().getExternalLookup())
3868 PP.getHeaderSearchInfo().SetExternalLookup(this);
3869 }
3870 break;
3871
3872 case FP_PRAGMA_OPTIONS:
3873 // Later tables overwrite earlier ones.
3874 FPPragmaOptions.swap(Record);
3875 break;
3876
3877 case OPENCL_EXTENSIONS:
3878 for (unsigned I = 0, E = Record.size(); I != E; ) {
3879 auto Name = ReadString(Record, I);
3880 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3881 OptInfo.Supported = Record[I++] != 0;
3882 OptInfo.Enabled = Record[I++] != 0;
3883 OptInfo.WithPragma = Record[I++] != 0;
3884 OptInfo.Avail = Record[I++];
3885 OptInfo.Core = Record[I++];
3886 OptInfo.Opt = Record[I++];
3887 }
3888 break;
3889
3891 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3892 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
3893 break;
3894
3895 case KNOWN_NAMESPACES:
3896 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3897 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
3898 break;
3899
3900 case UNDEFINED_BUT_USED:
3901 if (Record.size() % 2 != 0)
3902 return llvm::createStringError(std::errc::illegal_byte_sequence,
3903 "invalid undefined-but-used record");
3904 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3905 UndefinedButUsed.push_back(
3906 {ReadDeclID(F, Record, I),
3907 ReadSourceLocation(F, Record, I).getRawEncoding()});
3908 }
3909 break;
3910
3912 for (unsigned I = 0, N = Record.size(); I != N;) {
3913 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
3914 const uint64_t Count = Record[I++];
3915 DelayedDeleteExprs.push_back(Count);
3916 for (uint64_t C = 0; C < Count; ++C) {
3917 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3918 bool IsArrayForm = Record[I++] == 1;
3919 DelayedDeleteExprs.push_back(IsArrayForm);
3920 }
3921 }
3922 break;
3923
3924 case IMPORTED_MODULES:
3925 if (!F.isModule()) {
3926 // If we aren't loading a module (which has its own exports), make
3927 // all of the imported modules visible.
3928 // FIXME: Deal with macros-only imports.
3929 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3930 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3931 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3932 if (GlobalID) {
3933 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3934 if (DeserializationListener)
3935 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3936 }
3937 }
3938 }
3939 break;
3940
3941 case MACRO_OFFSET: {
3942 if (F.LocalNumMacros != 0)
3943 return llvm::createStringError(
3944 std::errc::illegal_byte_sequence,
3945 "duplicate MACRO_OFFSET record in AST file");
3946 F.MacroOffsets = (const uint32_t *)Blob.data();
3947 F.LocalNumMacros = Record[0];
3948 unsigned LocalBaseMacroID = Record[1];
3950 F.BaseMacroID = getTotalNumMacros();
3951
3952 if (F.LocalNumMacros > 0) {
3953 // Introduce the global -> local mapping for macros within this module.
3954 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3955
3956 // Introduce the local -> global mapping for macros within this module.
3958 std::make_pair(LocalBaseMacroID,
3959 F.BaseMacroID - LocalBaseMacroID));
3960
3961 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3962 }
3963 break;
3964 }
3965
3967 LateParsedTemplates.emplace_back(
3968 std::piecewise_construct, std::forward_as_tuple(&F),
3969 std::forward_as_tuple(Record.begin(), Record.end()));
3970 break;
3971
3973 if (Record.size() != 1)
3974 return llvm::createStringError(std::errc::illegal_byte_sequence,
3975 "invalid pragma optimize record");
3976 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3977 break;
3978
3980 if (Record.size() != 1)
3981 return llvm::createStringError(std::errc::illegal_byte_sequence,
3982 "invalid pragma ms_struct record");
3983 PragmaMSStructState = Record[0];
3984 break;
3985
3987 if (Record.size() != 2)
3988 return llvm::createStringError(
3989 std::errc::illegal_byte_sequence,
3990 "invalid pragma pointers to members record");
3991 PragmaMSPointersToMembersState = Record[0];
3992 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3993 break;
3994
3996 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3997 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
3998 break;
3999
4001 if (Record.size() != 1)
4002 return llvm::createStringError(std::errc::illegal_byte_sequence,
4003 "invalid cuda pragma options record");
4004 ForceHostDeviceDepth = Record[0];
4005 break;
4006
4008 if (Record.size() < 3)
4009 return llvm::createStringError(std::errc::illegal_byte_sequence,
4010 "invalid pragma pack record");
4011 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4012 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4013 unsigned NumStackEntries = Record[2];
4014 unsigned Idx = 3;
4015 // Reset the stack when importing a new module.
4016 PragmaAlignPackStack.clear();
4017 for (unsigned I = 0; I < NumStackEntries; ++I) {
4018 PragmaAlignPackStackEntry Entry;
4019 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4020 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4021 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4022 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4023 Entry.SlotLabel = PragmaAlignPackStrings.back();
4024 PragmaAlignPackStack.push_back(Entry);
4025 }
4026 break;
4027 }
4028
4030 if (Record.size() < 3)
4031 return llvm::createStringError(std::errc::illegal_byte_sequence,
4032 "invalid pragma float control record");
4033 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4034 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4035 unsigned NumStackEntries = Record[2];
4036 unsigned Idx = 3;
4037 // Reset the stack when importing a new module.
4038 FpPragmaStack.clear();
4039 for (unsigned I = 0; I < NumStackEntries; ++I) {
4040 FpPragmaStackEntry Entry;
4041 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4042 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4043 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4044 FpPragmaStrings.push_back(ReadString(Record, Idx));
4045 Entry.SlotLabel = FpPragmaStrings.back();
4046 FpPragmaStack.push_back(Entry);
4047 }
4048 break;
4049 }
4050
4052 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4053 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4054 break;
4055 }
4056 }
4057}
4058
4059void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4060 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4061
4062 // Additional remapping information.
4063 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4064 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4065 F.ModuleOffsetMap = StringRef();
4066
4068 RemapBuilder MacroRemap(F.MacroRemap);
4069 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4070 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4071 RemapBuilder SelectorRemap(F.SelectorRemap);
4072
4073 auto &ImportedModuleVector = F.TransitiveImports;
4074 assert(ImportedModuleVector.empty());
4075
4076 while (Data < DataEnd) {
4077 // FIXME: Looking up dependency modules by filename is horrible. Let's
4078 // start fixing this with prebuilt, explicit and implicit modules and see
4079 // how it goes...
4080 using namespace llvm::support;
4081 ModuleKind Kind = static_cast<ModuleKind>(
4082 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4083 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4084 StringRef Name = StringRef((const char*)Data, Len);
4085 Data += Len;
4088 ? ModuleMgr.lookupByModuleName(Name)
4089 : ModuleMgr.lookupByFileName(Name));
4090 if (!OM) {
4091 std::string Msg = "refers to unknown module, cannot find ";
4092 Msg.append(std::string(Name));
4093 Error(Msg);
4094 return;
4095 }
4096
4097 ImportedModuleVector.push_back(OM);
4098
4099 uint32_t MacroIDOffset =
4100 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4101 uint32_t PreprocessedEntityIDOffset =
4102 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4103 uint32_t SubmoduleIDOffset =
4104 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4105 uint32_t SelectorIDOffset =
4106 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4107
4108 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4109 RemapBuilder &Remap) {
4110 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4111 if (Offset != None)
4112 Remap.insert(std::make_pair(Offset,
4113 static_cast<int>(BaseOffset - Offset)));
4114 };
4115
4116 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4117 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4118 PreprocessedEntityRemap);
4119 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4120 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4121 }
4122}
4123
4125ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4126 const ModuleFile *ImportedBy,
4127 unsigned ClientLoadCapabilities) {
4128 unsigned Idx = 0;
4129 F.ModuleMapPath = ReadPath(F, Record, Idx);
4130
4131 // Try to resolve ModuleName in the current header search context and
4132 // verify that it is found in the same module map file as we saved. If the
4133 // top-level AST file is a main file, skip this check because there is no
4134 // usable header search context.
4135 assert(!F.ModuleName.empty() &&
4136 "MODULE_NAME should come before MODULE_MAP_FILE");
4137 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4138 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4139 // An implicitly-loaded module file should have its module listed in some
4140 // module map file that we've already loaded.
4141 Module *M =
4142 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4143 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4144 OptionalFileEntryRef ModMap =
4145 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4146 // Don't emit module relocation error if we have -fno-validate-pch
4147 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4149 !ModMap) {
4150 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4151 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4152 // This module was defined by an imported (explicit) module.
4153 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4154 << ASTFE->getName();
4155 } else {
4156 // This module was built with a different module map.
4157 Diag(diag::err_imported_module_not_found)
4158 << F.ModuleName << F.FileName
4159 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4160 << !ImportedBy;
4161 // In case it was imported by a PCH, there's a chance the user is
4162 // just missing to include the search path to the directory containing
4163 // the modulemap.
4164 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4165 Diag(diag::note_imported_by_pch_module_not_found)
4166 << llvm::sys::path::parent_path(F.ModuleMapPath);
4167 }
4168 }
4169 return OutOfDate;
4170 }
4171
4172 assert(M && M->Name == F.ModuleName && "found module with different name");
4173
4174 // Check the primary module map file.
4175 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4176 if (!StoredModMap || *StoredModMap != ModMap) {
4177 assert(ModMap && "found module is missing module map file");
4178 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4179 "top-level import should be verified");
4180 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4181 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4182 Diag(diag::err_imported_module_modmap_changed)
4183 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4184 << ModMap->getName() << F.ModuleMapPath << NotImported;
4185 return OutOfDate;
4186 }
4187
4188 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4189 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4190 // FIXME: we should use input files rather than storing names.
4191 std::string Filename = ReadPath(F, Record, Idx);
4192 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4193 if (!SF) {
4194 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4195 Error("could not find file '" + Filename +"' referenced by AST file");
4196 return OutOfDate;
4197 }
4198 AdditionalStoredMaps.insert(*SF);
4199 }
4200
4201 // Check any additional module map files (e.g. module.private.modulemap)
4202 // that are not in the pcm.
4203 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4204 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4205 // Remove files that match
4206 // Note: SmallPtrSet::erase is really remove
4207 if (!AdditionalStoredMaps.erase(ModMap)) {
4208 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4209 Diag(diag::err_module_different_modmap)
4210 << F.ModuleName << /*new*/0 << ModMap.getName();
4211 return OutOfDate;
4212 }
4213 }
4214 }
4215
4216 // Check any additional module map files that are in the pcm, but not
4217 // found in header search. Cases that match are already removed.
4218 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4219 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4220 Diag(diag::err_module_different_modmap)
4221 << F.ModuleName << /*not new*/1 << ModMap.getName();
4222 return OutOfDate;
4223 }
4224 }
4225
4226 if (Listener)
4227 Listener->ReadModuleMapFile(F.ModuleMapPath);
4228 return Success;
4229}
4230
4231/// Move the given method to the back of the global list of methods.
4233 // Find the entry for this selector in the method pool.
4235 S.ObjC().MethodPool.find(Method->getSelector());
4236 if (Known == S.ObjC().MethodPool.end())
4237 return;
4238
4239 // Retrieve the appropriate method list.
4240 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4241 : Known->second.second;
4242 bool Found = false;
4243 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4244 if (!Found) {
4245 if (List->getMethod() == Method) {
4246 Found = true;
4247 } else {
4248 // Keep searching.
4249 continue;
4250 }
4251 }
4252
4253 if (List->getNext())
4254 List->setMethod(List->getNext()->getMethod());
4255 else
4256 List->setMethod(Method);
4257 }
4258}
4259
4261 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4262 for (Decl *D : Names) {
4263 bool wasHidden = !D->isUnconditionallyVisible();
4265
4266 if (wasHidden && SemaObj) {
4267 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4268 moveMethodToBackOfGlobalList(*SemaObj, Method);
4269 }
4270 }
4271 }
4272}
4273
4275 Module::NameVisibilityKind NameVisibility,
4276 SourceLocation ImportLoc) {
4279 Stack.push_back(Mod);
4280 while (!Stack.empty()) {
4281 Mod = Stack.pop_back_val();
4282
4283 if (NameVisibility <= Mod->NameVisibility) {
4284 // This module already has this level of visibility (or greater), so
4285 // there is nothing more to do.
4286 continue;
4287 }
4288
4289 if (Mod->isUnimportable()) {
4290 // Modules that aren't importable cannot be made visible.
4291 continue;
4292 }
4293
4294 // Update the module's name visibility.
4295 Mod->NameVisibility = NameVisibility;
4296
4297 // If we've already deserialized any names from this module,
4298 // mark them as visible.
4299 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4300 if (Hidden != HiddenNamesMap.end()) {
4301 auto HiddenNames = std::move(*Hidden);
4302 HiddenNamesMap.erase(Hidden);
4303 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4304 assert(!HiddenNamesMap.contains(Mod) &&
4305 "making names visible added hidden names");
4306 }
4307
4308 // Push any exported modules onto the stack to be marked as visible.
4310 Mod->getExportedModules(Exports);
4312 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4313 Module *Exported = *I;
4314 if (Visited.insert(Exported).second)
4315 Stack.push_back(Exported);
4316 }
4317 }
4318}
4319
4320/// We've merged the definition \p MergedDef into the existing definition
4321/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4322/// visible.
4324 NamedDecl *MergedDef) {
4325 if (!Def->isUnconditionallyVisible()) {
4326 // If MergedDef is visible or becomes visible, make the definition visible.
4327 if (MergedDef->isUnconditionallyVisible())
4329 else {
4330 getContext().mergeDefinitionIntoModule(
4331 Def, MergedDef->getImportedOwningModule(),
4332 /*NotifyListeners*/ false);
4333 PendingMergedDefinitionsToDeduplicate.insert(Def);
4334 }
4335 }
4336}
4337
4339 if (GlobalIndex)
4340 return false;
4341
4342 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4343 !PP.getLangOpts().Modules)
4344 return true;
4345
4346 // Try to load the global index.
4347 TriedLoadingGlobalIndex = true;
4348 StringRef ModuleCachePath
4349 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4350 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4351 GlobalModuleIndex::readIndex(ModuleCachePath);
4352 if (llvm::Error Err = std::move(Result.second)) {
4353 assert(!Result.first);
4354 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4355 return true;
4356 }
4357
4358 GlobalIndex.reset(Result.first);
4359 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4360 return false;
4361}
4362
4364 return PP.getLangOpts().Modules && UseGlobalIndex &&
4365 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4366}
4367
4369 // Overwrite the timestamp file contents so that file's mtime changes.
4370 std::string TimestampFilename = MF.getTimestampFilename();
4371 std::error_code EC;
4372 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4373 llvm::sys::fs::OF_TextWithCRLF);
4374 if (EC)
4375 return;
4376 OS << "Timestamp file\n";
4377 OS.close();
4378 OS.clear_error(); // Avoid triggering a fatal error.
4379}
4380
4381/// Given a cursor at the start of an AST file, scan ahead and drop the
4382/// cursor into the start of the given block ID, returning false on success and
4383/// true on failure.
4384static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4385 while (true) {
4386 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4387 if (!MaybeEntry) {
4388 // FIXME this drops errors on the floor.
4389 consumeError(MaybeEntry.takeError());
4390 return true;
4391 }
4392 llvm::BitstreamEntry Entry = MaybeEntry.get();
4393
4394 switch (Entry.Kind) {
4395 case llvm::BitstreamEntry::Error:
4396 case llvm::BitstreamEntry::EndBlock:
4397 return true;
4398
4399 case llvm::BitstreamEntry::Record:
4400 // Ignore top-level records.
4401 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4402 break;
4403 else {
4404 // FIXME this drops errors on the floor.
4405 consumeError(Skipped.takeError());
4406 return true;
4407 }
4408
4409 case llvm::BitstreamEntry::SubBlock:
4410 if (Entry.ID == BlockID) {
4411 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4412 // FIXME this drops the error on the floor.
4413 consumeError(std::move(Err));
4414 return true;
4415 }
4416 // Found it!
4417 return false;
4418 }
4419
4420 if (llvm::Error Err = Cursor.SkipBlock()) {
4421 // FIXME this drops the error on the floor.
4422 consumeError(std::move(Err));
4423 return true;
4424 }
4425 }
4426 }
4427}
4428
4430 SourceLocation ImportLoc,
4431 unsigned ClientLoadCapabilities,
4432 ModuleFile **NewLoadedModuleFile) {
4433 llvm::TimeTraceScope scope("ReadAST", FileName);
4434
4435 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4437 CurrentDeserializingModuleKind, Type);
4438
4439 // Defer any pending actions until we get to the end of reading the AST file.
4440 Deserializing AnASTFile(this);
4441
4442 // Bump the generation number.
4443 unsigned PreviousGeneration = 0;
4444 if (ContextObj)
4445 PreviousGeneration = incrementGeneration(*ContextObj);
4446
4447 unsigned NumModules = ModuleMgr.size();
4449 if (ASTReadResult ReadResult =
4450 ReadASTCore(FileName, Type, ImportLoc,
4451 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4452 ClientLoadCapabilities)) {
4453 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4454
4455 // If we find that any modules are unusable, the global index is going
4456 // to be out-of-date. Just remove it.
4457 GlobalIndex.reset();
4458 ModuleMgr.setGlobalIndex(nullptr);
4459 return ReadResult;
4460 }
4461
4462 if (NewLoadedModuleFile && !Loaded.empty())
4463 *NewLoadedModuleFile = Loaded.back().Mod;
4464
4465 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4466 // remove modules from this point. Various fields are updated during reading
4467 // the AST block and removing the modules would result in dangling pointers.
4468 // They are generally only incidentally dereferenced, ie. a binary search
4469 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4470 // be dereferenced but it wouldn't actually be used.
4471
4472 // Load the AST blocks of all of the modules that we loaded. We can still
4473 // hit errors parsing the ASTs at this point.
4474 for (ImportedModule &M : Loaded) {
4475 ModuleFile &F = *M.Mod;
4476 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4477
4478 // Read the AST block.
4479 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4480 Error(std::move(Err));
4481 return Failure;
4482 }
4483
4484 // The AST block should always have a definition for the main module.
4485 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4486 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4487 return Failure;
4488 }
4489
4490 // Read the extension blocks.
4492 if (llvm::Error Err = ReadExtensionBlock(F)) {
4493 Error(std::move(Err));
4494 return Failure;
4495 }
4496 }
4497
4498 // Once read, set the ModuleFile bit base offset and update the size in
4499 // bits of all files we've seen.
4500 F.GlobalBitOffset = TotalModulesSizeInBits;
4501 TotalModulesSizeInBits += F.SizeInBits;
4502 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4503 }
4504
4505 // Preload source locations and interesting indentifiers.
4506 for (ImportedModule &M : Loaded) {
4507 ModuleFile &F = *M.Mod;
4508
4509 // Map the original source file ID into the ID space of the current
4510 // compilation.
4512 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4513
4514 for (auto Offset : F.PreloadIdentifierOffsets) {
4515 const unsigned char *Data = F.IdentifierTableData + Offset;
4516
4517 ASTIdentifierLookupTrait Trait(*this, F);
4518 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4519 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4520
4521 IdentifierInfo *II;
4522 if (!PP.getLangOpts().CPlusPlus) {
4523 // Identifiers present in both the module file and the importing
4524 // instance are marked out-of-date so that they can be deserialized
4525 // on next use via ASTReader::updateOutOfDateIdentifier().
4526 // Identifiers present in the module file but not in the importing
4527 // instance are ignored for now, preventing growth of the identifier
4528 // table. They will be deserialized on first use via ASTReader::get().
4529 auto It = PP.getIdentifierTable().find(Key);
4530 if (It == PP.getIdentifierTable().end())
4531 continue;
4532 II = It->second;
4533 } else {
4534 // With C++ modules, not many identifiers are considered interesting.
4535 // All identifiers in the module file can be placed into the identifier
4536 // table of the importing instance and marked as out-of-date. This makes
4537 // ASTReader::get() a no-op, and deserialization will take place on
4538 // first/next use via ASTReader::updateOutOfDateIdentifier().
4539 II = &PP.getIdentifierTable().getOwn(Key);
4540 }
4541
4542 II->setOutOfDate(true);
4543
4544 // Mark this identifier as being from an AST file so that we can track
4545 // whether we need to serialize it.
4546 markIdentifierFromAST(*this, *II);
4547
4548 // Associate the ID with the identifier so that the writer can reuse it.
4549 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4550 SetIdentifierInfo(ID, II);
4551 }
4552 }
4553
4554 // Builtins and library builtins have already been initialized. Mark all
4555 // identifiers as out-of-date, so that they are deserialized on first use.
4556 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4557 for (auto &Id : PP.getIdentifierTable())
4558 Id.second->setOutOfDate(true);
4559
4560 // Mark selectors as out of date.
4561 for (const auto &Sel : SelectorGeneration)
4562 SelectorOutOfDate[Sel.first] = true;
4563
4564 // Setup the import locations and notify the module manager that we've
4565 // committed to these module files.
4566 for (ImportedModule &M : Loaded) {
4567 ModuleFile &F = *M.Mod;
4568
4569 ModuleMgr.moduleFileAccepted(&F);
4570
4571 // Set the import location.
4572 F.DirectImportLoc = ImportLoc;
4573 // FIXME: We assume that locations from PCH / preamble do not need
4574 // any translation.
4575 if (!M.ImportedBy)
4576 F.ImportLoc = M.ImportLoc;
4577 else
4578 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4579 }
4580
4581 // Resolve any unresolved module exports.
4582 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4583 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4584 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4585 Module *ResolvedMod = getSubmodule(GlobalID);
4586
4587 switch (Unresolved.Kind) {
4588 case UnresolvedModuleRef::Conflict:
4589 if (ResolvedMod) {
4590 Module::Conflict Conflict;
4591 Conflict.Other = ResolvedMod;
4592 Conflict.Message = Unresolved.String.str();
4593 Unresolved.Mod->Conflicts.push_back(Conflict);
4594 }
4595 continue;
4596
4597 case UnresolvedModuleRef::Import:
4598 if (ResolvedMod)
4599 Unresolved.Mod->Imports.insert(ResolvedMod);
4600 continue;
4601
4602 case UnresolvedModuleRef::Affecting:
4603 if (ResolvedMod)
4604 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4605 continue;
4606
4607 case UnresolvedModuleRef::Export:
4608 if (ResolvedMod || Unresolved.IsWildcard)
4609 Unresolved.Mod->Exports.push_back(
4610 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4611 continue;
4612 }
4613 }
4614 UnresolvedModuleRefs.clear();
4615
4616 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4617 // Might be unnecessary as use declarations are only used to build the
4618 // module itself.
4619
4620 if (ContextObj)
4621 InitializeContext();
4622
4623 if (SemaObj)
4624 UpdateSema();
4625
4626 if (DeserializationListener)
4627 DeserializationListener->ReaderInitialized(this);
4628
4629 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4630 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4631 // If this AST file is a precompiled preamble, then set the
4632 // preamble file ID of the source manager to the file source file
4633 // from which the preamble was built.
4634 if (Type == MK_Preamble) {
4635 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4636 } else if (Type == MK_MainFile) {
4637 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4638 }
4639 }
4640
4641 // For any Objective-C class definitions we have already loaded, make sure
4642 // that we load any additional categories.
4643 if (ContextObj) {
4644 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4645 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4646 ObjCClassesLoaded[I], PreviousGeneration);
4647 }
4648 }
4649
4650 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4652 // Now we are certain that the module and all modules it depends on are
4653 // up-to-date. For implicitly-built module files, ensure the corresponding
4654 // timestamp files are up-to-date in this build session.
4655 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4656 ImportedModule &M = Loaded[I];
4657 if (M.Mod->Kind == MK_ImplicitModule &&
4658 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4659 updateModuleTimestamp(*M.Mod);
4660 }
4661 }
4662
4663 return Success;
4664}
4665
4666static ASTFileSignature readASTFileSignature(StringRef PCH);
4667
4668/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4669static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4670 // FIXME checking magic headers is done in other places such as
4671 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4672 // always done the same. Unify it all with a helper.
4673 if (!Stream.canSkipToPos(4))
4674 return llvm::createStringError(std::errc::illegal_byte_sequence,
4675 "file too small to contain AST file magic");
4676 for (unsigned C : {'C', 'P', 'C', 'H'})
4677 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4678 if (Res.get() != C)
4679 return llvm::createStringError(
4680 std::errc::illegal_byte_sequence,
4681 "file doesn't start with AST file magic");
4682 } else
4683 return Res.takeError();
4684 return llvm::Error::success();
4685}
4686
4688 switch (Kind) {
4689 case MK_PCH:
4690 return 0; // PCH
4691 case MK_ImplicitModule:
4692 case MK_ExplicitModule:
4693 case MK_PrebuiltModule:
4694 return 1; // module
4695 case MK_MainFile:
4696 case MK_Preamble:
4697 return 2; // main source file
4698 }
4699 llvm_unreachable("unknown module kind");
4700}
4701
4703ASTReader::ReadASTCore(StringRef FileName,
4705 SourceLocation ImportLoc,
4706 ModuleFile *ImportedBy,
4708 off_t ExpectedSize, time_t ExpectedModTime,
4709 ASTFileSignature ExpectedSignature,
4710 unsigned ClientLoadCapabilities) {
4711 ModuleFile *M;
4712 std::string ErrorStr;
4714 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4715 getGeneration(), ExpectedSize, ExpectedModTime,
4716 ExpectedSignature, readASTFileSignature,
4717 M, ErrorStr);
4718
4719 switch (AddResult) {
4721 Diag(diag::remark_module_import)
4722 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4723 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4724 return Success;
4725
4727 // Load module file below.
4728 break;
4729
4731 // The module file was missing; if the client can handle that, return
4732 // it.
4733 if (ClientLoadCapabilities & ARR_Missing)
4734 return Missing;
4735
4736 // Otherwise, return an error.
4737 Diag(diag::err_ast_file_not_found)
4738 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4739 << ErrorStr;
4740 return Failure;
4741
4743 // We couldn't load the module file because it is out-of-date. If the
4744 // client can handle out-of-date, return it.
4745 if (ClientLoadCapabilities & ARR_OutOfDate)
4746 return OutOfDate;
4747
4748 // Otherwise, return an error.
4749 Diag(diag::err_ast_file_out_of_date)
4750 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4751 << ErrorStr;
4752 return Failure;
4753 }
4754
4755 assert(M && "Missing module file");
4756
4757 bool ShouldFinalizePCM = false;
4758 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4759 auto &MC = getModuleManager().getModuleCache();
4760 if (ShouldFinalizePCM)
4761 MC.finalizePCM(FileName);
4762 else
4763 MC.tryToDropPCM(FileName);
4764 });
4765 ModuleFile &F = *M;
4766 BitstreamCursor &Stream = F.Stream;
4767 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4768 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4769
4770 // Sniff for the signature.
4771 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4772 Diag(diag::err_ast_file_invalid)
4773 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4774 return Failure;
4775 }
4776
4777 // This is used for compatibility with older PCH formats.
4778 bool HaveReadControlBlock = false;
4779 while (true) {
4780 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4781 if (!MaybeEntry) {
4782 Error(MaybeEntry.takeError());
4783 return Failure;
4784 }
4785 llvm::BitstreamEntry Entry = MaybeEntry.get();
4786
4787 switch (Entry.Kind) {
4788 case llvm::BitstreamEntry::Error:
4789 case llvm::BitstreamEntry::Record:
4790 case llvm::BitstreamEntry::EndBlock:
4791 Error("invalid record at top-level of AST file");
4792 return Failure;
4793
4794 case llvm::BitstreamEntry::SubBlock:
4795 break;
4796 }
4797
4798 switch (Entry.ID) {
4799 case CONTROL_BLOCK_ID:
4800 HaveReadControlBlock = true;
4801 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4802 case Success:
4803 // Check that we didn't try to load a non-module AST file as a module.
4804 //
4805 // FIXME: Should we also perform the converse check? Loading a module as
4806 // a PCH file sort of works, but it's a bit wonky.
4808 Type == MK_PrebuiltModule) &&
4809 F.ModuleName.empty()) {
4810 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4811 if (Result != OutOfDate ||
4812 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4813 Diag(diag::err_module_file_not_module) << FileName;
4814 return Result;
4815 }
4816 break;
4817
4818 case Failure: return Failure;
4819 case Missing: return Missing;
4820 case OutOfDate: return OutOfDate;
4821 case VersionMismatch: return VersionMismatch;
4822 case ConfigurationMismatch: return ConfigurationMismatch;
4823 case HadErrors: return HadErrors;
4824 }
4825 break;
4826
4827 case AST_BLOCK_ID:
4828 if (!HaveReadControlBlock) {
4829 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4830 Diag(diag::err_pch_version_too_old);
4831 return VersionMismatch;
4832 }
4833
4834 // Record that we've loaded this module.
4835 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4836 ShouldFinalizePCM = true;
4837 return Success;
4838
4839 default:
4840 if (llvm::Error Err = Stream.SkipBlock()) {
4841 Error(std::move(Err));
4842 return Failure;
4843 }
4844 break;
4845 }
4846 }
4847
4848 llvm_unreachable("unexpected break; expected return");
4849}
4850
4852ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4853 unsigned ClientLoadCapabilities) {
4854 const HeaderSearchOptions &HSOpts =
4855 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4856 bool AllowCompatibleConfigurationMismatch =
4858 bool DisableValidation = shouldDisableValidationForFile(F);
4859
4860 ASTReadResult Result = readUnhashedControlBlockImpl(
4861 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4862 Listener.get(),
4863 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4864
4865 // If F was directly imported by another module, it's implicitly validated by
4866 // the importing module.
4867 if (DisableValidation || WasImportedBy ||
4868 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4869 return Success;
4870
4871 if (Result == Failure) {
4872 Error("malformed block record in AST file");
4873 return Failure;
4874 }
4875
4876 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4877 // If this module has already been finalized in the ModuleCache, we're stuck
4878 // with it; we can only load a single version of each module.
4879 //
4880 // This can happen when a module is imported in two contexts: in one, as a
4881 // user module; in another, as a system module (due to an import from
4882 // another module marked with the [system] flag). It usually indicates a
4883 // bug in the module map: this module should also be marked with [system].
4884 //
4885 // If -Wno-system-headers (the default), and the first import is as a
4886 // system module, then validation will fail during the as-user import,
4887 // since -Werror flags won't have been validated. However, it's reasonable
4888 // to treat this consistently as a system module.
4889 //
4890 // If -Wsystem-headers, the PCM on disk was built with
4891 // -Wno-system-headers, and the first import is as a user module, then
4892 // validation will fail during the as-system import since the PCM on disk
4893 // doesn't guarantee that -Werror was respected. However, the -Werror
4894 // flags were checked during the initial as-user import.
4895 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4896 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4897 return Success;
4898 }
4899 }
4900
4901 return Result;
4902}
4903
4904ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4905 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4906 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4907 bool ValidateDiagnosticOptions) {
4908 // Initialize a stream.
4909 BitstreamCursor Stream(StreamData);
4910
4911 // Sniff for the signature.
4912 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4913 // FIXME this drops the error on the floor.
4914 consumeError(std::move(Err));
4915 return Failure;
4916 }
4917
4918 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4920 return Failure;
4921
4922 // Read all of the records in the options block.
4923 RecordData Record;
4924 ASTReadResult Result = Success;
4925 while (true) {
4926 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4927 if (!MaybeEntry) {
4928 // FIXME this drops the error on the floor.
4929 consumeError(MaybeEntry.takeError());
4930 return Failure;
4931 }
4932 llvm::BitstreamEntry Entry = MaybeEntry.get();
4933
4934 switch (Entry.Kind) {
4935 case llvm::BitstreamEntry::Error:
4936 case llvm::BitstreamEntry::SubBlock:
4937 return Failure;
4938
4939 case llvm::BitstreamEntry::EndBlock:
4940 return Result;
4941
4942 case llvm::BitstreamEntry::Record:
4943 // The interesting case.
4944 break;
4945 }
4946
4947 // Read and process a record.
4948 Record.clear();
4949 StringRef Blob;
4950 Expected<unsigned> MaybeRecordType =
4951 Stream.readRecord(Entry.ID, Record, &Blob);
4952 if (!MaybeRecordType) {
4953 // FIXME this drops the error.
4954 return Failure;
4955 }
4956 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4957 case SIGNATURE:
4958 if (F) {
4959 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
4961 "Dummy AST file signature not backpatched in ASTWriter.");
4962 }
4963 break;
4964 case AST_BLOCK_HASH:
4965 if (F) {
4966 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
4968 "Dummy AST block hash not backpatched in ASTWriter.");
4969 }
4970 break;
4971 case DIAGNOSTIC_OPTIONS: {
4972 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4973 if (Listener && ValidateDiagnosticOptions &&
4974 !AllowCompatibleConfigurationMismatch &&
4975 ParseDiagnosticOptions(Record, Complain, *Listener))
4976 Result = OutOfDate; // Don't return early. Read the signature.
4977 break;
4978 }
4979 case HEADER_SEARCH_PATHS: {
4980 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4981 if (Listener && !AllowCompatibleConfigurationMismatch &&
4982 ParseHeaderSearchPaths(Record, Complain, *Listener))
4983 Result = ConfigurationMismatch;
4984 break;
4985 }
4987 if (!F)
4988 break;
4989 if (F->PragmaDiagMappings.empty())
4990 F->PragmaDiagMappings.swap(Record);
4991 else
4992 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4993 Record.begin(), Record.end());
4994 break;
4996 if (F)
4997 F->SearchPathUsage = ReadBitVector(Record, Blob);
4998 break;
4999 case VFS_USAGE:
5000 if (F)
5001 F->VFSUsage = ReadBitVector(Record, Blob);
5002 break;
5003 }
5004 }
5005}
5006
5007/// Parse a record and blob containing module file extension metadata.
5010 StringRef Blob,
5011 ModuleFileExtensionMetadata &Metadata) {
5012 if (Record.size() < 4) return true;
5013
5014 Metadata.MajorVersion = Record[0];
5015 Metadata.MinorVersion = Record[1];
5016
5017 unsigned BlockNameLen = Record[2];
5018 unsigned UserInfoLen = Record[3];
5019
5020 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5021
5022 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5023 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5024 Blob.data() + BlockNameLen + UserInfoLen);
5025 return false;
5026}
5027
5028llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5029 BitstreamCursor &Stream = F.Stream;
5030
5031 RecordData Record;
5032 while (true) {
5033 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5034 if (!MaybeEntry)
5035 return MaybeEntry.takeError();
5036 llvm::BitstreamEntry Entry = MaybeEntry.get();
5037
5038 switch (Entry.Kind) {
5039 case llvm::BitstreamEntry::SubBlock:
5040 if (llvm::Error Err = Stream.SkipBlock())
5041 return Err;
5042 continue;
5043 case llvm::BitstreamEntry::EndBlock:
5044 return llvm::Error::success();
5045 case llvm::BitstreamEntry::Error:
5046 return llvm::createStringError(std::errc::illegal_byte_sequence,
5047 "malformed block record in AST file");
5048 case llvm::BitstreamEntry::Record:
5049 break;
5050 }
5051
5052 Record.clear();
5053 StringRef Blob;
5054 Expected<unsigned> MaybeRecCode =
5055 Stream.readRecord(Entry.ID, Record, &Blob);
5056 if (!MaybeRecCode)
5057 return MaybeRecCode.takeError();
5058 switch (MaybeRecCode.get()) {
5059 case EXTENSION_METADATA: {
5061 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5062 return llvm::createStringError(
5063 std::errc::illegal_byte_sequence,
5064 "malformed EXTENSION_METADATA in AST file");
5065
5066 // Find a module file extension with this block name.
5067 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5068 if (Known == ModuleFileExtensions.end()) break;
5069
5070 // Form a reader.
5071 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5072 F, Stream)) {
5073 F.ExtensionReaders.push_back(std::move(Reader));
5074 }
5075
5076 break;
5077 }
5078 }
5079 }
5080
5081 return llvm::Error::success();
5082}
5083
5085 assert(ContextObj && "no context to initialize");
5086 ASTContext &Context = *ContextObj;
5087
5088 // If there's a listener, notify them that we "read" the translation unit.
5089 if (DeserializationListener)
5090 DeserializationListener->DeclRead(
5092 Context.getTranslationUnitDecl());
5093
5094 // FIXME: Find a better way to deal with collisions between these
5095 // built-in types. Right now, we just ignore the problem.
5096
5097 // Load the special types.
5098 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5099 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5100 if (!Context.CFConstantStringTypeDecl)
5101 Context.setCFConstantStringType(GetType(String));
5102 }
5103
5104 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5105 QualType FileType = GetType(File);
5106 if (FileType.isNull()) {
5107 Error("FILE type is NULL");
5108 return;
5109 }
5110
5111 if (!Context.FILEDecl) {
5112 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5113 Context.setFILEDecl(Typedef->getDecl());
5114 else {
5115 const TagType *Tag = FileType->getAs<TagType>();
5116 if (!Tag) {
5117 Error("Invalid FILE type in AST file");
5118 return;
5119 }
5120 Context.setFILEDecl(Tag->getDecl());
5121 }
5122 }
5123 }
5124
5125 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5126 QualType Jmp_bufType = GetType(Jmp_buf);
5127 if (Jmp_bufType.isNull()) {
5128 Error("jmp_buf type is NULL");
5129 return;
5130 }
5131
5132 if (!Context.jmp_bufDecl) {
5133 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5134 Context.setjmp_bufDecl(Typedef->getDecl());
5135 else {
5136 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5137 if (!Tag) {
5138 Error("Invalid jmp_buf type in AST file");
5139 return;
5140 }
5141 Context.setjmp_bufDecl(Tag->getDecl());
5142 }
5143 }
5144 }
5145
5146 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5147 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5148 if (Sigjmp_bufType.isNull()) {
5149 Error("sigjmp_buf type is NULL");
5150 return;
5151 }
5152
5153 if (!Context.sigjmp_bufDecl) {
5154 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5155 Context.setsigjmp_bufDecl(Typedef->getDecl());
5156 else {
5157 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5158 assert(Tag && "Invalid sigjmp_buf type in AST file");
5159 Context.setsigjmp_bufDecl(Tag->getDecl());
5160 }
5161 }
5162 }
5163
5164 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5165 if (Context.ObjCIdRedefinitionType.isNull())
5166 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5167 }
5168
5169 if (TypeID ObjCClassRedef =
5171 if (Context.ObjCClassRedefinitionType.isNull())
5172 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5173 }
5174
5175 if (TypeID ObjCSelRedef =
5176 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5177 if (Context.ObjCSelRedefinitionType.isNull())
5178 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5179 }
5180
5181 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5182 QualType Ucontext_tType = GetType(Ucontext_t);
5183 if (Ucontext_tType.isNull()) {
5184 Error("ucontext_t type is NULL");
5185 return;
5186 }
5187
5188 if (!Context.ucontext_tDecl) {
5189 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5190 Context.setucontext_tDecl(Typedef->getDecl());
5191 else {
5192 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5193 assert(Tag && "Invalid ucontext_t type in AST file");
5194 Context.setucontext_tDecl(Tag->getDecl());
5195 }
5196 }
5197 }
5198 }
5199
5200 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5201
5202 // If there were any CUDA special declarations, deserialize them.
5203 if (!CUDASpecialDeclRefs.empty()) {
5204 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5206 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5207 }
5208
5209 // Re-export any modules that were imported by a non-module AST file.
5210 // FIXME: This does not make macro-only imports visible again.
5211 for (auto &Import : PendingImportedModules) {
5212 if (Module *Imported = getSubmodule(Import.ID)) {
5213 makeModuleVisible(Imported, Module::AllVisible,
5214 /*ImportLoc=*/Import.ImportLoc);
5215 if (Import.ImportLoc.isValid())
5216 PP.makeModuleVisible(Imported, Import.ImportLoc);
5217 // This updates visibility for Preprocessor only. For Sema, which can be
5218 // nullptr here, we do the same later, in UpdateSema().
5219 }
5220 }
5221
5222 // Hand off these modules to Sema.
5223 PendingImportedModulesSema.append(PendingImportedModules);
5224 PendingImportedModules.clear();
5225}
5226
5228 // Nothing to do for now.
5229}
5230
5231/// Reads and return the signature record from \p PCH's control block, or
5232/// else returns 0.
5234 BitstreamCursor Stream(PCH);
5235 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5236 // FIXME this drops the error on the floor.
5237 consumeError(std::move(Err));
5238 return ASTFileSignature();
5239 }
5240
5241 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5243 return ASTFileSignature();
5244
5245 // Scan for SIGNATURE inside the diagnostic options block.
5247 while (true) {
5249 Stream.advanceSkippingSubblocks();
5250 if (!MaybeEntry) {
5251 // FIXME this drops the error on the floor.
5252 consumeError(MaybeEntry.takeError());
5253 return ASTFileSignature();
5254 }
5255 llvm::BitstreamEntry Entry = MaybeEntry.get();
5256
5257 if (Entry.Kind != llvm::BitstreamEntry::Record)
5258 return ASTFileSignature();
5259
5260 Record.clear();
5261 StringRef Blob;
5262 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5263 if (!MaybeRecord) {
5264 // FIXME this drops the error on the floor.
5265 consumeError(MaybeRecord.takeError());
5266 return ASTFileSignature();
5267 }
5268 if (SIGNATURE == MaybeRecord.get()) {
5269 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5270 assert(Signature != ASTFileSignature::createDummy() &&
5271 "Dummy AST file signature not backpatched in ASTWriter.");
5272 return Signature;
5273 }
5274 }
5275}
5276
5277/// Retrieve the name of the original source file name
5278/// directly from the AST file, without actually loading the AST
5279/// file.
5281 const std::string &ASTFileName, FileManager &FileMgr,
5282 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5283 // Open the AST file.
5284 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5285 /*RequiresNullTerminator=*/false);
5286 if (!Buffer) {
5287 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5288 << ASTFileName << Buffer.getError().message();
5289 return std::string();
5290 }
5291
5292 // Initialize the stream
5293 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5294
5295 // Sniff for the signature.
5296 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5297 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5298 return std::string();
5299 }
5300
5301 // Scan for the CONTROL_BLOCK_ID block.
5302 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5303 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5304 return std::string();
5305 }
5306
5307 // Scan for ORIGINAL_FILE inside the control block.
5309 while (true) {
5311 Stream.advanceSkippingSubblocks();
5312 if (!MaybeEntry) {
5313 // FIXME this drops errors on the floor.
5314 consumeError(MaybeEntry.takeError());
5315 return std::string();
5316 }
5317 llvm::BitstreamEntry Entry = MaybeEntry.get();
5318
5319 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5320 return std::string();
5321
5322 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5323 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5324 return std::string();
5325 }
5326
5327 Record.clear();
5328 StringRef Blob;
5329 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5330 if (!MaybeRecord) {
5331 // FIXME this drops the errors on the floor.
5332 consumeError(MaybeRecord.takeError());
5333 return std::string();
5334 }
5335 if (ORIGINAL_FILE == MaybeRecord.get())
5336 return Blob.str();
5337 }
5338}
5339
5340namespace {
5341
5342 class SimplePCHValidator : public ASTReaderListener {
5343 const LangOptions &ExistingLangOpts;
5344 const TargetOptions &ExistingTargetOpts;
5345 const PreprocessorOptions &ExistingPPOpts;
5346 std::string ExistingModuleCachePath;
5347 FileManager &FileMgr;
5348 bool StrictOptionMatches;
5349
5350 public:
5351 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5352 const TargetOptions &ExistingTargetOpts,
5353 const PreprocessorOptions &ExistingPPOpts,
5354 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5355 bool StrictOptionMatches)
5356 : ExistingLangOpts(ExistingLangOpts),
5357 ExistingTargetOpts(ExistingTargetOpts),
5358 ExistingPPOpts(ExistingPPOpts),
5359 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5360 StrictOptionMatches(StrictOptionMatches) {}
5361
5362 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5363 bool AllowCompatibleDifferences) override {
5364 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5365 AllowCompatibleDifferences);
5366 }
5367
5368 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5369 bool AllowCompatibleDifferences) override {
5370 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5371 AllowCompatibleDifferences);
5372 }
5373
5374 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5375 StringRef SpecificModuleCachePath,
5376 bool Complain) override {
5377 return checkModuleCachePath(
5378 FileMgr.getVirtualFileSystem(), SpecificModuleCachePath,
5379 ExistingModuleCachePath, nullptr, ExistingLangOpts, ExistingPPOpts);
5380 }
5381
5382 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5383 bool ReadMacros, bool Complain,
5384 std::string &SuggestedPredefines) override {
5386 PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,
5387 SuggestedPredefines, ExistingLangOpts,
5388 StrictOptionMatches ? OptionValidateStrictMatches
5390 }
5391 };
5392
5393} // namespace
5394
5396 StringRef Filename, FileManager &FileMgr,
5397 const InMemoryModuleCache &ModuleCache,
5398 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5399 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5400 unsigned ClientLoadCapabilities) {
5401 // Open the AST file.
5402 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5403 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5404 if (!Buffer) {
5405 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5406 // read again later, but we do not have the context here to determine if it
5407 // is safe to change the result of InMemoryModuleCache::getPCMState().
5408
5409 // FIXME: This allows use of the VFS; we do not allow use of the
5410 // VFS when actually loading a module.
5411 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5412 if (!BufferOrErr)
5413 return true;
5414 OwnedBuffer = std::move(*BufferOrErr);
5415 Buffer = OwnedBuffer.get();
5416 }
5417
5418 // Initialize the stream
5419 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5420 BitstreamCursor Stream(Bytes);
5421
5422 // Sniff for the signature.
5423 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5424 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5425 return true;
5426 }
5427
5428 // Scan for the CONTROL_BLOCK_ID block.
5430 return true;
5431
5432 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5433 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5434 bool NeedsImports = Listener.needsImportVisitation();
5435 BitstreamCursor InputFilesCursor;
5436 uint64_t InputFilesOffsetBase = 0;
5437
5439 std::string ModuleDir;
5440 bool DoneWithControlBlock = false;
5441 while (!DoneWithControlBlock) {
5442 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5443 if (!MaybeEntry) {
5444 // FIXME this drops the error on the floor.
5445 consumeError(MaybeEntry.takeError());
5446 return true;
5447 }
5448 llvm::BitstreamEntry Entry = MaybeEntry.get();
5449
5450 switch (Entry.Kind) {
5451 case llvm::BitstreamEntry::SubBlock: {
5452 switch (Entry.ID) {
5453 case OPTIONS_BLOCK_ID: {
5454 std::string IgnoredSuggestedPredefines;
5455 if (ReadOptionsBlock(Stream, ClientLoadCapabilities,
5456 /*AllowCompatibleConfigurationMismatch*/ false,
5457 Listener, IgnoredSuggestedPredefines) != Success)
5458 return true;
5459 break;
5460 }
5461
5463 InputFilesCursor = Stream;
5464 if (llvm::Error Err = Stream.SkipBlock()) {
5465 // FIXME this drops the error on the floor.
5466 consumeError(std::move(Err));
5467 return true;
5468 }
5469 if (NeedsInputFiles &&
5470 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5471 return true;
5472 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5473 break;
5474
5475 default:
5476 if (llvm::Error Err = Stream.SkipBlock()) {
5477 // FIXME this drops the error on the floor.
5478 consumeError(std::move(Err));
5479 return true;
5480 }
5481 break;
5482 }
5483
5484 continue;
5485 }
5486
5487 case llvm::BitstreamEntry::EndBlock:
5488 DoneWithControlBlock = true;
5489 break;
5490
5491 case llvm::BitstreamEntry::Error:
5492 return true;
5493
5494 case llvm::BitstreamEntry::Record:
5495 break;
5496 }
5497
5498 if (DoneWithControlBlock) break;
5499
5500 Record.clear();
5501 StringRef Blob;
5502 Expected<unsigned> MaybeRecCode =
5503 Stream.readRecord(Entry.ID, Record, &Blob);
5504 if (!MaybeRecCode) {
5505 // FIXME this drops the error.
5506 return Failure;
5507 }
5508 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5509 case METADATA:
5510 if (Record[0] != VERSION_MAJOR)
5511 return true;
5512 if (Listener.ReadFullVersionInformation(Blob))
5513 return true;
5514 break;
5515 case MODULE_NAME:
5516 Listener.ReadModuleName(Blob);
5517 break;
5518 case MODULE_DIRECTORY:
5519 ModuleDir = std::string(Blob);
5520 break;
5521 case MODULE_MAP_FILE: {
5522 unsigned Idx = 0;
5523 auto Path = ReadString(Record, Idx);
5524 ResolveImportedPath(Path, ModuleDir);
5525 Listener.ReadModuleMapFile(Path);
5526 break;
5527 }
5528 case INPUT_FILE_OFFSETS: {
5529 if (!NeedsInputFiles)
5530 break;
5531
5532 unsigned NumInputFiles = Record[0];
5533 unsigned NumUserFiles = Record[1];
5534 const llvm::support::unaligned_uint64_t *InputFileOffs =
5535 (const llvm::support::unaligned_uint64_t *)Blob.data();
5536 for (unsigned I = 0; I != NumInputFiles; ++I) {
5537 // Go find this input file.
5538 bool isSystemFile = I >= NumUserFiles;
5539
5540 if (isSystemFile && !NeedsSystemInputFiles)
5541 break; // the rest are system input files
5542
5543 BitstreamCursor &Cursor = InputFilesCursor;
5544 SavedStreamPosition SavedPosition(Cursor);
5545 if (llvm::Error Err =
5546 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5547 // FIXME this drops errors on the floor.
5548 consumeError(std::move(Err));
5549 }
5550
5551 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5552 if (!MaybeCode) {
5553 // FIXME this drops errors on the floor.
5554 consumeError(MaybeCode.takeError());
5555 }
5556 unsigned Code = MaybeCode.get();
5557
5559 StringRef Blob;
5560 bool shouldContinue = false;
5561 Expected<unsigned> MaybeRecordType =
5562 Cursor.readRecord(Code, Record, &Blob);
5563 if (!MaybeRecordType) {
5564 // FIXME this drops errors on the floor.
5565 consumeError(MaybeRecordType.takeError());
5566 }
5567 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5568 case INPUT_FILE_HASH:
5569 break;
5570 case INPUT_FILE:
5571 bool Overridden = static_cast<bool>(Record[3]);
5572 std::string Filename = std::string(Blob);
5573 ResolveImportedPath(Filename, ModuleDir);
5574 shouldContinue = Listener.visitInputFile(
5575 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5576 break;
5577 }
5578 if (!shouldContinue)
5579 break;
5580 }
5581 break;
5582 }
5583
5584 case IMPORTS: {
5585 if (!NeedsImports)
5586 break;
5587
5588 unsigned Idx = 0, N = Record.size();
5589 while (Idx < N) {
5590 // Read information about the AST file.
5591
5592 // Skip Kind
5593 Idx++;
5594 bool IsStandardCXXModule = Record[Idx++];
5595
5596 // Skip ImportLoc
5597 Idx++;
5598
5599 // In C++20 Modules, we don't record the path to imported
5600 // modules in the BMI files.
5601 if (IsStandardCXXModule) {
5602 std::string ModuleName = ReadString(Record, Idx);
5603 Listener.visitImport(ModuleName, /*Filename=*/"");
5604 continue;
5605 }
5606
5607 // Skip Size, ModTime and Signature
5608 Idx += 1 + 1 + ASTFileSignature::size;
5609 std::string ModuleName = ReadString(Record, Idx);
5610 std::string Filename = ReadString(Record, Idx);
5611 ResolveImportedPath(Filename, ModuleDir);
5612 Listener.visitImport(ModuleName, Filename);
5613 }
5614 break;
5615 }
5616
5617 default:
5618 // No other validation to perform.
5619 break;
5620 }
5621 }
5622
5623 // Look for module file extension blocks, if requested.
5624 if (FindModuleFileExtensions) {
5625 BitstreamCursor SavedStream = Stream;
5626 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5627 bool DoneWithExtensionBlock = false;
5628 while (!DoneWithExtensionBlock) {
5629 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5630 if (!MaybeEntry) {
5631 // FIXME this drops the error.
5632 return true;
5633 }
5634 llvm::BitstreamEntry Entry = MaybeEntry.get();
5635
5636 switch (Entry.Kind) {
5637 case llvm::BitstreamEntry::SubBlock:
5638 if (llvm::Error Err = Stream.SkipBlock()) {
5639 // FIXME this drops the error on the floor.
5640 consumeError(std::move(Err));
5641 return true;
5642 }
5643 continue;
5644
5645 case llvm::BitstreamEntry::EndBlock:
5646 DoneWithExtensionBlock = true;
5647 continue;
5648
5649 case llvm::BitstreamEntry::Error:
5650 return true;
5651
5652 case llvm::BitstreamEntry::Record:
5653 break;
5654 }
5655
5656 Record.clear();
5657 StringRef Blob;
5658 Expected<unsigned> MaybeRecCode =
5659 Stream.readRecord(Entry.ID, Record, &Blob);
5660 if (!MaybeRecCode) {
5661 // FIXME this drops the error.
5662 return true;
5663 }
5664 switch (MaybeRecCode.get()) {
5665 case EXTENSION_METADATA: {
5667 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5668 return true;
5669
5670 Listener.readModuleFileExtension(Metadata);
5671 break;
5672 }
5673 }
5674 }
5675 }
5676 Stream = SavedStream;
5677 }
5678
5679 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5680 if (readUnhashedControlBlockImpl(
5681 nullptr, Bytes, ClientLoadCapabilities,
5682 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5683 ValidateDiagnosticOptions) != Success)
5684 return true;
5685
5686 return false;
5687}
5688
5690 const InMemoryModuleCache &ModuleCache,
5691 const PCHContainerReader &PCHContainerRdr,
5692 const LangOptions &LangOpts,
5693 const TargetOptions &TargetOpts,
5694 const PreprocessorOptions &PPOpts,
5695 StringRef ExistingModuleCachePath,
5696 bool RequireStrictOptionMatches) {
5697 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5698 ExistingModuleCachePath, FileMgr,
5699 RequireStrictOptionMatches);
5700 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5701 PCHContainerRdr,
5702 /*FindModuleFileExtensions=*/false, validator,
5703 /*ValidateDiagnosticOptions=*/true);
5704}
5705
5706llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5707 unsigned ClientLoadCapabilities) {
5708 // Enter the submodule block.
5709 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5710 return Err;
5711
5712 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5713 bool First = true;
5714 Module *CurrentModule = nullptr;
5715 RecordData Record;
5716 while (true) {
5718 F.Stream.advanceSkippingSubblocks();
5719 if (!MaybeEntry)
5720 return MaybeEntry.takeError();
5721 llvm::BitstreamEntry Entry = MaybeEntry.get();
5722
5723 switch (Entry.Kind) {
5724 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5725 case llvm::BitstreamEntry::Error:
5726 return llvm::createStringError(std::errc::illegal_byte_sequence,
5727 "malformed block record in AST file");
5728 case llvm::BitstreamEntry::EndBlock:
5729 return llvm::Error::success();
5730 case llvm::BitstreamEntry::Record:
5731 // The interesting case.
5732 break;
5733 }
5734
5735 // Read a record.
5736 StringRef Blob;
5737 Record.clear();
5738 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5739 if (!MaybeKind)
5740 return MaybeKind.takeError();
5741 unsigned Kind = MaybeKind.get();
5742
5743 if ((Kind == SUBMODULE_METADATA) != First)
5744 return llvm::createStringError(
5745 std::errc::illegal_byte_sequence,
5746 "submodule metadata record should be at beginning of block");
5747 First = false;
5748
5749 // Submodule information is only valid if we have a current module.
5750 // FIXME: Should we error on these cases?
5751 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5752 Kind != SUBMODULE_DEFINITION)
5753 continue;
5754
5755 switch (Kind) {
5756 default: // Default behavior: ignore.
5757 break;
5758
5759 case SUBMODULE_DEFINITION: {
5760 if (Record.size() < 13)
5761 return llvm::createStringError(std::errc::illegal_byte_sequence,
5762 "malformed module definition");
5763
5764 StringRef Name = Blob;
5765 unsigned Idx = 0;
5766 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5767 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5769 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5770 bool IsFramework = Record[Idx++];
5771 bool IsExplicit = Record[Idx++];
5772 bool IsSystem = Record[Idx++];
5773 bool IsExternC = Record[Idx++];
5774 bool InferSubmodules = Record[Idx++];
5775 bool InferExplicitSubmodules = Record[Idx++];
5776 bool InferExportWildcard = Record[Idx++];
5777 bool ConfigMacrosExhaustive = Record[Idx++];
5778 bool ModuleMapIsPrivate = Record[Idx++];
5779 bool NamedModuleHasInit = Record[Idx++];
5780
5781 Module *ParentModule = nullptr;
5782 if (Parent)
5783 ParentModule = getSubmodule(Parent);
5784
5785 // Retrieve this (sub)module from the module map, creating it if
5786 // necessary.
5787 CurrentModule =
5788 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5789 .first;
5790
5791 // FIXME: Call ModMap.setInferredModuleAllowedBy()
5792
5793 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5794 if (GlobalIndex >= SubmodulesLoaded.size() ||
5795 SubmodulesLoaded[GlobalIndex])
5796 return llvm::createStringError(std::errc::invalid_argument,
5797 "too many submodules");
5798
5799 if (!ParentModule) {
5800 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5801 // Don't emit module relocation error if we have -fno-validate-pch
5802 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5804 CurFile != F.File) {
5805 auto ConflictError =
5806 PartialDiagnostic(diag::err_module_file_conflict,
5807 ContextObj->DiagAllocator)
5808 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5809 << F.File.getName();
5810 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5811 }
5812 }
5813
5814 F.DidReadTopLevelSubmodule = true;
5815 CurrentModule->setASTFile(F.File);
5816 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5817 }
5818
5819 CurrentModule->Kind = Kind;
5820 CurrentModule->DefinitionLoc = DefinitionLoc;
5821 CurrentModule->Signature = F.Signature;
5822 CurrentModule->IsFromModuleFile = true;
5823 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5824 CurrentModule->IsExternC = IsExternC;
5825 CurrentModule->InferSubmodules = InferSubmodules;
5826 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5827 CurrentModule->InferExportWildcard = InferExportWildcard;
5828 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5829 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5830 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5831 if (DeserializationListener)
5832 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5833
5834 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5835
5836 // Clear out data that will be replaced by what is in the module file.
5837 CurrentModule->LinkLibraries.clear();
5838 CurrentModule->ConfigMacros.clear();
5839 CurrentModule->UnresolvedConflicts.clear();
5840 CurrentModule->Conflicts.clear();
5841
5842 // The module is available unless it's missing a requirement; relevant
5843 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5844 // Missing headers that were present when the module was built do not
5845 // make it unavailable -- if we got this far, this must be an explicitly
5846 // imported module file.
5847 CurrentModule->Requirements.clear();
5848 CurrentModule->MissingHeaders.clear();
5849 CurrentModule->IsUnimportable =
5850 ParentModule && ParentModule->IsUnimportable;
5851 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5852 break;
5853 }
5854
5856 // FIXME: This doesn't work for framework modules as `Filename` is the
5857 // name as written in the module file and does not include
5858 // `Headers/`, so this path will never exist.
5859 std::string Filename = std::string(Blob);
5860 ResolveImportedPath(F, Filename);
5861 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5862 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5863 // FIXME: NameAsWritten
5864 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5865 }
5866 // Note that it's too late at this point to return out of date if the
5867 // name from the PCM doesn't match up with the one in the module map,
5868 // but also quite unlikely since we will have already checked the
5869 // modification time and size of the module map file itself.
5870 }
5871 break;
5872 }
5873
5874 case SUBMODULE_HEADER:
5877 // We lazily associate headers with their modules via the HeaderInfo table.
5878 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5879 // of complete filenames or remove it entirely.
5880 break;
5881
5884 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5885 // them here.
5886 break;
5887
5888 case SUBMODULE_TOPHEADER: {
5889 std::string HeaderName(Blob);
5890 ResolveImportedPath(F, HeaderName);
5891 CurrentModule->addTopHeaderFilename(HeaderName);
5892 break;
5893 }
5894
5896 // See comments in SUBMODULE_UMBRELLA_HEADER
5897 std::string Dirname = std::string(Blob);
5898 ResolveImportedPath(F, Dirname);
5899 if (auto Umbrella =
5900 PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5901 if (!CurrentModule->getUmbrellaDirAsWritten()) {
5902 // FIXME: NameAsWritten
5903 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5904 }
5905 }
5906 break;
5907 }
5908
5909 case SUBMODULE_METADATA: {
5910 F.BaseSubmoduleID = getTotalNumSubmodules();
5912 unsigned LocalBaseSubmoduleID = Record[1];
5913 if (F.LocalNumSubmodules > 0) {
5914 // Introduce the global -> local mapping for submodules within this
5915 // module.
5916 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5917
5918 // Introduce the local -> global mapping for submodules within this
5919 // module.
5921 std::make_pair(LocalBaseSubmoduleID,
5922 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5923
5924 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5925 }
5926 break;
5927 }
5928
5929 case SUBMODULE_IMPORTS:
5930 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5931 UnresolvedModuleRef Unresolved;
5932 Unresolved.File = &F;
5933 Unresolved.Mod = CurrentModule;
5934 Unresolved.ID = Record[Idx];
5935 Unresolved.Kind = UnresolvedModuleRef::Import;
5936 Unresolved.IsWildcard = false;
5937 UnresolvedModuleRefs.push_back(Unresolved);
5938 }
5939 break;
5940
5942 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5943 UnresolvedModuleRef Unresolved;
5944 Unresolved.File = &F;
5945 Unresolved.Mod = CurrentModule;
5946 Unresolved.ID = Record[Idx];
5947 Unresolved.Kind = UnresolvedModuleRef::Affecting;
5948 Unresolved.IsWildcard = false;
5949 UnresolvedModuleRefs.push_back(Unresolved);
5950 }
5951 break;
5952
5953 case SUBMODULE_EXPORTS:
5954 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5955 UnresolvedModuleRef Unresolved;
5956 Unresolved.File = &F;
5957 Unresolved.Mod = CurrentModule;
5958 Unresolved.ID = Record[Idx];
5959 Unresolved.Kind = UnresolvedModuleRef::Export;
5960 Unresolved.IsWildcard = Record[Idx + 1];
5961 UnresolvedModuleRefs.push_back(Unresolved);
5962 }
5963
5964 // Once we've loaded the set of exports, there's no reason to keep
5965 // the parsed, unresolved exports around.
5966 CurrentModule->UnresolvedExports.clear();
5967 break;
5968
5969 case SUBMODULE_REQUIRES:
5970 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5971 PP.getTargetInfo());
5972 break;
5973
5975 ModMap.resolveLinkAsDependencies(CurrentModule);
5976 CurrentModule->LinkLibraries.push_back(
5977 Module::LinkLibrary(std::string(Blob), Record[0]));
5978 break;
5979
5981 CurrentModule->ConfigMacros.push_back(Blob.str());
5982 break;
5983
5984 case SUBMODULE_CONFLICT: {
5985 UnresolvedModuleRef Unresolved;
5986 Unresolved.File = &F;
5987 Unresolved.Mod = CurrentModule;
5988 Unresolved.ID = Record[0];
5989 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5990 Unresolved.IsWildcard = false;
5991 Unresolved.String = Blob;
5992 UnresolvedModuleRefs.push_back(Unresolved);
5993 break;
5994 }
5995
5997 if (!ContextObj)
5998 break;
6000 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6001 Inits.push_back(ReadDeclID(F, Record, I));
6002 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6003 break;
6004 }
6005
6007 CurrentModule->ExportAsModule = Blob.str();
6008 ModMap.addLinkAsDependency(CurrentModule);
6009 break;
6010 }
6011 }
6012}
6013
6014/// Parse the record that corresponds to a LangOptions data
6015/// structure.
6016///
6017/// This routine parses the language options from the AST file and then gives
6018/// them to the AST listener if one is set.
6019///
6020/// \returns true if the listener deems the file unacceptable, false otherwise.
6021bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6022 bool Complain,
6023 ASTReaderListener &Listener,
6024 bool AllowCompatibleDifferences) {
6025 LangOptions LangOpts;
6026 unsigned Idx = 0;
6027#define LANGOPT(Name, Bits, Default, Description) \
6028 LangOpts.Name = Record[Idx++];
6029#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6030 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6031#include "clang/Basic/LangOptions.def"
6032#define SANITIZER(NAME, ID) \
6033 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6034#include "clang/Basic/Sanitizers.def"
6035
6036 for (unsigned N = Record[Idx++]; N; --N)
6037 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6038
6039 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6040 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6041 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6042
6043 LangOpts.CurrentModule = ReadString(Record, Idx);
6044
6045 // Comment options.
6046 for (unsigned N = Record[Idx++]; N; --N) {
6047 LangOpts.CommentOpts.BlockCommandNames.push_back(
6048 ReadString(Record, Idx));
6049 }
6050 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6051
6052 // OpenMP offloading options.
6053 for (unsigned N = Record[Idx++]; N; --N) {
6054 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6055 }
6056
6057 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6058
6059 return Listener.ReadLanguageOptions(LangOpts, Complain,
6060 AllowCompatibleDifferences);
6061}
6062
6063bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
6064 ASTReaderListener &Listener,
6065 bool AllowCompatibleDifferences) {
6066 unsigned Idx = 0;
6067 TargetOptions TargetOpts;
6068 TargetOpts.Triple = ReadString(Record, Idx);
6069 TargetOpts.CPU = ReadString(Record, Idx);
6070 TargetOpts.TuneCPU = ReadString(Record, Idx);
6071 TargetOpts.ABI = ReadString(Record, Idx);
6072 for (unsigned N = Record[Idx++]; N; --N) {
6073 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6074 }
6075 for (unsigned N = Record[Idx++]; N; --N) {
6076 TargetOpts.Features.push_back(ReadString(Record, Idx));
6077 }
6078
6079 return Listener.ReadTargetOptions(TargetOpts, Complain,
6080 AllowCompatibleDifferences);
6081}
6082
6083bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
6084 ASTReaderListener &Listener) {
6086 unsigned Idx = 0;
6087#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6088#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6089 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6090#include "clang/Basic/DiagnosticOptions.def"
6091
6092 for (unsigned N = Record[Idx++]; N; --N)
6093 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6094 for (unsigned N = Record[Idx++]; N; --N)
6095 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6096
6097 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
6098}
6099
6100bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6101 ASTReaderListener &Listener) {
6102 FileSystemOptions FSOpts;
6103 unsigned Idx = 0;
6104 FSOpts.WorkingDir = ReadString(Record, Idx);
6105 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6106}
6107
6108bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6109 bool Complain,
6110 ASTReaderListener &Listener) {
6111 HeaderSearchOptions HSOpts;
6112 unsigned Idx = 0;
6113 HSOpts.Sysroot = ReadString(Record, Idx);
6114
6115 HSOpts.ResourceDir = ReadString(Record, Idx);
6116 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6117 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6118 HSOpts.DisableModuleHash = Record[Idx++];
6119 HSOpts.ImplicitModuleMaps = Record[Idx++];
6120 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6121 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6122 HSOpts.UseBuiltinIncludes = Record[Idx++];
6123 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6124 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6125 HSOpts.UseLibcxx = Record[Idx++];
6126 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6127
6128 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
6129 Complain);
6130}
6131
6132bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6133 ASTReaderListener &Listener) {
6134 HeaderSearchOptions HSOpts;
6135 unsigned Idx = 0;
6136
6137 // Include entries.
6138 for (unsigned N = Record[Idx++]; N; --N) {
6139 std::string Path = ReadString(Record, Idx);
6141 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6142 bool IsFramework = Record[Idx++];
6143 bool IgnoreSysRoot = Record[Idx++];
6144 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6145 IgnoreSysRoot);
6146 }
6147
6148 // System header prefixes.
6149 for (unsigned N = Record[Idx++]; N; --N) {
6150 std::string Prefix = ReadString(Record, Idx);
6151 bool IsSystemHeader = Record[Idx++];
6152 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6153 }
6154
6155 // VFS overlay files.
6156 for (unsigned N = Record[Idx++]; N; --N) {
6157 std::string VFSOverlayFile = ReadString(Record, Idx);
6158 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6159 }
6160
6161 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6162}
6163
6164bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6165 bool Complain,
6166 ASTReaderListener &Listener,
6167 std::string &SuggestedPredefines) {
6168 PreprocessorOptions PPOpts;
6169 unsigned Idx = 0;
6170
6171 // Macro definitions/undefs
6172 bool ReadMacros = Record[Idx++];
6173 if (ReadMacros) {
6174 for (unsigned N = Record[Idx++]; N; --N) {
6175 std::string Macro = ReadString(Record, Idx);
6176 bool IsUndef = Record[Idx++];
6177 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6178 }
6179 }
6180
6181 // Includes
6182 for (unsigned N = Record[Idx++]; N; --N) {
6183 PPOpts.Includes.push_back(ReadString(Record, Idx));
6184 }
6185
6186 // Macro Includes
6187 for (unsigned N = Record[Idx++]; N; --N) {
6188 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6189 }
6190
6191 PPOpts.UsePredefines = Record[Idx++];
6192 PPOpts.DetailedRecord = Record[Idx++];
6193 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6195 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6196 SuggestedPredefines.clear();
6197 return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
6198 SuggestedPredefines);
6199}
6200
6201std::pair<ModuleFile *, unsigned>
6202ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6203 GlobalPreprocessedEntityMapType::iterator
6204 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6205 assert(I != GlobalPreprocessedEntityMap.end() &&
6206 "Corrupted global preprocessed entity map");
6207 ModuleFile *M = I->second;
6208 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6209 return std::make_pair(M, LocalIndex);
6210}
6211
6212llvm::iterator_range<PreprocessingRecord::iterator>
6213ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6214 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6215 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6217
6218 return llvm::make_range(PreprocessingRecord::iterator(),
6220}
6221
6222bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6223 unsigned int ClientLoadCapabilities) {
6224 return ClientLoadCapabilities & ARR_OutOfDate &&
6225 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6226}
6227
6228llvm::iterator_range<ASTReader::ModuleDeclIterator>
6230 return llvm::make_range(
6231 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6232 ModuleDeclIterator(this, &Mod,
6234}
6235
6237 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6238 assert(I != GlobalSkippedRangeMap.end() &&
6239 "Corrupted global skipped range map");
6240 ModuleFile *M = I->second;
6241 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6242 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6243 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6244 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6245 ReadSourceLocation(*M, RawRange.getEnd()));
6246 assert(Range.isValid());
6247 return Range;
6248}
6249
6251 PreprocessedEntityID PPID = Index+1;
6252 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6253 ModuleFile &M = *PPInfo.first;
6254 unsigned LocalIndex = PPInfo.second;
6255 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6256
6257 if (!PP.getPreprocessingRecord()) {
6258 Error("no preprocessing record");
6259 return nullptr;
6260 }
6261
6263 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6264 M.MacroOffsetsBase + PPOffs.getOffset())) {
6265 Error(std::move(Err));
6266 return nullptr;
6267 }
6268
6270 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6271 if (!MaybeEntry) {
6272 Error(MaybeEntry.takeError());
6273 return nullptr;
6274 }
6275 llvm::BitstreamEntry Entry = MaybeEntry.get();
6276
6277 if (Entry.Kind != llvm::BitstreamEntry::Record)
6278 return nullptr;
6279
6280 // Read the record.
6281 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6282 ReadSourceLocation(M, PPOffs.getEnd()));
6283 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6284 StringRef Blob;
6286 Expected<unsigned> MaybeRecType =
6287 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6288 if (!MaybeRecType) {
6289 Error(MaybeRecType.takeError());
6290 return nullptr;
6291 }
6292 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6293 case PPD_MACRO_EXPANSION: {
6294 bool isBuiltin = Record[0];
6295 IdentifierInfo *Name = nullptr;
6296 MacroDefinitionRecord *Def = nullptr;
6297 if (isBuiltin)
6298 Name = getLocalIdentifier(M, Record[1]);
6299 else {
6300 PreprocessedEntityID GlobalID =
6301 getGlobalPreprocessedEntityID(M, Record[1]);
6302 Def = cast<MacroDefinitionRecord>(
6303 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6304 }
6305
6306 MacroExpansion *ME;
6307 if (isBuiltin)
6308 ME = new (PPRec) MacroExpansion(Name, Range);
6309 else
6310 ME = new (PPRec) MacroExpansion(Def, Range);
6311
6312 return ME;
6313 }
6314
6315 case PPD_MACRO_DEFINITION: {
6316 // Decode the identifier info and then check again; if the macro is
6317 // still defined and associated with the identifier,
6318 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6319 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6320
6321 if (DeserializationListener)
6322 DeserializationListener->MacroDefinitionRead(PPID, MD);
6323
6324 return MD;
6325 }
6326
6328 const char *FullFileNameStart = Blob.data() + Record[0];
6329 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6331 if (!FullFileName.empty())
6332 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6333
6334 // FIXME: Stable encoding
6336 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6338 = new (PPRec) InclusionDirective(PPRec, Kind,
6339 StringRef(Blob.data(), Record[0]),
6340 Record[1], Record[3],
6341 File,
6342 Range);
6343 return ID;
6344 }
6345 }
6346
6347 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6348}
6349
6350/// Find the next module that contains entities and return the ID
6351/// of the first entry.
6352///
6353/// \param SLocMapI points at a chunk of a module that contains no
6354/// preprocessed entities or the entities it contains are not the ones we are
6355/// looking for.
6356PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6357 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6358 ++SLocMapI;
6359 for (GlobalSLocOffsetMapType::const_iterator
6360 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6361 ModuleFile &M = *SLocMapI->second;
6363 return M.BasePreprocessedEntityID;
6364 }
6365
6366 return getTotalNumPreprocessedEntities();
6367}
6368
6369namespace {
6370
6371struct PPEntityComp {
6372 const ASTReader &Reader;
6373 ModuleFile &M;
6374
6375 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6376
6377 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6378 SourceLocation LHS = getLoc(L);
6379 SourceLocation RHS = getLoc(R);
6380 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6381 }
6382
6383 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6384 SourceLocation LHS = getLoc(L);
6385 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6386 }
6387
6388 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6389 SourceLocation RHS = getLoc(R);
6390 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6391 }
6392
6393 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6394 return Reader.ReadSourceLocation(M, PPE.getBegin());
6395 }
6396};
6397
6398} // namespace
6399
6400PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6401 bool EndsAfter) const {
6402 if (SourceMgr.isLocalSourceLocation(Loc))
6403 return getTotalNumPreprocessedEntities();
6404
6405 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6406 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6407 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6408 "Corrupted global sloc offset map");
6409
6410 if (SLocMapI->second->NumPreprocessedEntities == 0)
6411 return findNextPreprocessedEntity(SLocMapI);
6412
6413 ModuleFile &M = *SLocMapI->second;
6414
6415 using pp_iterator = const PPEntityOffset *;
6416
6417 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6418 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6419
6420 size_t Count = M.NumPreprocessedEntities;
6421 size_t Half;
6422 pp_iterator First = pp_begin;
6423 pp_iterator PPI;
6424
6425 if (EndsAfter) {
6426 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6427 PPEntityComp(*this, M));
6428 } else {
6429 // Do a binary search manually instead of using std::lower_bound because
6430 // The end locations of entities may be unordered (when a macro expansion
6431 // is inside another macro argument), but for this case it is not important
6432 // whether we get the first macro expansion or its containing macro.
6433 while (Count > 0) {
6434 Half = Count / 2;
6435 PPI = First;
6436 std::advance(PPI, Half);
6437 if (SourceMgr.isBeforeInTranslationUnit(
6438 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6439 First = PPI;
6440 ++First;
6441 Count = Count - Half - 1;
6442 } else
6443 Count = Half;
6444 }
6445 }
6446
6447 if (PPI == pp_end)
6448 return findNextPreprocessedEntity(SLocMapI);
6449
6450 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6451}
6452
6453/// Returns a pair of [Begin, End) indices of preallocated
6454/// preprocessed entities that \arg Range encompasses.
6455std::pair<unsigned, unsigned>
6457 if (Range.isInvalid())
6458 return std::make_pair(0,0);
6459 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6460
6461 PreprocessedEntityID BeginID =
6462 findPreprocessedEntity(Range.getBegin(), false);
6463 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6464 return std::make_pair(BeginID, EndID);
6465}
6466
6467/// Optionally returns true or false if the preallocated preprocessed
6468/// entity with index \arg Index came from file \arg FID.
6469std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6470 FileID FID) {
6471 if (FID.isInvalid())
6472 return false;
6473
6474 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6475 ModuleFile &M = *PPInfo.first;
6476 unsigned LocalIndex = PPInfo.second;
6477 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6478
6479 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6480 if (Loc.isInvalid())
6481 return false;
6482
6483 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6484 return true;
6485 else
6486 return false;
6487}
6488
6489namespace {
6490
6491 /// Visitor used to search for information about a header file.
6492 class HeaderFileInfoVisitor {
6493 FileEntryRef FE;
6494 std::optional<HeaderFileInfo> HFI;
6495
6496 public:
6497 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6498
6499 bool operator()(ModuleFile &M) {
6502 if (!Table)
6503 return false;
6504
6505 // Look in the on-disk hash table for an entry for this file name.
6506 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6507 if (Pos == Table->end())
6508 return false;
6509
6510 HFI = *Pos;
6511 return true;
6512 }
6513
6514 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6515 };
6516
6517} // namespace
6518
6520 HeaderFileInfoVisitor Visitor(FE);
6521 ModuleMgr.visit(Visitor);
6522 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6523 return *HFI;
6524
6525 return HeaderFileInfo();
6526}
6527
6529 using DiagState = DiagnosticsEngine::DiagState;
6531
6532 for (ModuleFile &F : ModuleMgr) {
6533 unsigned Idx = 0;
6534 auto &Record = F.PragmaDiagMappings;
6535 if (Record.empty())
6536 continue;
6537
6538 DiagStates.clear();
6539
6540 auto ReadDiagState = [&](const DiagState &BasedOn,
6541 bool IncludeNonPragmaStates) {
6542 unsigned BackrefID = Record[Idx++];
6543 if (BackrefID != 0)
6544 return DiagStates[BackrefID - 1];
6545
6546 // A new DiagState was created here.
6547 Diag.DiagStates.push_back(BasedOn);
6548 DiagState *NewState = &Diag.DiagStates.back();
6549 DiagStates.push_back(NewState);
6550 unsigned Size = Record[Idx++];
6551 assert(Idx + Size * 2 <= Record.size() &&
6552 "Invalid data, not enough diag/map pairs");
6553 while (Size--) {
6554 unsigned DiagID = Record[Idx++];
6555 DiagnosticMapping NewMapping =
6557 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6558 continue;
6559
6560 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6561
6562 // If this mapping was specified as a warning but the severity was
6563 // upgraded due to diagnostic settings, simulate the current diagnostic
6564 // settings (and use a warning).
6565 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6567 NewMapping.setUpgradedFromWarning(false);
6568 }
6569
6570 Mapping = NewMapping;
6571 }
6572 return NewState;
6573 };
6574
6575 // Read the first state.
6576 DiagState *FirstState;
6577 if (F.Kind == MK_ImplicitModule) {
6578 // Implicitly-built modules are reused with different diagnostic
6579 // settings. Use the initial diagnostic state from Diag to simulate this
6580 // compilation's diagnostic settings.
6581 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6582 DiagStates.push_back(FirstState);
6583
6584 // Skip the initial diagnostic state from the serialized module.
6585 assert(Record[1] == 0 &&
6586 "Invalid data, unexpected backref in initial state");
6587 Idx = 3 + Record[2] * 2;
6588 assert(Idx < Record.size() &&
6589 "Invalid data, not enough state change pairs in initial state");
6590 } else if (F.isModule()) {
6591 // For an explicit module, preserve the flags from the module build
6592 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6593 // -Wblah flags.
6594 unsigned Flags = Record[Idx++];
6595 DiagState Initial;
6596 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6597 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6598 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6599 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6600 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6601 Initial.ExtBehavior = (diag::Severity)Flags;
6602 FirstState = ReadDiagState(Initial, true);
6603
6604 assert(F.OriginalSourceFileID.isValid());
6605
6606 // Set up the root buffer of the module to start with the initial
6607 // diagnostic state of the module itself, to cover files that contain no
6608 // explicit transitions (for which we did not serialize anything).
6609 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6610 .StateTransitions.push_back({FirstState, 0});
6611 } else {
6612 // For prefix ASTs, start with whatever the user configured on the
6613 // command line.
6614 Idx++; // Skip flags.
6615 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6616 }
6617
6618 // Read the state transitions.
6619 unsigned NumLocations = Record[Idx++];
6620 while (NumLocations--) {
6621 assert(Idx < Record.size() &&
6622 "Invalid data, missing pragma diagnostic states");
6623 FileID FID = ReadFileID(F, Record, Idx);
6624 assert(FID.isValid() && "invalid FileID for transition");
6625 unsigned Transitions = Record[Idx++];
6626
6627 // Note that we don't need to set up Parent/ParentOffset here, because
6628 // we won't be changing the diagnostic state within imported FileIDs
6629 // (other than perhaps appending to the main source file, which has no
6630 // parent).
6631 auto &F = Diag.DiagStatesByLoc.Files[FID];
6632 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6633 for (unsigned I = 0; I != Transitions; ++I) {
6634 unsigned Offset = Record[Idx++];
6635 auto *State = ReadDiagState(*FirstState, false);
6636 F.StateTransitions.push_back({State, Offset});
6637 }
6638 }
6639
6640 // Read the final state.
6641 assert(Idx < Record.size() &&
6642 "Invalid data, missing final pragma diagnostic state");
6643 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6644 auto *CurState = ReadDiagState(*FirstState, false);
6645
6646 if (!F.isModule()) {
6647 Diag.DiagStatesByLoc.CurDiagState = CurState;
6648 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6649
6650 // Preserve the property that the imaginary root file describes the
6651 // current state.
6652 FileID NullFile;
6653 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6654 if (T.empty())
6655 T.push_back({CurState, 0});
6656 else
6657 T[0].State = CurState;
6658 }
6659
6660 // Don't try to read these mappings again.
6661 Record.clear();
6662 }
6663}
6664
6665/// Get the correct cursor and offset for loading a type.
6666ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
6667 auto [M, Index] = translateTypeIDToIndex(ID);
6668 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
6670}
6671
6672static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6673 switch (code) {
6674#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6675 case TYPE_##CODE_ID: return Type::CLASS_ID;
6676#include "clang/Serialization/TypeBitCodes.def"
6677 default:
6678 return std::nullopt;
6679 }
6680}
6681
6682/// Read and return the type with the given index..
6683///
6684/// The index is the type ID, shifted and minus the number of predefs. This
6685/// routine actually reads the record corresponding to the type at the given
6686/// location. It is a helper routine for GetType, which deals with reading type
6687/// IDs.
6688QualType ASTReader::readTypeRecord(TypeID ID) {
6689 assert(ContextObj && "reading type with no AST context");
6690 ASTContext &Context = *ContextObj;
6691 RecordLocation Loc = TypeCursorForIndex(ID);
6692 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6693
6694 // Keep track of where we are in the stream, then jump back there
6695 // after reading this type.
6696 SavedStreamPosition SavedPosition(DeclsCursor);
6697
6698 ReadingKindTracker ReadingKind(Read_Type, *this);
6699
6700 // Note that we are loading a type record.
6701 Deserializing AType(this);
6702
6703 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6704 Error(std::move(Err));
6705 return QualType();
6706 }
6707 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6708 if (!RawCode) {
6709 Error(RawCode.takeError());
6710 return QualType();
6711 }
6712
6713 ASTRecordReader Record(*this, *Loc.F);
6714 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6715 if (!Code) {
6716 Error(Code.takeError());
6717 return QualType();
6718 }
6719 if (Code.get() == TYPE_EXT_QUAL) {
6720 QualType baseType = Record.readQualType();
6721 Qualifiers quals = Record.readQualifiers();
6722 return Context.getQualifiedType(baseType, quals);
6723 }
6724
6725 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6726 if (!maybeClass) {
6727 Error("Unexpected code for type");
6728 return QualType();
6729 }
6730
6732 return TypeReader.read(*maybeClass);
6733}
6734
6735namespace clang {
6736
6737class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6739
6740 ASTRecordReader &Reader;
6741 LocSeq *Seq;
6742
6743 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6744 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6745
6746 TypeSourceInfo *GetTypeSourceInfo() {
6747 return Reader.readTypeSourceInfo();
6748 }
6749
6750 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6751 return Reader.readNestedNameSpecifierLoc();
6752 }
6753
6754 Attr *ReadAttr() {
6755 return Reader.readAttr();
6756 }
6757
6758public:
6760 : Reader(Reader), Seq(Seq) {}
6761
6762 // We want compile-time assurance that we've enumerated all of
6763 // these, so unfortunately we have to declare them first, then
6764 // define them out-of-line.
6765#define ABSTRACT_TYPELOC(CLASS, PARENT)
6766#define TYPELOC(CLASS, PARENT) \
6767 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6768#include "clang/AST/TypeLocNodes.def"
6769
6770 void VisitFunctionTypeLoc(FunctionTypeLoc);
6771 void VisitArrayTypeLoc(ArrayTypeLoc);
6772};
6773
6774} // namespace clang
6775
6776void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6777 // nothing to do
6778}
6779
6780void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6781 TL.setBuiltinLoc(readSourceLocation());
6782 if (TL.needsExtraLocalData()) {
6783 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6784 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6785 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6786 TL.setModeAttr(Reader.readInt());
6787 }
6788}
6789
6790void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6791 TL.setNameLoc(readSourceLocation());
6792}
6793
6794void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6795 TL.setStarLoc(readSourceLocation());
6796}
6797
6798void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6799 // nothing to do
6800}
6801
6802void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6803 // nothing to do
6804}
6805
6806void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6807 // nothing to do
6808}
6809
6810void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6811 TL.setExpansionLoc(readSourceLocation());
6812}
6813
6814void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6815 TL.setCaretLoc(readSourceLocation());
6816}
6817
6818void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6819 TL.setAmpLoc(readSourceLocation());
6820}
6821
6822void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6823 TL.setAmpAmpLoc(readSourceLocation());
6824}
6825
6826void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6827 TL.setStarLoc(readSourceLocation());
6828 TL.setClassTInfo(GetTypeSourceInfo());
6829}
6830
6832 TL.setLBracketLoc(readSourceLocation());
6833 TL.setRBracketLoc(readSourceLocation());
6834 if (Reader.readBool())
6835 TL.setSizeExpr(Reader.readExpr());
6836 else
6837 TL.setSizeExpr(nullptr);
6838}
6839
6840void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6841 VisitArrayTypeLoc(TL);
6842}
6843
6844void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6845 VisitArrayTypeLoc(TL);
6846}
6847
6848void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6849 VisitArrayTypeLoc(TL);
6850}
6851
6852void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6854 VisitArrayTypeLoc(TL);
6855}
6856
6857void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6859
6860 TL.setAttrNameLoc(readSourceLocation());
6861 TL.setAttrOperandParensRange(readSourceRange());
6862 TL.setAttrExprOperand(Reader.readExpr());
6863}
6864
6865void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6867 TL.setNameLoc(readSourceLocation());
6868}
6869
6870void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6871 TL.setNameLoc(readSourceLocation());
6872}
6873
6874void TypeLocReader::VisitDependentVectorTypeLoc(
6876 TL.setNameLoc(readSourceLocation());
6877}
6878
6879void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6880 TL.setNameLoc(readSourceLocation());
6881}
6882
6883void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6884 TL.setAttrNameLoc(readSourceLocation());
6885 TL.setAttrOperandParensRange(readSourceRange());
6886 TL.setAttrRowOperand(Reader.readExpr());
6887 TL.setAttrColumnOperand(Reader.readExpr());
6888}
6889
6890void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6892 TL.setAttrNameLoc(readSourceLocation());
6893 TL.setAttrOperandParensRange(readSourceRange());
6894 TL.setAttrRowOperand(Reader.readExpr());
6895 TL.setAttrColumnOperand(Reader.readExpr());
6896}
6897
6899 TL.setLocalRangeBegin(readSourceLocation());
6900 TL.setLParenLoc(readSourceLocation());
6901 TL.setRParenLoc(readSourceLocation());
6902 TL.setExceptionSpecRange(readSourceRange());
6903 TL.setLocalRangeEnd(readSourceLocation());
6904 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6905 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6906 }
6907}
6908
6909void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6910 VisitFunctionTypeLoc(TL);
6911}
6912
6913void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6914 VisitFunctionTypeLoc(TL);
6915}
6916
6917void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6918 TL.setNameLoc(readSourceLocation());
6919}
6920
6921void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6922 TL.setNameLoc(readSourceLocation());
6923}
6924
6925void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6926 TL.setNameLoc(readSourceLocation());
6927}
6928
6929void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6930 TL.setTypeofLoc(readSourceLocation());
6931 TL.setLParenLoc(readSourceLocation());
6932 TL.setRParenLoc(readSourceLocation());
6933}
6934
6935void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6936 TL.setTypeofLoc(readSourceLocation());
6937 TL.setLParenLoc(readSourceLocation());
6938 TL.setRParenLoc(readSourceLocation());
6939 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6940}
6941
6942void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6943 TL.setDecltypeLoc(readSourceLocation());
6944 TL.setRParenLoc(readSourceLocation());
6945}
6946
6947void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6948 TL.setEllipsisLoc(readSourceLocation());
6949}
6950
6951void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6952 TL.setKWLoc(readSourceLocation());
6953 TL.setLParenLoc(readSourceLocation());
6954 TL.setRParenLoc(readSourceLocation());
6955 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6956}
6957
6959 auto NNS = readNestedNameSpecifierLoc();
6960 auto TemplateKWLoc = readSourceLocation();
6961 auto ConceptNameLoc = readDeclarationNameInfo();
6962 auto FoundDecl = readDeclAs<NamedDecl>();
6963 auto NamedConcept = readDeclAs<ConceptDecl>();
6964 auto *CR = ConceptReference::Create(
6965 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
6966 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
6967 return CR;
6968}
6969
6970void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6971 TL.setNameLoc(readSourceLocation());
6972 if (Reader.readBool())
6973 TL.setConceptReference(Reader.readConceptReference());
6974 if (Reader.readBool())
6975 TL.setRParenLoc(readSourceLocation());
6976}
6977
6978void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6980 TL.setTemplateNameLoc(readSourceLocation());
6981}
6982
6983void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6984 TL.setNameLoc(readSourceLocation());
6985}
6986
6987void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6988 TL.setNameLoc(readSourceLocation());
6989}
6990
6991void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6992 TL.setAttr(ReadAttr());
6993}
6994
6995void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6996 // Nothing to do
6997}
6998
6999void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7000 // Nothing to do.
7001}
7002
7003void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7004 TL.setNameLoc(readSourceLocation());
7005}
7006
7007void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7009 TL.setNameLoc(readSourceLocation());
7010}
7011
7012void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7014 TL.setNameLoc(readSourceLocation());
7015}
7016
7017void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7019 TL.setTemplateKeywordLoc(readSourceLocation());
7020 TL.setTemplateNameLoc(readSourceLocation());
7021 TL.setLAngleLoc(readSourceLocation());
7022 TL.setRAngleLoc(readSourceLocation());
7023 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7024 TL.setArgLocInfo(i,
7025 Reader.readTemplateArgumentLocInfo(
7026 TL.getTypePtr()->template_arguments()[i].getKind()));
7027}
7028
7029void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7030 TL.setLParenLoc(readSourceLocation());
7031 TL.setRParenLoc(readSourceLocation());
7032}
7033
7034void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7035 TL.setElaboratedKeywordLoc(readSourceLocation());
7036 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7037}
7038
7039void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7040 TL.setNameLoc(readSourceLocation());
7041}
7042
7043void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7044 TL.setElaboratedKeywordLoc(readSourceLocation());
7045 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7046 TL.setNameLoc(readSourceLocation());
7047}
7048
7049void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7051 TL.setElaboratedKeywordLoc(readSourceLocation());
7052 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7053 TL.setTemplateKeywordLoc(readSourceLocation());
7054 TL.setTemplateNameLoc(readSourceLocation());
7055 TL.setLAngleLoc(readSourceLocation());
7056 TL.setRAngleLoc(readSourceLocation());
7057 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7058 TL.setArgLocInfo(I,
7059 Reader.readTemplateArgumentLocInfo(
7060 TL.getTypePtr()->template_arguments()[I].getKind()));
7061}
7062
7063void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7064 TL.setEllipsisLoc(readSourceLocation());
7065}
7066
7067void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7068 TL.setNameLoc(readSourceLocation());
7069 TL.setNameEndLoc(readSourceLocation());
7070}
7071
7072void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7073 if (TL.getNumProtocols()) {
7074 TL.setProtocolLAngleLoc(readSourceLocation());
7075 TL.setProtocolRAngleLoc(readSourceLocation());
7076 }
7077 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7078 TL.setProtocolLoc(i, readSourceLocation());
7079}
7080
7081void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7082 TL.setHasBaseTypeAsWritten(Reader.readBool());
7083 TL.setTypeArgsLAngleLoc(readSourceLocation());
7084 TL.setTypeArgsRAngleLoc(readSourceLocation());
7085 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7086 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7087 TL.setProtocolLAngleLoc(readSourceLocation());
7088 TL.setProtocolRAngleLoc(readSourceLocation());
7089 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7090 TL.setProtocolLoc(i, readSourceLocation());
7091}
7092
7093void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7094 TL.setStarLoc(readSourceLocation());
7095}
7096
7097void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7098 TL.setKWLoc(readSourceLocation());
7099 TL.setLParenLoc(readSourceLocation());
7100 TL.setRParenLoc(readSourceLocation());
7101}
7102
7103void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7104 TL.setKWLoc(readSourceLocation());
7105}
7106
7107void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7108 TL.setNameLoc(readSourceLocation());
7109}
7110void TypeLocReader::VisitDependentBitIntTypeLoc(
7112 TL.setNameLoc(readSourceLocation());
7113}
7114
7116 LocSeq::State Seq(ParentSeq);
7117 TypeLocReader TLR(*this, Seq);
7118 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7119 TLR.Visit(TL);
7120}
7121
7123 QualType InfoTy = readType();
7124 if (InfoTy.isNull())
7125 return nullptr;
7126
7127 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7128 readTypeLoc(TInfo->getTypeLoc());
7129 return TInfo;
7130}
7131
7133 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7134}
7135
7137 return ID >> 32;
7138}
7139
7141 // We don't need to erase the higher bits since if these bits are not 0,
7142 // it must be larger than NUM_PREDEF_TYPE_IDS.
7144}
7145
7146std::pair<ModuleFile *, unsigned>
7147ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7148 assert(!isPredefinedType(ID) &&
7149 "Predefined type shouldn't be in TypesLoaded");
7150 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7151 assert(ModuleFileIndex && "Untranslated Local Decl?");
7152
7153 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7154 assert(OwningModuleFile &&
7155 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7156
7157 return {OwningModuleFile,
7158 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7159}
7160
7162 assert(ContextObj && "reading type with no AST context");
7163 ASTContext &Context = *ContextObj;
7164
7165 unsigned FastQuals = ID & Qualifiers::FastMask;
7166
7167 if (isPredefinedType(ID)) {
7168 QualType T;
7169 unsigned Index = getIndexForTypeID(ID);
7170 switch ((PredefinedTypeIDs)Index) {
7172 // We should never use this one.
7173 llvm_unreachable("Invalid predefined type");
7174 break;
7176 return QualType();
7178 T = Context.VoidTy;
7179 break;
7181 T = Context.BoolTy;
7182 break;
7185 // FIXME: Check that the signedness of CharTy is correct!
7186 T = Context.CharTy;
7187 break;
7189 T = Context.UnsignedCharTy;
7190 break;
7192 T = Context.UnsignedShortTy;
7193 break;
7195 T = Context.UnsignedIntTy;
7196 break;
7198 T = Context.UnsignedLongTy;
7199 break;
7201 T = Context.UnsignedLongLongTy;
7202 break;
7204 T = Context.UnsignedInt128Ty;
7205 break;
7207 T = Context.SignedCharTy;
7208 break;
7210 T = Context.WCharTy;
7211 break;
7213 T = Context.ShortTy;
7214 break;
7215 case PREDEF_TYPE_INT_ID:
7216 T = Context.IntTy;
7217 break;
7219 T = Context.LongTy;
7220 break;
7222 T = Context.LongLongTy;
7223 break;
7225 T = Context.Int128Ty;
7226 break;
7228 T = Context.BFloat16Ty;
7229 break;
7231 T = Context.HalfTy;
7232 break;
7234 T = Context.FloatTy;
7235 break;
7237 T = Context.DoubleTy;
7238 break;
7240 T = Context.LongDoubleTy;
7241 break;
7243 T = Context.ShortAccumTy;
7244 break;
7246 T = Context.AccumTy;
7247 break;
7249 T = Context.LongAccumTy;
7250 break;
7252 T = Context.UnsignedShortAccumTy;
7253 break;
7255 T = Context.UnsignedAccumTy;
7256 break;
7258 T = Context.UnsignedLongAccumTy;
7259 break;
7261 T = Context.ShortFractTy;
7262 break;
7264 T = Context.FractTy;
7265 break;
7267 T = Context.LongFractTy;
7268 break;
7270 T = Context.UnsignedShortFractTy;
7271 break;
7273 T = Context.UnsignedFractTy;
7274 break;
7276 T = Context.UnsignedLongFractTy;
7277 break;
7279 T = Context.SatShortAccumTy;
7280 break;
7282 T = Context.SatAccumTy;
7283 break;
7285 T = Context.SatLongAccumTy;
7286 break;
7288 T = Context.SatUnsignedShortAccumTy;
7289 break;
7291 T = Context.SatUnsignedAccumTy;
7292 break;
7294 T = Context.SatUnsignedLongAccumTy;
7295 break;
7297 T = Context.SatShortFractTy;
7298 break;
7300 T = Context.SatFractTy;
7301 break;
7303 T = Context.SatLongFractTy;
7304 break;
7306 T = Context.SatUnsignedShortFractTy;
7307 break;
7309 T = Context.SatUnsignedFractTy;
7310 break;
7312 T = Context.SatUnsignedLongFractTy;
7313 break;
7315 T = Context.Float16Ty;
7316 break;
7318 T = Context.Float128Ty;
7319 break;
7321 T = Context.Ibm128Ty;
7322 break;
7324 T = Context.OverloadTy;
7325 break;
7327 T = Context.UnresolvedTemplateTy;
7328 break;
7330 T = Context.BoundMemberTy;
7331 break;
7333 T = Context.PseudoObjectTy;
7334 break;
7336 T = Context.DependentTy;
7337 break;
7339 T = Context.UnknownAnyTy;
7340 break;
7342 T = Context.NullPtrTy;
7343 break;
7345 T = Context.Char8Ty;
7346 break;
7348 T = Context.Char16Ty;
7349 break;
7351 T = Context.Char32Ty;
7352 break;
7354 T = Context.ObjCBuiltinIdTy;
7355 break;
7357 T = Context.ObjCBuiltinClassTy;
7358 break;
7360 T = Context.ObjCBuiltinSelTy;
7361 break;
7362#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7363 case PREDEF_TYPE_##Id##_ID: \
7364 T = Context.SingletonId; \
7365 break;
7366#include "clang/Basic/OpenCLImageTypes.def"
7367#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7368 case PREDEF_TYPE_##Id##_ID: \
7369 T = Context.Id##Ty; \
7370 break;
7371#include "clang/Basic/OpenCLExtensionTypes.def"
7373 T = Context.OCLSamplerTy;
7374 break;
7376 T = Context.OCLEventTy;
7377 break;
7379 T = Context.OCLClkEventTy;
7380 break;
7382 T = Context.OCLQueueTy;
7383 break;
7385 T = Context.OCLReserveIDTy;
7386 break;
7388 T = Context.getAutoDeductType();
7389 break;
7391 T = Context.getAutoRRefDeductType();
7392 break;
7394 T = Context.ARCUnbridgedCastTy;
7395 break;
7397 T = Context.BuiltinFnTy;
7398 break;
7400 T = Context.IncompleteMatrixIdxTy;
7401 break;
7403 T = Context.ArraySectionTy;
7404 break;
7406 T = Context.OMPArrayShapingTy;
7407 break;
7409 T = Context.OMPIteratorTy;
7410 break;
7411#define SVE_TYPE(Name, Id, SingletonId) \
7412 case PREDEF_TYPE_##Id##_ID: \
7413 T = Context.SingletonId; \
7414 break;
7415#include "clang/Basic/AArch64SVEACLETypes.def"
7416#define PPC_VECTOR_TYPE(Name, Id, Size) \
7417 case PREDEF_TYPE_##Id##_ID: \
7418 T = Context.Id##Ty; \
7419 break;
7420#include "clang/Basic/PPCTypes.def"
7421#define RVV_TYPE(Name, Id, SingletonId) \
7422 case PREDEF_TYPE_##Id##_ID: \
7423 T = Context.SingletonId; \
7424 break;
7425#include "clang/Basic/RISCVVTypes.def"
7426#define WASM_TYPE(Name, Id, SingletonId) \
7427 case PREDEF_TYPE_##Id##_ID: \
7428 T = Context.SingletonId; \
7429 break;
7430#include "clang/Basic/WebAssemblyReferenceTypes.def"
7431#define AMDGPU_TYPE(Name, Id, SingletonId) \
7432 case PREDEF_TYPE_##Id##_ID: \
7433 T = Context.SingletonId; \
7434 break;
7435#include "clang/Basic/AMDGPUTypes.def"
7436 }
7437
7438 assert(!T.isNull() && "Unknown predefined type");
7439 return T.withFastQualifiers(FastQuals);
7440 }
7441
7442 unsigned Index = translateTypeIDToIndex(ID).second;
7443
7444 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7445 if (TypesLoaded[Index].isNull()) {
7446 TypesLoaded[Index] = readTypeRecord(ID);
7447 if (TypesLoaded[Index].isNull())
7448 return QualType();
7449
7450 TypesLoaded[Index]->setFromAST();
7451 if (DeserializationListener)
7452 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7453 TypesLoaded[Index]);
7454 }
7455
7456 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7457}
7458
7460 return GetType(getGlobalTypeID(F, LocalID));
7461}
7462
7464 LocalTypeID LocalID) const {
7465 if (isPredefinedType(LocalID))
7466 return LocalID;
7467
7468 if (!F.ModuleOffsetMap.empty())
7469 ReadModuleOffsetMap(F);
7470
7471 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
7472 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
7473
7474 if (ModuleFileIndex == 0)
7476
7477 ModuleFile &MF =
7478 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
7479 ModuleFileIndex = MF.Index + 1;
7480 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
7481}
7482
7485 switch (Kind) {
7487 return readExpr();
7489 return readTypeSourceInfo();
7491 NestedNameSpecifierLoc QualifierLoc =
7492 readNestedNameSpecifierLoc();
7493 SourceLocation TemplateNameLoc = readSourceLocation();
7494 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7495 TemplateNameLoc, SourceLocation());
7496 }
7498 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7499 SourceLocation TemplateNameLoc = readSourceLocation();
7500 SourceLocation EllipsisLoc = readSourceLocation();
7501 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7502 TemplateNameLoc, EllipsisLoc);
7503 }
7510 // FIXME: Is this right?
7511 return TemplateArgumentLocInfo();
7512 }
7513 llvm_unreachable("unexpected template argument loc");
7514}
7515
7517 TemplateArgument Arg = readTemplateArgument();
7518
7520 if (readBool()) // bool InfoHasSameExpr.
7522 }
7523 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7524}
7525
7528 Result.setLAngleLoc(readSourceLocation());
7529 Result.setRAngleLoc(readSourceLocation());
7530 unsigned NumArgsAsWritten = readInt();
7531 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7532 Result.addArgument(readTemplateArgumentLoc());
7533}
7534
7538 readTemplateArgumentListInfo(Result);
7539 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7540}
7541
7543
7545 if (NumCurrentElementsDeserializing) {
7546 // We arrange to not care about the complete redeclaration chain while we're
7547 // deserializing. Just remember that the AST has marked this one as complete
7548 // but that it's not actually complete yet, so we know we still need to
7549 // complete it later.
7550 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7551 return;
7552 }
7553
7554 if (!D->getDeclContext()) {
7555 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7556 return;
7557 }
7558
7559 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7560
7561 // If this is a named declaration, complete it by looking it up
7562 // within its context.
7563 //
7564 // FIXME: Merging a function definition should merge
7565 // all mergeable entities within it.
7566 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7567 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7568 if (!getContext().getLangOpts().CPlusPlus &&
7569 isa<TranslationUnitDecl>(DC)) {
7570 // Outside of C++, we don't have a lookup table for the TU, so update
7571 // the identifier instead. (For C++ modules, we don't store decls
7572 // in the serialized identifier table, so we do the lookup in the TU.)
7573 auto *II = Name.getAsIdentifierInfo();
7574 assert(II && "non-identifier name in C?");
7575 if (II->isOutOfDate())
7576 updateOutOfDateIdentifier(*II);
7577 } else
7578 DC->lookup(Name);
7579 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7580 // Find all declarations of this kind from the relevant context.
7581 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7582 auto *DC = cast<DeclContext>(DCDecl);
7584 FindExternalLexicalDecls(
7585 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7586 }
7587 }
7588 }
7589
7590 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7591 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7592 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7593 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7594 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7595 if (auto *Template = FD->getPrimaryTemplate())
7596 Template->LoadLazySpecializations();
7597 }
7598}
7599
7602 RecordLocation Loc = getLocalBitOffset(Offset);
7603 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7604 SavedStreamPosition SavedPosition(Cursor);
7605 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7606 Error(std::move(Err));
7607 return nullptr;
7608 }
7609 ReadingKindTracker ReadingKind(Read_Decl, *this);
7610 Deserializing D(this);
7611
7612 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7613 if (!MaybeCode) {
7614 Error(MaybeCode.takeError());
7615 return nullptr;
7616 }
7617 unsigned Code = MaybeCode.get();
7618
7619 ASTRecordReader Record(*this, *Loc.F);
7620 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7621 if (!MaybeRecCode) {
7622 Error(MaybeRecCode.takeError());
7623 return nullptr;
7624 }
7625 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7626 Error("malformed AST file: missing C++ ctor initializers");
7627 return nullptr;
7628 }
7629
7630 return Record.readCXXCtorInitializers();
7631}
7632
7634 assert(ContextObj && "reading base specifiers with no AST context");
7635 ASTContext &Context = *ContextObj;
7636
7637 RecordLocation Loc = getLocalBitOffset(Offset);
7638 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7639 SavedStreamPosition SavedPosition(Cursor);
7640 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7641 Error(std::move(Err));
7642 return nullptr;
7643 }
7644 ReadingKindTracker ReadingKind(Read_Decl, *this);
7645 Deserializing D(this);
7646
7647 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7648 if (!MaybeCode) {
7649 Error(MaybeCode.takeError());
7650 return nullptr;
7651 }
7652 unsigned Code = MaybeCode.get();
7653
7654 ASTRecordReader Record(*this, *Loc.F);
7655 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7656 if (!MaybeRecCode) {
7657 Error(MaybeCode.takeError());
7658 return nullptr;
7659 }
7660 unsigned RecCode = MaybeRecCode.get();
7661
7662 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7663 Error("malformed AST file: missing C++ base specifiers");
7664 return nullptr;
7665 }
7666
7667 unsigned NumBases = Record.readInt();
7668 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7669 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7670 for (unsigned I = 0; I != NumBases; ++I)
7671 Bases[I] = Record.readCXXBaseSpecifier();
7672 return Bases;
7673}
7674
7676 LocalDeclID LocalID) const {
7677 if (LocalID < NUM_PREDEF_DECL_IDS)
7678 return GlobalDeclID(LocalID.getRawValue());
7679
7680 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
7681 DeclID ID = LocalID.getLocalDeclIndex();
7682
7683 if (!F.ModuleOffsetMap.empty())
7684 ReadModuleOffsetMap(F);
7685
7686 ModuleFile *OwningModuleFile =
7687 OwningModuleFileIndex == 0
7688 ? &F
7689 : F.TransitiveImports[OwningModuleFileIndex - 1];
7690
7691 if (OwningModuleFileIndex == 0)
7692 ID -= NUM_PREDEF_DECL_IDS;
7693
7694 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
7695 return GlobalDeclID(NewModuleFileIndex, ID);
7696}
7697
7699 // Predefined decls aren't from any module.
7700 if (ID < NUM_PREDEF_DECL_IDS)
7701 return false;
7702
7703 unsigned ModuleFileIndex = ID.getModuleFileIndex();
7704 return M.Index == ModuleFileIndex - 1;
7705}
7706
7708 // Predefined decls aren't from any module.
7709 if (ID < NUM_PREDEF_DECL_IDS)
7710 return nullptr;
7711
7712 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
7713 assert(ModuleFileIndex && "Untranslated Local Decl?");
7714
7715 return &getModuleManager()[ModuleFileIndex - 1];
7716}
7717
7719 if (!D->isFromASTFile())
7720 return nullptr;
7721
7722 return getOwningModuleFile(D->getGlobalID());
7723}
7724
7726 if (ID < NUM_PREDEF_DECL_IDS)
7727 return SourceLocation();
7728
7729 if (Decl *D = GetExistingDecl(ID))
7730 return D->getLocation();
7731
7733 DeclCursorForID(ID, Loc);
7734 return Loc;
7735}
7736
7738 switch (ID) {
7740 return nullptr;
7741
7743 return Context.getTranslationUnitDecl();
7744
7746 return Context.getObjCIdDecl();
7747
7749 return Context.getObjCSelDecl();
7750
7752 return Context.getObjCClassDecl();
7753
7755 return Context.getObjCProtocolDecl();
7756
7758 return Context.getInt128Decl();
7759
7761 return Context.getUInt128Decl();
7762
7764 return Context.getObjCInstanceTypeDecl();
7765
7767 return Context.getBuiltinVaListDecl();
7768
7770 return Context.getVaListTagDecl();
7771
7773 return Context.getBuiltinMSVaListDecl();
7774
7776 return Context.getMSGuidTagDecl();
7777
7779 return Context.getExternCContextDecl();
7780
7782 return Context.getMakeIntegerSeqDecl();
7783
7785 return Context.getCFConstantStringDecl();
7786
7788 return Context.getCFConstantStringTagDecl();
7789
7791 return Context.getTypePackElementDecl();
7792 }
7793 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7794}
7795
7796unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
7797 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
7798 if (!OwningModuleFile) {
7799 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
7800 return GlobalID.getRawValue();
7801 }
7802
7803 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
7804}
7805
7807 assert(ContextObj && "reading decl with no AST context");
7808
7809 if (ID < NUM_PREDEF_DECL_IDS) {
7810 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7811 if (D) {
7812 // Track that we have merged the declaration with ID \p ID into the
7813 // pre-existing predefined declaration \p D.
7814 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7815 if (Merged.empty())
7816 Merged.push_back(ID);
7817 }
7818 return D;
7819 }
7820
7821 unsigned Index = translateGlobalDeclIDToIndex(ID);
7822
7823 if (Index >= DeclsLoaded.size()) {
7824 assert(0 && "declaration ID out-of-range for AST file");
7825 Error("declaration ID out-of-range for AST file");
7826 return nullptr;
7827 }
7828
7829 return DeclsLoaded[Index];
7830}
7831
7833 if (ID < NUM_PREDEF_DECL_IDS)
7834 return GetExistingDecl(ID);
7835
7836 unsigned Index = translateGlobalDeclIDToIndex(ID);
7837
7838 if (Index >= DeclsLoaded.size()) {
7839 assert(0 && "declaration ID out-of-range for AST file");
7840 Error("declaration ID out-of-range for AST file");
7841 return nullptr;
7842 }
7843
7844 if (!DeclsLoaded[Index]) {
7845 ReadDeclRecord(ID);
7846 if (DeserializationListener)
7847 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7848 }
7849
7850 return DeclsLoaded[Index];
7851}
7852
7854 GlobalDeclID GlobalID) {
7855 if (GlobalID < NUM_PREDEF_DECL_IDS)
7856 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
7857
7858 if (!M.ModuleOffsetMap.empty())
7859 ReadModuleOffsetMap(M);
7860
7861 ModuleFile *Owner = getOwningModuleFile(GlobalID);
7862 DeclID ID = GlobalID.getLocalDeclIndex();
7863
7864 if (Owner == &M) {
7865 ID += NUM_PREDEF_DECL_IDS;
7866 return LocalDeclID::get(*this, M, ID);
7867 }
7868
7869 uint64_t OrignalModuleFileIndex = 0;
7870 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
7871 if (M.TransitiveImports[I] == Owner) {
7872 OrignalModuleFileIndex = I + 1;
7873 break;
7874 }
7875
7876 if (!OrignalModuleFileIndex)
7877 return LocalDeclID();
7878
7879 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
7880}
7881
7883 unsigned &Idx) {
7884 if (Idx >= Record.size()) {
7885 Error("Corrupted AST file");
7886 return GlobalDeclID(0);
7887 }
7888
7889 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
7890}
7891
7892/// Resolve the offset of a statement into a statement.
7893///
7894/// This operation will read a new statement from the external
7895/// source each time it is called, and is meant to be used via a
7896/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7898 // Switch case IDs are per Decl.
7899 ClearSwitchCaseIDs();
7900
7901 // Offset here is a global offset across the entire chain.
7902 RecordLocation Loc = getLocalBitOffset(Offset);
7903 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7904 Error(std::move(Err));
7905 return nullptr;
7906 }
7907 assert(NumCurrentElementsDeserializing == 0 &&
7908 "should not be called while already deserializing");
7909 Deserializing D(this);
7910 return ReadStmtFromStream(*Loc.F);
7911}
7912
7914 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7915 SmallVectorImpl<Decl *> &Decls) {
7916 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7917
7918 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7919 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7920 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7921 auto K = (Decl::Kind)+LexicalDecls[I];
7922 if (!IsKindWeWant(K))
7923 continue;
7924
7925 auto ID = (DeclID) + LexicalDecls[I + 1];
7926
7927 // Don't add predefined declarations to the lexical context more
7928 // than once.
7929 if (ID < NUM_PREDEF_DECL_IDS) {
7930 if (PredefsVisited[ID])
7931 continue;
7932
7933 PredefsVisited[ID] = true;
7934 }
7935
7936 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
7937 assert(D->getKind() == K && "wrong kind for lexical decl");
7938 if (!DC->isDeclInLexicalTraversal(D))
7939 Decls.push_back(D);
7940 }
7941 }
7942 };
7943
7944 if (isa<TranslationUnitDecl>(DC)) {
7945 for (const auto &Lexical : TULexicalDecls)
7946 Visit(Lexical.first, Lexical.second);
7947 } else {
7948 auto I = LexicalDecls.find(DC);
7949 if (I != LexicalDecls.end())
7950 Visit(I->second.first, I->second.second);
7951 }
7952
7953 ++NumLexicalDeclContextsRead;
7954}
7955
7956namespace {
7957
7958class UnalignedDeclIDComp {
7959 ASTReader &Reader;
7960 ModuleFile &Mod;
7961
7962public:
7963 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
7964 : Reader(Reader), Mod(M) {}
7965
7966 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
7967 SourceLocation LHS = getLocation(L);
7968 SourceLocation RHS = getLocation(R);
7969 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7970 }
7971
7972 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
7973 SourceLocation RHS = getLocation(R);
7974 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7975 }
7976
7977 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
7978 SourceLocation LHS = getLocation(L);
7979 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7980 }
7981
7982 SourceLocation getLocation(unaligned_decl_id_t ID) const {
7983 return Reader.getSourceManager().getFileLoc(
7985 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
7986 }
7987};
7988
7989} // namespace
7990
7992 unsigned Offset, unsigned Length,
7993 SmallVectorImpl<Decl *> &Decls) {
7994 SourceManager &SM = getSourceManager();
7995
7996 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7997 if (I == FileDeclIDs.end())
7998 return;
7999
8000 FileDeclsInfo &DInfo = I->second;
8001 if (DInfo.Decls.empty())
8002 return;
8003
8005 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8006 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8007
8008 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8010 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8011 if (BeginIt != DInfo.Decls.begin())
8012 --BeginIt;
8013
8014 // If we are pointing at a top-level decl inside an objc container, we need
8015 // to backtrack until we find it otherwise we will fail to report that the
8016 // region overlaps with an objc container.
8017 while (BeginIt != DInfo.Decls.begin() &&
8018 GetDecl(getGlobalDeclID(*DInfo.Mod,
8019 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8020 ->isTopLevelDeclInObjCContainer())
8021 --BeginIt;
8022
8024 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8025 if (EndIt != DInfo.Decls.end())
8026 ++EndIt;
8027
8028 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8029 ++DIt)
8030 Decls.push_back(GetDecl(getGlobalDeclID(
8031 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8032}
8033
8034bool
8036 DeclarationName Name) {
8037 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8038 "DeclContext has no visible decls in storage");
8039 if (!Name)
8040 return false;
8041
8042 auto It = Lookups.find(DC);
8043 if (It == Lookups.end())
8044 return false;
8045
8046 Deserializing LookupResults(this);
8047
8048 // Load the list of declarations.
8051
8052 for (GlobalDeclID ID : It->second.Table.find(Name)) {
8053 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8054 if (ND->getDeclName() == Name && Found.insert(ND).second)
8055 Decls.push_back(ND);
8056 }
8057
8058 ++NumVisibleDeclContextsRead;
8059 SetExternalVisibleDeclsForName(DC, Name, Decls);
8060 return !Decls.empty();
8061}
8062
8064 if (!DC->hasExternalVisibleStorage())
8065 return;
8066
8067 auto It = Lookups.find(DC);
8068 assert(It != Lookups.end() &&
8069 "have external visible storage but no lookup tables");
8070
8071 DeclsMap Decls;
8072
8073 for (GlobalDeclID ID : It->second.Table.findAll()) {
8074 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8075 Decls[ND->getDeclName()].push_back(ND);
8076 }
8077
8078 ++NumVisibleDeclContextsRead;
8079
8080 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8081 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8082 }
8083 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8084}
8085
8088 auto I = Lookups.find(Primary);
8089 return I == Lookups.end() ? nullptr : &I->second;
8090}
8091
8092/// Under non-PCH compilation the consumer receives the objc methods
8093/// before receiving the implementation, and codegen depends on this.
8094/// We simulate this by deserializing and passing to consumer the methods of the
8095/// implementation before passing the deserialized implementation decl.
8097 ASTConsumer *Consumer) {
8098 assert(ImplD && Consumer);
8099
8100 for (auto *I : ImplD->methods())
8101 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8102
8103 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8104}
8105
8106void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8107 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8108 PassObjCImplDeclToConsumer(ImplD, Consumer);
8109 else
8110 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8111}
8112
8114 this->Consumer = Consumer;
8115
8116 if (Consumer)
8117 PassInterestingDeclsToConsumer();
8118
8119 if (DeserializationListener)
8120 DeserializationListener->ReaderInitialized(this);
8121}
8122
8124 std::fprintf(stderr, "*** AST File Statistics:\n");
8125
8126 unsigned NumTypesLoaded =
8127 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8128 unsigned NumDeclsLoaded =
8129 DeclsLoaded.size() -
8130 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8131 unsigned NumIdentifiersLoaded =
8132 IdentifiersLoaded.size() -
8133 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8134 unsigned NumMacrosLoaded =
8135 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8136 unsigned NumSelectorsLoaded =
8137 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8138
8139 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8140 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8141 NumSLocEntriesRead, TotalNumSLocEntries,
8142 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8143 if (!TypesLoaded.empty())
8144 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8145 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8146 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8147 if (!DeclsLoaded.empty())
8148 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8149 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8150 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8151 if (!IdentifiersLoaded.empty())
8152 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8153 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8154 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8155 if (!MacrosLoaded.empty())
8156 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8157 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8158 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8159 if (!SelectorsLoaded.empty())
8160 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8161 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8162 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8163 if (TotalNumStatements)
8164 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8165 NumStatementsRead, TotalNumStatements,
8166 ((float)NumStatementsRead/TotalNumStatements * 100));
8167 if (TotalNumMacros)
8168 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8169 NumMacrosRead, TotalNumMacros,
8170 ((float)NumMacrosRead/TotalNumMacros * 100));
8171 if (TotalLexicalDeclContexts)
8172 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8173 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8174 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8175 * 100));
8176 if (TotalVisibleDeclContexts)
8177 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8178 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8179 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8180 * 100));
8181 if (TotalNumMethodPoolEntries)
8182 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8183 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8184 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8185 * 100));
8186 if (NumMethodPoolLookups)
8187 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8188 NumMethodPoolHits, NumMethodPoolLookups,
8189 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8190 if (NumMethodPoolTableLookups)
8191 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8192 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8193 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8194 * 100.0));
8195 if (NumIdentifierLookupHits)
8196 std::fprintf(stderr,
8197 " %u / %u identifier table lookups succeeded (%f%%)\n",
8198 NumIdentifierLookupHits, NumIdentifierLookups,
8199 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8200
8201 if (GlobalIndex) {
8202 std::fprintf(stderr, "\n");
8203 GlobalIndex->printStats();
8204 }
8205
8206 std::fprintf(stderr, "\n");
8207 dump();
8208 std::fprintf(stderr, "\n");
8209}
8210
8211template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8212LLVM_DUMP_METHOD static void
8213dumpModuleIDMap(StringRef Name,
8214 const ContinuousRangeMap<Key, ModuleFile *,
8215 InitialCapacity> &Map) {
8216 if (Map.begin() == Map.end())
8217 return;
8218
8220
8221 llvm::errs() << Name << ":\n";
8222 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8223 I != IEnd; ++I)
8224 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
8225 << "\n";
8226}
8227
8228LLVM_DUMP_METHOD void ASTReader::dump() {
8229 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8230 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8231 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8232 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8233 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8234 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8235 dumpModuleIDMap("Global preprocessed entity map",
8236 GlobalPreprocessedEntityMap);
8237
8238 llvm::errs() << "\n*** PCH/Modules Loaded:";
8239 for (ModuleFile &M : ModuleMgr)
8240 M.dump();
8241}
8242
8243/// Return the amount of memory used by memory buffers, breaking down
8244/// by heap-backed versus mmap'ed memory.
8246 for (ModuleFile &I : ModuleMgr) {
8247 if (llvm::MemoryBuffer *buf = I.Buffer) {
8248 size_t bytes = buf->getBufferSize();
8249 switch (buf->getBufferKind()) {
8250 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8251 sizes.malloc_bytes += bytes;
8252 break;
8253 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8254 sizes.mmap_bytes += bytes;
8255 break;
8256 }
8257 }
8258 }
8259}
8260
8262 SemaObj = &S;
8263 S.addExternalSource(this);
8264
8265 // Makes sure any declarations that were deserialized "too early"
8266 // still get added to the identifier's declaration chains.
8267 for (GlobalDeclID ID : PreloadedDeclIDs) {
8268 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8269 pushExternalDeclIntoScope(D, D->getDeclName());
8270 }
8271 PreloadedDeclIDs.clear();
8272
8273 // FIXME: What happens if these are changed by a module import?
8274 if (!FPPragmaOptions.empty()) {
8275 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8276 FPOptionsOverride NewOverrides =
8277 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8278 SemaObj->CurFPFeatures =
8279 NewOverrides.applyOverrides(SemaObj->getLangOpts());
8280 }
8281
8282 SemaObj->OpenCLFeatures = OpenCLExtensions;
8283
8284 UpdateSema();
8285}
8286
8288 assert(SemaObj && "no Sema to update");
8289
8290 // Load the offsets of the declarations that Sema references.
8291 // They will be lazily deserialized when needed.
8292 if (!SemaDeclRefs.empty()) {
8293 assert(SemaDeclRefs.size() % 3 == 0);
8294 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8295 if (!SemaObj->StdNamespace)
8296 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
8297 if (!SemaObj->StdBadAlloc)
8298 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
8299 if (!SemaObj->StdAlignValT)
8300 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
8301 }
8302 SemaDeclRefs.clear();
8303 }
8304
8305 // Update the state of pragmas. Use the same API as if we had encountered the
8306 // pragma in the source.
8307 if(OptimizeOffPragmaLocation.isValid())
8308 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8309 if (PragmaMSStructState != -1)
8310 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8311 if (PointersToMembersPragmaLocation.isValid()) {
8312 SemaObj->ActOnPragmaMSPointersToMembers(
8314 PragmaMSPointersToMembersState,
8315 PointersToMembersPragmaLocation);
8316 }
8317 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8318
8319 if (PragmaAlignPackCurrentValue) {
8320 // The bottom of the stack might have a default value. It must be adjusted
8321 // to the current value to ensure that the packing state is preserved after
8322 // popping entries that were included/imported from a PCH/module.
8323 bool DropFirst = false;
8324 if (!PragmaAlignPackStack.empty() &&
8325 PragmaAlignPackStack.front().Location.isInvalid()) {
8326 assert(PragmaAlignPackStack.front().Value ==
8327 SemaObj->AlignPackStack.DefaultValue &&
8328 "Expected a default alignment value");
8329 SemaObj->AlignPackStack.Stack.emplace_back(
8330 PragmaAlignPackStack.front().SlotLabel,
8331 SemaObj->AlignPackStack.CurrentValue,
8332 SemaObj->AlignPackStack.CurrentPragmaLocation,
8333 PragmaAlignPackStack.front().PushLocation);
8334 DropFirst = true;
8335 }
8336 for (const auto &Entry :
8337 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8338 SemaObj->AlignPackStack.Stack.emplace_back(
8339 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8340 }
8341 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8342 assert(*PragmaAlignPackCurrentValue ==
8343 SemaObj->AlignPackStack.DefaultValue &&
8344 "Expected a default align and pack value");
8345 // Keep the current values.
8346 } else {
8347 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8348 SemaObj->AlignPackStack.CurrentPragmaLocation =
8349 PragmaAlignPackCurrentLocation;
8350 }
8351 }
8352 if (FpPragmaCurrentValue) {
8353 // The bottom of the stack might have a default value. It must be adjusted
8354 // to the current value to ensure that fp-pragma state is preserved after
8355 // popping entries that were included/imported from a PCH/module.
8356 bool DropFirst = false;
8357 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8358 assert(FpPragmaStack.front().Value ==
8359 SemaObj->FpPragmaStack.DefaultValue &&
8360 "Expected a default pragma float_control value");
8361 SemaObj->FpPragmaStack.Stack.emplace_back(
8362 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8363 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8364 FpPragmaStack.front().PushLocation);
8365 DropFirst = true;
8366 }
8367 for (const auto &Entry :
8368 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8369 SemaObj->FpPragmaStack.Stack.emplace_back(
8370 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8371 if (FpPragmaCurrentLocation.isInvalid()) {
8372 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8373 "Expected a default pragma float_control value");
8374 // Keep the current values.
8375 } else {
8376 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8377 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8378 }
8379 }
8380
8381 // For non-modular AST files, restore visiblity of modules.
8382 for (auto &Import : PendingImportedModulesSema) {
8383 if (Import.ImportLoc.isInvalid())
8384 continue;
8385 if (Module *Imported = getSubmodule(Import.ID)) {
8386 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8387 }
8388 }
8389 PendingImportedModulesSema.clear();
8390}
8391
8393 // Note that we are loading an identifier.
8394 Deserializing AnIdentifier(this);
8395
8396 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8397 NumIdentifierLookups,
8398 NumIdentifierLookupHits);
8399
8400 // We don't need to do identifier table lookups in C++ modules (we preload
8401 // all interesting declarations, and don't need to use the scope for name
8402 // lookups). Perform the lookup in PCH files, though, since we don't build
8403 // a complete initial identifier table if we're carrying on from a PCH.
8404 if (PP.getLangOpts().CPlusPlus) {
8405 for (auto *F : ModuleMgr.pch_modules())
8406 if (Visitor(*F))
8407 break;
8408 } else {
8409 // If there is a global index, look there first to determine which modules
8410 // provably do not have any results for this identifier.
8412 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8413 if (!loadGlobalIndex()) {
8414 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8415 HitsPtr = &Hits;
8416 }
8417 }
8418
8419 ModuleMgr.visit(Visitor, HitsPtr);
8420 }
8421
8422 IdentifierInfo *II = Visitor.getIdentifierInfo();
8423 markIdentifierUpToDate(II);
8424 return II;
8425}
8426
8427namespace clang {
8428
8429 /// An identifier-lookup iterator that enumerates all of the
8430 /// identifiers stored within a set of AST files.
8432 /// The AST reader whose identifiers are being enumerated.
8433 const ASTReader &Reader;
8434
8435 /// The current index into the chain of AST files stored in
8436 /// the AST reader.
8437 unsigned Index;
8438
8439 /// The current position within the identifier lookup table
8440 /// of the current AST file.
8441 ASTIdentifierLookupTable::key_iterator Current;
8442
8443 /// The end position within the identifier lookup table of
8444 /// the current AST file.
8445 ASTIdentifierLookupTable::key_iterator End;
8446
8447 /// Whether to skip any modules in the ASTReader.
8448 bool SkipModules;
8449
8450 public:
8451 explicit ASTIdentifierIterator(const ASTReader &Reader,
8452 bool SkipModules = false);
8453
8454 StringRef Next() override;
8455 };
8456
8457} // namespace clang
8458
8460 bool SkipModules)
8461 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8462}
8463
8465 while (Current == End) {
8466 // If we have exhausted all of our AST files, we're done.
8467 if (Index == 0)
8468 return StringRef();
8469
8470 --Index;
8471 ModuleFile &F = Reader.ModuleMgr[Index];
8472 if (SkipModules && F.isModule())
8473 continue;
8474
8475 ASTIdentifierLookupTable *IdTable =
8477 Current = IdTable->key_begin();
8478 End = IdTable->key_end();
8479 }
8480
8481 // We have any identifiers remaining in the current AST file; return
8482 // the next one.
8483 StringRef Result = *Current;
8484 ++Current;
8485 return Result;
8486}
8487
8488namespace {
8489
8490/// A utility for appending two IdentifierIterators.
8491class ChainedIdentifierIterator : public IdentifierIterator {
8492 std::unique_ptr<IdentifierIterator> Current;
8493 std::unique_ptr<IdentifierIterator> Queued;
8494
8495public:
8496 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8497 std::unique_ptr<IdentifierIterator> Second)
8498 : Current(std::move(First)), Queued(std::move(Second)) {}
8499
8500 StringRef Next() override {
8501 if (!Current)
8502 return StringRef();
8503
8504 StringRef result = Current->Next();
8505 if (!result.empty())
8506 return result;
8507
8508 // Try the queued iterator, which may itself be empty.
8509 Current.reset();
8510 std::swap(Current, Queued);
8511 return Next();
8512 }
8513};
8514
8515} // namespace
8516
8518 if (!loadGlobalIndex()) {
8519 std::unique_ptr<IdentifierIterator> ReaderIter(
8520 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8521 std::unique_ptr<IdentifierIterator> ModulesIter(
8522 GlobalIndex->createIdentifierIterator());
8523 return new ChainedIdentifierIterator(std::move(ReaderIter),
8524 std::move(ModulesIter));
8525 }
8526
8527 return new ASTIdentifierIterator(*this);
8528}
8529
8530namespace clang {
8531namespace serialization {
8532
8534 ASTReader &Reader;
8535 Selector Sel;
8536 unsigned PriorGeneration;
8537 unsigned InstanceBits = 0;
8538 unsigned FactoryBits = 0;
8539 bool InstanceHasMoreThanOneDecl = false;
8540 bool FactoryHasMoreThanOneDecl = false;
8541 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8542 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8543
8544 public:
8546 unsigned PriorGeneration)
8547 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8548
8550 if (!M.SelectorLookupTable)
8551 return false;
8552
8553 // If we've already searched this module file, skip it now.
8554 if (M.Generation <= PriorGeneration)
8555 return true;
8556
8557 ++Reader.NumMethodPoolTableLookups;
8558 ASTSelectorLookupTable *PoolTable
8560 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8561 if (Pos == PoolTable->end())
8562 return false;
8563
8564 ++Reader.NumMethodPoolTableHits;
8565 ++Reader.NumSelectorsRead;
8566 // FIXME: Not quite happy with the statistics here. We probably should
8567 // disable this tracking when called via LoadSelector.
8568 // Also, should entries without methods count as misses?
8569 ++Reader.NumMethodPoolEntriesRead;
8571 if (Reader.DeserializationListener)
8572 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8573
8574 // Append methods in the reverse order, so that later we can process them
8575 // in the order they appear in the source code by iterating through
8576 // the vector in the reverse order.
8577 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8578 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8579 InstanceBits = Data.InstanceBits;
8580 FactoryBits = Data.FactoryBits;
8581 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8582 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8583 return false;
8584 }
8585
8586 /// Retrieve the instance methods found by this visitor.
8588 return InstanceMethods;
8589 }
8590
8591 /// Retrieve the instance methods found by this visitor.
8593 return FactoryMethods;
8594 }
8595
8596 unsigned getInstanceBits() const { return InstanceBits; }
8597 unsigned getFactoryBits() const { return FactoryBits; }
8598
8600 return InstanceHasMoreThanOneDecl;
8601 }
8602
8603 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8604 };
8605
8606} // namespace serialization
8607} // namespace clang
8608
8609/// Add the given set of methods to the method list.
8611 ObjCMethodList &List) {
8612 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8613 S.ObjC().addMethodToGlobalList(&List, M);
8614}
8615
8617 // Get the selector generation and update it to the current generation.
8618 unsigned &Generation = SelectorGeneration[Sel];
8619 unsigned PriorGeneration = Generation;
8620 Generation = getGeneration();
8621 SelectorOutOfDate[Sel] = false;
8622
8623 // Search for methods defined with this selector.
8624 ++NumMethodPoolLookups;
8625 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8626 ModuleMgr.visit(Visitor);
8627
8628 if (Visitor.getInstanceMethods().empty() &&
8629 Visitor.getFactoryMethods().empty())
8630 return;
8631
8632 ++NumMethodPoolHits;
8633
8634 if (!getSema())
8635 return;
8636
8637 Sema &S = *getSema();
8639 S.ObjC()
8640 .MethodPool
8641 .insert(std::make_pair(Sel, SemaObjC::GlobalMethodPool::Lists()))
8642 .first;
8643
8644 Pos->second.first.setBits(Visitor.getInstanceBits());
8645 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8646 Pos->second.second.setBits(Visitor.getFactoryBits());
8647 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8648
8649 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8650 // when building a module we keep every method individually and may need to
8651 // update hasMoreThanOneDecl as we add the methods.
8652 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8653 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8654}
8655
8657 if (SelectorOutOfDate[Sel])
8658 ReadMethodPool(Sel);
8659}
8660
8663 Namespaces.clear();
8664
8665 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8666 if (NamespaceDecl *Namespace
8667 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8668 Namespaces.push_back(Namespace);
8669 }
8670}
8671
8673 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8674 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8675 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
8676 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
8678 Undefined.insert(std::make_pair(D, Loc));
8679 }
8680 UndefinedButUsed.clear();
8681}
8682
8684 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8685 Exprs) {
8686 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8687 FieldDecl *FD =
8688 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
8689 uint64_t Count = DelayedDeleteExprs[Idx++];
8690 for (uint64_t C = 0; C < Count; ++C) {
8691 SourceLocation DeleteLoc =
8692 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8693 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8694 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8695 }
8696 }
8697}
8698
8700 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8701 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8702 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8703 if (Var)
8704 TentativeDefs.push_back(Var);
8705 }
8706 TentativeDefinitions.clear();
8707}
8708
8711 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8713 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8714 if (D)
8715 Decls.push_back(D);
8716 }
8717 UnusedFileScopedDecls.clear();
8718}
8719
8722 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8724 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8725 if (D)
8726 Decls.push_back(D);
8727 }
8728 DelegatingCtorDecls.clear();
8729}
8730
8732 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8734 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8735 if (D)
8736 Decls.push_back(D);
8737 }
8738 ExtVectorDecls.clear();
8739}
8740
8743 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8744 ++I) {
8745 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8746 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8747 if (D)
8748 Decls.insert(D);
8749 }
8750 UnusedLocalTypedefNameCandidates.clear();
8751}
8752
8755 for (auto I : DeclsToCheckForDeferredDiags) {
8756 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8757 if (D)
8758 Decls.insert(D);
8759 }
8760 DeclsToCheckForDeferredDiags.clear();
8761}
8762
8764 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8765 if (ReferencedSelectorsData.empty())
8766 return;
8767
8768 // If there are @selector references added them to its pool. This is for
8769 // implementation of -Wselector.
8770 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8771 unsigned I = 0;
8772 while (I < DataSize) {
8773 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8774 SourceLocation SelLoc
8775 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8776 Sels.push_back(std::make_pair(Sel, SelLoc));
8777 }
8778 ReferencedSelectorsData.clear();
8779}
8780
8782 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8783 if (WeakUndeclaredIdentifiers.empty())
8784 return;
8785
8786 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8787 IdentifierInfo *WeakId
8788 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8789 IdentifierInfo *AliasId
8790 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8792 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8793 WeakInfo WI(AliasId, Loc);
8794 WeakIDs.push_back(std::make_pair(WeakId, WI));
8795 }
8796 WeakUndeclaredIdentifiers.clear();
8797}
8798
8800 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8802 VTableUse &TableInfo = VTableUses[Idx++];
8803 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
8804 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
8805 VT.DefinitionRequired = TableInfo.Used;
8806 VTables.push_back(VT);
8807 }
8808
8809 VTableUses.clear();
8810}
8811
8813 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8814 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8815 PendingInstantiation &Inst = PendingInstantiations[Idx++];
8816 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
8818
8819 Pending.push_back(std::make_pair(D, Loc));
8820 }
8821 PendingInstantiations.clear();
8822}
8823
8825 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8826 &LPTMap) {
8827 for (auto &LPT : LateParsedTemplates) {
8828 ModuleFile *FMod = LPT.first;
8829 RecordDataImpl &LateParsed = LPT.second;
8830 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8831 /* In loop */) {
8832 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
8833
8834 auto LT = std::make_unique<LateParsedTemplate>();
8835 LT->D = ReadDecl(*FMod, LateParsed, Idx);
8836 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8837
8839 assert(F && "No module");
8840
8841 unsigned TokN = LateParsed[Idx++];
8842 LT->Toks.reserve(TokN);
8843 for (unsigned T = 0; T < TokN; ++T)
8844 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8845
8846 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8847 }
8848 }
8849
8850 LateParsedTemplates.clear();
8851}
8852
8854 if (Lambda->getLambdaContextDecl()) {
8855 // Keep track of this lambda so it can be merged with another lambda that
8856 // is loaded later.
8857 LambdaDeclarationsForMerging.insert(
8859 Lambda->getLambdaIndexInContext()},
8860 const_cast<CXXRecordDecl *>(Lambda)});
8861 }
8862}
8863
8865 // It would be complicated to avoid reading the methods anyway. So don't.
8866 ReadMethodPool(Sel);
8867}
8868
8870 assert(ID && "Non-zero identifier ID required");
8871 unsigned Index = translateIdentifierIDToIndex(ID).second;
8872 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
8873 IdentifiersLoaded[Index] = II;
8874 if (DeserializationListener)
8875 DeserializationListener->IdentifierRead(ID, II);
8876}
8877
8878/// Set the globally-visible declarations associated with the given
8879/// identifier.
8880///
8881/// If the AST reader is currently in a state where the given declaration IDs
8882/// cannot safely be resolved, they are queued until it is safe to resolve
8883/// them.
8884///
8885/// \param II an IdentifierInfo that refers to one or more globally-visible
8886/// declarations.
8887///
8888/// \param DeclIDs the set of declaration IDs with the name @p II that are
8889/// visible at global scope.
8890///
8891/// \param Decls if non-null, this vector will be populated with the set of
8892/// deserialized declarations. These declarations will not be pushed into
8893/// scope.
8896 SmallVectorImpl<Decl *> *Decls) {
8897 if (NumCurrentElementsDeserializing && !Decls) {
8898 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8899 return;
8900 }
8901
8902 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8903 if (!SemaObj) {
8904 // Queue this declaration so that it will be added to the
8905 // translation unit scope and identifier's declaration chain
8906 // once a Sema object is known.
8907 PreloadedDeclIDs.push_back(DeclIDs[I]);
8908 continue;
8909 }
8910
8911 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8912
8913 // If we're simply supposed to record the declarations, do so now.
8914 if (Decls) {
8915 Decls->push_back(D);
8916 continue;
8917 }
8918
8919 // Introduce this declaration into the translation-unit scope
8920 // and add it to the declaration chain for this identifier, so
8921 // that (unqualified) name lookup will find it.
8922 pushExternalDeclIntoScope(D, II);
8923 }
8924}
8925
8926std::pair<ModuleFile *, unsigned>
8927ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
8928 if (ID == 0)
8929 return {nullptr, 0};
8930
8931 unsigned ModuleFileIndex = ID >> 32;
8932 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
8933
8934 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
8935 assert(getModuleManager().size() > ModuleFileIndex - 1);
8936
8937 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
8938 assert(LocalID < MF.LocalNumIdentifiers);
8939 return {&MF, MF.BaseIdentifierID + LocalID};
8940}
8941
8943 if (ID == 0)
8944 return nullptr;
8945
8946 if (IdentifiersLoaded.empty()) {
8947 Error("no identifier table in AST file");
8948 return nullptr;
8949 }
8950
8951 auto [M, Index] = translateIdentifierIDToIndex(ID);
8952 if (!IdentifiersLoaded[Index]) {
8953 assert(M != nullptr && "Untranslated Identifier ID?");
8954 assert(Index >= M->BaseIdentifierID);
8955 unsigned LocalIndex = Index - M->BaseIdentifierID;
8956 const unsigned char *Data =
8957 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
8958
8959 ASTIdentifierLookupTrait Trait(*this, *M);
8960 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8961 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8962 auto &II = PP.getIdentifierTable().get(Key);
8963 IdentifiersLoaded[Index] = &II;
8964 markIdentifierFromAST(*this, II);
8965 if (DeserializationListener)
8966 DeserializationListener->IdentifierRead(ID, &II);
8967 }
8968
8969 return IdentifiersLoaded[Index];
8970}
8971
8973 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8974}
8975
8977 if (LocalID < NUM_PREDEF_IDENT_IDS)
8978 return LocalID;
8979
8980 if (!M.ModuleOffsetMap.empty())
8981 ReadModuleOffsetMap(M);
8982
8983 unsigned ModuleFileIndex = LocalID >> 32;
8984 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
8985 ModuleFile *MF =
8986 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
8987 assert(MF && "malformed identifier ID encoding?");
8988
8989 if (!ModuleFileIndex)
8990 LocalID -= NUM_PREDEF_IDENT_IDS;
8991
8992 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
8993}
8994
8996 if (ID == 0)
8997 return nullptr;
8998
8999 if (MacrosLoaded.empty()) {
9000 Error("no macro table in AST file");
9001 return nullptr;
9002 }
9003
9005 if (!MacrosLoaded[ID]) {
9007 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
9008 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
9009 ModuleFile *M = I->second;
9010 unsigned Index = ID - M->BaseMacroID;
9011 MacrosLoaded[ID] =
9012 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
9013
9014 if (DeserializationListener)
9015 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
9016 MacrosLoaded[ID]);
9017 }
9018
9019 return MacrosLoaded[ID];
9020}
9021
9023 if (LocalID < NUM_PREDEF_MACRO_IDS)
9024 return LocalID;
9025
9026 if (!M.ModuleOffsetMap.empty())
9027 ReadModuleOffsetMap(M);
9028
9030 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
9031 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
9032
9033 return LocalID + I->second;
9034}
9035
9037ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9038 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9039 return LocalID;
9040
9041 if (!M.ModuleOffsetMap.empty())
9042 ReadModuleOffsetMap(M);
9043
9046 assert(I != M.SubmoduleRemap.end()
9047 && "Invalid index into submodule index remap");
9048
9049 return LocalID + I->second;
9050}
9051
9053 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9054 assert(GlobalID == 0 && "Unhandled global submodule ID");
9055 return nullptr;
9056 }
9057
9058 if (GlobalID > SubmodulesLoaded.size()) {
9059 Error("submodule ID out of range in AST file");
9060 return nullptr;
9061 }
9062
9063 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9064}
9065
9067 return getSubmodule(ID);
9068}
9069
9071 if (ID & 1) {
9072 // It's a module, look it up by submodule ID.
9073 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9074 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9075 } else {
9076 // It's a prefix (preamble, PCH, ...). Look it up by index.
9077 unsigned IndexFromEnd = ID >> 1;
9078 assert(IndexFromEnd && "got reference to unknown module file");
9079 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9080 }
9081}
9082
9084 if (!M)
9085 return 1;
9086
9087 // For a file representing a module, use the submodule ID of the top-level
9088 // module as the file ID. For any other kind of file, the number of such
9089 // files loaded beforehand will be the same on reload.
9090 // FIXME: Is this true even if we have an explicit module file and a PCH?
9091 if (M->isModule())
9092 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9093
9094 auto PCHModules = getModuleManager().pch_modules();
9095 auto I = llvm::find(PCHModules, M);
9096 assert(I != PCHModules.end() && "emitting reference to unknown file");
9097 return (I - PCHModules.end()) << 1;
9098}
9099
9100std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9101 if (Module *M = getSubmodule(ID))
9102 return ASTSourceDescriptor(*M);
9103
9104 // If there is only a single PCH, return it instead.
9105 // Chained PCH are not supported.
9106 const auto &PCHChain = ModuleMgr.pch_modules();
9107 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9108 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9109 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9110 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9111 return ASTSourceDescriptor(ModuleName,
9112 llvm::sys::path::parent_path(MF.FileName),
9113 FileName, MF.Signature);
9114 }
9115 return std::nullopt;
9116}
9117
9119 auto I = DefinitionSource.find(FD);
9120 if (I == DefinitionSource.end())
9121 return EK_ReplyHazy;
9122 return I->second ? EK_Never : EK_Always;
9123}
9124
9126 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9127}
9128
9130 if (ID == 0)
9131 return Selector();
9132
9133 if (ID > SelectorsLoaded.size()) {
9134 Error("selector ID out of range in AST file");
9135 return Selector();
9136 }
9137
9138 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9139 // Load this selector from the selector table.
9140 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9141 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9142 ModuleFile &M = *I->second;
9143 ASTSelectorLookupTrait Trait(*this, M);
9144 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9145 SelectorsLoaded[ID - 1] =
9146 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9147 if (DeserializationListener)
9148 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9149 }
9150
9151 return SelectorsLoaded[ID - 1];
9152}
9153
9155 return DecodeSelector(ID);
9156}
9157
9159 // ID 0 (the null selector) is considered an external selector.
9160 return getTotalNumSelectors() + 1;
9161}
9162
9164ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9165 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9166 return LocalID;
9167
9168 if (!M.ModuleOffsetMap.empty())
9169 ReadModuleOffsetMap(M);
9170
9173 assert(I != M.SelectorRemap.end()
9174 && "Invalid index into selector index remap");
9175
9176 return LocalID + I->second;
9177}
9178
9181 switch (Name.getNameKind()) {
9186
9189
9193
9200 break;
9201 }
9202 return DeclarationNameLoc();
9203}
9204
9206 DeclarationNameInfo NameInfo;
9207 NameInfo.setName(readDeclarationName());
9208 NameInfo.setLoc(readSourceLocation());
9209 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9210 return NameInfo;
9211}
9212
9214 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9215}
9216
9219 unsigned NumTPLists = readInt();
9220 Info.NumTemplParamLists = NumTPLists;
9221 if (NumTPLists) {
9222 Info.TemplParamLists =
9223 new (getContext()) TemplateParameterList *[NumTPLists];
9224 for (unsigned i = 0; i != NumTPLists; ++i)
9226 }
9227}
9228
9231 SourceLocation TemplateLoc = readSourceLocation();
9232 SourceLocation LAngleLoc = readSourceLocation();
9233 SourceLocation RAngleLoc = readSourceLocation();
9234
9235 unsigned NumParams = readInt();
9237 Params.reserve(NumParams);
9238 while (NumParams--)
9239 Params.push_back(readDeclAs<NamedDecl>());
9240
9241 bool HasRequiresClause = readBool();
9242 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9243
9245 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9246 return TemplateParams;
9247}
9248
9251 bool Canonicalize) {
9252 unsigned NumTemplateArgs = readInt();
9253 TemplArgs.reserve(NumTemplateArgs);
9254 while (NumTemplateArgs--)
9255 TemplArgs.push_back(readTemplateArgument(Canonicalize));
9256}
9257
9258/// Read a UnresolvedSet structure.
9260 unsigned NumDecls = readInt();
9261 Set.reserve(getContext(), NumDecls);
9262 while (NumDecls--) {
9263 GlobalDeclID ID = readDeclID();
9265 Set.addLazyDecl(getContext(), ID, AS);
9266 }
9267}
9268
9271 bool isVirtual = readBool();
9272 bool isBaseOfClass = readBool();
9273 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9274 bool inheritConstructors = readBool();
9277 SourceLocation EllipsisLoc = readSourceLocation();
9278 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9279 EllipsisLoc);
9280 Result.setInheritConstructors(inheritConstructors);
9281 return Result;
9282}
9283
9286 ASTContext &Context = getContext();
9287 unsigned NumInitializers = readInt();
9288 assert(NumInitializers && "wrote ctor initializers but have no inits");
9289 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9290 for (unsigned i = 0; i != NumInitializers; ++i) {
9291 TypeSourceInfo *TInfo = nullptr;
9292 bool IsBaseVirtual = false;
9293 FieldDecl *Member = nullptr;
9294 IndirectFieldDecl *IndirectMember = nullptr;
9295
9297 switch (Type) {
9299 TInfo = readTypeSourceInfo();
9300 IsBaseVirtual = readBool();
9301 break;
9302
9304 TInfo = readTypeSourceInfo();
9305 break;
9306
9308 Member = readDeclAs<FieldDecl>();
9309 break;
9310
9312 IndirectMember = readDeclAs<IndirectFieldDecl>();
9313 break;
9314 }
9315
9316 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9317 Expr *Init = readExpr();
9318 SourceLocation LParenLoc = readSourceLocation();
9319 SourceLocation RParenLoc = readSourceLocation();
9320
9321 CXXCtorInitializer *BOMInit;
9323 BOMInit = new (Context)
9324 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9325 RParenLoc, MemberOrEllipsisLoc);
9327 BOMInit = new (Context)
9328 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9329 else if (Member)
9330 BOMInit = new (Context)
9331 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9332 Init, RParenLoc);
9333 else
9334 BOMInit = new (Context)
9335 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9336 LParenLoc, Init, RParenLoc);
9337
9338 if (/*IsWritten*/readBool()) {
9339 unsigned SourceOrder = readInt();
9340 BOMInit->setSourceOrder(SourceOrder);
9341 }
9342
9343 CtorInitializers[i] = BOMInit;
9344 }
9345
9346 return CtorInitializers;
9347}
9348
9351 ASTContext &Context = getContext();
9352 unsigned N = readInt();
9354 for (unsigned I = 0; I != N; ++I) {
9355 auto Kind = readNestedNameSpecifierKind();
9356 switch (Kind) {
9360 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9361 break;
9362 }
9363
9365 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9367 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9368 break;
9369 }
9370
9372 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9374 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9375 break;
9376 }
9377
9380 bool Template = readBool();
9382 if (!T)
9383 return NestedNameSpecifierLoc();
9384 SourceLocation ColonColonLoc = readSourceLocation();
9385
9386 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9387 Builder.Extend(Context,
9388 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9389 T->getTypeLoc(), ColonColonLoc);
9390 break;
9391 }
9392
9394 SourceLocation ColonColonLoc = readSourceLocation();
9395 Builder.MakeGlobal(Context, ColonColonLoc);
9396 break;
9397 }
9398
9400 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9402 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9403 break;
9404 }
9405 }
9406 }
9407
9408 return Builder.getWithLocInContext(Context);
9409}
9410
9412 unsigned &Idx, LocSeq *Seq) {
9415 return SourceRange(beg, end);
9416}
9417
9419 const StringRef Blob) {
9420 unsigned Count = Record[0];
9421 const char *Byte = Blob.data();
9422 llvm::BitVector Ret = llvm::BitVector(Count, false);
9423 for (unsigned I = 0; I < Count; ++Byte)
9424 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9425 if (*Byte & (1 << Bit))
9426 Ret[I] = true;
9427 return Ret;
9428}
9429
9430/// Read a floating-point value
9431llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9432 return llvm::APFloat(Sem, readAPInt());
9433}
9434
9435// Read a string
9436std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9437 unsigned Len = Record[Idx++];
9438 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9439 Idx += Len;
9440 return Result;
9441}
9442
9444 unsigned &Idx) {
9445 std::string Filename = ReadString(Record, Idx);
9447 return Filename;
9448}
9449
9450std::string ASTReader::ReadPath(StringRef BaseDirectory,
9451 const RecordData &Record, unsigned &Idx) {
9452 std::string Filename = ReadString(Record, Idx);
9453 if (!BaseDirectory.empty())
9454 ResolveImportedPath(Filename, BaseDirectory);
9455 return Filename;
9456}
9457
9459 unsigned &Idx) {
9460 unsigned Major = Record[Idx++];
9461 unsigned Minor = Record[Idx++];
9462 unsigned Subminor = Record[Idx++];
9463 if (Minor == 0)
9464 return VersionTuple(Major);
9465 if (Subminor == 0)
9466 return VersionTuple(Major, Minor - 1);
9467 return VersionTuple(Major, Minor - 1, Subminor - 1);
9468}
9469
9471 const RecordData &Record,
9472 unsigned &Idx) {
9473 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9475}
9476
9477DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9478 return Diag(CurrentImportLoc, DiagID);
9479}
9480
9482 return Diags.Report(Loc, DiagID);
9483}
9484
9486 // When Sema is available, avoid duplicate errors.
9487 if (SemaObj) {
9488 SemaObj->warnStackExhausted(Loc);
9489 return;
9490 }
9491
9492 if (WarnedStackExhausted)
9493 return;
9494 WarnedStackExhausted = true;
9495
9496 Diag(Loc, diag::warn_stack_exhausted);
9497}
9498
9499/// Retrieve the identifier table associated with the
9500/// preprocessor.
9502 return PP.getIdentifierTable();
9503}
9504
9505/// Record that the given ID maps to the given switch-case
9506/// statement.
9508 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9509 "Already have a SwitchCase with this ID");
9510 (*CurrSwitchCaseStmts)[ID] = SC;
9511}
9512
9513/// Retrieve the switch-case statement with the given ID.
9515 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9516 return (*CurrSwitchCaseStmts)[ID];
9517}
9518
9520 CurrSwitchCaseStmts->clear();
9521}
9522
9524 ASTContext &Context = getContext();
9525 std::vector<RawComment *> Comments;
9526 for (SmallVectorImpl<std::pair<BitstreamCursor,
9527 serialization::ModuleFile *>>::iterator
9528 I = CommentsCursors.begin(),
9529 E = CommentsCursors.end();
9530 I != E; ++I) {
9531 Comments.clear();
9532 BitstreamCursor &Cursor = I->first;
9533 serialization::ModuleFile &F = *I->second;
9534 SavedStreamPosition SavedPosition(Cursor);
9535
9537 while (true) {
9539 Cursor.advanceSkippingSubblocks(
9540 BitstreamCursor::AF_DontPopBlockAtEnd);
9541 if (!MaybeEntry) {
9542 Error(MaybeEntry.takeError());
9543 return;
9544 }
9545 llvm::BitstreamEntry Entry = MaybeEntry.get();
9546
9547 switch (Entry.Kind) {
9548 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9549 case llvm::BitstreamEntry::Error:
9550 Error("malformed block record in AST file");
9551 return;
9552 case llvm::BitstreamEntry::EndBlock:
9553 goto NextCursor;
9554 case llvm::BitstreamEntry::Record:
9555 // The interesting case.
9556 break;
9557 }
9558
9559 // Read a record.
9560 Record.clear();
9561 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9562 if (!MaybeComment) {
9563 Error(MaybeComment.takeError());
9564 return;
9565 }
9566 switch ((CommentRecordTypes)MaybeComment.get()) {
9567 case COMMENTS_RAW_COMMENT: {
9568 unsigned Idx = 0;
9569 SourceRange SR = ReadSourceRange(F, Record, Idx);
9572 bool IsTrailingComment = Record[Idx++];
9573 bool IsAlmostTrailingComment = Record[Idx++];
9574 Comments.push_back(new (Context) RawComment(
9575 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9576 break;
9577 }
9578 }
9579 }
9580 NextCursor:
9581 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9582 FileToOffsetToComment;
9583 for (RawComment *C : Comments) {
9584 SourceLocation CommentLoc = C->getBeginLoc();
9585 if (CommentLoc.isValid()) {
9586 std::pair<FileID, unsigned> Loc =
9587 SourceMgr.getDecomposedLoc(CommentLoc);
9588 if (Loc.first.isValid())
9589 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9590 }
9591 }
9592 }
9593}
9594
9596 serialization::ModuleFile &MF, bool IncludeSystem,
9597 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9598 bool IsSystem)>
9599 Visitor) {
9600 unsigned NumUserInputs = MF.NumUserInputFiles;
9601 unsigned NumInputs = MF.InputFilesLoaded.size();
9602 assert(NumUserInputs <= NumInputs);
9603 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9604 for (unsigned I = 0; I < N; ++I) {
9605 bool IsSystem = I >= NumUserInputs;
9606 InputFileInfo IFI = getInputFileInfo(MF, I+1);
9607 Visitor(IFI, IsSystem);
9608 }
9609}
9610
9612 bool IncludeSystem, bool Complain,
9613 llvm::function_ref<void(const serialization::InputFile &IF,
9614 bool isSystem)> Visitor) {
9615 unsigned NumUserInputs = MF.NumUserInputFiles;
9616 unsigned NumInputs = MF.InputFilesLoaded.size();
9617 assert(NumUserInputs <= NumInputs);
9618 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9619 for (unsigned I = 0; I < N; ++I) {
9620 bool IsSystem = I >= NumUserInputs;
9621 InputFile IF = getInputFile(MF, I+1, Complain);
9622 Visitor(IF, IsSystem);
9623 }
9624}
9625
9628 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9629 unsigned NumInputs = MF.InputFilesLoaded.size();
9630 for (unsigned I = 0; I < NumInputs; ++I) {
9631 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9632 if (IFI.TopLevel && IFI.ModuleMap)
9633 if (auto FE = getInputFile(MF, I + 1).getFile())
9634 Visitor(*FE);
9635 }
9636}
9637
9638void ASTReader::finishPendingActions() {
9639 while (
9640 !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9641 !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9642 !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9643 !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9644 !PendingObjCExtensionIvarRedeclarations.empty()) {
9645 // If any identifiers with corresponding top-level declarations have
9646 // been loaded, load those declarations now.
9647 using TopLevelDeclsMap =
9648 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9649 TopLevelDeclsMap TopLevelDecls;
9650
9651 while (!PendingIdentifierInfos.empty()) {
9652 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9654 std::move(PendingIdentifierInfos.back().second);
9655 PendingIdentifierInfos.pop_back();
9656
9657 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9658 }
9659
9660 // Load each function type that we deferred loading because it was a
9661 // deduced type that might refer to a local type declared within itself.
9662 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9663 auto *FD = PendingDeducedFunctionTypes[I].first;
9664 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9665
9666 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
9667 // If we gave a function a deduced return type, remember that we need to
9668 // propagate that along the redeclaration chain.
9669 if (DT->isDeduced()) {
9670 PendingDeducedTypeUpdates.insert(
9671 {FD->getCanonicalDecl(), FD->getReturnType()});
9672 continue;
9673 }
9674
9675 // The function has undeduced DeduceType return type. We hope we can
9676 // find the deduced type by iterating the redecls in other modules
9677 // later.
9678 PendingUndeducedFunctionDecls.push_back(FD);
9679 continue;
9680 }
9681 }
9682 PendingDeducedFunctionTypes.clear();
9683
9684 // Load each variable type that we deferred loading because it was a
9685 // deduced type that might refer to a local type declared within itself.
9686 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9687 auto *VD = PendingDeducedVarTypes[I].first;
9688 VD->setType(GetType(PendingDeducedVarTypes[I].second));
9689 }
9690 PendingDeducedVarTypes.clear();
9691
9692 // For each decl chain that we wanted to complete while deserializing, mark
9693 // it as "still needs to be completed".
9694 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9695 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9696 }
9697 PendingIncompleteDeclChains.clear();
9698
9699 // Load pending declaration chains.
9700 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9701 loadPendingDeclChain(PendingDeclChains[I].first,
9702 PendingDeclChains[I].second);
9703 PendingDeclChains.clear();
9704
9705 // Make the most recent of the top-level declarations visible.
9706 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9707 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9708 IdentifierInfo *II = TLD->first;
9709 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9710 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9711 }
9712 }
9713
9714 // Load any pending macro definitions.
9715 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9716 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9718 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9719 // Initialize the macro history from chained-PCHs ahead of module imports.
9720 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9721 ++IDIdx) {
9722 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9723 if (!Info.M->isModule())
9724 resolvePendingMacro(II, Info);
9725 }
9726 // Handle module imports.
9727 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9728 ++IDIdx) {
9729 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9730 if (Info.M->isModule())
9731 resolvePendingMacro(II, Info);
9732 }
9733 }
9734 PendingMacroIDs.clear();
9735
9736 // Wire up the DeclContexts for Decls that we delayed setting until
9737 // recursive loading is completed.
9738 while (!PendingDeclContextInfos.empty()) {
9739 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9740 PendingDeclContextInfos.pop_front();
9741 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9742 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9743 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9744 }
9745
9746 // Perform any pending declaration updates.
9747 while (!PendingUpdateRecords.empty()) {
9748 auto Update = PendingUpdateRecords.pop_back_val();
9749 ReadingKindTracker ReadingKind(Read_Decl, *this);
9750 loadDeclUpdateRecords(Update);
9751 }
9752
9753 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9754 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9755 auto DuplicateIvars =
9756 PendingObjCExtensionIvarRedeclarations.back().second;
9757 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9759 ExtensionsPair.first->getASTContext(),
9760 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9761 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9762 /*Complain =*/false,
9763 /*ErrorOnTagTypeMismatch =*/true);
9764 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9765 // Merge redeclared ivars with their predecessors.
9766 for (auto IvarPair : DuplicateIvars) {
9767 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9768 // Change semantic DeclContext but keep the lexical one.
9769 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9770 Ivar->getLexicalDeclContext(),
9771 getContext());
9772 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9773 }
9774 // Invalidate duplicate extension and the cached ivar list.
9775 ExtensionsPair.first->setInvalidDecl();
9776 ExtensionsPair.second->getClassInterface()
9777 ->getDefinition()
9778 ->setIvarList(nullptr);
9779 } else {
9780 for (auto IvarPair : DuplicateIvars) {
9781 Diag(IvarPair.first->getLocation(),
9782 diag::err_duplicate_ivar_declaration)
9783 << IvarPair.first->getIdentifier();
9784 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9785 }
9786 }
9787 PendingObjCExtensionIvarRedeclarations.pop_back();
9788 }
9789 }
9790
9791 // At this point, all update records for loaded decls are in place, so any
9792 // fake class definitions should have become real.
9793 assert(PendingFakeDefinitionData.empty() &&
9794 "faked up a class definition but never saw the real one");
9795
9796 // If we deserialized any C++ or Objective-C class definitions, any
9797 // Objective-C protocol definitions, or any redeclarable templates, make sure
9798 // that all redeclarations point to the definitions. Note that this can only
9799 // happen now, after the redeclaration chains have been fully wired.
9800 for (Decl *D : PendingDefinitions) {
9801 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9802 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9803 // Make sure that the TagType points at the definition.
9804 const_cast<TagType*>(TagT)->decl = TD;
9805 }
9806
9807 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9808 for (auto *R = getMostRecentExistingDecl(RD); R;
9809 R = R->getPreviousDecl()) {
9810 assert((R == D) ==
9811 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9812 "declaration thinks it's the definition but it isn't");
9813 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9814 }
9815 }
9816
9817 continue;
9818 }
9819
9820 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9821 // Make sure that the ObjCInterfaceType points at the definition.
9822 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9823 ->Decl = ID;
9824
9825 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9826 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9827
9828 continue;
9829 }
9830
9831 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9832 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9833 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9834
9835 continue;
9836 }
9837
9838 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9839 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9840 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9841 }
9842 PendingDefinitions.clear();
9843
9844 // Load the bodies of any functions or methods we've encountered. We do
9845 // this now (delayed) so that we can be sure that the declaration chains
9846 // have been fully wired up (hasBody relies on this).
9847 // FIXME: We shouldn't require complete redeclaration chains here.
9848 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9849 PBEnd = PendingBodies.end();
9850 PB != PBEnd; ++PB) {
9851 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9852 // For a function defined inline within a class template, force the
9853 // canonical definition to be the one inside the canonical definition of
9854 // the template. This ensures that we instantiate from a correct view
9855 // of the template.
9856 //
9857 // Sadly we can't do this more generally: we can't be sure that all
9858 // copies of an arbitrary class definition will have the same members
9859 // defined (eg, some member functions may not be instantiated, and some
9860 // special members may or may not have been implicitly defined).
9861 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9862 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9863 continue;
9864
9865 // FIXME: Check for =delete/=default?
9866 const FunctionDecl *Defn = nullptr;
9867 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9868 FD->setLazyBody(PB->second);
9869 } else {
9870 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9871 mergeDefinitionVisibility(NonConstDefn, FD);
9872
9873 if (!FD->isLateTemplateParsed() &&
9874 !NonConstDefn->isLateTemplateParsed() &&
9875 // We only perform ODR checks for decls not in the explicit
9876 // global module fragment.
9877 !shouldSkipCheckingODR(FD) &&
9878 !shouldSkipCheckingODR(NonConstDefn) &&
9879 FD->getODRHash() != NonConstDefn->getODRHash()) {
9880 if (!isa<CXXMethodDecl>(FD)) {
9881 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9882 } else if (FD->getLexicalParent()->isFileContext() &&
9883 NonConstDefn->getLexicalParent()->isFileContext()) {
9884 // Only diagnose out-of-line method definitions. If they are
9885 // in class definitions, then an error will be generated when
9886 // processing the class bodies.
9887 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9888 }
9889 }
9890 }
9891 continue;
9892 }
9893
9894 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9895 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9896 MD->setLazyBody(PB->second);
9897 }
9898 PendingBodies.clear();
9899
9900 // Inform any classes that had members added that they now have more members.
9901 for (auto [RD, MD] : PendingAddedClassMembers) {
9902 RD->addedMember(MD);
9903 }
9904 PendingAddedClassMembers.clear();
9905
9906 // Do some cleanup.
9907 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9909 PendingMergedDefinitionsToDeduplicate.clear();
9910}
9911
9912void ASTReader::diagnoseOdrViolations() {
9913 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9914 PendingRecordOdrMergeFailures.empty() &&
9915 PendingFunctionOdrMergeFailures.empty() &&
9916 PendingEnumOdrMergeFailures.empty() &&
9917 PendingObjCInterfaceOdrMergeFailures.empty() &&
9918 PendingObjCProtocolOdrMergeFailures.empty())
9919 return;
9920
9921 // Trigger the import of the full definition of each class that had any
9922 // odr-merging problems, so we can produce better diagnostics for them.
9923 // These updates may in turn find and diagnose some ODR failures, so take
9924 // ownership of the set first.
9925 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9926 PendingOdrMergeFailures.clear();
9927 for (auto &Merge : OdrMergeFailures) {
9928 Merge.first->buildLookup();
9929 Merge.first->decls_begin();
9930 Merge.first->bases_begin();
9931 Merge.first->vbases_begin();
9932 for (auto &RecordPair : Merge.second) {
9933 auto *RD = RecordPair.first;
9934 RD->decls_begin();
9935 RD->bases_begin();
9936 RD->vbases_begin();
9937 }
9938 }
9939
9940 // Trigger the import of the full definition of each record in C/ObjC.
9941 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9942 PendingRecordOdrMergeFailures.clear();
9943 for (auto &Merge : RecordOdrMergeFailures) {
9944 Merge.first->decls_begin();
9945 for (auto &D : Merge.second)
9946 D->decls_begin();
9947 }
9948
9949 // Trigger the import of the full interface definition.
9950 auto ObjCInterfaceOdrMergeFailures =
9951 std::move(PendingObjCInterfaceOdrMergeFailures);
9952 PendingObjCInterfaceOdrMergeFailures.clear();
9953 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9954 Merge.first->decls_begin();
9955 for (auto &InterfacePair : Merge.second)
9956 InterfacePair.first->decls_begin();
9957 }
9958
9959 // Trigger the import of functions.
9960 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9961 PendingFunctionOdrMergeFailures.clear();
9962 for (auto &Merge : FunctionOdrMergeFailures) {
9963 Merge.first->buildLookup();
9964 Merge.first->decls_begin();
9965 Merge.first->getBody();
9966 for (auto &FD : Merge.second) {
9967 FD->buildLookup();
9968 FD->decls_begin();
9969 FD->getBody();
9970 }
9971 }
9972
9973 // Trigger the import of enums.
9974 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9975 PendingEnumOdrMergeFailures.clear();
9976 for (auto &Merge : EnumOdrMergeFailures) {
9977 Merge.first->decls_begin();
9978 for (auto &Enum : Merge.second) {
9979 Enum->decls_begin();
9980 }
9981 }
9982
9983 // Trigger the import of the full protocol definition.
9984 auto ObjCProtocolOdrMergeFailures =
9985 std::move(PendingObjCProtocolOdrMergeFailures);
9986 PendingObjCProtocolOdrMergeFailures.clear();
9987 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9988 Merge.first->decls_begin();
9989 for (auto &ProtocolPair : Merge.second)
9990 ProtocolPair.first->decls_begin();
9991 }
9992
9993 // For each declaration from a merged context, check that the canonical
9994 // definition of that context also contains a declaration of the same
9995 // entity.
9996 //
9997 // Caution: this loop does things that might invalidate iterators into
9998 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9999 while (!PendingOdrMergeChecks.empty()) {
10000 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10001
10002 // FIXME: Skip over implicit declarations for now. This matters for things
10003 // like implicitly-declared special member functions. This isn't entirely
10004 // correct; we can end up with multiple unmerged declarations of the same
10005 // implicit entity.
10006 if (D->isImplicit())
10007 continue;
10008
10009 DeclContext *CanonDef = D->getDeclContext();
10010
10011 bool Found = false;
10012 const Decl *DCanon = D->getCanonicalDecl();
10013
10014 for (auto *RI : D->redecls()) {
10015 if (RI->getLexicalDeclContext() == CanonDef) {
10016 Found = true;
10017 break;
10018 }
10019 }
10020 if (Found)
10021 continue;
10022
10023 // Quick check failed, time to do the slow thing. Note, we can't just
10024 // look up the name of D in CanonDef here, because the member that is
10025 // in CanonDef might not be found by name lookup (it might have been
10026 // replaced by a more recent declaration in the lookup table), and we
10027 // can't necessarily find it in the redeclaration chain because it might
10028 // be merely mergeable, not redeclarable.
10030 for (auto *CanonMember : CanonDef->decls()) {
10031 if (CanonMember->getCanonicalDecl() == DCanon) {
10032 // This can happen if the declaration is merely mergeable and not
10033 // actually redeclarable (we looked for redeclarations earlier).
10034 //
10035 // FIXME: We should be able to detect this more efficiently, without
10036 // pulling in all of the members of CanonDef.
10037 Found = true;
10038 break;
10039 }
10040 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10041 if (ND->getDeclName() == D->getDeclName())
10042 Candidates.push_back(ND);
10043 }
10044
10045 if (!Found) {
10046 // The AST doesn't like TagDecls becoming invalid after they've been
10047 // completed. We only really need to mark FieldDecls as invalid here.
10048 if (!isa<TagDecl>(D))
10049 D->setInvalidDecl();
10050
10051 // Ensure we don't accidentally recursively enter deserialization while
10052 // we're producing our diagnostic.
10053 Deserializing RecursionGuard(this);
10054
10055 std::string CanonDefModule =
10057 cast<Decl>(CanonDef));
10058 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10060 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10061
10062 if (Candidates.empty())
10063 Diag(cast<Decl>(CanonDef)->getLocation(),
10064 diag::note_module_odr_violation_no_possible_decls) << D;
10065 else {
10066 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10067 Diag(Candidates[I]->getLocation(),
10068 diag::note_module_odr_violation_possible_decl)
10069 << Candidates[I];
10070 }
10071
10072 DiagnosedOdrMergeFailures.insert(CanonDef);
10073 }
10074 }
10075
10076 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10077 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10078 ObjCInterfaceOdrMergeFailures.empty() &&
10079 ObjCProtocolOdrMergeFailures.empty())
10080 return;
10081
10082 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10083 getPreprocessor().getLangOpts());
10084
10085 // Issue any pending ODR-failure diagnostics.
10086 for (auto &Merge : OdrMergeFailures) {
10087 // If we've already pointed out a specific problem with this class, don't
10088 // bother issuing a general "something's different" diagnostic.
10089 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10090 continue;
10091
10092 bool Diagnosed = false;
10093 CXXRecordDecl *FirstRecord = Merge.first;
10094 for (auto &RecordPair : Merge.second) {
10095 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10096 RecordPair.second)) {
10097 Diagnosed = true;
10098 break;
10099 }
10100 }
10101
10102 if (!Diagnosed) {
10103 // All definitions are updates to the same declaration. This happens if a
10104 // module instantiates the declaration of a class template specialization
10105 // and two or more other modules instantiate its definition.
10106 //
10107 // FIXME: Indicate which modules had instantiations of this definition.
10108 // FIXME: How can this even happen?
10109 Diag(Merge.first->getLocation(),
10110 diag::err_module_odr_violation_different_instantiations)
10111 << Merge.first;
10112 }
10113 }
10114
10115 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10116 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10117 for (auto &Merge : RecordOdrMergeFailures) {
10118 // If we've already pointed out a specific problem with this class, don't
10119 // bother issuing a general "something's different" diagnostic.
10120 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10121 continue;
10122
10123 RecordDecl *FirstRecord = Merge.first;
10124 bool Diagnosed = false;
10125 for (auto *SecondRecord : Merge.second) {
10126 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10127 Diagnosed = true;
10128 break;
10129 }
10130 }
10131 (void)Diagnosed;
10132 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10133 }
10134
10135 // Issue ODR failures diagnostics for functions.
10136 for (auto &Merge : FunctionOdrMergeFailures) {
10137 FunctionDecl *FirstFunction = Merge.first;
10138 bool Diagnosed = false;
10139 for (auto &SecondFunction : Merge.second) {
10140 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10141 Diagnosed = true;
10142 break;
10143 }
10144 }
10145 (void)Diagnosed;
10146 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10147 }
10148
10149 // Issue ODR failures diagnostics for enums.
10150 for (auto &Merge : EnumOdrMergeFailures) {
10151 // If we've already pointed out a specific problem with this enum, don't
10152 // bother issuing a general "something's different" diagnostic.
10153 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10154 continue;
10155
10156 EnumDecl *FirstEnum = Merge.first;
10157 bool Diagnosed = false;
10158 for (auto &SecondEnum : Merge.second) {
10159 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10160 Diagnosed = true;
10161 break;
10162 }
10163 }
10164 (void)Diagnosed;
10165 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10166 }
10167
10168 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10169 // If we've already pointed out a specific problem with this interface,
10170 // don't bother issuing a general "something's different" diagnostic.
10171 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10172 continue;
10173
10174 bool Diagnosed = false;
10175 ObjCInterfaceDecl *FirstID = Merge.first;
10176 for (auto &InterfacePair : Merge.second) {
10177 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10178 InterfacePair.second)) {
10179 Diagnosed = true;
10180 break;
10181 }
10182 }
10183 (void)Diagnosed;
10184 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10185 }
10186
10187 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10188 // If we've already pointed out a specific problem with this protocol,
10189 // don't bother issuing a general "something's different" diagnostic.
10190 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10191 continue;
10192
10193 ObjCProtocolDecl *FirstProtocol = Merge.first;
10194 bool Diagnosed = false;
10195 for (auto &ProtocolPair : Merge.second) {
10196 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10197 ProtocolPair.second)) {
10198 Diagnosed = true;
10199 break;
10200 }
10201 }
10202 (void)Diagnosed;
10203 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10204 }
10205}
10206
10208 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10209 ReadTimer->startTimer();
10210}
10211
10213 assert(NumCurrentElementsDeserializing &&
10214 "FinishedDeserializing not paired with StartedDeserializing");
10215 if (NumCurrentElementsDeserializing == 1) {
10216 // We decrease NumCurrentElementsDeserializing only after pending actions
10217 // are finished, to avoid recursively re-calling finishPendingActions().
10218 finishPendingActions();
10219 }
10220 --NumCurrentElementsDeserializing;
10221
10222 if (NumCurrentElementsDeserializing == 0) {
10223 // Propagate exception specification and deduced type updates along
10224 // redeclaration chains.
10225 //
10226 // We do this now rather than in finishPendingActions because we want to
10227 // be able to walk the complete redeclaration chains of the updated decls.
10228 while (!PendingExceptionSpecUpdates.empty() ||
10229 !PendingDeducedTypeUpdates.empty()) {
10230 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10231 PendingExceptionSpecUpdates.clear();
10232 for (auto Update : ESUpdates) {
10233 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10234 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10235 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10236 if (auto *Listener = getContext().getASTMutationListener())
10237 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10238 for (auto *Redecl : Update.second->redecls())
10239 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10240 }
10241
10242 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10243 PendingDeducedTypeUpdates.clear();
10244 for (auto Update : DTUpdates) {
10245 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10246 // FIXME: If the return type is already deduced, check that it matches.
10248 Update.second);
10249 }
10250
10251 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10252 PendingUndeducedFunctionDecls.clear();
10253 // We hope we can find the deduced type for the functions by iterating
10254 // redeclarations in other modules.
10255 for (FunctionDecl *UndeducedFD : UDTUpdates)
10256 (void)UndeducedFD->getMostRecentDecl();
10257 }
10258
10259 if (ReadTimer)
10260 ReadTimer->stopTimer();
10261
10262 diagnoseOdrViolations();
10263
10264 // We are not in recursive loading, so it's safe to pass the "interesting"
10265 // decls to the consumer.
10266 if (Consumer)
10267 PassInterestingDeclsToConsumer();
10268 }
10269}
10270
10271void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10272 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10273 // Remove any fake results before adding any real ones.
10274 auto It = PendingFakeLookupResults.find(II);
10275 if (It != PendingFakeLookupResults.end()) {
10276 for (auto *ND : It->second)
10277 SemaObj->IdResolver.RemoveDecl(ND);
10278 // FIXME: this works around module+PCH performance issue.
10279 // Rather than erase the result from the map, which is O(n), just clear
10280 // the vector of NamedDecls.
10281 It->second.clear();
10282 }
10283 }
10284
10285 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10286 SemaObj->TUScope->AddDecl(D);
10287 } else if (SemaObj->TUScope) {
10288 // Adding the decl to IdResolver may have failed because it was already in
10289 // (even though it was not added in scope). If it is already in, make sure
10290 // it gets in the scope as well.
10291 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10292 SemaObj->TUScope->AddDecl(D);
10293 }
10294}
10295
10297 ASTContext *Context,
10298 const PCHContainerReader &PCHContainerRdr,
10299 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10300 StringRef isysroot,
10301 DisableValidationForModuleKind DisableValidationKind,
10302 bool AllowASTWithCompilerErrors,
10303 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10304 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10305 std::unique_ptr<llvm::Timer> ReadTimer)
10306 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10308 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10309 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10310 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10311 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10312 PCHContainerRdr, PP.getHeaderSearchInfo()),
10313 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10314 DisableValidationKind(DisableValidationKind),
10315 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10316 AllowConfigurationMismatch(AllowConfigurationMismatch),
10317 ValidateSystemInputs(ValidateSystemInputs),
10318 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10319 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10320 SourceMgr.setExternalSLocEntrySource(this);
10321
10322 for (const auto &Ext : Extensions) {
10323 auto BlockName = Ext->getExtensionMetadata().BlockName;
10324 auto Known = ModuleFileExtensions.find(BlockName);
10325 if (Known != ModuleFileExtensions.end()) {
10326 Diags.Report(diag::warn_duplicate_module_file_extension)
10327 << BlockName;
10328 continue;
10329 }
10330
10331 ModuleFileExtensions.insert({BlockName, Ext});
10332 }
10333}
10334
10336 if (OwnsDeserializationListener)
10337 delete DeserializationListener;
10338}
10339
10341 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10342}
10343
10345 unsigned AbbrevID) {
10346 Idx = 0;
10347 Record.clear();
10348 return Cursor.readRecord(AbbrevID, Record);
10349}
10350//===----------------------------------------------------------------------===//
10351//// OMPClauseReader implementation
10352////===----------------------------------------------------------------------===//
10353
10354// This has to be in namespace clang because it's friended by all
10355// of the OMP clauses.
10356namespace clang {
10357
10358class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10360 ASTContext &Context;
10361
10362public:
10364 : Record(Record), Context(Record.getContext()) {}
10365#define GEN_CLANG_CLAUSE_CLASS
10366#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10367#include "llvm/Frontend/OpenMP/OMP.inc"
10371};
10372
10373} // end namespace clang
10374
10376 return OMPClauseReader(*this).readClause();
10377}
10378
10380 OMPClause *C = nullptr;
10381 switch (llvm::omp::Clause(Record.readInt())) {
10382 case llvm::omp::OMPC_if:
10383 C = new (Context) OMPIfClause();
10384 break;
10385 case llvm::omp::OMPC_final:
10386 C = new (Context) OMPFinalClause();
10387 break;
10388 case llvm::omp::OMPC_num_threads:
10389 C = new (Context) OMPNumThreadsClause();
10390 break;
10391 case llvm::omp::OMPC_safelen:
10392 C = new (Context) OMPSafelenClause();
10393 break;
10394 case llvm::omp::OMPC_simdlen:
10395 C = new (Context) OMPSimdlenClause();
10396 break;
10397 case llvm::omp::OMPC_sizes: {
10398 unsigned NumSizes = Record.readInt();
10399 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10400 break;
10401 }
10402 case llvm::omp::OMPC_full:
10403 C = OMPFullClause::CreateEmpty(Context);
10404 break;
10405 case llvm::omp::OMPC_partial:
10407 break;
10408 case llvm::omp::OMPC_allocator:
10409 C = new (Context) OMPAllocatorClause();
10410 break;
10411 case llvm::omp::OMPC_collapse:
10412 C = new (Context) OMPCollapseClause();
10413 break;
10414 case llvm::omp::OMPC_default:
10415 C = new (Context) OMPDefaultClause();
10416 break;
10417 case llvm::omp::OMPC_proc_bind:
10418 C = new (Context) OMPProcBindClause();
10419 break;
10420 case llvm::omp::OMPC_schedule:
10421 C = new (Context) OMPScheduleClause();
10422 break;
10423 case llvm::omp::OMPC_ordered:
10424 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10425 break;
10426 case llvm::omp::OMPC_nowait:
10427 C = new (Context) OMPNowaitClause();
10428 break;
10429 case llvm::omp::OMPC_untied:
10430 C = new (Context) OMPUntiedClause();
10431 break;
10432 case llvm::omp::OMPC_mergeable:
10433 C = new (Context) OMPMergeableClause();
10434 break;
10435 case llvm::omp::OMPC_read:
10436 C = new (Context) OMPReadClause();
10437 break;
10438 case llvm::omp::OMPC_write:
10439 C = new (Context) OMPWriteClause();
10440 break;
10441 case llvm::omp::OMPC_update:
10442 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10443 break;
10444 case llvm::omp::OMPC_capture:
10445 C = new (Context) OMPCaptureClause();
10446 break;
10447 case llvm::omp::OMPC_compare:
10448 C = new (Context) OMPCompareClause();
10449 break;
10450 case llvm::omp::OMPC_fail:
10451 C = new (Context) OMPFailClause();
10452 break;
10453 case llvm::omp::OMPC_seq_cst:
10454 C = new (Context) OMPSeqCstClause();
10455 break;
10456 case llvm::omp::OMPC_acq_rel:
10457 C = new (Context) OMPAcqRelClause();
10458 break;
10459 case llvm::omp::OMPC_acquire:
10460 C = new (Context) OMPAcquireClause();
10461 break;
10462 case llvm::omp::OMPC_release:
10463 C = new (Context) OMPReleaseClause();
10464 break;
10465 case llvm::omp::OMPC_relaxed:
10466 C = new (Context) OMPRelaxedClause();
10467 break;
10468 case llvm::omp::OMPC_weak:
10469 C = new (Context) OMPWeakClause();
10470 break;
10471 case llvm::omp::OMPC_threads:
10472 C = new (Context) OMPThreadsClause();
10473 break;
10474 case llvm::omp::OMPC_simd:
10475 C = new (Context) OMPSIMDClause();
10476 break;
10477 case llvm::omp::OMPC_nogroup:
10478 C = new (Context) OMPNogroupClause();
10479 break;
10480 case llvm::omp::OMPC_unified_address:
10481 C = new (Context) OMPUnifiedAddressClause();
10482 break;
10483 case llvm::omp::OMPC_unified_shared_memory:
10484 C = new (Context) OMPUnifiedSharedMemoryClause();
10485 break;
10486 case llvm::omp::OMPC_reverse_offload:
10487 C = new (Context) OMPReverseOffloadClause();
10488 break;
10489 case llvm::omp::OMPC_dynamic_allocators:
10490 C = new (Context) OMPDynamicAllocatorsClause();
10491 break;
10492 case llvm::omp::OMPC_atomic_default_mem_order:
10493 C = new (Context) OMPAtomicDefaultMemOrderClause();
10494 break;
10495 case llvm::omp::OMPC_at:
10496 C = new (Context) OMPAtClause();
10497 break;
10498 case llvm::omp::OMPC_severity:
10499 C = new (Context) OMPSeverityClause();
10500 break;
10501 case llvm::omp::OMPC_message:
10502 C = new (Context) OMPMessageClause();
10503 break;
10504 case llvm::omp::OMPC_private:
10505 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10506 break;
10507 case llvm::omp::OMPC_firstprivate:
10508 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10509 break;
10510 case llvm::omp::OMPC_lastprivate:
10511 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10512 break;
10513 case llvm::omp::OMPC_shared:
10514 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10515 break;
10516 case llvm::omp::OMPC_reduction: {
10517 unsigned N = Record.readInt();
10518 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10519 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10520 break;
10521 }
10522 case llvm::omp::OMPC_task_reduction:
10523 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10524 break;
10525 case llvm::omp::OMPC_in_reduction:
10526 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10527 break;
10528 case llvm::omp::OMPC_linear:
10529 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10530 break;
10531 case llvm::omp::OMPC_aligned:
10532 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10533 break;
10534 case llvm::omp::OMPC_copyin:
10535 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10536 break;
10537 case llvm::omp::OMPC_copyprivate:
10538 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10539 break;
10540 case llvm::omp::OMPC_flush:
10541 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10542 break;
10543 case llvm::omp::OMPC_depobj:
10545 break;
10546 case llvm::omp::OMPC_depend: {
10547 unsigned NumVars = Record.readInt();
10548 unsigned NumLoops = Record.readInt();
10549 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10550 break;
10551 }
10552 case llvm::omp::OMPC_device:
10553 C = new (Context) OMPDeviceClause();
10554 break;
10555 case llvm::omp::OMPC_map: {
10557 Sizes.NumVars = Record.readInt();
10558 Sizes.NumUniqueDeclarations = Record.readInt();
10559 Sizes.NumComponentLists = Record.readInt();
10560 Sizes.NumComponents = Record.readInt();
10561 C = OMPMapClause::CreateEmpty(Context, Sizes);
10562 break;
10563 }
10564 case llvm::omp::OMPC_num_teams:
10565 C = new (Context) OMPNumTeamsClause();
10566 break;
10567 case llvm::omp::OMPC_thread_limit:
10568 C = new (Context) OMPThreadLimitClause();
10569 break;
10570 case llvm::omp::OMPC_priority:
10571 C = new (Context) OMPPriorityClause();
10572 break;
10573 case llvm::omp::OMPC_grainsize:
10574 C = new (Context) OMPGrainsizeClause();
10575 break;
10576 case llvm::omp::OMPC_num_tasks:
10577 C = new (Context) OMPNumTasksClause();
10578 break;
10579 case llvm::omp::OMPC_hint:
10580 C = new (Context) OMPHintClause();
10581 break;
10582 case llvm::omp::OMPC_dist_schedule:
10583 C = new (Context) OMPDistScheduleClause();
10584 break;
10585 case llvm::omp::OMPC_defaultmap:
10586 C = new (Context) OMPDefaultmapClause();
10587 break;
10588 case llvm::omp::OMPC_to: {
10590 Sizes.NumVars = Record.readInt();
10591 Sizes.NumUniqueDeclarations = Record.readInt();
10592 Sizes.NumComponentLists = Record.readInt();
10593 Sizes.NumComponents = Record.readInt();
10594 C = OMPToClause::CreateEmpty(Context, Sizes);
10595 break;
10596 }
10597 case llvm::omp::OMPC_from: {
10599 Sizes.NumVars = Record.readInt();
10600 Sizes.NumUniqueDeclarations = Record.readInt();
10601 Sizes.NumComponentLists = Record.readInt();
10602 Sizes.NumComponents = Record.readInt();
10603 C = OMPFromClause::CreateEmpty(Context, Sizes);
10604 break;
10605 }
10606 case llvm::omp::OMPC_use_device_ptr: {
10608 Sizes.NumVars = Record.readInt();
10609 Sizes.NumUniqueDeclarations = Record.readInt();
10610 Sizes.NumComponentLists = Record.readInt();
10611 Sizes.NumComponents = Record.readInt();
10612 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10613 break;
10614 }
10615 case llvm::omp::OMPC_use_device_addr: {
10617 Sizes.NumVars = Record.readInt();
10618 Sizes.NumUniqueDeclarations = Record.readInt();
10619 Sizes.NumComponentLists = Record.readInt();
10620 Sizes.NumComponents = Record.readInt();
10621 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10622 break;
10623 }
10624 case llvm::omp::OMPC_is_device_ptr: {
10626 Sizes.NumVars = Record.readInt();
10627 Sizes.NumUniqueDeclarations = Record.readInt();
10628 Sizes.NumComponentLists = Record.readInt();
10629 Sizes.NumComponents = Record.readInt();
10630 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10631 break;
10632 }
10633 case llvm::omp::OMPC_has_device_addr: {
10635 Sizes.NumVars = Record.readInt();
10636 Sizes.NumUniqueDeclarations = Record.readInt();
10637 Sizes.NumComponentLists = Record.readInt();
10638 Sizes.NumComponents = Record.readInt();
10639 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10640 break;
10641 }
10642 case llvm::omp::OMPC_allocate:
10643 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10644 break;
10645 case llvm::omp::OMPC_nontemporal:
10646 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10647 break;
10648 case llvm::omp::OMPC_inclusive:
10649 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10650 break;
10651 case llvm::omp::OMPC_exclusive:
10652 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10653 break;
10654 case llvm::omp::OMPC_order:
10655 C = new (Context) OMPOrderClause();
10656 break;
10657 case llvm::omp::OMPC_init:
10658 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10659 break;
10660 case llvm::omp::OMPC_use:
10661 C = new (Context) OMPUseClause();
10662 break;
10663 case llvm::omp::OMPC_destroy:
10664 C = new (Context) OMPDestroyClause();
10665 break;
10666 case llvm::omp::OMPC_novariants:
10667 C = new (Context) OMPNovariantsClause();
10668 break;
10669 case llvm::omp::OMPC_nocontext:
10670 C = new (Context) OMPNocontextClause();
10671 break;
10672 case llvm::omp::OMPC_detach:
10673 C = new (Context) OMPDetachClause();
10674 break;
10675 case llvm::omp::OMPC_uses_allocators:
10676 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10677 break;
10678 case llvm::omp::OMPC_affinity:
10679 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10680 break;
10681 case llvm::omp::OMPC_filter:
10682 C = new (Context) OMPFilterClause();
10683 break;
10684 case llvm::omp::OMPC_bind:
10685 C = OMPBindClause::CreateEmpty(Context);
10686 break;
10687 case llvm::omp::OMPC_align:
10688 C = new (Context) OMPAlignClause();
10689 break;
10690 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10691 C = new (Context) OMPXDynCGroupMemClause();
10692 break;
10693 case llvm::omp::OMPC_doacross: {
10694 unsigned NumVars = Record.readInt();
10695 unsigned NumLoops = Record.readInt();
10696 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10697 break;
10698 }
10699 case llvm::omp::OMPC_ompx_attribute:
10700 C = new (Context) OMPXAttributeClause();
10701 break;
10702 case llvm::omp::OMPC_ompx_bare:
10703 C = new (Context) OMPXBareClause();
10704 break;
10705#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10706 case llvm::omp::Enum: \
10707 break;
10708#include "llvm/Frontend/OpenMP/OMPKinds.def"
10709 default:
10710 break;
10711 }
10712 assert(C && "Unknown OMPClause type");
10713
10714 Visit(C);
10715 C->setLocStart(Record.readSourceLocation());
10716 C->setLocEnd(Record.readSourceLocation());
10717
10718 return C;
10719}
10720
10722 C->setPreInitStmt(Record.readSubStmt(),
10723 static_cast<OpenMPDirectiveKind>(Record.readInt()));
10724}
10725
10728 C->setPostUpdateExpr(Record.readSubExpr());
10729}
10730
10731void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10733 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10734 C->setNameModifierLoc(Record.readSourceLocation());
10735 C->setColonLoc(Record.readSourceLocation());
10736 C->setCondition(Record.readSubExpr());
10737 C->setLParenLoc(Record.readSourceLocation());
10738}
10739
10740void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10742 C->setCondition(Record.readSubExpr());
10743 C->setLParenLoc(Record.readSourceLocation());
10744}
10745
10746void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10748 C->setNumThreads(Record.readSubExpr());
10749 C->setLParenLoc(Record.readSourceLocation());
10750}
10751
10752void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10753 C->setSafelen(Record.readSubExpr());
10754 C->setLParenLoc(Record.readSourceLocation());
10755}
10756
10757void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10758 C->setSimdlen(Record.readSubExpr());
10759 C->setLParenLoc(Record.readSourceLocation());
10760}
10761
10762void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10763 for (Expr *&E : C->getSizesRefs())
10764 E = Record.readSubExpr();
10765 C->setLParenLoc(Record.readSourceLocation());
10766}
10767
10768void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10769
10770void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10771 C->setFactor(Record.readSubExpr());
10772 C->setLParenLoc(Record.readSourceLocation());
10773}
10774
10775void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10776 C->setAllocator(Record.readExpr());
10777 C->setLParenLoc(Record.readSourceLocation());
10778}
10779
10780void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10781 C->setNumForLoops(Record.readSubExpr());
10782 C->setLParenLoc(Record.readSourceLocation());
10783}
10784
10785void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10786 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10787 C->setLParenLoc(Record.readSourceLocation());
10788 C->setDefaultKindKwLoc(Record.readSourceLocation());
10789}
10790
10791void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10792 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10793 C->setLParenLoc(Record.readSourceLocation());
10794 C->setProcBindKindKwLoc(Record.readSourceLocation());
10795}
10796
10797void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10799 C->setScheduleKind(
10800 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10801 C->setFirstScheduleModifier(
10802 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10803 C->setSecondScheduleModifier(
10804 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10805 C->setChunkSize(Record.readSubExpr());
10806 C->setLParenLoc(Record.readSourceLocation());
10807 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10808 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10809 C->setScheduleKindLoc(Record.readSourceLocation());
10810 C->setCommaLoc(Record.readSourceLocation());
10811}
10812
10813void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10814 C->setNumForLoops(Record.readSubExpr());
10815 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10816 C->setLoopNumIterations(I, Record.readSubExpr());
10817 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10818 C->setLoopCounter(I, Record.readSubExpr());
10819 C->setLParenLoc(Record.readSourceLocation());
10820}
10821
10822void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10823 C->setEventHandler(Record.readSubExpr());
10824 C->setLParenLoc(Record.readSourceLocation());
10825}
10826
10827void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10828
10829void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10830
10831void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10832
10833void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10834
10835void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10836
10837void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10838 if (C->isExtended()) {
10839 C->setLParenLoc(Record.readSourceLocation());
10840 C->setArgumentLoc(Record.readSourceLocation());
10841 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10842 }
10843}
10844
10845void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10846
10847void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10848
10849// Read the parameter of fail clause. This will have been saved when
10850// OMPClauseWriter is called.
10851void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10852 C->setLParenLoc(Record.readSourceLocation());
10853 SourceLocation FailParameterLoc = Record.readSourceLocation();
10854 C->setFailParameterLoc(FailParameterLoc);
10855 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10856 C->setFailParameter(CKind);
10857}
10858
10859void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10860
10861void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10862
10863void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10864
10865void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10866
10867void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10868
10869void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
10870
10871void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10872
10873void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10874
10875void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10876
10877void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10878 unsigned NumVars = C->varlist_size();
10880 Vars.reserve(NumVars);
10881 for (unsigned I = 0; I != NumVars; ++I)
10882 Vars.push_back(Record.readSubExpr());
10883 C->setVarRefs(Vars);
10884 C->setIsTarget(Record.readBool());
10885 C->setIsTargetSync(Record.readBool());
10886 C->setLParenLoc(Record.readSourceLocation());
10887 C->setVarLoc(Record.readSourceLocation());
10888}
10889
10890void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10891 C->setInteropVar(Record.readSubExpr());
10892 C->setLParenLoc(Record.readSourceLocation());
10893 C->setVarLoc(Record.readSourceLocation());
10894}
10895
10896void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10897 C->setInteropVar(Record.readSubExpr());
10898 C->setLParenLoc(Record.readSourceLocation());
10899 C->setVarLoc(Record.readSourceLocation());
10900}
10901
10902void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10904 C->setCondition(Record.readSubExpr());
10905 C->setLParenLoc(Record.readSourceLocation());
10906}
10907
10908void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10910 C->setCondition(Record.readSubExpr());
10911 C->setLParenLoc(Record.readSourceLocation());
10912}
10913
10914void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10915
10916void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10918
10919void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10920
10921void
10922OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10923}
10924
10925void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10927 C->setAtomicDefaultMemOrderKind(
10928 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10929 C->setLParenLoc(Record.readSourceLocation());
10930 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10931}
10932
10933void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10934 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10935 C->setLParenLoc(Record.readSourceLocation());
10936 C->setAtKindKwLoc(Record.readSourceLocation());
10937}
10938
10939void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10940 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10941 C->setLParenLoc(Record.readSourceLocation());
10942 C->setSeverityKindKwLoc(Record.readSourceLocation());
10943}
10944
10945void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10946 C->setMessageString(Record.readSubExpr());
10947 C->setLParenLoc(Record.readSourceLocation());
10948}
10949
10950void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10951 C->setLParenLoc(Record.readSourceLocation());
10952 unsigned NumVars = C->varlist_size();
10954 Vars.reserve(NumVars);
10955 for (unsigned i = 0; i != NumVars; ++i)
10956 Vars.push_back(Record.readSubExpr());
10957 C->setVarRefs(Vars);
10958 Vars.clear();
10959 for (unsigned i = 0; i != NumVars; ++i)
10960 Vars.push_back(Record.readSubExpr());
10961 C->setPrivateCopies(Vars);
10962}
10963
10964void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10966 C->setLParenLoc(Record.readSourceLocation());
10967 unsigned NumVars = C->varlist_size();
10969 Vars.reserve(NumVars);
10970 for (unsigned i = 0; i != NumVars; ++i)
10971 Vars.push_back(Record.readSubExpr());
10972 C->setVarRefs(Vars);
10973 Vars.clear();
10974 for (unsigned i = 0; i != NumVars; ++i)
10975 Vars.push_back(Record.readSubExpr());
10976 C->setPrivateCopies(Vars);
10977 Vars.clear();
10978 for (unsigned i = 0; i != NumVars; ++i)
10979 Vars.push_back(Record.readSubExpr());
10980 C->setInits(Vars);
10981}
10982
10983void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10985 C->setLParenLoc(Record.readSourceLocation());
10986 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10987 C->setKindLoc(Record.readSourceLocation());
10988 C->setColonLoc(Record.readSourceLocation());
10989 unsigned NumVars = C->varlist_size();
10991 Vars.reserve(NumVars);
10992 for (unsigned i = 0; i != NumVars; ++i)
10993 Vars.push_back(Record.readSubExpr());
10994 C->setVarRefs(Vars);
10995 Vars.clear();
10996 for (unsigned i = 0; i != NumVars; ++i)
10997 Vars.push_back(Record.readSubExpr());
10998 C->setPrivateCopies(Vars);
10999 Vars.clear();
11000 for (unsigned i = 0; i != NumVars; ++i)
11001 Vars.push_back(Record.readSubExpr());
11002 C->setSourceExprs(Vars);
11003 Vars.clear();
11004 for (unsigned i = 0; i != NumVars; ++i)
11005 Vars.push_back(Record.readSubExpr());
11006 C->setDestinationExprs(Vars);
11007 Vars.clear();
11008 for (unsigned i = 0; i != NumVars; ++i)
11009 Vars.push_back(Record.readSubExpr());
11010 C->setAssignmentOps(Vars);
11011}
11012
11013void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11014 C->setLParenLoc(Record.readSourceLocation());
11015 unsigned NumVars = C->varlist_size();
11017 Vars.reserve(NumVars);
11018 for (unsigned i = 0; i != NumVars; ++i)
11019 Vars.push_back(Record.readSubExpr());
11020 C->setVarRefs(Vars);
11021}
11022
11023void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11025 C->setLParenLoc(Record.readSourceLocation());
11026 C->setModifierLoc(Record.readSourceLocation());
11027 C->setColonLoc(Record.readSourceLocation());
11028 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11029 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11030 C->setQualifierLoc(NNSL);
11031 C->setNameInfo(DNI);
11032
11033 unsigned NumVars = C->varlist_size();
11035 Vars.reserve(NumVars);
11036 for (unsigned i = 0; i != NumVars; ++i)
11037 Vars.push_back(Record.readSubExpr());
11038 C->setVarRefs(Vars);
11039 Vars.clear();
11040 for (unsigned i = 0; i != NumVars; ++i)
11041 Vars.push_back(Record.readSubExpr());
11042 C->setPrivates(Vars);
11043 Vars.clear();
11044 for (unsigned i = 0; i != NumVars; ++i)
11045 Vars.push_back(Record.readSubExpr());
11046 C->setLHSExprs(Vars);
11047 Vars.clear();
11048 for (unsigned i = 0; i != NumVars; ++i)
11049 Vars.push_back(Record.readSubExpr());
11050 C->setRHSExprs(Vars);
11051 Vars.clear();
11052 for (unsigned i = 0; i != NumVars; ++i)
11053 Vars.push_back(Record.readSubExpr());
11054 C->setReductionOps(Vars);
11055 if (C->getModifier() == OMPC_REDUCTION_inscan) {
11056 Vars.clear();
11057 for (unsigned i = 0; i != NumVars; ++i)
11058 Vars.push_back(Record.readSubExpr());
11059 C->setInscanCopyOps(Vars);
11060 Vars.clear();
11061 for (unsigned i = 0; i != NumVars; ++i)
11062 Vars.push_back(Record.readSubExpr());
11063 C->setInscanCopyArrayTemps(Vars);
11064 Vars.clear();
11065 for (unsigned i = 0; i != NumVars; ++i)
11066 Vars.push_back(Record.readSubExpr());
11067 C->setInscanCopyArrayElems(Vars);
11068 }
11069}
11070
11071void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11073 C->setLParenLoc(Record.readSourceLocation());
11074 C->setColonLoc(Record.readSourceLocation());
11075 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11076 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11077 C->setQualifierLoc(NNSL);
11078 C->setNameInfo(DNI);
11079
11080 unsigned NumVars = C->varlist_size();
11082 Vars.reserve(NumVars);
11083 for (unsigned I = 0; I != NumVars; ++I)
11084 Vars.push_back(Record.readSubExpr());
11085 C->setVarRefs(Vars);
11086 Vars.clear();
11087 for (unsigned I = 0; I != NumVars; ++I)
11088 Vars.push_back(Record.readSubExpr());
11089 C->setPrivates(Vars);
11090 Vars.clear();
11091 for (unsigned I = 0; I != NumVars; ++I)
11092 Vars.push_back(Record.readSubExpr());
11093 C->setLHSExprs(Vars);
11094 Vars.clear();
11095 for (unsigned I = 0; I != NumVars; ++I)
11096 Vars.push_back(Record.readSubExpr());
11097 C->setRHSExprs(Vars);
11098 Vars.clear();
11099 for (unsigned I = 0; I != NumVars; ++I)
11100 Vars.push_back(Record.readSubExpr());
11101 C->setReductionOps(Vars);
11102}
11103
11104void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11106 C->setLParenLoc(Record.readSourceLocation());
11107 C->setColonLoc(Record.readSourceLocation());
11108 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11109 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11110 C->setQualifierLoc(NNSL);
11111 C->setNameInfo(DNI);
11112
11113 unsigned NumVars = C->varlist_size();
11115 Vars.reserve(NumVars);
11116 for (unsigned I = 0; I != NumVars; ++I)
11117 Vars.push_back(Record.readSubExpr());
11118 C->setVarRefs(Vars);
11119 Vars.clear();
11120 for (unsigned I = 0; I != NumVars; ++I)
11121 Vars.push_back(Record.readSubExpr());
11122 C->setPrivates(Vars);
11123 Vars.clear();
11124 for (unsigned I = 0; I != NumVars; ++I)
11125 Vars.push_back(Record.readSubExpr());
11126 C->setLHSExprs(Vars);
11127 Vars.clear();
11128 for (unsigned I = 0; I != NumVars; ++I)
11129 Vars.push_back(Record.readSubExpr());
11130 C->setRHSExprs(Vars);
11131 Vars.clear();
11132 for (unsigned I = 0; I != NumVars; ++I)
11133 Vars.push_back(Record.readSubExpr());
11134 C->setReductionOps(Vars);
11135 Vars.clear();
11136 for (unsigned I = 0; I != NumVars; ++I)
11137 Vars.push_back(Record.readSubExpr());
11138 C->setTaskgroupDescriptors(Vars);
11139}
11140
11141void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11143 C->setLParenLoc(Record.readSourceLocation());
11144 C->setColonLoc(Record.readSourceLocation());
11145 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11146 C->setModifierLoc(Record.readSourceLocation());
11147 unsigned NumVars = C->varlist_size();
11149 Vars.reserve(NumVars);
11150 for (unsigned i = 0; i != NumVars; ++i)
11151 Vars.push_back(Record.readSubExpr());
11152 C->setVarRefs(Vars);
11153 Vars.clear();
11154 for (unsigned i = 0; i != NumVars; ++i)
11155 Vars.push_back(Record.readSubExpr());
11156 C->setPrivates(Vars);
11157 Vars.clear();
11158 for (unsigned i = 0; i != NumVars; ++i)
11159 Vars.push_back(Record.readSubExpr());
11160 C->setInits(Vars);
11161 Vars.clear();
11162 for (unsigned i = 0; i != NumVars; ++i)
11163 Vars.push_back(Record.readSubExpr());
11164 C->setUpdates(Vars);
11165 Vars.clear();
11166 for (unsigned i = 0; i != NumVars; ++i)
11167 Vars.push_back(Record.readSubExpr());
11168 C->setFinals(Vars);
11169 C->setStep(Record.readSubExpr());
11170 C->setCalcStep(Record.readSubExpr());
11171 Vars.clear();
11172 for (unsigned I = 0; I != NumVars + 1; ++I)
11173 Vars.push_back(Record.readSubExpr());
11174 C->setUsedExprs(Vars);
11175}
11176
11177void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11178 C->setLParenLoc(Record.readSourceLocation());
11179 C->setColonLoc(Record.readSourceLocation());
11180 unsigned NumVars = C->varlist_size();
11182 Vars.reserve(NumVars);
11183 for (unsigned i = 0; i != NumVars; ++i)
11184 Vars.push_back(Record.readSubExpr());
11185 C->setVarRefs(Vars);
11186 C->setAlignment(Record.readSubExpr());
11187}
11188
11189void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11190 C->setLParenLoc(Record.readSourceLocation());
11191 unsigned NumVars = C->varlist_size();
11193 Exprs.reserve(NumVars);
11194 for (unsigned i = 0; i != NumVars; ++i)
11195 Exprs.push_back(Record.readSubExpr());
11196 C->setVarRefs(Exprs);
11197 Exprs.clear();
11198 for (unsigned i = 0; i != NumVars; ++i)
11199 Exprs.push_back(Record.readSubExpr());
11200 C->setSourceExprs(Exprs);
11201 Exprs.clear();
11202 for (unsigned i = 0; i != NumVars; ++i)
11203 Exprs.push_back(Record.readSubExpr());
11204 C->setDestinationExprs(Exprs);
11205 Exprs.clear();
11206 for (unsigned i = 0; i != NumVars; ++i)
11207 Exprs.push_back(Record.readSubExpr());
11208 C->setAssignmentOps(Exprs);
11209}
11210
11211void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11212 C->setLParenLoc(Record.readSourceLocation());
11213 unsigned NumVars = C->varlist_size();
11215 Exprs.reserve(NumVars);
11216 for (unsigned i = 0; i != NumVars; ++i)
11217 Exprs.push_back(Record.readSubExpr());
11218 C->setVarRefs(Exprs);
11219 Exprs.clear();
11220 for (unsigned i = 0; i != NumVars; ++i)
11221 Exprs.push_back(Record.readSubExpr());
11222 C->setSourceExprs(Exprs);
11223 Exprs.clear();
11224 for (unsigned i = 0; i != NumVars; ++i)
11225 Exprs.push_back(Record.readSubExpr());
11226 C->setDestinationExprs(Exprs);
11227 Exprs.clear();
11228 for (unsigned i = 0; i != NumVars; ++i)
11229 Exprs.push_back(Record.readSubExpr());
11230 C->setAssignmentOps(Exprs);
11231}
11232
11233void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11234 C->setLParenLoc(Record.readSourceLocation());
11235 unsigned NumVars = C->varlist_size();
11237 Vars.reserve(NumVars);
11238 for (unsigned i = 0; i != NumVars; ++i)
11239 Vars.push_back(Record.readSubExpr());
11240 C->setVarRefs(Vars);
11241}
11242
11243void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11244 C->setDepobj(Record.readSubExpr());
11245 C->setLParenLoc(Record.readSourceLocation());
11246}
11247
11248void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11249 C->setLParenLoc(Record.readSourceLocation());
11250 C->setModifier(Record.readSubExpr());
11251 C->setDependencyKind(
11252 static_cast<OpenMPDependClauseKind>(Record.readInt()));
11253 C->setDependencyLoc(Record.readSourceLocation());
11254 C->setColonLoc(Record.readSourceLocation());
11255 C->setOmpAllMemoryLoc(Record.readSourceLocation());
11256 unsigned NumVars = C->varlist_size();
11258 Vars.reserve(NumVars);
11259 for (unsigned I = 0; I != NumVars; ++I)
11260 Vars.push_back(Record.readSubExpr());
11261 C->setVarRefs(Vars);
11262 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11263 C->setLoopData(I, Record.readSubExpr());
11264}
11265
11266void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11268 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11269 C->setDevice(Record.readSubExpr());
11270 C->setModifierLoc(Record.readSourceLocation());
11271 C->setLParenLoc(Record.readSourceLocation());
11272}
11273
11274void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11275 C->setLParenLoc(Record.readSourceLocation());
11276 bool HasIteratorModifier = false;
11277 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11278 C->setMapTypeModifier(
11279 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11280 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11281 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11282 HasIteratorModifier = true;
11283 }
11284 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11285 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11286 C->setMapType(
11287 static_cast<OpenMPMapClauseKind>(Record.readInt()));
11288 C->setMapLoc(Record.readSourceLocation());
11289 C->setColonLoc(Record.readSourceLocation());
11290 auto NumVars = C->varlist_size();
11291 auto UniqueDecls = C->getUniqueDeclarationsNum();
11292 auto TotalLists = C->getTotalComponentListNum();
11293 auto TotalComponents = C->getTotalComponentsNum();
11294
11296 Vars.reserve(NumVars);
11297 for (unsigned i = 0; i != NumVars; ++i)
11298 Vars.push_back(Record.readExpr());
11299 C->setVarRefs(Vars);
11300
11301 SmallVector<Expr *, 16> UDMappers;
11302 UDMappers.reserve(NumVars);
11303 for (unsigned I = 0; I < NumVars; ++I)
11304 UDMappers.push_back(Record.readExpr());
11305 C->setUDMapperRefs(UDMappers);
11306
11307 if (HasIteratorModifier)
11308 C->setIteratorModifier(Record.readExpr());
11309
11311 Decls.reserve(UniqueDecls);
11312 for (unsigned i = 0; i < UniqueDecls; ++i)
11313 Decls.push_back(Record.readDeclAs<ValueDecl>());
11314 C->setUniqueDecls(Decls);
11315
11316 SmallVector<unsigned, 16> ListsPerDecl;
11317 ListsPerDecl.reserve(UniqueDecls);
11318 for (unsigned i = 0; i < UniqueDecls; ++i)
11319 ListsPerDecl.push_back(Record.readInt());
11320 C->setDeclNumLists(ListsPerDecl);
11321
11322 SmallVector<unsigned, 32> ListSizes;
11323 ListSizes.reserve(TotalLists);
11324 for (unsigned i = 0; i < TotalLists; ++i)
11325 ListSizes.push_back(Record.readInt());
11326 C->setComponentListSizes(ListSizes);
11327
11329 Components.reserve(TotalComponents);
11330 for (unsigned i = 0; i < TotalComponents; ++i) {
11331 Expr *AssociatedExprPr = Record.readExpr();
11332 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11333 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11334 /*IsNonContiguous=*/false);
11335 }
11336 C->setComponents(Components, ListSizes);
11337}
11338
11339void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11340 C->setLParenLoc(Record.readSourceLocation());
11341 C->setColonLoc(Record.readSourceLocation());
11342 C->setAllocator(Record.readSubExpr());
11343 unsigned NumVars = C->varlist_size();
11345 Vars.reserve(NumVars);
11346 for (unsigned i = 0; i != NumVars; ++i)
11347 Vars.push_back(Record.readSubExpr());
11348 C->setVarRefs(Vars);
11349}
11350
11351void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11353 C->setNumTeams(Record.readSubExpr());
11354 C->setLParenLoc(Record.readSourceLocation());
11355}
11356
11357void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11359 C->setThreadLimit(Record.readSubExpr());
11360 C->setLParenLoc(Record.readSourceLocation());
11361}
11362
11363void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11365 C->setPriority(Record.readSubExpr());
11366 C->setLParenLoc(Record.readSourceLocation());
11367}
11368
11369void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11371 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11372 C->setGrainsize(Record.readSubExpr());
11373 C->setModifierLoc(Record.readSourceLocation());
11374 C->setLParenLoc(Record.readSourceLocation());
11375}
11376
11377void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11379 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11380 C->setNumTasks(Record.readSubExpr());
11381 C->setModifierLoc(Record.readSourceLocation());
11382 C->setLParenLoc(Record.readSourceLocation());
11383}
11384
11385void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11386 C->setHint(Record.readSubExpr());
11387 C->setLParenLoc(Record.readSourceLocation());
11388}
11389
11390void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11392 C->setDistScheduleKind(
11393 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11394 C->setChunkSize(Record.readSubExpr());
11395 C->setLParenLoc(Record.readSourceLocation());
11396 C->setDistScheduleKindLoc(Record.readSourceLocation());
11397 C->setCommaLoc(Record.readSourceLocation());
11398}
11399
11400void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11401 C->setDefaultmapKind(
11402 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11403 C->setDefaultmapModifier(
11404 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11405 C->setLParenLoc(Record.readSourceLocation());
11406 C->setDefaultmapModifierLoc(Record.readSourceLocation());
11407 C->setDefaultmapKindLoc(Record.readSourceLocation());
11408}
11409
11410void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11411 C->setLParenLoc(Record.readSourceLocation());
11412 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11413 C->setMotionModifier(
11414 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11415 C->setMotionModifierLoc(I, Record.readSourceLocation());
11416 }
11417 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11418 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11419 C->setColonLoc(Record.readSourceLocation());
11420 auto NumVars = C->varlist_size();
11421 auto UniqueDecls = C->getUniqueDeclarationsNum();
11422 auto TotalLists = C->getTotalComponentListNum();
11423 auto TotalComponents = C->getTotalComponentsNum();
11424
11426 Vars.reserve(NumVars);
11427 for (unsigned i = 0; i != NumVars; ++i)
11428 Vars.push_back(Record.readSubExpr());
11429 C->setVarRefs(Vars);
11430
11431 SmallVector<Expr *, 16> UDMappers;
11432 UDMappers.reserve(NumVars);
11433 for (unsigned I = 0; I < NumVars; ++I)
11434 UDMappers.push_back(Record.readSubExpr());
11435 C->setUDMapperRefs(UDMappers);
11436
11438 Decls.reserve(UniqueDecls);
11439 for (unsigned i = 0; i < UniqueDecls; ++i)
11440 Decls.push_back(Record.readDeclAs<ValueDecl>());
11441 C->setUniqueDecls(Decls);
11442
11443 SmallVector<unsigned, 16> ListsPerDecl;
11444 ListsPerDecl.reserve(UniqueDecls);
11445 for (unsigned i = 0; i < UniqueDecls; ++i)
11446 ListsPerDecl.push_back(Record.readInt());
11447 C->setDeclNumLists(ListsPerDecl);
11448
11449 SmallVector<unsigned, 32> ListSizes;
11450 ListSizes.reserve(TotalLists);
11451 for (unsigned i = 0; i < TotalLists; ++i)
11452 ListSizes.push_back(Record.readInt());
11453 C->setComponentListSizes(ListSizes);
11454
11456 Components.reserve(TotalComponents);
11457 for (unsigned i = 0; i < TotalComponents; ++i) {
11458 Expr *AssociatedExprPr = Record.readSubExpr();
11459 bool IsNonContiguous = Record.readBool();
11460 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11461 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11462 }
11463 C->setComponents(Components, ListSizes);
11464}
11465
11466void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11467 C->setLParenLoc(Record.readSourceLocation());
11468 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11469 C->setMotionModifier(
11470 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11471 C->setMotionModifierLoc(I, Record.readSourceLocation());
11472 }
11473 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11474 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11475 C->setColonLoc(Record.readSourceLocation());
11476 auto NumVars = C->varlist_size();
11477 auto UniqueDecls = C->getUniqueDeclarationsNum();
11478 auto TotalLists = C->getTotalComponentListNum();
11479 auto TotalComponents = C->getTotalComponentsNum();
11480
11482 Vars.reserve(NumVars);
11483 for (unsigned i = 0; i != NumVars; ++i)
11484 Vars.push_back(Record.readSubExpr());
11485 C->setVarRefs(Vars);
11486
11487 SmallVector<Expr *, 16> UDMappers;
11488 UDMappers.reserve(NumVars);
11489 for (unsigned I = 0; I < NumVars; ++I)
11490 UDMappers.push_back(Record.readSubExpr());
11491 C->setUDMapperRefs(UDMappers);
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 *AssociatedExprPr = Record.readSubExpr();
11515 bool IsNonContiguous = Record.readBool();
11516 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11517 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11518 }
11519 C->setComponents(Components, ListSizes);
11520}
11521
11522void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *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 for (unsigned i = 0; i != NumVars; ++i)
11536 Vars.push_back(Record.readSubExpr());
11537 C->setPrivateCopies(Vars);
11538 Vars.clear();
11539 for (unsigned i = 0; i != NumVars; ++i)
11540 Vars.push_back(Record.readSubExpr());
11541 C->setInits(Vars);
11542
11544 Decls.reserve(UniqueDecls);
11545 for (unsigned i = 0; i < UniqueDecls; ++i)
11546 Decls.push_back(Record.readDeclAs<ValueDecl>());
11547 C->setUniqueDecls(Decls);
11548
11549 SmallVector<unsigned, 16> ListsPerDecl;
11550 ListsPerDecl.reserve(UniqueDecls);
11551 for (unsigned i = 0; i < UniqueDecls; ++i)
11552 ListsPerDecl.push_back(Record.readInt());
11553 C->setDeclNumLists(ListsPerDecl);
11554
11555 SmallVector<unsigned, 32> ListSizes;
11556 ListSizes.reserve(TotalLists);
11557 for (unsigned i = 0; i < TotalLists; ++i)
11558 ListSizes.push_back(Record.readInt());
11559 C->setComponentListSizes(ListSizes);
11560
11562 Components.reserve(TotalComponents);
11563 for (unsigned i = 0; i < TotalComponents; ++i) {
11564 auto *AssociatedExprPr = Record.readSubExpr();
11565 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11566 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11567 /*IsNonContiguous=*/false);
11568 }
11569 C->setComponents(Components, ListSizes);
11570}
11571
11572void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11573 C->setLParenLoc(Record.readSourceLocation());
11574 auto NumVars = C->varlist_size();
11575 auto UniqueDecls = C->getUniqueDeclarationsNum();
11576 auto TotalLists = C->getTotalComponentListNum();
11577 auto TotalComponents = C->getTotalComponentsNum();
11578
11580 Vars.reserve(NumVars);
11581 for (unsigned i = 0; i != NumVars; ++i)
11582 Vars.push_back(Record.readSubExpr());
11583 C->setVarRefs(Vars);
11584
11586 Decls.reserve(UniqueDecls);
11587 for (unsigned i = 0; i < UniqueDecls; ++i)
11588 Decls.push_back(Record.readDeclAs<ValueDecl>());
11589 C->setUniqueDecls(Decls);
11590
11591 SmallVector<unsigned, 16> ListsPerDecl;
11592 ListsPerDecl.reserve(UniqueDecls);
11593 for (unsigned i = 0; i < UniqueDecls; ++i)
11594 ListsPerDecl.push_back(Record.readInt());
11595 C->setDeclNumLists(ListsPerDecl);
11596
11597 SmallVector<unsigned, 32> ListSizes;
11598 ListSizes.reserve(TotalLists);
11599 for (unsigned i = 0; i < TotalLists; ++i)
11600 ListSizes.push_back(Record.readInt());
11601 C->setComponentListSizes(ListSizes);
11602
11604 Components.reserve(TotalComponents);
11605 for (unsigned i = 0; i < TotalComponents; ++i) {
11606 Expr *AssociatedExpr = Record.readSubExpr();
11607 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11608 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11609 /*IsNonContiguous*/ false);
11610 }
11611 C->setComponents(Components, ListSizes);
11612}
11613
11614void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11615 C->setLParenLoc(Record.readSourceLocation());
11616 auto NumVars = C->varlist_size();
11617 auto UniqueDecls = C->getUniqueDeclarationsNum();
11618 auto TotalLists = C->getTotalComponentListNum();
11619 auto TotalComponents = C->getTotalComponentsNum();
11620
11622 Vars.reserve(NumVars);
11623 for (unsigned i = 0; i != NumVars; ++i)
11624 Vars.push_back(Record.readSubExpr());
11625 C->setVarRefs(Vars);
11626 Vars.clear();
11627
11629 Decls.reserve(UniqueDecls);
11630 for (unsigned i = 0; i < UniqueDecls; ++i)
11631 Decls.push_back(Record.readDeclAs<ValueDecl>());
11632 C->setUniqueDecls(Decls);
11633
11634 SmallVector<unsigned, 16> ListsPerDecl;
11635 ListsPerDecl.reserve(UniqueDecls);
11636 for (unsigned i = 0; i < UniqueDecls; ++i)
11637 ListsPerDecl.push_back(Record.readInt());
11638 C->setDeclNumLists(ListsPerDecl);
11639
11640 SmallVector<unsigned, 32> ListSizes;
11641 ListSizes.reserve(TotalLists);
11642 for (unsigned i = 0; i < TotalLists; ++i)
11643 ListSizes.push_back(Record.readInt());
11644 C->setComponentListSizes(ListSizes);
11645
11647 Components.reserve(TotalComponents);
11648 for (unsigned i = 0; i < TotalComponents; ++i) {
11649 Expr *AssociatedExpr = Record.readSubExpr();
11650 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11651 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11652 /*IsNonContiguous=*/false);
11653 }
11654 C->setComponents(Components, ListSizes);
11655}
11656
11657void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11658 C->setLParenLoc(Record.readSourceLocation());
11659 auto NumVars = C->varlist_size();
11660 auto UniqueDecls = C->getUniqueDeclarationsNum();
11661 auto TotalLists = C->getTotalComponentListNum();
11662 auto TotalComponents = C->getTotalComponentsNum();
11663
11665 Vars.reserve(NumVars);
11666 for (unsigned I = 0; I != NumVars; ++I)
11667 Vars.push_back(Record.readSubExpr());
11668 C->setVarRefs(Vars);
11669 Vars.clear();
11670
11672 Decls.reserve(UniqueDecls);
11673 for (unsigned I = 0; I < UniqueDecls; ++I)
11674 Decls.push_back(Record.readDeclAs<ValueDecl>());
11675 C->setUniqueDecls(Decls);
11676
11677 SmallVector<unsigned, 16> ListsPerDecl;
11678 ListsPerDecl.reserve(UniqueDecls);
11679 for (unsigned I = 0; I < UniqueDecls; ++I)
11680 ListsPerDecl.push_back(Record.readInt());
11681 C->setDeclNumLists(ListsPerDecl);
11682
11683 SmallVector<unsigned, 32> ListSizes;
11684 ListSizes.reserve(TotalLists);
11685 for (unsigned i = 0; i < TotalLists; ++i)
11686 ListSizes.push_back(Record.readInt());
11687 C->setComponentListSizes(ListSizes);
11688
11690 Components.reserve(TotalComponents);
11691 for (unsigned I = 0; I < TotalComponents; ++I) {
11692 Expr *AssociatedExpr = Record.readSubExpr();
11693 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11694 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11695 /*IsNonContiguous=*/false);
11696 }
11697 C->setComponents(Components, ListSizes);
11698}
11699
11700void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11701 C->setLParenLoc(Record.readSourceLocation());
11702 unsigned NumVars = C->varlist_size();
11704 Vars.reserve(NumVars);
11705 for (unsigned i = 0; i != NumVars; ++i)
11706 Vars.push_back(Record.readSubExpr());
11707 C->setVarRefs(Vars);
11708 Vars.clear();
11709 Vars.reserve(NumVars);
11710 for (unsigned i = 0; i != NumVars; ++i)
11711 Vars.push_back(Record.readSubExpr());
11712 C->setPrivateRefs(Vars);
11713}
11714
11715void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11716 C->setLParenLoc(Record.readSourceLocation());
11717 unsigned NumVars = C->varlist_size();
11719 Vars.reserve(NumVars);
11720 for (unsigned i = 0; i != NumVars; ++i)
11721 Vars.push_back(Record.readSubExpr());
11722 C->setVarRefs(Vars);
11723}
11724
11725void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11726 C->setLParenLoc(Record.readSourceLocation());
11727 unsigned NumVars = C->varlist_size();
11729 Vars.reserve(NumVars);
11730 for (unsigned i = 0; i != NumVars; ++i)
11731 Vars.push_back(Record.readSubExpr());
11732 C->setVarRefs(Vars);
11733}
11734
11735void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11736 C->setLParenLoc(Record.readSourceLocation());
11737 unsigned NumOfAllocators = C->getNumberOfAllocators();
11739 Data.reserve(NumOfAllocators);
11740 for (unsigned I = 0; I != NumOfAllocators; ++I) {
11741 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11742 D.Allocator = Record.readSubExpr();
11743 D.AllocatorTraits = Record.readSubExpr();
11744 D.LParenLoc = Record.readSourceLocation();
11745 D.RParenLoc = Record.readSourceLocation();
11746 }
11747 C->setAllocatorsData(Data);
11748}
11749
11750void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11751 C->setLParenLoc(Record.readSourceLocation());
11752 C->setModifier(Record.readSubExpr());
11753 C->setColonLoc(Record.readSourceLocation());
11754 unsigned NumOfLocators = C->varlist_size();
11755 SmallVector<Expr *, 4> Locators;
11756 Locators.reserve(NumOfLocators);
11757 for (unsigned I = 0; I != NumOfLocators; ++I)
11758 Locators.push_back(Record.readSubExpr());
11759 C->setVarRefs(Locators);
11760}
11761
11762void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11763 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11764 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11765 C->setLParenLoc(Record.readSourceLocation());
11766 C->setKindKwLoc(Record.readSourceLocation());
11767 C->setModifierKwLoc(Record.readSourceLocation());
11768}
11769
11770void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11772 C->setThreadID(Record.readSubExpr());
11773 C->setLParenLoc(Record.readSourceLocation());
11774}
11775
11776void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11777 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11778 C->setLParenLoc(Record.readSourceLocation());
11779 C->setBindKindLoc(Record.readSourceLocation());
11780}
11781
11782void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11783 C->setAlignment(Record.readExpr());
11784 C->setLParenLoc(Record.readSourceLocation());
11785}
11786
11787void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11789 C->setSize(Record.readSubExpr());
11790 C->setLParenLoc(Record.readSourceLocation());
11791}
11792
11793void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11794 C->setLParenLoc(Record.readSourceLocation());
11795 C->setDependenceType(
11796 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11797 C->setDependenceLoc(Record.readSourceLocation());
11798 C->setColonLoc(Record.readSourceLocation());
11799 unsigned NumVars = C->varlist_size();
11801 Vars.reserve(NumVars);
11802 for (unsigned I = 0; I != NumVars; ++I)
11803 Vars.push_back(Record.readSubExpr());
11804 C->setVarRefs(Vars);
11805 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11806 C->setLoopData(I, Record.readSubExpr());
11807}
11808
11809void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11810 AttrVec Attrs;
11811 Record.readAttributes(Attrs);
11812 C->setAttrs(Attrs);
11813 C->setLocStart(Record.readSourceLocation());
11814 C->setLParenLoc(Record.readSourceLocation());
11815 C->setLocEnd(Record.readSourceLocation());
11816}
11817
11818void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11819
11822 TI.Sets.resize(readUInt32());
11823 for (auto &Set : TI.Sets) {
11824 Set.Kind = readEnum<llvm::omp::TraitSet>();
11825 Set.Selectors.resize(readUInt32());
11826 for (auto &Selector : Set.Selectors) {
11827 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11828 Selector.ScoreOrCondition = nullptr;
11829 if (readBool())
11830 Selector.ScoreOrCondition = readExprRef();
11831 Selector.Properties.resize(readUInt32());
11832 for (auto &Property : Selector.Properties)
11833 Property.Kind = readEnum<llvm::omp::TraitProperty>();
11834 }
11835 }
11836 return &TI;
11837}
11838
11840 if (!Data)
11841 return;
11842 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11843 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11844 skipInts(3);
11845 }
11846 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11847 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11848 Clauses[I] = readOMPClause();
11849 Data->setClauses(Clauses);
11850 if (Data->hasAssociatedStmt())
11851 Data->setAssociatedStmt(readStmt());
11852 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11853 Data->getChildren()[I] = readStmt();
11854}
11855
11857 unsigned NumVars = readInt();
11859 for (unsigned I = 0; I < NumVars; ++I)
11860 VarList.push_back(readSubExpr());
11861 return VarList;
11862}
11863
11865 unsigned NumExprs = readInt();
11867 for (unsigned I = 0; I < NumExprs; ++I)
11868 ExprList.push_back(readSubExpr());
11869 return ExprList;
11870}
11871
11873 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
11876
11877 switch (ClauseKind) {
11879 SourceLocation LParenLoc = readSourceLocation();
11880 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
11881 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
11882 EndLoc);
11883 }
11884 case OpenACCClauseKind::If: {
11885 SourceLocation LParenLoc = readSourceLocation();
11886 Expr *CondExpr = readSubExpr();
11887 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
11888 EndLoc);
11889 }
11891 SourceLocation LParenLoc = readSourceLocation();
11892 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
11893 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
11894 CondExpr, EndLoc);
11895 }
11897 SourceLocation LParenLoc = readSourceLocation();
11898 unsigned NumClauses = readInt();
11900 for (unsigned I = 0; I < NumClauses; ++I)
11901 IntExprs.push_back(readSubExpr());
11902 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
11903 IntExprs, EndLoc);
11904 }
11906 SourceLocation LParenLoc = readSourceLocation();
11907 Expr *IntExpr = readSubExpr();
11908 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
11909 IntExpr, EndLoc);
11910 }
11912 SourceLocation LParenLoc = readSourceLocation();
11913 Expr *IntExpr = readSubExpr();
11914 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
11915 IntExpr, EndLoc);
11916 }
11918 SourceLocation LParenLoc = readSourceLocation();
11920 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
11921 VarList, EndLoc);
11922 }
11924 SourceLocation LParenLoc = readSourceLocation();
11926 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
11927 VarList, EndLoc);
11928 }
11930 SourceLocation LParenLoc = readSourceLocation();
11932 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
11933 VarList, EndLoc);
11934 }
11936 SourceLocation LParenLoc = readSourceLocation();
11938 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
11939 VarList, EndLoc);
11940 }
11942 SourceLocation LParenLoc = readSourceLocation();
11944 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
11945 VarList, EndLoc);
11946 }
11948 SourceLocation LParenLoc = readSourceLocation();
11950 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
11951 VarList, EndLoc);
11952 }
11956 SourceLocation LParenLoc = readSourceLocation();
11958 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
11959 LParenLoc, VarList, EndLoc);
11960 }
11964 SourceLocation LParenLoc = readSourceLocation();
11965 bool IsReadOnly = readBool();
11967 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
11968 LParenLoc, IsReadOnly, VarList, EndLoc);
11969 }
11973 SourceLocation LParenLoc = readSourceLocation();
11974 bool IsZero = readBool();
11976 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
11977 LParenLoc, IsZero, VarList, EndLoc);
11978 }
11982 SourceLocation LParenLoc = readSourceLocation();
11983 bool IsZero = readBool();
11985 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
11986 LParenLoc, IsZero, VarList, EndLoc);
11987 }
11989 SourceLocation LParenLoc = readSourceLocation();
11990 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
11991 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
11992 AsyncExpr, EndLoc);
11993 }
11995 SourceLocation LParenLoc = readSourceLocation();
11996 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
11997 SourceLocation QueuesLoc = readSourceLocation();
11999 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
12000 DevNumExpr, QueuesLoc, QueueIdExprs,
12001 EndLoc);
12002 }
12005 SourceLocation LParenLoc = readSourceLocation();
12007 unsigned NumArchs = readInt();
12008
12009 for (unsigned I = 0; I < NumArchs; ++I) {
12010 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
12012 Archs.emplace_back(Ident, Loc);
12013 }
12014
12015 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
12016 LParenLoc, Archs, EndLoc);
12017 }
12019 SourceLocation LParenLoc = readSourceLocation();
12020 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();
12022 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
12023 VarList, EndLoc);
12024 }
12026 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
12028 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
12030 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
12031
12051 llvm_unreachable("Clause serialization not yet implemented");
12052 }
12053 llvm_unreachable("Invalid Clause Kind");
12054}
12055
12058 for (unsigned I = 0; I < Clauses.size(); ++I)
12059 Clauses[I] = readOpenACCClause();
12060}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:4687
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8096
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:839
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:4669
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:508
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:515
static void updateModuleTimestamp(ModuleFile &MF)
Definition: ASTReader.cpp:4368
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7136
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:614
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:665
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain)
Definition: ASTReader.cpp:478
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4232
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:2746
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:1028
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:5008
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:557
static Decl * getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID)
Definition: ASTReader.cpp:7737
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II)
Definition: ASTReader.cpp:1054
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:8610
static bool isPredefinedType(serialization::TypeID ID)
Definition: ASTReader.cpp:7140
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1040
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6672
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:889
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8213
OptionValidation
Definition: ASTReader.cpp:649
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:652
@ OptionValidateNone
Definition: ASTReader.cpp:650
@ OptionValidateContradictions
Definition: ASTReader.cpp:651
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:389
#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:282
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
Definition: ASTReader.cpp:5233
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:4384
static unsigned getIndexForTypeID(serialization::TypeID ID)
Definition: ASTReader.cpp:7132
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:876
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:127
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the Diagnostic IDs-related interfaces.
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:2989
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:46
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
static std::string getName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the clang::SanitizerKind enum.
uint32_t Id
Definition: SemaARM.cpp:1143
This file declares semantic analysis for CUDA constructs.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ __2f16 b
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Definition: ASTConsumer.cpp:22
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
CanQualType AccumTy
Definition: ASTContext.h:1131
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1150
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1100
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1149
CanQualType LongTy
Definition: ASTContext.h:1127
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1127
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1140
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:1133
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:1136
CanQualType ShortAccumTy
Definition: ASTContext.h:1131
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1239
CanQualType FloatTy
Definition: ASTContext.h:1130
CanQualType DoubleTy
Definition: ASTContext.h:1130
CanQualType SatLongAccumTy
Definition: ASTContext.h:1136
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2026
CanQualType LongDoubleTy
Definition: ASTContext.h:1130
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1159
CanQualType Char16Ty
Definition: ASTContext.h:1125
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2004
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1135
CanQualType DependentTy
Definition: ASTContext.h:1146
CanQualType NullPtrTy
Definition: ASTContext.h:1145
CanQualType OMPIteratorTy
Definition: ASTContext.h:1159
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:826
CanQualType SatShortFractTy
Definition: ASTContext.h:1139
CanQualType Ibm128Ty
Definition: ASTContext.h:1130
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1137
CanQualType ArraySectionTy
Definition: ASTContext.h:1158
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1150
CanQualType BoolTy
Definition: ASTContext.h:1119
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1135
CanQualType Float128Ty
Definition: ASTContext.h:1130
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1150
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1146
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2038
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1128
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1133
CanQualType ShortFractTy
Definition: ASTContext.h:1134
CanQualType BoundMemberTy
Definition: ASTContext.h:1146
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1140
CanQualType CharTy
Definition: ASTContext.h:1120
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1127
CanQualType PseudoObjectTy
Definition: ASTContext.h:1149
CanQualType Float16Ty
Definition: ASTContext.h:1144
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
CanQualType SignedCharTy
Definition: ASTContext.h:1127
CanQualType OverloadTy
Definition: ASTContext.h:1146
CanQualType OCLClkEventTy
Definition: ASTContext.h:1155
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:1137
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:1129
CanQualType BuiltinFnTy
Definition: ASTContext.h:1148
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1155
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1118
CanQualType UnsignedCharTy
Definition: ASTContext.h:1128
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1135
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:733
CanQualType UnsignedIntTy
Definition: ASTContext.h:1128
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2188
CanQualType UnknownAnyTy
Definition: ASTContext.h:1147
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1129
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1156
CanQualType UnsignedShortTy
Definition: ASTContext.h:1128
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1141
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1464
CanQualType ShortTy
Definition: ASTContext.h:1127
CanQualType FractTy
Definition: ASTContext.h:1134
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1132
CanQualType Char32Ty
Definition: ASTContext.h:1126
CanQualType SatFractTy
Definition: ASTContext.h:1139
CanQualType SatLongFractTy
Definition: ASTContext.h:1139
CanQualType OCLQueueTy
Definition: ASTContext.h:1156
CanQualType LongFractTy
Definition: ASTContext.h:1134
CanQualType SatShortAccumTy
Definition: ASTContext.h:1136
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1143
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1157
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2014
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1138
CanQualType LongLongTy
Definition: ASTContext.h:1127
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
CanQualType WCharTy
Definition: ASTContext.h:1121
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:1060
CanQualType Char8Ty
Definition: ASTContext.h:1124
CanQualType HalfTy
Definition: ASTContext.h:1142
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1133
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1155
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:8431
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8459
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8464
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:6469
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6250
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2293
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:9626
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:901
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:9037
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9118
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9501
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1767
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7698
friend class ASTIdentifierIterator
Definition: ASTReader.h:370
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1576
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9507
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9477
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2375
Decl * ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition: ASTReader.h:1954
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9436
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8753
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8261
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1609
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1622
@ 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:1613
@ 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:1617
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
Definition: ASTReader.cpp:8683
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:7991
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6236
serialization::TypeID getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7463
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8228
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8853
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1875
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2409
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9125
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:7913
ModuleFile * getOwningModuleFile(const Decl *D) const
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7718
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9100
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8087
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7459
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9519
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2240
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:8894
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4338
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9523
SourceManager & getSourceManager() const
Definition: ASTReader.h:1594
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7725
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:4274
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5227
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2387
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7601
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:9595
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:8113
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:7853
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2304
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:8035
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8699
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7542
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7882
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:1504
~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:7544
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:1796
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8869
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:2006
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:6456
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8392
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:8972
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:9611
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:9066
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6229
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7897
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9154
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1868
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8995
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:8672
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8720
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7161
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2144
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9411
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:7675
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:8781
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8063
void warnStackExhausted(SourceLocation Loc)
Definition: ASTReader.cpp:9485
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8741
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:5395
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8731
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:2730
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2382
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:1759
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8709
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:8763
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9129
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:4429
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1775
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9443
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9083
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8942
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:385
@ Success
The control block was read successfully.
Definition: ASTReader.h:388
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:405
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:398
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:391
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:401
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:408
@ Missing
The AST file was missing.
Definition: ASTReader.h:394
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9458
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1823
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9514
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
Definition: ASTReader.cpp:8976
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:8824
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8517
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8799
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:4363
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9158
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8656
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7806
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9418
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:9070
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8864
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6528
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4260
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8287
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7832
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:1539
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:8812
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1771
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9470
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:8661
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:9052
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8123
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:4323
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:9164
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:8616
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5084
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:7633
FileManager & getFileManager() const
Definition: ASTReader.h:1595
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:5689
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:2268
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2150
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6519
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:9022
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:9431
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7516
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7115
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9259
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9249
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9217
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9180
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9270
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:9205
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7484
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:7122
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7526
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9213
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:9350
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:6958
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:9230
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:9285
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7536
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Attr * readAttr()
Reads one attribute from the current stream position, advancing Idx.
Expr * readExpr()
Reads an expression.
SourceLocation readSourceLocation(LocSeq *Seq=nullptr)
Read a source location, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCIntExprList()
Read a list of Exprs used for a int-expr-list.
Expr * readSubExpr()
Reads a sub-expression operand during statement reading.
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Wrapper for source info for array parameter types.
Definition: TypeLoc.h: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:1688
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:1457
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1090
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:246
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:159
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:200
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:215
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:224
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:169
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:206
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:184
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:164
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:230
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:175
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:262
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:193
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:240
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:235
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:125
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:88
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
An object that helps properly build a continuous range map from a set of values.
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
typename Representation::const_iterator const_iterator
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2666
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:2639
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2654
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1399
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2339
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2660
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:2680
unsigned getModuleFileIndex() const
Definition: DeclID.h:130
DeclID getRawValue() const
Definition: DeclID.h:120
unsigned getLocalDeclIndex() const
Definition: DeclBase.cpp:2193
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: DeclID.h:113
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1040
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:154
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:838
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:795
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:1028
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
Kind getKind() const
Definition: DeclBase.h:448
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.cpp:113
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:849
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:731
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:6907
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.
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h: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:3840
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:919
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:982
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:989
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:883
Represents a member of a struct/union/class.
Definition: Decl.h:3030
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, std::optional< int64_t > MaybeLimit=std::nullopt)
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:1932
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2264
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
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:446
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:3314
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...
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Definition: ASTReader.cpp:911
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:7336
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)
static OpenACCAutoClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, 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 OpenACCIndependentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static 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:461
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:868
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:816
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:858
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:452
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:581
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:1722
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:137
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:941
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
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:319
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:363
@ FastMask
The fast qualifier mask.
Definition: Type.h:366
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1412
Represents a struct/union/class.
Definition: Decl.h:4141
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:5936
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:216
iterator find(Selector Sel)
Definition: SemaObjC.h:215
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: SemaObjC.h:212
std::pair< ObjCMethodList, ObjCMethodList > Lists
Definition: SemaObjC.h:211
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:232
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
SemaObjC & ObjC()
Definition: Sema.h:1204
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:963
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:596
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:558
IdentifierResolver IdResolver
Definition: Sema.h:3003
PragmaMsStackAction
Definition: Sema.h:1503
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:826
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:3557
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:6541
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:3189
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6831
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:6898
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6759
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:7714
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:1829
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3405
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:667
Represents a variable declaration or definition.
Definition: Decl.h:879
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:252
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2067
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1178
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:372
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition: ModuleFile.h:321
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition: ModuleFile.h:435
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition: ModuleFile.h: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:463
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Definition: ModuleFile.h:370
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:367
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:483
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition: ModuleFile.h:466
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition: ModuleFile.h:338
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:325
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:442
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition: ModuleFile.h:317
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:420
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition: ModuleFile.h:491
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition: ModuleFile.h:391
SourceLocation ImportLoc
The source location where this module was first imported.
Definition: ModuleFile.h:233
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition: ModuleFile.h:458
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition: ModuleFile.h:296
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition: ModuleFile.h:331
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
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition: ModuleFile.h:158
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition: ModuleFile.h:363
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:400
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:509
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:417
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition: ModuleFile.h:455
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition: ModuleFile.h:282
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition: ModuleFile.h:395
unsigned Index
The index of this module in the list of modules.
Definition: ModuleFile.h:133
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:403
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:479
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:475
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition: ModuleFile.h:378
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:360
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:452
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:354
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:334
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition: ModuleFile.h:428
void dump()
Dump debugging output for this module.
Definition: ModuleFile.cpp:47
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition: ModuleFile.h:448
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition: ModuleFile.h:384
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition: ModuleFile.h: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:423
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
Definition: ModuleFile.h:351
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition: ModuleFile.h:345
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:406
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:445
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition: ModuleFile.h:488
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition: ModuleFile.h:376
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:413
ModuleKind Kind
The type of this module.
Definition: ModuleFile.h: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:348
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition: ModuleFile.h:470
std::string BaseDirectory
The base directory of the module.
Definition: ModuleFile.h:145
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition: ModuleFile.h:502
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:46
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
AddModuleResult
The result of attempting to add a new module.
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
void visit(llvm::function_ref< bool(ModuleFile &M)> Visitor, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:211
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:227
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:228
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:234
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:246
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:247
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:8545
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8587
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8592
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:121
32 aligned uint64_t in the AST file.
Definition: ASTBitCodes.h:194
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:1017
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:1012
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:1022
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1046
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1063
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:950
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:972
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:945
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:907
Trait class used to search the on-disk hash table containing all of the header search information.
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:876
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:2012
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1136
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1191
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1150
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:995
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:944
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1100
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:974
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:923
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1085
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:884
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1076
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1070
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:887
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:926
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:917
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1097
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:911
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:890
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:908
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:905
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:896
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:902
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1082
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:893
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:914
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1088
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:938
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:929
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:881
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1079
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1073
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:878
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:1025
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1094
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
Definition: ASTBitCodes.h:1126
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:920
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1091
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:899
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:971
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1426
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1306
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1429
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1315
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1156
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1184
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1187
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1172
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1169
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1175
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1181
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1166
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1178
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.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:88
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:432
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
Definition: ASTBitCodes.h:286
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:825
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:807
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:845
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:804
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:853
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:810
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:801
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:793
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:821
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:837
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:814
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:834
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:849
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:797
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:828
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:831
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:818
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:841
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:856
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition: ASTBitCodes.h:94
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:66
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:185
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:383
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:396
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:393
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:402
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:399
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:390
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:167
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:289
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:182
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:188
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:314
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:311
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:296
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:300
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:322
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:308
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:304
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:317
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:344
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:338
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:335
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:328
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:860
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:730
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:744
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:734
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:740
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:748
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:170
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:464
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:47
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:70
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:752
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:767
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:763
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:758
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:770
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:774
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:348
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:375
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:378
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:355
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:364
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:371
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:360
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:368
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:351
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:406
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:414
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:423
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:411
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:420
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:408
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:417
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:426
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:440
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:445
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:442
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:778
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:787
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:780
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:783
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
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:63
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:164
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:449
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:590
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:524
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:710
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:616
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:520
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:579
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:462
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:612
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:716
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:549
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:609
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:606
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
Definition: ASTBitCodes.h:723
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:559
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:666
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:707
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:474
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:626
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:540
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:677
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:586
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:687
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:654
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:556
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:482
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:647
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:536
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:720
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:701
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:564
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:544
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:576
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:663
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:633
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:680
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:527
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:552
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:698
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:637
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:533
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:672
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:511
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:659
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:603
@ 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:630
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:600
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:568
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:704
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:501
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:573
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:669
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:622
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:683
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:154
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:289
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:56
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:93
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition: DeclID.h:33
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: DeclID.h:83
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:38
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:86
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: DeclID.h:47
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: DeclID.h:71
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:59
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:50
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:56
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:44
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:53
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:65
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:68
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:80
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: DeclID.h:35
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:62
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:74
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:41
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:77
@ 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
const FunctionProtoType * T
OpenACCReductionOperator
Definition: OpenACCKinds.h:495
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:2479
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:325
@ 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
#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:5065
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:59
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:119
LazyIdentifierInfoPtr LazyControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
Definition: HeaderSearch.h:133
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:81
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:74
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:123
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:70
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:137
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:86
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition: Module.h: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.
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:704
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:718
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:705
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:711
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:1514
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:2023