1//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
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 ASTWriter class, which writes AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ASTCommon.h"
14#include "ASTReaderInternals.h"
15#include "MultiOnDiskHashTable.h"
16#include "TemplateArgumentHasher.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTUnresolvedSet.h"
19#include "clang/AST/AbstractTypeWriter.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclContextInternals.h"
25#include "clang/AST/DeclFriend.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/DeclarationName.h"
29#include "clang/AST/Expr.h"
30#include "clang/AST/ExprCXX.h"
31#include "clang/AST/LambdaCapture.h"
32#include "clang/AST/NestedNameSpecifier.h"
33#include "clang/AST/OpenACCClause.h"
34#include "clang/AST/OpenMPClause.h"
35#include "clang/AST/RawCommentList.h"
36#include "clang/AST/TemplateName.h"
37#include "clang/AST/Type.h"
38#include "clang/AST/TypeLoc.h"
39#include "clang/AST/TypeLocVisitor.h"
40#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/DiagnosticOptions.h"
42#include "clang/Basic/FileEntry.h"
43#include "clang/Basic/FileManager.h"
44#include "clang/Basic/FileSystemOptions.h"
45#include "clang/Basic/IdentifierTable.h"
46#include "clang/Basic/LLVM.h"
47#include "clang/Basic/Lambda.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/Module.h"
50#include "clang/Basic/ObjCRuntime.h"
51#include "clang/Basic/OpenACCKinds.h"
52#include "clang/Basic/OpenCLOptions.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/SourceManagerInternals.h"
56#include "clang/Basic/Specifiers.h"
57#include "clang/Basic/TargetInfo.h"
58#include "clang/Basic/TargetOptions.h"
59#include "clang/Basic/Version.h"
60#include "clang/Lex/HeaderSearch.h"
61#include "clang/Lex/HeaderSearchOptions.h"
62#include "clang/Lex/MacroInfo.h"
63#include "clang/Lex/ModuleMap.h"
64#include "clang/Lex/PreprocessingRecord.h"
65#include "clang/Lex/Preprocessor.h"
66#include "clang/Lex/PreprocessorOptions.h"
67#include "clang/Lex/Token.h"
68#include "clang/Sema/IdentifierResolver.h"
69#include "clang/Sema/ObjCMethodList.h"
70#include "clang/Sema/Sema.h"
71#include "clang/Sema/SemaCUDA.h"
72#include "clang/Sema/SemaObjC.h"
73#include "clang/Sema/Weak.h"
74#include "clang/Serialization/ASTBitCodes.h"
75#include "clang/Serialization/ASTReader.h"
76#include "clang/Serialization/ASTRecordWriter.h"
77#include "clang/Serialization/InMemoryModuleCache.h"
78#include "clang/Serialization/ModuleCache.h"
79#include "clang/Serialization/ModuleFile.h"
80#include "clang/Serialization/ModuleFileExtension.h"
81#include "clang/Serialization/SerializationDiagnostic.h"
82#include "llvm/ADT/APFloat.h"
83#include "llvm/ADT/APInt.h"
84#include "llvm/ADT/ArrayRef.h"
85#include "llvm/ADT/DenseMap.h"
86#include "llvm/ADT/DenseSet.h"
87#include "llvm/ADT/PointerIntPair.h"
88#include "llvm/ADT/STLExtras.h"
89#include "llvm/ADT/ScopeExit.h"
90#include "llvm/ADT/SmallPtrSet.h"
91#include "llvm/ADT/SmallString.h"
92#include "llvm/ADT/SmallVector.h"
93#include "llvm/ADT/StringRef.h"
94#include "llvm/Bitstream/BitCodes.h"
95#include "llvm/Bitstream/BitstreamWriter.h"
96#include "llvm/Support/Compression.h"
97#include "llvm/Support/DJB.h"
98#include "llvm/Support/EndianStream.h"
99#include "llvm/Support/ErrorHandling.h"
100#include "llvm/Support/LEB128.h"
101#include "llvm/Support/MemoryBuffer.h"
102#include "llvm/Support/OnDiskHashTable.h"
103#include "llvm/Support/Path.h"
104#include "llvm/Support/SHA1.h"
105#include "llvm/Support/TimeProfiler.h"
106#include "llvm/Support/VersionTuple.h"
107#include "llvm/Support/raw_ostream.h"
108#include <algorithm>
109#include <cassert>
110#include <cstdint>
111#include <cstdlib>
112#include <cstring>
113#include <ctime>
114#include <limits>
115#include <memory>
116#include <optional>
117#include <queue>
118#include <tuple>
119#include <utility>
120#include <vector>
121
122using namespace clang;
123using namespace clang::serialization;
124
125template <typename T, typename Allocator>
126static StringRef bytes(const std::vector<T, Allocator> &v) {
127 if (v.empty()) return StringRef();
128 return StringRef(reinterpret_cast<const char*>(&v[0]),
129 sizeof(T) * v.size());
130}
131
132template <typename T>
133static StringRef bytes(const SmallVectorImpl<T> &v) {
134 return StringRef(reinterpret_cast<const char*>(v.data()),
135 sizeof(T) * v.size());
136}
137
138static std::string bytes(const std::vector<bool> &V) {
139 std::string Str;
140 Str.reserve(res: V.size() / 8);
141 for (unsigned I = 0, E = V.size(); I < E;) {
142 char Byte = 0;
143 for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
144 Byte |= V[I] << Bit;
145 Str += Byte;
146 }
147 return Str;
148}
149
150//===----------------------------------------------------------------------===//
151// Type serialization
152//===----------------------------------------------------------------------===//
153
154static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
155 switch (id) {
156#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
157 case Type::CLASS_ID: return TYPE_##CODE_ID;
158#include "clang/Serialization/TypeBitCodes.def"
159 case Type::Builtin:
160 llvm_unreachable("shouldn't be serializing a builtin type this way");
161 }
162 llvm_unreachable("bad type kind");
163}
164
165namespace {
166
167struct AffectingModuleMaps {
168 llvm::DenseSet<FileID> DefinitionFileIDs;
169 llvm::DenseSet<const FileEntry *> DefinitionFiles;
170};
171
172std::optional<AffectingModuleMaps>
173GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) {
174 if (!PP.getHeaderSearchInfo()
175 .getHeaderSearchOpts()
176 .ModulesPruneNonAffectingModuleMaps)
177 return std::nullopt;
178
179 const HeaderSearch &HS = PP.getHeaderSearchInfo();
180 const SourceManager &SM = PP.getSourceManager();
181 const ModuleMap &MM = HS.getModuleMap();
182
183 // Module maps used only by textual headers are special. Their FileID is
184 // non-affecting, but their FileEntry is (i.e. must be written as InputFile).
185 enum AffectedReason : bool {
186 AR_TextualHeader = 0,
187 AR_ImportOrTextualHeader = 1,
188 };
189 auto AssignMostImportant = [](AffectedReason &LHS, AffectedReason RHS) {
190 LHS = std::max(a: LHS, b: RHS);
191 };
192 llvm::DenseMap<FileID, AffectedReason> ModuleMaps;
193 llvm::DenseMap<const Module *, AffectedReason> ProcessedModules;
194 auto CollectModuleMapsForHierarchy = [&](const Module *M,
195 AffectedReason Reason) {
196 M = M->getTopLevelModule();
197
198 // We need to process the header either when it was not present or when we
199 // previously flagged module map as textual headers and now we found a
200 // proper import.
201 if (auto [It, Inserted] = ProcessedModules.insert(KV: {M, Reason});
202 !Inserted && Reason <= It->second) {
203 return;
204 } else {
205 It->second = Reason;
206 }
207
208 std::queue<const Module *> Q;
209 Q.push(x: M);
210 while (!Q.empty()) {
211 const Module *Mod = Q.front();
212 Q.pop();
213
214 // The containing module map is affecting, because it's being pointed
215 // into by Module::DefinitionLoc.
216 if (auto F = MM.getContainingModuleMapFileID(Module: Mod); F.isValid())
217 AssignMostImportant(ModuleMaps[F], Reason);
218 // For inferred modules, the module map that allowed inferring is not
219 // related to the virtual containing module map file. It did affect the
220 // compilation, though.
221 if (auto UniqF = MM.getModuleMapFileIDForUniquing(M: Mod); UniqF.isValid())
222 AssignMostImportant(ModuleMaps[UniqF], Reason);
223
224 for (auto *SubM : Mod->submodules())
225 Q.push(x: SubM);
226 }
227 };
228
229 // Handle all the affecting modules referenced from the root module.
230
231 CollectModuleMapsForHierarchy(RootModule, AR_ImportOrTextualHeader);
232
233 std::queue<const Module *> Q;
234 Q.push(x: RootModule);
235 while (!Q.empty()) {
236 const Module *CurrentModule = Q.front();
237 Q.pop();
238
239 for (const Module *ImportedModule : CurrentModule->Imports)
240 CollectModuleMapsForHierarchy(ImportedModule, AR_ImportOrTextualHeader);
241 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
242 CollectModuleMapsForHierarchy(UndeclaredModule, AR_ImportOrTextualHeader);
243
244 for (auto *M : CurrentModule->submodules())
245 Q.push(x: M);
246 }
247
248 // Handle textually-included headers that belong to other modules.
249
250 SmallVector<OptionalFileEntryRef, 16> FilesByUID;
251 HS.getFileMgr().GetUniqueIDMapping(UIDToFiles&: FilesByUID);
252
253 if (FilesByUID.size() > HS.header_file_size())
254 FilesByUID.resize(N: HS.header_file_size());
255
256 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
257 OptionalFileEntryRef File = FilesByUID[UID];
258 if (!File)
259 continue;
260
261 const HeaderFileInfo *HFI = HS.getExistingLocalFileInfo(FE: *File);
262 if (!HFI)
263 continue; // We have no information on this being a header file.
264 if (!HFI->isCompilingModuleHeader && HFI->isModuleHeader)
265 continue; // Modular header, handled in the above module-based loop.
266 if (!HFI->isCompilingModuleHeader && !HFI->IsLocallyIncluded)
267 continue; // Non-modular header not included locally is not affecting.
268
269 for (const auto &KH : HS.findResolvedModulesForHeader(File: *File))
270 if (const Module *M = KH.getModule())
271 CollectModuleMapsForHierarchy(M, AR_TextualHeader);
272 }
273
274 // FIXME: This algorithm is not correct for module map hierarchies where
275 // module map file defining a (sub)module of a top-level module X includes
276 // a module map file that defines a (sub)module of another top-level module Y.
277 // Whenever X is affecting and Y is not, "replaying" this PCM file will fail
278 // when parsing module map files for X due to not knowing about the `extern`
279 // module map for Y.
280 //
281 // We don't have a good way to fix it here. We could mark all children of
282 // affecting module map files as being affecting as well, but that's
283 // expensive. SourceManager does not model the edge from parent to child
284 // SLocEntries, so instead, we would need to iterate over leaf module map
285 // files, walk up their include hierarchy and check whether we arrive at an
286 // affecting module map.
287 //
288 // Instead of complicating and slowing down this function, we should probably
289 // just ban module map hierarchies where module map defining a (sub)module X
290 // includes a module map defining a module that's not a submodule of X.
291
292 llvm::DenseSet<const FileEntry *> ModuleFileEntries;
293 llvm::DenseSet<FileID> ModuleFileIDs;
294 for (auto [FID, Reason] : ModuleMaps) {
295 if (Reason == AR_ImportOrTextualHeader)
296 ModuleFileIDs.insert(V: FID);
297 if (auto *FE = SM.getFileEntryForID(FID))
298 ModuleFileEntries.insert(V: FE);
299 }
300
301 AffectingModuleMaps R;
302 R.DefinitionFileIDs = std::move(ModuleFileIDs);
303 R.DefinitionFiles = std::move(ModuleFileEntries);
304 return std::move(R);
305}
306
307class ASTTypeWriter {
308 ASTWriter &Writer;
309 ASTWriter::RecordData Record;
310 ASTRecordWriter BasicWriter;
311
312public:
313 ASTTypeWriter(ASTContext &Context, ASTWriter &Writer)
314 : Writer(Writer), BasicWriter(Context, Writer, Record) {}
315
316 uint64_t write(QualType T) {
317 if (T.hasLocalNonFastQualifiers()) {
318 Qualifiers Qs = T.getLocalQualifiers();
319 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
320 BasicWriter.writeQualifiers(Qs);
321 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
322 }
323
324 const Type *typePtr = T.getTypePtr();
325 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
326 atw.write(typePtr);
327 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
328 /*abbrev*/ 0);
329 }
330};
331
332class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
333 using LocSeq = SourceLocationSequence;
334
335 ASTRecordWriter &Record;
336 LocSeq *Seq;
337
338 void addSourceLocation(SourceLocation Loc) {
339 Record.AddSourceLocation(Loc, Seq);
340 }
341 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); }
342
343public:
344 TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq)
345 : Record(Record), Seq(Seq) {}
346
347#define ABSTRACT_TYPELOC(CLASS, PARENT)
348#define TYPELOC(CLASS, PARENT) \
349 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
350#include "clang/AST/TypeLocNodes.def"
351
352 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
353 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
354};
355
356} // namespace
357
358void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
359 // nothing to do
360}
361
362void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
363 addSourceLocation(Loc: TL.getBuiltinLoc());
364 if (TL.needsExtraLocalData()) {
365 Record.push_back(N: TL.getWrittenTypeSpec());
366 Record.push_back(N: static_cast<uint64_t>(TL.getWrittenSignSpec()));
367 Record.push_back(N: static_cast<uint64_t>(TL.getWrittenWidthSpec()));
368 Record.push_back(N: TL.hasModeAttr());
369 }
370}
371
372void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
373 addSourceLocation(Loc: TL.getNameLoc());
374}
375
376void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
377 addSourceLocation(Loc: TL.getStarLoc());
378}
379
380void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
381 // nothing to do
382}
383
384void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
385 // nothing to do
386}
387
388void TypeLocWriter::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
389 // nothing to do
390}
391
392void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
393 addSourceLocation(Loc: TL.getCaretLoc());
394}
395
396void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
397 addSourceLocation(Loc: TL.getAmpLoc());
398}
399
400void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
401 addSourceLocation(Loc: TL.getAmpAmpLoc());
402}
403
404void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
405 addSourceLocation(Loc: TL.getStarLoc());
406 Record.AddNestedNameSpecifierLoc(NNS: TL.getQualifierLoc());
407}
408
409void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
410 addSourceLocation(Loc: TL.getLBracketLoc());
411 addSourceLocation(Loc: TL.getRBracketLoc());
412 Record.push_back(N: TL.getSizeExpr() ? 1 : 0);
413 if (TL.getSizeExpr())
414 Record.AddStmt(TL.getSizeExpr());
415}
416
417void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
418 VisitArrayTypeLoc(TL);
419}
420
421void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
422 VisitArrayTypeLoc(TL);
423}
424
425void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
426 VisitArrayTypeLoc(TL);
427}
428
429void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
430 DependentSizedArrayTypeLoc TL) {
431 VisitArrayTypeLoc(TL);
432}
433
434void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
435 DependentAddressSpaceTypeLoc TL) {
436 addSourceLocation(Loc: TL.getAttrNameLoc());
437 SourceRange range = TL.getAttrOperandParensRange();
438 addSourceLocation(Loc: range.getBegin());
439 addSourceLocation(Loc: range.getEnd());
440 Record.AddStmt(TL.getAttrExprOperand());
441}
442
443void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
444 DependentSizedExtVectorTypeLoc TL) {
445 addSourceLocation(Loc: TL.getNameLoc());
446}
447
448void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
449 addSourceLocation(Loc: TL.getNameLoc());
450}
451
452void TypeLocWriter::VisitDependentVectorTypeLoc(
453 DependentVectorTypeLoc TL) {
454 addSourceLocation(Loc: TL.getNameLoc());
455}
456
457void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
458 addSourceLocation(Loc: TL.getNameLoc());
459}
460
461void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
462 addSourceLocation(Loc: TL.getAttrNameLoc());
463 SourceRange range = TL.getAttrOperandParensRange();
464 addSourceLocation(Loc: range.getBegin());
465 addSourceLocation(Loc: range.getEnd());
466 Record.AddStmt(S: TL.getAttrRowOperand());
467 Record.AddStmt(S: TL.getAttrColumnOperand());
468}
469
470void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
471 DependentSizedMatrixTypeLoc TL) {
472 addSourceLocation(Loc: TL.getAttrNameLoc());
473 SourceRange range = TL.getAttrOperandParensRange();
474 addSourceLocation(Loc: range.getBegin());
475 addSourceLocation(Loc: range.getEnd());
476 Record.AddStmt(S: TL.getAttrRowOperand());
477 Record.AddStmt(S: TL.getAttrColumnOperand());
478}
479
480void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
481 addSourceLocation(Loc: TL.getLocalRangeBegin());
482 addSourceLocation(Loc: TL.getLParenLoc());
483 addSourceLocation(Loc: TL.getRParenLoc());
484 addSourceRange(Range: TL.getExceptionSpecRange());
485 addSourceLocation(Loc: TL.getLocalRangeEnd());
486 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
487 Record.AddDeclRef(TL.getParam(i));
488}
489
490void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
491 VisitFunctionTypeLoc(TL);
492}
493
494void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
495 VisitFunctionTypeLoc(TL);
496}
497
498void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
499 addSourceLocation(Loc: TL.getNameLoc());
500}
501
502void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
503 addSourceLocation(Loc: TL.getNameLoc());
504}
505
506void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
507 addSourceLocation(Loc: TL.getNameLoc());
508}
509
510void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
511 if (TL.getNumProtocols()) {
512 addSourceLocation(Loc: TL.getProtocolLAngleLoc());
513 addSourceLocation(Loc: TL.getProtocolRAngleLoc());
514 }
515 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
516 addSourceLocation(Loc: TL.getProtocolLoc(i));
517}
518
519void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
520 addSourceLocation(Loc: TL.getTypeofLoc());
521 addSourceLocation(Loc: TL.getLParenLoc());
522 addSourceLocation(Loc: TL.getRParenLoc());
523}
524
525void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
526 addSourceLocation(Loc: TL.getTypeofLoc());
527 addSourceLocation(Loc: TL.getLParenLoc());
528 addSourceLocation(Loc: TL.getRParenLoc());
529 Record.AddTypeSourceInfo(TInfo: TL.getUnmodifiedTInfo());
530}
531
532void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
533 addSourceLocation(Loc: TL.getDecltypeLoc());
534 addSourceLocation(Loc: TL.getRParenLoc());
535}
536
537void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
538 addSourceLocation(Loc: TL.getKWLoc());
539 addSourceLocation(Loc: TL.getLParenLoc());
540 addSourceLocation(Loc: TL.getRParenLoc());
541 Record.AddTypeSourceInfo(TInfo: TL.getUnderlyingTInfo());
542}
543
544void ASTRecordWriter::AddConceptReference(const ConceptReference *CR) {
545 assert(CR);
546 AddNestedNameSpecifierLoc(NNS: CR->getNestedNameSpecifierLoc());
547 AddSourceLocation(Loc: CR->getTemplateKWLoc());
548 AddDeclarationNameInfo(NameInfo: CR->getConceptNameInfo());
549 AddDeclRef(CR->getFoundDecl());
550 AddDeclRef(CR->getNamedConcept());
551 push_back(N: CR->getTemplateArgsAsWritten() != nullptr);
552 if (CR->getTemplateArgsAsWritten())
553 AddASTTemplateArgumentListInfo(ASTTemplArgList: CR->getTemplateArgsAsWritten());
554}
555
556void TypeLocWriter::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
557 addSourceLocation(Loc: TL.getEllipsisLoc());
558}
559
560void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
561 addSourceLocation(Loc: TL.getNameLoc());
562 auto *CR = TL.getConceptReference();
563 Record.push_back(N: TL.isConstrained() && CR);
564 if (TL.isConstrained() && CR)
565 Record.AddConceptReference(CR);
566 Record.push_back(N: TL.isDecltypeAuto());
567 if (TL.isDecltypeAuto())
568 addSourceLocation(Loc: TL.getRParenLoc());
569}
570
571void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
572 DeducedTemplateSpecializationTypeLoc TL) {
573 addSourceLocation(Loc: TL.getTemplateNameLoc());
574}
575
576void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
577 addSourceLocation(Loc: TL.getNameLoc());
578}
579
580void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
581 addSourceLocation(Loc: TL.getNameLoc());
582}
583
584void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
585 Record.AddAttr(A: TL.getAttr());
586}
587
588void TypeLocWriter::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
589 // Nothing to do
590}
591
592void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
593 // Nothing to do.
594}
595
596void TypeLocWriter::VisitHLSLAttributedResourceTypeLoc(
597 HLSLAttributedResourceTypeLoc TL) {
598 // Nothing to do.
599}
600
601void TypeLocWriter::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
602 // Nothing to do.
603}
604
605void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
606 addSourceLocation(Loc: TL.getNameLoc());
607}
608
609void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
610 SubstTemplateTypeParmTypeLoc TL) {
611 addSourceLocation(Loc: TL.getNameLoc());
612}
613
614void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
615 SubstTemplateTypeParmPackTypeLoc TL) {
616 addSourceLocation(Loc: TL.getNameLoc());
617}
618
619void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
620 TemplateSpecializationTypeLoc TL) {
621 addSourceLocation(Loc: TL.getTemplateKeywordLoc());
622 addSourceLocation(Loc: TL.getTemplateNameLoc());
623 addSourceLocation(Loc: TL.getLAngleLoc());
624 addSourceLocation(Loc: TL.getRAngleLoc());
625 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
626 Record.AddTemplateArgumentLocInfo(Kind: TL.getArgLoc(i).getArgument().getKind(),
627 Arg: TL.getArgLoc(i).getLocInfo());
628}
629
630void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
631 addSourceLocation(Loc: TL.getLParenLoc());
632 addSourceLocation(Loc: TL.getRParenLoc());
633}
634
635void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
636 addSourceLocation(Loc: TL.getExpansionLoc());
637}
638
639void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
640 addSourceLocation(Loc: TL.getElaboratedKeywordLoc());
641 Record.AddNestedNameSpecifierLoc(NNS: TL.getQualifierLoc());
642}
643
644void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
645 addSourceLocation(Loc: TL.getNameLoc());
646}
647
648void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
649 addSourceLocation(Loc: TL.getElaboratedKeywordLoc());
650 Record.AddNestedNameSpecifierLoc(NNS: TL.getQualifierLoc());
651 addSourceLocation(Loc: TL.getNameLoc());
652}
653
654void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
655 DependentTemplateSpecializationTypeLoc TL) {
656 addSourceLocation(Loc: TL.getElaboratedKeywordLoc());
657 Record.AddNestedNameSpecifierLoc(NNS: TL.getQualifierLoc());
658 addSourceLocation(Loc: TL.getTemplateKeywordLoc());
659 addSourceLocation(Loc: TL.getTemplateNameLoc());
660 addSourceLocation(Loc: TL.getLAngleLoc());
661 addSourceLocation(Loc: TL.getRAngleLoc());
662 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
663 Record.AddTemplateArgumentLocInfo(Kind: TL.getArgLoc(i: I).getArgument().getKind(),
664 Arg: TL.getArgLoc(i: I).getLocInfo());
665}
666
667void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
668 addSourceLocation(Loc: TL.getEllipsisLoc());
669}
670
671void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
672 addSourceLocation(Loc: TL.getNameLoc());
673 addSourceLocation(Loc: TL.getNameEndLoc());
674}
675
676void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
677 Record.push_back(N: TL.hasBaseTypeAsWritten());
678 addSourceLocation(Loc: TL.getTypeArgsLAngleLoc());
679 addSourceLocation(Loc: TL.getTypeArgsRAngleLoc());
680 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
681 Record.AddTypeSourceInfo(TInfo: TL.getTypeArgTInfo(i));
682 addSourceLocation(Loc: TL.getProtocolLAngleLoc());
683 addSourceLocation(Loc: TL.getProtocolRAngleLoc());
684 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
685 addSourceLocation(Loc: TL.getProtocolLoc(i));
686}
687
688void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
689 addSourceLocation(Loc: TL.getStarLoc());
690}
691
692void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
693 addSourceLocation(Loc: TL.getKWLoc());
694 addSourceLocation(Loc: TL.getLParenLoc());
695 addSourceLocation(Loc: TL.getRParenLoc());
696}
697
698void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
699 addSourceLocation(Loc: TL.getKWLoc());
700}
701
702void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
703 addSourceLocation(Loc: TL.getNameLoc());
704}
705void TypeLocWriter::VisitDependentBitIntTypeLoc(
706 clang::DependentBitIntTypeLoc TL) {
707 addSourceLocation(Loc: TL.getNameLoc());
708}
709
710void ASTWriter::WriteTypeAbbrevs() {
711 using namespace llvm;
712
713 std::shared_ptr<BitCodeAbbrev> Abv;
714
715 // Abbreviation for TYPE_EXT_QUAL
716 Abv = std::make_shared<BitCodeAbbrev>();
717 Abv->Add(OpInfo: BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
718 Abv->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
719 Abv->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
720 TypeExtQualAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
721}
722
723//===----------------------------------------------------------------------===//
724// ASTWriter Implementation
725//===----------------------------------------------------------------------===//
726
727static void EmitBlockID(unsigned ID, const char *Name,
728 llvm::BitstreamWriter &Stream,
729 ASTWriter::RecordDataImpl &Record) {
730 Record.clear();
731 Record.push_back(Elt: ID);
732 Stream.EmitRecord(Code: llvm::bitc::BLOCKINFO_CODE_SETBID, Vals: Record);
733
734 // Emit the block name if present.
735 if (!Name || Name[0] == 0)
736 return;
737 Record.clear();
738 while (*Name)
739 Record.push_back(Elt: *Name++);
740 Stream.EmitRecord(Code: llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Vals: Record);
741}
742
743static void EmitRecordID(unsigned ID, const char *Name,
744 llvm::BitstreamWriter &Stream,
745 ASTWriter::RecordDataImpl &Record) {
746 Record.clear();
747 Record.push_back(Elt: ID);
748 while (*Name)
749 Record.push_back(Elt: *Name++);
750 Stream.EmitRecord(Code: llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Vals: Record);
751}
752
753static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
754 ASTWriter::RecordDataImpl &Record) {
755#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
756 RECORD(STMT_STOP);
757 RECORD(STMT_NULL_PTR);
758 RECORD(STMT_REF_PTR);
759 RECORD(STMT_NULL);
760 RECORD(STMT_COMPOUND);
761 RECORD(STMT_CASE);
762 RECORD(STMT_DEFAULT);
763 RECORD(STMT_LABEL);
764 RECORD(STMT_ATTRIBUTED);
765 RECORD(STMT_IF);
766 RECORD(STMT_SWITCH);
767 RECORD(STMT_WHILE);
768 RECORD(STMT_DO);
769 RECORD(STMT_FOR);
770 RECORD(STMT_GOTO);
771 RECORD(STMT_INDIRECT_GOTO);
772 RECORD(STMT_CONTINUE);
773 RECORD(STMT_BREAK);
774 RECORD(STMT_RETURN);
775 RECORD(STMT_DECL);
776 RECORD(STMT_GCCASM);
777 RECORD(STMT_MSASM);
778 RECORD(EXPR_PREDEFINED);
779 RECORD(EXPR_DECL_REF);
780 RECORD(EXPR_INTEGER_LITERAL);
781 RECORD(EXPR_FIXEDPOINT_LITERAL);
782 RECORD(EXPR_FLOATING_LITERAL);
783 RECORD(EXPR_IMAGINARY_LITERAL);
784 RECORD(EXPR_STRING_LITERAL);
785 RECORD(EXPR_CHARACTER_LITERAL);
786 RECORD(EXPR_PAREN);
787 RECORD(EXPR_PAREN_LIST);
788 RECORD(EXPR_UNARY_OPERATOR);
789 RECORD(EXPR_SIZEOF_ALIGN_OF);
790 RECORD(EXPR_ARRAY_SUBSCRIPT);
791 RECORD(EXPR_CALL);
792 RECORD(EXPR_MEMBER);
793 RECORD(EXPR_BINARY_OPERATOR);
794 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
795 RECORD(EXPR_CONDITIONAL_OPERATOR);
796 RECORD(EXPR_IMPLICIT_CAST);
797 RECORD(EXPR_CSTYLE_CAST);
798 RECORD(EXPR_COMPOUND_LITERAL);
799 RECORD(EXPR_EXT_VECTOR_ELEMENT);
800 RECORD(EXPR_INIT_LIST);
801 RECORD(EXPR_DESIGNATED_INIT);
802 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
803 RECORD(EXPR_IMPLICIT_VALUE_INIT);
804 RECORD(EXPR_NO_INIT);
805 RECORD(EXPR_VA_ARG);
806 RECORD(EXPR_ADDR_LABEL);
807 RECORD(EXPR_STMT);
808 RECORD(EXPR_CHOOSE);
809 RECORD(EXPR_GNU_NULL);
810 RECORD(EXPR_SHUFFLE_VECTOR);
811 RECORD(EXPR_BLOCK);
812 RECORD(EXPR_GENERIC_SELECTION);
813 RECORD(EXPR_OBJC_STRING_LITERAL);
814 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
815 RECORD(EXPR_OBJC_ARRAY_LITERAL);
816 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
817 RECORD(EXPR_OBJC_ENCODE);
818 RECORD(EXPR_OBJC_SELECTOR_EXPR);
819 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
820 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
821 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
822 RECORD(EXPR_OBJC_KVC_REF_EXPR);
823 RECORD(EXPR_OBJC_MESSAGE_EXPR);
824 RECORD(STMT_OBJC_FOR_COLLECTION);
825 RECORD(STMT_OBJC_CATCH);
826 RECORD(STMT_OBJC_FINALLY);
827 RECORD(STMT_OBJC_AT_TRY);
828 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
829 RECORD(STMT_OBJC_AT_THROW);
830 RECORD(EXPR_OBJC_BOOL_LITERAL);
831 RECORD(STMT_CXX_CATCH);
832 RECORD(STMT_CXX_TRY);
833 RECORD(STMT_CXX_FOR_RANGE);
834 RECORD(EXPR_CXX_OPERATOR_CALL);
835 RECORD(EXPR_CXX_MEMBER_CALL);
836 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
837 RECORD(EXPR_CXX_CONSTRUCT);
838 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
839 RECORD(EXPR_CXX_STATIC_CAST);
840 RECORD(EXPR_CXX_DYNAMIC_CAST);
841 RECORD(EXPR_CXX_REINTERPRET_CAST);
842 RECORD(EXPR_CXX_CONST_CAST);
843 RECORD(EXPR_CXX_ADDRSPACE_CAST);
844 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
845 RECORD(EXPR_USER_DEFINED_LITERAL);
846 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
847 RECORD(EXPR_CXX_BOOL_LITERAL);
848 RECORD(EXPR_CXX_PAREN_LIST_INIT);
849 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
850 RECORD(EXPR_CXX_TYPEID_EXPR);
851 RECORD(EXPR_CXX_TYPEID_TYPE);
852 RECORD(EXPR_CXX_THIS);
853 RECORD(EXPR_CXX_THROW);
854 RECORD(EXPR_CXX_DEFAULT_ARG);
855 RECORD(EXPR_CXX_DEFAULT_INIT);
856 RECORD(EXPR_CXX_BIND_TEMPORARY);
857 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
858 RECORD(EXPR_CXX_NEW);
859 RECORD(EXPR_CXX_DELETE);
860 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
861 RECORD(EXPR_EXPR_WITH_CLEANUPS);
862 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
863 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
864 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
865 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
866 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
867 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
868 RECORD(EXPR_CXX_NOEXCEPT);
869 RECORD(EXPR_OPAQUE_VALUE);
870 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
871 RECORD(EXPR_TYPE_TRAIT);
872 RECORD(EXPR_ARRAY_TYPE_TRAIT);
873 RECORD(EXPR_PACK_EXPANSION);
874 RECORD(EXPR_SIZEOF_PACK);
875 RECORD(EXPR_PACK_INDEXING);
876 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
877 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
878 RECORD(EXPR_FUNCTION_PARM_PACK);
879 RECORD(EXPR_MATERIALIZE_TEMPORARY);
880 RECORD(EXPR_CUDA_KERNEL_CALL);
881 RECORD(EXPR_CXX_UUIDOF_EXPR);
882 RECORD(EXPR_CXX_UUIDOF_TYPE);
883 RECORD(EXPR_LAMBDA);
884#undef RECORD
885}
886
887void ASTWriter::WriteBlockInfoBlock() {
888 RecordData Record;
889 Stream.EnterBlockInfoBlock();
890
891#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
892#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
893
894 // Control Block.
895 BLOCK(CONTROL_BLOCK);
896 RECORD(METADATA);
897 RECORD(MODULE_NAME);
898 RECORD(MODULE_DIRECTORY);
899 RECORD(MODULE_MAP_FILE);
900 RECORD(IMPORT);
901 RECORD(ORIGINAL_FILE);
902 RECORD(ORIGINAL_FILE_ID);
903 RECORD(INPUT_FILE_OFFSETS);
904
905 BLOCK(OPTIONS_BLOCK);
906 RECORD(LANGUAGE_OPTIONS);
907 RECORD(TARGET_OPTIONS);
908 RECORD(FILE_SYSTEM_OPTIONS);
909 RECORD(HEADER_SEARCH_OPTIONS);
910 RECORD(PREPROCESSOR_OPTIONS);
911
912 BLOCK(INPUT_FILES_BLOCK);
913 RECORD(INPUT_FILE);
914 RECORD(INPUT_FILE_HASH);
915
916 // AST Top-Level Block.
917 BLOCK(AST_BLOCK);
918 RECORD(TYPE_OFFSET);
919 RECORD(DECL_OFFSET);
920 RECORD(IDENTIFIER_OFFSET);
921 RECORD(IDENTIFIER_TABLE);
922 RECORD(EAGERLY_DESERIALIZED_DECLS);
923 RECORD(MODULAR_CODEGEN_DECLS);
924 RECORD(SPECIAL_TYPES);
925 RECORD(STATISTICS);
926 RECORD(TENTATIVE_DEFINITIONS);
927 RECORD(SELECTOR_OFFSETS);
928 RECORD(METHOD_POOL);
929 RECORD(PP_COUNTER_VALUE);
930 RECORD(SOURCE_LOCATION_OFFSETS);
931 RECORD(EXT_VECTOR_DECLS);
932 RECORD(UNUSED_FILESCOPED_DECLS);
933 RECORD(PPD_ENTITIES_OFFSETS);
934 RECORD(VTABLE_USES);
935 RECORD(PPD_SKIPPED_RANGES);
936 RECORD(REFERENCED_SELECTOR_POOL);
937 RECORD(TU_UPDATE_LEXICAL);
938 RECORD(SEMA_DECL_REFS);
939 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
940 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
941 RECORD(UPDATE_VISIBLE);
942 RECORD(DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD);
943 RECORD(RELATED_DECLS_MAP);
944 RECORD(DECL_UPDATE_OFFSETS);
945 RECORD(DECL_UPDATES);
946 RECORD(CUDA_SPECIAL_DECL_REFS);
947 RECORD(HEADER_SEARCH_TABLE);
948 RECORD(FP_PRAGMA_OPTIONS);
949 RECORD(OPENCL_EXTENSIONS);
950 RECORD(OPENCL_EXTENSION_TYPES);
951 RECORD(OPENCL_EXTENSION_DECLS);
952 RECORD(DELEGATING_CTORS);
953 RECORD(KNOWN_NAMESPACES);
954 RECORD(MODULE_OFFSET_MAP);
955 RECORD(SOURCE_MANAGER_LINE_TABLE);
956 RECORD(OBJC_CATEGORIES_MAP);
957 RECORD(FILE_SORTED_DECLS);
958 RECORD(IMPORTED_MODULES);
959 RECORD(OBJC_CATEGORIES);
960 RECORD(MACRO_OFFSET);
961 RECORD(INTERESTING_IDENTIFIERS);
962 RECORD(UNDEFINED_BUT_USED);
963 RECORD(LATE_PARSED_TEMPLATE);
964 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
965 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
966 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
967 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
968 RECORD(DELETE_EXPRS_TO_ANALYZE);
969 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
970 RECORD(PP_CONDITIONAL_STACK);
971 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
972 RECORD(PP_ASSUME_NONNULL_LOC);
973 RECORD(PP_UNSAFE_BUFFER_USAGE);
974 RECORD(VTABLES_TO_EMIT);
975
976 // SourceManager Block.
977 BLOCK(SOURCE_MANAGER_BLOCK);
978 RECORD(SM_SLOC_FILE_ENTRY);
979 RECORD(SM_SLOC_BUFFER_ENTRY);
980 RECORD(SM_SLOC_BUFFER_BLOB);
981 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
982 RECORD(SM_SLOC_EXPANSION_ENTRY);
983
984 // Preprocessor Block.
985 BLOCK(PREPROCESSOR_BLOCK);
986 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
987 RECORD(PP_MACRO_FUNCTION_LIKE);
988 RECORD(PP_MACRO_OBJECT_LIKE);
989 RECORD(PP_MODULE_MACRO);
990 RECORD(PP_TOKEN);
991
992 // Submodule Block.
993 BLOCK(SUBMODULE_BLOCK);
994 RECORD(SUBMODULE_METADATA);
995 RECORD(SUBMODULE_DEFINITION);
996 RECORD(SUBMODULE_UMBRELLA_HEADER);
997 RECORD(SUBMODULE_HEADER);
998 RECORD(SUBMODULE_TOPHEADER);
999 RECORD(SUBMODULE_UMBRELLA_DIR);
1000 RECORD(SUBMODULE_IMPORTS);
1001 RECORD(SUBMODULE_AFFECTING_MODULES);
1002 RECORD(SUBMODULE_EXPORTS);
1003 RECORD(SUBMODULE_REQUIRES);
1004 RECORD(SUBMODULE_EXCLUDED_HEADER);
1005 RECORD(SUBMODULE_LINK_LIBRARY);
1006 RECORD(SUBMODULE_CONFIG_MACRO);
1007 RECORD(SUBMODULE_CONFLICT);
1008 RECORD(SUBMODULE_PRIVATE_HEADER);
1009 RECORD(SUBMODULE_TEXTUAL_HEADER);
1010 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1011 RECORD(SUBMODULE_INITIALIZERS);
1012 RECORD(SUBMODULE_EXPORT_AS);
1013
1014 // Comments Block.
1015 BLOCK(COMMENTS_BLOCK);
1016 RECORD(COMMENTS_RAW_COMMENT);
1017
1018 // Decls and Types block.
1019 BLOCK(DECLTYPES_BLOCK);
1020 RECORD(TYPE_EXT_QUAL);
1021 RECORD(TYPE_COMPLEX);
1022 RECORD(TYPE_POINTER);
1023 RECORD(TYPE_BLOCK_POINTER);
1024 RECORD(TYPE_LVALUE_REFERENCE);
1025 RECORD(TYPE_RVALUE_REFERENCE);
1026 RECORD(TYPE_MEMBER_POINTER);
1027 RECORD(TYPE_CONSTANT_ARRAY);
1028 RECORD(TYPE_INCOMPLETE_ARRAY);
1029 RECORD(TYPE_VARIABLE_ARRAY);
1030 RECORD(TYPE_VECTOR);
1031 RECORD(TYPE_EXT_VECTOR);
1032 RECORD(TYPE_FUNCTION_NO_PROTO);
1033 RECORD(TYPE_FUNCTION_PROTO);
1034 RECORD(TYPE_TYPEDEF);
1035 RECORD(TYPE_TYPEOF_EXPR);
1036 RECORD(TYPE_TYPEOF);
1037 RECORD(TYPE_RECORD);
1038 RECORD(TYPE_ENUM);
1039 RECORD(TYPE_OBJC_INTERFACE);
1040 RECORD(TYPE_OBJC_OBJECT_POINTER);
1041 RECORD(TYPE_DECLTYPE);
1042 RECORD(TYPE_ELABORATED);
1043 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1044 RECORD(TYPE_UNRESOLVED_USING);
1045 RECORD(TYPE_INJECTED_CLASS_NAME);
1046 RECORD(TYPE_OBJC_OBJECT);
1047 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1048 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1049 RECORD(TYPE_DEPENDENT_NAME);
1050 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1051 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1052 RECORD(TYPE_PAREN);
1053 RECORD(TYPE_MACRO_QUALIFIED);
1054 RECORD(TYPE_PACK_EXPANSION);
1055 RECORD(TYPE_ATTRIBUTED);
1056 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1057 RECORD(TYPE_AUTO);
1058 RECORD(TYPE_UNARY_TRANSFORM);
1059 RECORD(TYPE_ATOMIC);
1060 RECORD(TYPE_DECAYED);
1061 RECORD(TYPE_ADJUSTED);
1062 RECORD(TYPE_OBJC_TYPE_PARAM);
1063 RECORD(LOCAL_REDECLARATIONS);
1064 RECORD(DECL_TYPEDEF);
1065 RECORD(DECL_TYPEALIAS);
1066 RECORD(DECL_ENUM);
1067 RECORD(DECL_RECORD);
1068 RECORD(DECL_ENUM_CONSTANT);
1069 RECORD(DECL_FUNCTION);
1070 RECORD(DECL_OBJC_METHOD);
1071 RECORD(DECL_OBJC_INTERFACE);
1072 RECORD(DECL_OBJC_PROTOCOL);
1073 RECORD(DECL_OBJC_IVAR);
1074 RECORD(DECL_OBJC_AT_DEFS_FIELD);
1075 RECORD(DECL_OBJC_CATEGORY);
1076 RECORD(DECL_OBJC_CATEGORY_IMPL);
1077 RECORD(DECL_OBJC_IMPLEMENTATION);
1078 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1079 RECORD(DECL_OBJC_PROPERTY);
1080 RECORD(DECL_OBJC_PROPERTY_IMPL);
1081 RECORD(DECL_FIELD);
1082 RECORD(DECL_MS_PROPERTY);
1083 RECORD(DECL_VAR);
1084 RECORD(DECL_IMPLICIT_PARAM);
1085 RECORD(DECL_PARM_VAR);
1086 RECORD(DECL_FILE_SCOPE_ASM);
1087 RECORD(DECL_BLOCK);
1088 RECORD(DECL_CONTEXT_LEXICAL);
1089 RECORD(DECL_CONTEXT_VISIBLE);
1090 RECORD(DECL_CONTEXT_MODULE_LOCAL_VISIBLE);
1091 RECORD(DECL_NAMESPACE);
1092 RECORD(DECL_NAMESPACE_ALIAS);
1093 RECORD(DECL_USING);
1094 RECORD(DECL_USING_SHADOW);
1095 RECORD(DECL_USING_DIRECTIVE);
1096 RECORD(DECL_UNRESOLVED_USING_VALUE);
1097 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1098 RECORD(DECL_LINKAGE_SPEC);
1099 RECORD(DECL_EXPORT);
1100 RECORD(DECL_CXX_RECORD);
1101 RECORD(DECL_CXX_METHOD);
1102 RECORD(DECL_CXX_CONSTRUCTOR);
1103 RECORD(DECL_CXX_DESTRUCTOR);
1104 RECORD(DECL_CXX_CONVERSION);
1105 RECORD(DECL_ACCESS_SPEC);
1106 RECORD(DECL_FRIEND);
1107 RECORD(DECL_FRIEND_TEMPLATE);
1108 RECORD(DECL_CLASS_TEMPLATE);
1109 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1110 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1111 RECORD(DECL_VAR_TEMPLATE);
1112 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1113 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1114 RECORD(DECL_FUNCTION_TEMPLATE);
1115 RECORD(DECL_TEMPLATE_TYPE_PARM);
1116 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1117 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1118 RECORD(DECL_CONCEPT);
1119 RECORD(DECL_REQUIRES_EXPR_BODY);
1120 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1121 RECORD(DECL_STATIC_ASSERT);
1122 RECORD(DECL_CXX_BASE_SPECIFIERS);
1123 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1124 RECORD(DECL_INDIRECTFIELD);
1125 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1126 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1127 RECORD(DECL_IMPORT);
1128 RECORD(DECL_OMP_THREADPRIVATE);
1129 RECORD(DECL_EMPTY);
1130 RECORD(DECL_OBJC_TYPE_PARAM);
1131 RECORD(DECL_OMP_CAPTUREDEXPR);
1132 RECORD(DECL_PRAGMA_COMMENT);
1133 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1134 RECORD(DECL_OMP_DECLARE_REDUCTION);
1135 RECORD(DECL_OMP_ALLOCATE);
1136 RECORD(DECL_HLSL_BUFFER);
1137 RECORD(DECL_OPENACC_DECLARE);
1138 RECORD(DECL_OPENACC_ROUTINE);
1139
1140 // Statements and Exprs can occur in the Decls and Types block.
1141 AddStmtsExprs(Stream, Record);
1142
1143 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1144 RECORD(PPD_MACRO_EXPANSION);
1145 RECORD(PPD_MACRO_DEFINITION);
1146 RECORD(PPD_INCLUSION_DIRECTIVE);
1147
1148 // Decls and Types block.
1149 BLOCK(EXTENSION_BLOCK);
1150 RECORD(EXTENSION_METADATA);
1151
1152 BLOCK(UNHASHED_CONTROL_BLOCK);
1153 RECORD(SIGNATURE);
1154 RECORD(AST_BLOCK_HASH);
1155 RECORD(DIAGNOSTIC_OPTIONS);
1156 RECORD(HEADER_SEARCH_PATHS);
1157 RECORD(DIAG_PRAGMA_MAPPINGS);
1158 RECORD(HEADER_SEARCH_ENTRY_USAGE);
1159 RECORD(VFS_USAGE);
1160
1161#undef RECORD
1162#undef BLOCK
1163 Stream.ExitBlock();
1164}
1165
1166/// Prepares a path for being written to an AST file by converting it
1167/// to an absolute path and removing nested './'s.
1168///
1169/// \return \c true if the path was changed.
1170static bool cleanPathForOutput(FileManager &FileMgr,
1171 SmallVectorImpl<char> &Path) {
1172 bool Changed = FileMgr.makeAbsolutePath(Path);
1173 return Changed | llvm::sys::path::remove_dots(path&: Path);
1174}
1175
1176/// Adjusts the given filename to only write out the portion of the
1177/// filename that is not part of the system root directory.
1178///
1179/// \param Filename the file name to adjust.
1180///
1181/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1182/// the returned filename will be adjusted by this root directory.
1183///
1184/// \returns either the original filename (if it needs no adjustment) or the
1185/// adjusted filename (which points into the @p Filename parameter).
1186static const char *
1187adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1188 assert(Filename && "No file name to adjust?");
1189
1190 if (BaseDir.empty())
1191 return Filename;
1192
1193 // Verify that the filename and the system root have the same prefix.
1194 unsigned Pos = 0;
1195 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1196 if (Filename[Pos] != BaseDir[Pos])
1197 return Filename; // Prefixes don't match.
1198
1199 // We hit the end of the filename before we hit the end of the system root.
1200 if (!Filename[Pos])
1201 return Filename;
1202
1203 // If there's not a path separator at the end of the base directory nor
1204 // immediately after it, then this isn't within the base directory.
1205 if (!llvm::sys::path::is_separator(value: Filename[Pos])) {
1206 if (!llvm::sys::path::is_separator(value: BaseDir.back()))
1207 return Filename;
1208 } else {
1209 // If the file name has a '/' at the current position, skip over the '/'.
1210 // We distinguish relative paths from absolute paths by the
1211 // absence of '/' at the beginning of relative paths.
1212 //
1213 // FIXME: This is wrong. We distinguish them by asking if the path is
1214 // absolute, which isn't the same thing. And there might be multiple '/'s
1215 // in a row. Use a better mechanism to indicate whether we have emitted an
1216 // absolute or relative path.
1217 ++Pos;
1218 }
1219
1220 return Filename + Pos;
1221}
1222
1223std::pair<ASTFileSignature, ASTFileSignature>
1224ASTWriter::createSignature() const {
1225 StringRef AllBytes(Buffer.data(), Buffer.size());
1226
1227 llvm::SHA1 Hasher;
1228 Hasher.update(Str: AllBytes.slice(Start: ASTBlockRange.first, End: ASTBlockRange.second));
1229 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Bytes: Hasher.result());
1230
1231 // Add the remaining bytes:
1232 // 1. Before the unhashed control block.
1233 Hasher.update(Str: AllBytes.slice(Start: 0, End: UnhashedControlBlockRange.first));
1234 // 2. Between the unhashed control block and the AST block.
1235 Hasher.update(
1236 Str: AllBytes.slice(Start: UnhashedControlBlockRange.second, End: ASTBlockRange.first));
1237 // 3. After the AST block.
1238 Hasher.update(Str: AllBytes.substr(Start: ASTBlockRange.second));
1239 ASTFileSignature Signature = ASTFileSignature::create(Bytes: Hasher.result());
1240
1241 return std::make_pair(x&: ASTBlockHash, y&: Signature);
1242}
1243
1244ASTFileSignature ASTWriter::createSignatureForNamedModule() const {
1245 llvm::SHA1 Hasher;
1246 Hasher.update(Str: StringRef(Buffer.data(), Buffer.size()));
1247
1248 assert(WritingModule);
1249 assert(WritingModule->isNamedModule());
1250
1251 // We need to combine all the export imported modules no matter
1252 // we used it or not.
1253 for (auto [ExportImported, _] : WritingModule->Exports)
1254 Hasher.update(Data: ExportImported->Signature);
1255
1256 // We combine all the used modules to make sure the signature is precise.
1257 // Consider the case like:
1258 //
1259 // // a.cppm
1260 // export module a;
1261 // export inline int a() { ... }
1262 //
1263 // // b.cppm
1264 // export module b;
1265 // import a;
1266 // export inline int b() { return a(); }
1267 //
1268 // Since both `a()` and `b()` are inline, we need to make sure the BMI of
1269 // `b.pcm` will change after the implementation of `a()` changes. We can't
1270 // get that naturally since we won't record the body of `a()` during the
1271 // writing process. We can't reuse ODRHash here since ODRHash won't calculate
1272 // the called function recursively. So ODRHash will be problematic if `a()`
1273 // calls other inline functions.
1274 //
1275 // Probably we can solve this by a new hash mechanism. But the safety and
1276 // efficiency may a problem too. Here we just combine the hash value of the
1277 // used modules conservatively.
1278 for (Module *M : TouchedTopLevelModules)
1279 Hasher.update(Data: M->Signature);
1280
1281 return ASTFileSignature::create(Bytes: Hasher.result());
1282}
1283
1284static void BackpatchSignatureAt(llvm::BitstreamWriter &Stream,
1285 const ASTFileSignature &S, uint64_t BitNo) {
1286 for (uint8_t Byte : S) {
1287 Stream.BackpatchByte(BitNo, NewByte: Byte);
1288 BitNo += 8;
1289 }
1290}
1291
1292ASTFileSignature ASTWriter::backpatchSignature() {
1293 if (isWritingStdCXXNamedModules()) {
1294 ASTFileSignature Signature = createSignatureForNamedModule();
1295 BackpatchSignatureAt(Stream, S: Signature, BitNo: SignatureOffset);
1296 return Signature;
1297 }
1298
1299 if (!WritingModule ||
1300 !PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent)
1301 return {};
1302
1303 // For implicit modules, write the hash of the PCM as its signature.
1304 ASTFileSignature ASTBlockHash;
1305 ASTFileSignature Signature;
1306 std::tie(args&: ASTBlockHash, args&: Signature) = createSignature();
1307
1308 BackpatchSignatureAt(Stream, S: ASTBlockHash, BitNo: ASTBlockHashOffset);
1309 BackpatchSignatureAt(Stream, S: Signature, BitNo: SignatureOffset);
1310
1311 return Signature;
1312}
1313
1314void ASTWriter::writeUnhashedControlBlock(Preprocessor &PP) {
1315 using namespace llvm;
1316
1317 // Flush first to prepare the PCM hash (signature).
1318 Stream.FlushToWord();
1319 UnhashedControlBlockRange.first = Stream.GetCurrentBitNo() >> 3;
1320
1321 // Enter the block and prepare to write records.
1322 RecordData Record;
1323 Stream.EnterSubblock(BlockID: UNHASHED_CONTROL_BLOCK_ID, CodeLen: 5);
1324
1325 // For implicit modules and C++20 named modules, write the hash of the PCM as
1326 // its signature.
1327 if (isWritingStdCXXNamedModules() ||
1328 (WritingModule &&
1329 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent)) {
1330 // At this point, we don't know the actual signature of the file or the AST
1331 // block - we're only able to compute those at the end of the serialization
1332 // process. Let's store dummy signatures for now, and replace them with the
1333 // real ones later on.
1334 // The bitstream VBR-encodes record elements, which makes backpatching them
1335 // really difficult. Let's store the signatures as blobs instead - they are
1336 // guaranteed to be word-aligned, and we control their format/encoding.
1337 auto Dummy = ASTFileSignature::createDummy();
1338 SmallString<128> Blob{Dummy.begin(), Dummy.end()};
1339
1340 // We don't need AST Block hash in named modules.
1341 if (!isWritingStdCXXNamedModules()) {
1342 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1343 Abbrev->Add(OpInfo: BitCodeAbbrevOp(AST_BLOCK_HASH));
1344 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1345 unsigned ASTBlockHashAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1346
1347 Record.push_back(Elt: AST_BLOCK_HASH);
1348 Stream.EmitRecordWithBlob(Abbrev: ASTBlockHashAbbrev, Vals: Record, Blob);
1349 ASTBlockHashOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1350 Record.clear();
1351 }
1352
1353 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1354 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SIGNATURE));
1355 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1356 unsigned SignatureAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1357
1358 Record.push_back(Elt: SIGNATURE);
1359 Stream.EmitRecordWithBlob(Abbrev: SignatureAbbrev, Vals: Record, Blob);
1360 SignatureOffset = Stream.GetCurrentBitNo() - Blob.size() * 8;
1361 Record.clear();
1362 }
1363
1364 const auto &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1365
1366 // Diagnostic options.
1367 const auto &Diags = PP.getDiagnostics();
1368 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1369 if (!HSOpts.ModulesSkipDiagnosticOptions) {
1370#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1371#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1372 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1373#include "clang/Basic/DiagnosticOptions.def"
1374 Record.push_back(Elt: DiagOpts.Warnings.size());
1375 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1376 AddString(Str: DiagOpts.Warnings[I], Record);
1377 Record.push_back(Elt: DiagOpts.Remarks.size());
1378 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1379 AddString(Str: DiagOpts.Remarks[I], Record);
1380 // Note: we don't serialize the log or serialization file names, because
1381 // they are generally transient files and will almost always be overridden.
1382 Stream.EmitRecord(Code: DIAGNOSTIC_OPTIONS, Vals: Record);
1383 Record.clear();
1384 }
1385
1386 // Header search paths.
1387 if (!HSOpts.ModulesSkipHeaderSearchPaths) {
1388 // Include entries.
1389 Record.push_back(Elt: HSOpts.UserEntries.size());
1390 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1391 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1392 AddString(Str: Entry.Path, Record);
1393 Record.push_back(Elt: static_cast<unsigned>(Entry.Group));
1394 Record.push_back(Elt: Entry.IsFramework);
1395 Record.push_back(Elt: Entry.IgnoreSysRoot);
1396 }
1397
1398 // System header prefixes.
1399 Record.push_back(Elt: HSOpts.SystemHeaderPrefixes.size());
1400 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1401 AddString(Str: HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1402 Record.push_back(Elt: HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1403 }
1404
1405 // VFS overlay files.
1406 Record.push_back(Elt: HSOpts.VFSOverlayFiles.size());
1407 for (StringRef VFSOverlayFile : HSOpts.VFSOverlayFiles)
1408 AddString(Str: VFSOverlayFile, Record);
1409
1410 Stream.EmitRecord(Code: HEADER_SEARCH_PATHS, Vals: Record);
1411 }
1412
1413 if (!HSOpts.ModulesSkipPragmaDiagnosticMappings)
1414 WritePragmaDiagnosticMappings(Diag: Diags, /* isModule = */ WritingModule);
1415
1416 // Header search entry usage.
1417 {
1418 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1419 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1420 Abbrev->Add(OpInfo: BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1421 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1422 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1423 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1424 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1425 HSEntryUsage.size()};
1426 Stream.EmitRecordWithBlob(Abbrev: HSUsageAbbrevCode, Vals: Record, Blob: bytes(V: HSEntryUsage));
1427 }
1428
1429 // VFS usage.
1430 {
1431 auto VFSUsage = PP.getHeaderSearchInfo().collectVFSUsageAndClear();
1432 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1433 Abbrev->Add(OpInfo: BitCodeAbbrevOp(VFS_USAGE));
1434 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1435 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1436 unsigned VFSUsageAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1437 RecordData::value_type Record[] = {VFS_USAGE, VFSUsage.size()};
1438 Stream.EmitRecordWithBlob(Abbrev: VFSUsageAbbrevCode, Vals: Record, Blob: bytes(V: VFSUsage));
1439 }
1440
1441 // Leave the options block.
1442 Stream.ExitBlock();
1443 UnhashedControlBlockRange.second = Stream.GetCurrentBitNo() >> 3;
1444}
1445
1446/// Write the control block.
1447void ASTWriter::WriteControlBlock(Preprocessor &PP, StringRef isysroot) {
1448 using namespace llvm;
1449
1450 SourceManager &SourceMgr = PP.getSourceManager();
1451 FileManager &FileMgr = PP.getFileManager();
1452
1453 Stream.EnterSubblock(BlockID: CONTROL_BLOCK_ID, CodeLen: 5);
1454 RecordData Record;
1455
1456 // Metadata
1457 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1458 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(METADATA));
1459 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1460 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1461 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1462 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1463 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1464 // Standard C++ module
1465 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1466 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1467 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1468 MetadataAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1469 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(MetadataAbbrev));
1470 assert((!WritingModule || isysroot.empty()) &&
1471 "writing module as a relocatable PCH?");
1472 {
1473 RecordData::value_type Record[] = {METADATA,
1474 VERSION_MAJOR,
1475 VERSION_MINOR,
1476 CLANG_VERSION_MAJOR,
1477 CLANG_VERSION_MINOR,
1478 !isysroot.empty(),
1479 isWritingStdCXXNamedModules(),
1480 IncludeTimestamps,
1481 ASTHasCompilerErrors};
1482 Stream.EmitRecordWithBlob(Abbrev: MetadataAbbrevCode, Vals: Record,
1483 Blob: getClangFullRepositoryVersion());
1484 }
1485
1486 if (WritingModule) {
1487 // Module name
1488 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1489 Abbrev->Add(OpInfo: BitCodeAbbrevOp(MODULE_NAME));
1490 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1491 unsigned AbbrevCode = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1492 RecordData::value_type Record[] = {MODULE_NAME};
1493 Stream.EmitRecordWithBlob(Abbrev: AbbrevCode, Vals: Record, Blob: WritingModule->Name);
1494
1495 auto BaseDir = [&]() -> std::optional<SmallString<128>> {
1496 if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
1497 // Use the current working directory as the base path for all inputs.
1498 auto CWD = FileMgr.getOptionalDirectoryRef(DirName: ".");
1499 return CWD->getName();
1500 }
1501 if (WritingModule->Directory) {
1502 return WritingModule->Directory->getName();
1503 }
1504 return std::nullopt;
1505 }();
1506 if (BaseDir) {
1507 cleanPathForOutput(FileMgr, Path&: *BaseDir);
1508
1509 // If the home of the module is the current working directory, then we
1510 // want to pick up the cwd of the build process loading the module, not
1511 // our cwd, when we load this module.
1512 if (!PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd &&
1513 (!PP.getHeaderSearchInfo()
1514 .getHeaderSearchOpts()
1515 .ModuleMapFileHomeIsCwd ||
1516 WritingModule->Directory->getName() != ".")) {
1517 // Module directory.
1518 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1519 Abbrev->Add(OpInfo: BitCodeAbbrevOp(MODULE_DIRECTORY));
1520 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1521 unsigned AbbrevCode = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1522
1523 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1524 Stream.EmitRecordWithBlob(Abbrev: AbbrevCode, Vals: Record, Blob: *BaseDir);
1525 }
1526
1527 // Write out all other paths relative to the base directory if possible.
1528 BaseDirectory.assign(first: BaseDir->begin(), last: BaseDir->end());
1529 } else if (!isysroot.empty()) {
1530 // Write out paths relative to the sysroot if possible.
1531 BaseDirectory = std::string(isysroot);
1532 }
1533 }
1534
1535 // Module map file
1536 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1537 Record.clear();
1538
1539 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1540 AddPath(Path: WritingModule->PresumedModuleMapFile.empty()
1541 ? Map.getModuleMapFileForUniquing(M: WritingModule)
1542 ->getNameAsRequested()
1543 : StringRef(WritingModule->PresumedModuleMapFile),
1544 Record);
1545
1546 // Additional module map files.
1547 if (auto *AdditionalModMaps =
1548 Map.getAdditionalModuleMapFiles(M: WritingModule)) {
1549 Record.push_back(Elt: AdditionalModMaps->size());
1550 SmallVector<FileEntryRef, 1> ModMaps(AdditionalModMaps->begin(),
1551 AdditionalModMaps->end());
1552 llvm::sort(C&: ModMaps, Comp: [](FileEntryRef A, FileEntryRef B) {
1553 return A.getName() < B.getName();
1554 });
1555 for (FileEntryRef F : ModMaps)
1556 AddPath(Path: F.getName(), Record);
1557 } else {
1558 Record.push_back(Elt: 0);
1559 }
1560
1561 Stream.EmitRecord(Code: MODULE_MAP_FILE, Vals: Record);
1562 }
1563
1564 // Imports
1565 if (Chain) {
1566 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1567 Abbrev->Add(OpInfo: BitCodeAbbrevOp(IMPORT));
1568 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind
1569 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ImportLoc
1570 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Module name len
1571 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Standard C++ mod
1572 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File size
1573 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File timestamp
1574 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File name len
1575 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Strings
1576 unsigned AbbrevCode = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
1577
1578 SmallString<128> Blob;
1579
1580 for (ModuleFile &M : Chain->getModuleManager()) {
1581 // Skip modules that weren't directly imported.
1582 if (!M.isDirectlyImported())
1583 continue;
1584
1585 Record.clear();
1586 Blob.clear();
1587
1588 Record.push_back(Elt: IMPORT);
1589 Record.push_back(Elt: (unsigned)M.Kind); // FIXME: Stable encoding
1590 AddSourceLocation(Loc: M.ImportLoc, Record);
1591 AddStringBlob(Str: M.ModuleName, Record, Blob);
1592 Record.push_back(Elt: M.StandardCXXModule);
1593
1594 // We don't want to hard code the information about imported modules
1595 // in the C++20 named modules.
1596 if (M.StandardCXXModule) {
1597 Record.push_back(Elt: 0);
1598 Record.push_back(Elt: 0);
1599 Record.push_back(Elt: 0);
1600 } else {
1601 // If we have calculated signature, there is no need to store
1602 // the size or timestamp.
1603 Record.push_back(Elt: M.Signature ? 0 : M.File.getSize());
1604 Record.push_back(Elt: M.Signature ? 0 : getTimestampForOutput(E: M.File));
1605
1606 llvm::append_range(C&: Blob, R&: M.Signature);
1607
1608 AddPathBlob(Str: M.FileName, Record, Blob);
1609 }
1610
1611 Stream.EmitRecordWithBlob(Abbrev: AbbrevCode, Vals: Record, Blob);
1612 }
1613 }
1614
1615 // Write the options block.
1616 Stream.EnterSubblock(BlockID: OPTIONS_BLOCK_ID, CodeLen: 4);
1617
1618 // Language options.
1619 Record.clear();
1620 const LangOptions &LangOpts = PP.getLangOpts();
1621#define LANGOPT(Name, Bits, Default, Description) \
1622 Record.push_back(LangOpts.Name);
1623#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1624 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1625#include "clang/Basic/LangOptions.def"
1626#define SANITIZER(NAME, ID) \
1627 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1628#include "clang/Basic/Sanitizers.def"
1629
1630 Record.push_back(Elt: LangOpts.ModuleFeatures.size());
1631 for (StringRef Feature : LangOpts.ModuleFeatures)
1632 AddString(Str: Feature, Record);
1633
1634 Record.push_back(Elt: (unsigned) LangOpts.ObjCRuntime.getKind());
1635 AddVersionTuple(Version: LangOpts.ObjCRuntime.getVersion(), Record);
1636
1637 AddString(Str: LangOpts.CurrentModule, Record);
1638
1639 // Comment options.
1640 Record.push_back(Elt: LangOpts.CommentOpts.BlockCommandNames.size());
1641 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1642 AddString(Str: I, Record);
1643 }
1644 Record.push_back(Elt: LangOpts.CommentOpts.ParseAllComments);
1645
1646 // OpenMP offloading options.
1647 Record.push_back(Elt: LangOpts.OMPTargetTriples.size());
1648 for (auto &T : LangOpts.OMPTargetTriples)
1649 AddString(Str: T.getTriple(), Record);
1650
1651 AddString(Str: LangOpts.OMPHostIRFile, Record);
1652
1653 Stream.EmitRecord(Code: LANGUAGE_OPTIONS, Vals: Record);
1654
1655 // Target options.
1656 Record.clear();
1657 const TargetInfo &Target = PP.getTargetInfo();
1658 const TargetOptions &TargetOpts = Target.getTargetOpts();
1659 AddString(Str: TargetOpts.Triple, Record);
1660 AddString(Str: TargetOpts.CPU, Record);
1661 AddString(Str: TargetOpts.TuneCPU, Record);
1662 AddString(Str: TargetOpts.ABI, Record);
1663 Record.push_back(Elt: TargetOpts.FeaturesAsWritten.size());
1664 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1665 AddString(Str: TargetOpts.FeaturesAsWritten[I], Record);
1666 }
1667 Record.push_back(Elt: TargetOpts.Features.size());
1668 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1669 AddString(Str: TargetOpts.Features[I], Record);
1670 }
1671 Stream.EmitRecord(Code: TARGET_OPTIONS, Vals: Record);
1672
1673 // File system options.
1674 Record.clear();
1675 const FileSystemOptions &FSOpts = FileMgr.getFileSystemOpts();
1676 AddString(Str: FSOpts.WorkingDir, Record);
1677 Stream.EmitRecord(Code: FILE_SYSTEM_OPTIONS, Vals: Record);
1678
1679 // Header search options.
1680 Record.clear();
1681 const HeaderSearchOptions &HSOpts =
1682 PP.getHeaderSearchInfo().getHeaderSearchOpts();
1683
1684 AddString(Str: HSOpts.Sysroot, Record);
1685 AddString(Str: HSOpts.ResourceDir, Record);
1686 AddString(Str: HSOpts.ModuleCachePath, Record);
1687 AddString(Str: HSOpts.ModuleUserBuildPath, Record);
1688 Record.push_back(Elt: HSOpts.DisableModuleHash);
1689 Record.push_back(Elt: HSOpts.ImplicitModuleMaps);
1690 Record.push_back(Elt: HSOpts.ModuleMapFileHomeIsCwd);
1691 Record.push_back(Elt: HSOpts.EnablePrebuiltImplicitModules);
1692 Record.push_back(Elt: HSOpts.UseBuiltinIncludes);
1693 Record.push_back(Elt: HSOpts.UseStandardSystemIncludes);
1694 Record.push_back(Elt: HSOpts.UseStandardCXXIncludes);
1695 Record.push_back(Elt: HSOpts.UseLibcxx);
1696 // Write out the specific module cache path that contains the module files.
1697 AddString(Str: PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1698 Stream.EmitRecord(Code: HEADER_SEARCH_OPTIONS, Vals: Record);
1699
1700 // Preprocessor options.
1701 Record.clear();
1702 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1703
1704 // If we're building an implicit module with a context hash, the importer is
1705 // guaranteed to have the same macros defined on the command line. Skip
1706 // writing them.
1707 bool SkipMacros = BuildingImplicitModule && !HSOpts.DisableModuleHash;
1708 bool WriteMacros = !SkipMacros;
1709 Record.push_back(Elt: WriteMacros);
1710 if (WriteMacros) {
1711 // Macro definitions.
1712 Record.push_back(Elt: PPOpts.Macros.size());
1713 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1714 AddString(Str: PPOpts.Macros[I].first, Record);
1715 Record.push_back(Elt: PPOpts.Macros[I].second);
1716 }
1717 }
1718
1719 // Includes
1720 Record.push_back(Elt: PPOpts.Includes.size());
1721 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1722 AddString(Str: PPOpts.Includes[I], Record);
1723
1724 // Macro includes
1725 Record.push_back(Elt: PPOpts.MacroIncludes.size());
1726 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1727 AddString(Str: PPOpts.MacroIncludes[I], Record);
1728
1729 Record.push_back(Elt: PPOpts.UsePredefines);
1730 // Detailed record is important since it is used for the module cache hash.
1731 Record.push_back(Elt: PPOpts.DetailedRecord);
1732 AddString(Str: PPOpts.ImplicitPCHInclude, Record);
1733 Record.push_back(Elt: static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1734 Stream.EmitRecord(Code: PREPROCESSOR_OPTIONS, Vals: Record);
1735
1736 // Leave the options block.
1737 Stream.ExitBlock();
1738
1739 // Original file name and file ID
1740 if (auto MainFile =
1741 SourceMgr.getFileEntryRefForID(FID: SourceMgr.getMainFileID())) {
1742 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1743 FileAbbrev->Add(OpInfo: BitCodeAbbrevOp(ORIGINAL_FILE));
1744 FileAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1745 FileAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1746 unsigned FileAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(FileAbbrev));
1747
1748 Record.clear();
1749 Record.push_back(Elt: ORIGINAL_FILE);
1750 AddFileID(FID: SourceMgr.getMainFileID(), Record);
1751 EmitRecordWithPath(Abbrev: FileAbbrevCode, Record, Path: MainFile->getName());
1752 }
1753
1754 Record.clear();
1755 AddFileID(FID: SourceMgr.getMainFileID(), Record);
1756 Stream.EmitRecord(Code: ORIGINAL_FILE_ID, Vals: Record);
1757
1758 WriteInputFiles(SourceMgr);
1759 Stream.ExitBlock();
1760}
1761
1762namespace {
1763
1764/// An input file.
1765struct InputFileEntry {
1766 FileEntryRef File;
1767 bool IsSystemFile;
1768 bool IsTransient;
1769 bool BufferOverridden;
1770 bool IsTopLevel;
1771 bool IsModuleMap;
1772 uint32_t ContentHash[2];
1773
1774 InputFileEntry(FileEntryRef File) : File(File) {}
1775
1776 void trySetContentHash(
1777 Preprocessor &PP,
1778 llvm::function_ref<std::optional<llvm::MemoryBufferRef>()> GetMemBuff) {
1779 ContentHash[0] = 0;
1780 ContentHash[1] = 0;
1781
1782 if (!PP.getHeaderSearchInfo()
1783 .getHeaderSearchOpts()
1784 .ValidateASTInputFilesContent)
1785 return;
1786
1787 auto MemBuff = GetMemBuff();
1788 if (!MemBuff) {
1789 PP.Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1790 << File.getName();
1791 return;
1792 }
1793
1794 uint64_t Hash = xxh3_64bits(data: MemBuff->getBuffer());
1795 ContentHash[0] = uint32_t(Hash);
1796 ContentHash[1] = uint32_t(Hash >> 32);
1797 }
1798};
1799
1800} // namespace
1801
1802SourceLocation ASTWriter::getAffectingIncludeLoc(const SourceManager &SourceMgr,
1803 const SrcMgr::FileInfo &File) {
1804 SourceLocation IncludeLoc = File.getIncludeLoc();
1805 if (IncludeLoc.isValid()) {
1806 FileID IncludeFID = SourceMgr.getFileID(SpellingLoc: IncludeLoc);
1807 assert(IncludeFID.isValid() && "IncludeLoc in invalid file");
1808 if (!IsSLocAffecting[IncludeFID.ID])
1809 IncludeLoc = SourceLocation();
1810 }
1811 return IncludeLoc;
1812}
1813
1814void ASTWriter::WriteInputFiles(SourceManager &SourceMgr) {
1815 using namespace llvm;
1816
1817 Stream.EnterSubblock(BlockID: INPUT_FILES_BLOCK_ID, CodeLen: 4);
1818
1819 // Create input-file abbreviation.
1820 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1821 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(INPUT_FILE));
1822 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1823 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1824 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1825 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1826 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1827 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Top-level
1828 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1829 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Name as req. len
1830 IFAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name as req. + name
1831 unsigned IFAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(IFAbbrev));
1832
1833 // Create input file hash abbreviation.
1834 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1835 IFHAbbrev->Add(OpInfo: BitCodeAbbrevOp(INPUT_FILE_HASH));
1836 IFHAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1837 IFHAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1838 unsigned IFHAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(IFHAbbrev));
1839
1840 uint64_t InputFilesOffsetBase = Stream.GetCurrentBitNo();
1841
1842 // Get all ContentCache objects for files.
1843 std::vector<InputFileEntry> UserFiles;
1844 std::vector<InputFileEntry> SystemFiles;
1845 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1846 // Get this source location entry.
1847 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(Index: I);
1848 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1849
1850 // We only care about file entries that were not overridden.
1851 if (!SLoc->isFile())
1852 continue;
1853 const SrcMgr::FileInfo &File = SLoc->getFile();
1854 const SrcMgr::ContentCache *Cache = &File.getContentCache();
1855 if (!Cache->OrigEntry)
1856 continue;
1857
1858 // Do not emit input files that do not affect current module.
1859 if (!IsSLocFileEntryAffecting[I])
1860 continue;
1861
1862 InputFileEntry Entry(*Cache->OrigEntry);
1863 Entry.IsSystemFile = isSystem(CK: File.getFileCharacteristic());
1864 Entry.IsTransient = Cache->IsTransient;
1865 Entry.BufferOverridden = Cache->BufferOverridden;
1866
1867 FileID IncludeFileID = SourceMgr.getFileID(SpellingLoc: File.getIncludeLoc());
1868 Entry.IsTopLevel = IncludeFileID.isInvalid() || IncludeFileID.ID < 0 ||
1869 !IsSLocFileEntryAffecting[IncludeFileID.ID];
1870 Entry.IsModuleMap = isModuleMap(CK: File.getFileCharacteristic());
1871
1872 Entry.trySetContentHash(PP&: *PP, GetMemBuff: [&] { return Cache->getBufferIfLoaded(); });
1873
1874 if (Entry.IsSystemFile)
1875 SystemFiles.push_back(x: Entry);
1876 else
1877 UserFiles.push_back(x: Entry);
1878 }
1879
1880 // FIXME: Make providing input files not in the SourceManager more flexible.
1881 // The SDKSettings.json file is necessary for correct evaluation of
1882 // availability annotations.
1883 StringRef Sysroot = PP->getHeaderSearchInfo().getHeaderSearchOpts().Sysroot;
1884 if (!Sysroot.empty()) {
1885 SmallString<128> SDKSettingsJSON = Sysroot;
1886 llvm::sys::path::append(path&: SDKSettingsJSON, a: "SDKSettings.json");
1887 FileManager &FM = PP->getFileManager();
1888 if (auto FE = FM.getOptionalFileRef(Filename: SDKSettingsJSON)) {
1889 InputFileEntry Entry(*FE);
1890 Entry.IsSystemFile = true;
1891 Entry.IsTransient = false;
1892 Entry.BufferOverridden = false;
1893 Entry.IsTopLevel = true;
1894 Entry.IsModuleMap = false;
1895 std::unique_ptr<MemoryBuffer> MB;
1896 Entry.trySetContentHash(PP&: *PP, GetMemBuff: [&]() -> std::optional<MemoryBufferRef> {
1897 if (auto MBOrErr = FM.getBufferForFile(Entry: Entry.File)) {
1898 MB = std::move(*MBOrErr);
1899 return MB->getMemBufferRef();
1900 }
1901 return std::nullopt;
1902 });
1903 SystemFiles.push_back(x: Entry);
1904 }
1905 }
1906
1907 // User files go at the front, system files at the back.
1908 auto SortedFiles = llvm::concat<InputFileEntry>(Ranges: std::move(UserFiles),
1909 Ranges: std::move(SystemFiles));
1910
1911 unsigned UserFilesNum = 0;
1912 // Write out all of the input files.
1913 std::vector<uint64_t> InputFileOffsets;
1914 for (const auto &Entry : SortedFiles) {
1915 uint32_t &InputFileID = InputFileIDs[Entry.File];
1916 if (InputFileID != 0)
1917 continue; // already recorded this file.
1918
1919 // Record this entry's offset.
1920 InputFileOffsets.push_back(x: Stream.GetCurrentBitNo() - InputFilesOffsetBase);
1921
1922 InputFileID = InputFileOffsets.size();
1923
1924 if (!Entry.IsSystemFile)
1925 ++UserFilesNum;
1926
1927 // Emit size/modification time for this file.
1928 // And whether this file was overridden.
1929 {
1930 SmallString<128> NameAsRequested = Entry.File.getNameAsRequested();
1931 SmallString<128> Name = Entry.File.getName();
1932
1933 PreparePathForOutput(Path&: NameAsRequested);
1934 PreparePathForOutput(Path&: Name);
1935
1936 if (Name == NameAsRequested)
1937 Name.clear();
1938
1939 RecordData::value_type Record[] = {
1940 INPUT_FILE,
1941 InputFileOffsets.size(),
1942 (uint64_t)Entry.File.getSize(),
1943 (uint64_t)getTimestampForOutput(E: Entry.File),
1944 Entry.BufferOverridden,
1945 Entry.IsTransient,
1946 Entry.IsTopLevel,
1947 Entry.IsModuleMap,
1948 NameAsRequested.size()};
1949
1950 Stream.EmitRecordWithBlob(Abbrev: IFAbbrevCode, Vals: Record,
1951 Blob: (NameAsRequested + Name).str());
1952 }
1953
1954 // Emit content hash for this file.
1955 {
1956 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1957 Entry.ContentHash[1]};
1958 Stream.EmitRecordWithAbbrev(Abbrev: IFHAbbrevCode, Vals: Record);
1959 }
1960 }
1961
1962 Stream.ExitBlock();
1963
1964 // Create input file offsets abbreviation.
1965 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1966 OffsetsAbbrev->Add(OpInfo: BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1967 OffsetsAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1968 OffsetsAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1969 // input files
1970 OffsetsAbbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1971 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(Abbv: std::move(OffsetsAbbrev));
1972
1973 // Write input file offsets.
1974 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1975 InputFileOffsets.size(), UserFilesNum};
1976 Stream.EmitRecordWithBlob(Abbrev: OffsetsAbbrevCode, Vals: Record, Blob: bytes(v: InputFileOffsets));
1977}
1978
1979//===----------------------------------------------------------------------===//
1980// Source Manager Serialization
1981//===----------------------------------------------------------------------===//
1982
1983/// Create an abbreviation for the SLocEntry that refers to a
1984/// file.
1985static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1986 using namespace llvm;
1987
1988 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1989 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1990 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1991 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1992 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1993 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1994 // FileEntry fields.
1995 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1996 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1997 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1998 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1999 return Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2000}
2001
2002/// Create an abbreviation for the SLocEntry that refers to a
2003/// buffer.
2004static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
2005 using namespace llvm;
2006
2007 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2008 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
2009 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2010 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
2011 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
2012 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
2013 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
2014 return Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2015}
2016
2017/// Create an abbreviation for the SLocEntry that refers to a
2018/// buffer's blob.
2019static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
2020 bool Compressed) {
2021 using namespace llvm;
2022
2023 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2024 Abbrev->Add(OpInfo: BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
2025 : SM_SLOC_BUFFER_BLOB));
2026 if (Compressed)
2027 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
2028 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
2029 return Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2030}
2031
2032/// Create an abbreviation for the SLocEntry that refers to a macro
2033/// expansion.
2034static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
2035 using namespace llvm;
2036
2037 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2038 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
2039 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
2040 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
2041 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
2042 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
2043 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
2044 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
2045 return Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2046}
2047
2048/// Emit key length and data length as ULEB-encoded data, and return them as a
2049/// pair.
2050static std::pair<unsigned, unsigned>
2051emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
2052 llvm::encodeULEB128(Value: KeyLen, OS&: Out);
2053 llvm::encodeULEB128(Value: DataLen, OS&: Out);
2054 return std::make_pair(x&: KeyLen, y&: DataLen);
2055}
2056
2057namespace {
2058
2059 // Trait used for the on-disk hash table of header search information.
2060 class HeaderFileInfoTrait {
2061 ASTWriter &Writer;
2062
2063 public:
2064 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
2065
2066 struct key_type {
2067 StringRef Filename;
2068 off_t Size;
2069 time_t ModTime;
2070 };
2071 using key_type_ref = const key_type &;
2072
2073 using UnresolvedModule =
2074 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
2075
2076 struct data_type {
2077 data_type(const HeaderFileInfo &HFI, bool AlreadyIncluded,
2078 ArrayRef<ModuleMap::KnownHeader> KnownHeaders,
2079 UnresolvedModule Unresolved)
2080 : HFI(HFI), AlreadyIncluded(AlreadyIncluded),
2081 KnownHeaders(KnownHeaders), Unresolved(Unresolved) {}
2082
2083 HeaderFileInfo HFI;
2084 bool AlreadyIncluded;
2085 SmallVector<ModuleMap::KnownHeader, 1> KnownHeaders;
2086 UnresolvedModule Unresolved;
2087 };
2088 using data_type_ref = const data_type &;
2089
2090 using hash_value_type = unsigned;
2091 using offset_type = unsigned;
2092
2093 hash_value_type ComputeHash(key_type_ref key) {
2094 // The hash is based only on size/time of the file, so that the reader can
2095 // match even when symlinking or excess path elements ("foo/../", "../")
2096 // change the form of the name. However, complete path is still the key.
2097 uint8_t buf[sizeof(key.Size) + sizeof(key.ModTime)];
2098 memcpy(dest: buf, src: &key.Size, n: sizeof(key.Size));
2099 memcpy(dest: buf + sizeof(key.Size), src: &key.ModTime, n: sizeof(key.ModTime));
2100 return llvm::xxh3_64bits(data: buf);
2101 }
2102
2103 std::pair<unsigned, unsigned>
2104 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
2105 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
2106 unsigned DataLen = 1 + sizeof(IdentifierID);
2107 for (auto ModInfo : Data.KnownHeaders)
2108 if (Writer.getLocalOrImportedSubmoduleID(Mod: ModInfo.getModule()))
2109 DataLen += 4;
2110 if (Data.Unresolved.getPointer())
2111 DataLen += 4;
2112 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
2113 }
2114
2115 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
2116 using namespace llvm::support;
2117
2118 endian::Writer LE(Out, llvm::endianness::little);
2119 LE.write<uint64_t>(Val: key.Size);
2120 KeyLen -= 8;
2121 LE.write<uint64_t>(Val: key.ModTime);
2122 KeyLen -= 8;
2123 Out.write(Ptr: key.Filename.data(), Size: KeyLen);
2124 }
2125
2126 void EmitData(raw_ostream &Out, key_type_ref key,
2127 data_type_ref Data, unsigned DataLen) {
2128 using namespace llvm::support;
2129
2130 endian::Writer LE(Out, llvm::endianness::little);
2131 uint64_t Start = Out.tell(); (void)Start;
2132
2133 unsigned char Flags = (Data.AlreadyIncluded << 6)
2134 | (Data.HFI.isImport << 5)
2135 | (Writer.isWritingStdCXXNamedModules() ? 0 :
2136 Data.HFI.isPragmaOnce << 4)
2137 | (Data.HFI.DirInfo << 1);
2138 LE.write<uint8_t>(Val: Flags);
2139
2140 if (Data.HFI.LazyControllingMacro.isID())
2141 LE.write<IdentifierID>(Val: Data.HFI.LazyControllingMacro.getID());
2142 else
2143 LE.write<IdentifierID>(
2144 Val: Writer.getIdentifierRef(II: Data.HFI.LazyControllingMacro.getPtr()));
2145
2146 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2147 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(Mod: M)) {
2148 uint32_t Value = (ModID << 3) | (unsigned)Role;
2149 assert((Value >> 3) == ModID && "overflow in header module info");
2150 LE.write<uint32_t>(Val: Value);
2151 }
2152 };
2153
2154 for (auto ModInfo : Data.KnownHeaders)
2155 EmitModule(ModInfo.getModule(), ModInfo.getRole());
2156 if (Data.Unresolved.getPointer())
2157 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2158
2159 assert(Out.tell() - Start == DataLen && "Wrong data length");
2160 }
2161 };
2162
2163} // namespace
2164
2165/// Write the header search block for the list of files that
2166///
2167/// \param HS The header search structure to save.
2168void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2169 HeaderFileInfoTrait GeneratorTrait(*this);
2170 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2171 SmallVector<const char *, 4> SavedStrings;
2172 unsigned NumHeaderSearchEntries = 0;
2173
2174 // Find all unresolved headers for the current module. We generally will
2175 // have resolved them before we get here, but not necessarily: we might be
2176 // compiling a preprocessed module, where there is no requirement for the
2177 // original files to exist any more.
2178 const HeaderFileInfo Empty; // So we can take a reference.
2179 if (WritingModule) {
2180 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2181 while (!Worklist.empty()) {
2182 Module *M = Worklist.pop_back_val();
2183 // We don't care about headers in unimportable submodules.
2184 if (M->isUnimportable())
2185 continue;
2186
2187 // Map to disk files where possible, to pick up any missing stat
2188 // information. This also means we don't need to check the unresolved
2189 // headers list when emitting resolved headers in the first loop below.
2190 // FIXME: It'd be preferable to avoid doing this if we were given
2191 // sufficient stat information in the module map.
2192 HS.getModuleMap().resolveHeaderDirectives(Mod: M, /*File=*/std::nullopt);
2193
2194 // If the file didn't exist, we can still create a module if we were given
2195 // enough information in the module map.
2196 for (const auto &U : M->MissingHeaders) {
2197 // Check that we were given enough information to build a module
2198 // without this file existing on disk.
2199 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2200 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2201 << WritingModule->getFullModuleName() << U.Size.has_value()
2202 << U.FileName;
2203 continue;
2204 }
2205
2206 // Form the effective relative pathname for the file.
2207 SmallString<128> Filename(M->Directory->getName());
2208 llvm::sys::path::append(path&: Filename, a: U.FileName);
2209 PreparePathForOutput(Path&: Filename);
2210
2211 StringRef FilenameDup = strdup(s: Filename.c_str());
2212 SavedStrings.push_back(Elt: FilenameDup.data());
2213
2214 HeaderFileInfoTrait::key_type Key = {
2215 .Filename: FilenameDup, .Size: *U.Size, .ModTime: IncludeTimestamps ? *U.ModTime : 0};
2216 HeaderFileInfoTrait::data_type Data = {
2217 Empty, false, {}, {M, ModuleMap::headerKindToRole(Kind: U.Kind)}};
2218 // FIXME: Deal with cases where there are multiple unresolved header
2219 // directives in different submodules for the same header.
2220 Generator.insert(Key, Data, InfoObj&: GeneratorTrait);
2221 ++NumHeaderSearchEntries;
2222 }
2223 auto SubmodulesRange = M->submodules();
2224 Worklist.append(in_start: SubmodulesRange.begin(), in_end: SubmodulesRange.end());
2225 }
2226 }
2227
2228 SmallVector<OptionalFileEntryRef, 16> FilesByUID;
2229 HS.getFileMgr().GetUniqueIDMapping(UIDToFiles&: FilesByUID);
2230
2231 if (FilesByUID.size() > HS.header_file_size())
2232 FilesByUID.resize(N: HS.header_file_size());
2233
2234 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2235 OptionalFileEntryRef File = FilesByUID[UID];
2236 if (!File)
2237 continue;
2238
2239 const HeaderFileInfo *HFI = HS.getExistingLocalFileInfo(FE: *File);
2240 if (!HFI)
2241 continue; // We have no information on this being a header file.
2242 if (!HFI->isCompilingModuleHeader && HFI->isModuleHeader)
2243 continue; // Header file info is tracked by the owning module file.
2244 if (!HFI->isCompilingModuleHeader && !HFI->IsLocallyIncluded)
2245 continue; // Header file info is tracked by the including module file.
2246
2247 // Massage the file path into an appropriate form.
2248 StringRef Filename = File->getName();
2249 SmallString<128> FilenameTmp(Filename);
2250 if (PreparePathForOutput(Path&: FilenameTmp)) {
2251 // If we performed any translation on the file name at all, we need to
2252 // save this string, since the generator will refer to it later.
2253 Filename = StringRef(strdup(s: FilenameTmp.c_str()));
2254 SavedStrings.push_back(Elt: Filename.data());
2255 }
2256
2257 bool Included = HFI->IsLocallyIncluded || PP->alreadyIncluded(File: *File);
2258
2259 HeaderFileInfoTrait::key_type Key = {
2260 .Filename: Filename, .Size: File->getSize(), .ModTime: getTimestampForOutput(E: *File)
2261 };
2262 HeaderFileInfoTrait::data_type Data = {
2263 *HFI, Included, HS.getModuleMap().findResolvedModulesForHeader(File: *File), {}
2264 };
2265 Generator.insert(Key, Data, InfoObj&: GeneratorTrait);
2266 ++NumHeaderSearchEntries;
2267 }
2268
2269 // Create the on-disk hash table in a buffer.
2270 SmallString<4096> TableData;
2271 uint32_t BucketOffset;
2272 {
2273 using namespace llvm::support;
2274
2275 llvm::raw_svector_ostream Out(TableData);
2276 // Make sure that no bucket is at offset 0
2277 endian::write<uint32_t>(os&: Out, value: 0, endian: llvm::endianness::little);
2278 BucketOffset = Generator.Emit(Out, InfoObj&: GeneratorTrait);
2279 }
2280
2281 // Create a blob abbreviation
2282 using namespace llvm;
2283
2284 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2285 Abbrev->Add(OpInfo: BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2286 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2287 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2288 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2289 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2290 unsigned TableAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2291
2292 // Write the header search table
2293 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2294 NumHeaderSearchEntries, TableData.size()};
2295 Stream.EmitRecordWithBlob(Abbrev: TableAbbrev, Vals: Record, Blob: TableData);
2296
2297 // Free all of the strings we had to duplicate.
2298 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2299 free(ptr: const_cast<char *>(SavedStrings[I]));
2300}
2301
2302static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2303 unsigned SLocBufferBlobCompressedAbbrv,
2304 unsigned SLocBufferBlobAbbrv) {
2305 using RecordDataType = ASTWriter::RecordData::value_type;
2306
2307 // Compress the buffer if possible. We expect that almost all PCM
2308 // consumers will not want its contents.
2309 SmallVector<uint8_t, 0> CompressedBuffer;
2310 if (llvm::compression::zstd::isAvailable()) {
2311 llvm::compression::zstd::compress(
2312 Input: llvm::arrayRefFromStringRef(Input: Blob.drop_back(N: 1)), CompressedBuffer, Level: 9);
2313 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2314 Stream.EmitRecordWithBlob(Abbrev: SLocBufferBlobCompressedAbbrv, Vals: Record,
2315 Blob: llvm::toStringRef(Input: CompressedBuffer));
2316 return;
2317 }
2318 if (llvm::compression::zlib::isAvailable()) {
2319 llvm::compression::zlib::compress(
2320 Input: llvm::arrayRefFromStringRef(Input: Blob.drop_back(N: 1)), CompressedBuffer);
2321 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
2322 Stream.EmitRecordWithBlob(Abbrev: SLocBufferBlobCompressedAbbrv, Vals: Record,
2323 Blob: llvm::toStringRef(Input: CompressedBuffer));
2324 return;
2325 }
2326
2327 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2328 Stream.EmitRecordWithBlob(Abbrev: SLocBufferBlobAbbrv, Vals: Record, Blob);
2329}
2330
2331/// Writes the block containing the serialized form of the
2332/// source manager.
2333///
2334/// TODO: We should probably use an on-disk hash table (stored in a
2335/// blob), indexed based on the file name, so that we only create
2336/// entries for files that we actually need. In the common case (no
2337/// errors), we probably won't have to create file entries for any of
2338/// the files in the AST.
2339void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
2340 RecordData Record;
2341
2342 // Enter the source manager block.
2343 Stream.EnterSubblock(BlockID: SOURCE_MANAGER_BLOCK_ID, CodeLen: 4);
2344 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2345
2346 // Abbreviations for the various kinds of source-location entries.
2347 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2348 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2349 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, Compressed: false);
2350 unsigned SLocBufferBlobCompressedAbbrv =
2351 CreateSLocBufferBlobAbbrev(Stream, Compressed: true);
2352 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2353
2354 // Write out the source location entry table. We skip the first
2355 // entry, which is always the same dummy entry.
2356 std::vector<uint32_t> SLocEntryOffsets;
2357 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2358 SLocEntryOffsets.reserve(n: SourceMgr.local_sloc_entry_size() - 1);
2359 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2360 I != N; ++I) {
2361 // Get this source location entry.
2362 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(Index: I);
2363 FileID FID = FileID::get(V: I);
2364 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2365
2366 // Record the offset of this source-location entry.
2367 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2368 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2369
2370 // Figure out which record code to use.
2371 unsigned Code;
2372 if (SLoc->isFile()) {
2373 const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2374 if (Cache->OrigEntry) {
2375 Code = SM_SLOC_FILE_ENTRY;
2376 } else
2377 Code = SM_SLOC_BUFFER_ENTRY;
2378 } else
2379 Code = SM_SLOC_EXPANSION_ENTRY;
2380 Record.clear();
2381 Record.push_back(Elt: Code);
2382
2383 if (SLoc->isFile()) {
2384 const SrcMgr::FileInfo &File = SLoc->getFile();
2385 const SrcMgr::ContentCache *Content = &File.getContentCache();
2386 // Do not emit files that were not listed as inputs.
2387 if (!IsSLocAffecting[I])
2388 continue;
2389 SLocEntryOffsets.push_back(x: Offset);
2390 // Starting offset of this entry within this module, so skip the dummy.
2391 Record.push_back(Elt: getAdjustedOffset(Offset: SLoc->getOffset()) - 2);
2392 AddSourceLocation(Loc: getAffectingIncludeLoc(SourceMgr, File), Record);
2393 Record.push_back(Elt: File.getFileCharacteristic()); // FIXME: stable encoding
2394 Record.push_back(Elt: File.hasLineDirectives());
2395
2396 bool EmitBlob = false;
2397 if (Content->OrigEntry) {
2398 assert(Content->OrigEntry == Content->ContentsEntry &&
2399 "Writing to AST an overridden file is not supported");
2400
2401 // The source location entry is a file. Emit input file ID.
2402 assert(InputFileIDs[*Content->OrigEntry] != 0 && "Missed file entry");
2403 Record.push_back(Elt: InputFileIDs[*Content->OrigEntry]);
2404
2405 Record.push_back(Elt: getAdjustedNumCreatedFIDs(FID));
2406
2407 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(Val: FID);
2408 if (FDI != FileDeclIDs.end()) {
2409 Record.push_back(Elt: FDI->second->FirstDeclIndex);
2410 Record.push_back(Elt: FDI->second->DeclIDs.size());
2411 } else {
2412 Record.push_back(Elt: 0);
2413 Record.push_back(Elt: 0);
2414 }
2415
2416 Stream.EmitRecordWithAbbrev(Abbrev: SLocFileAbbrv, Vals: Record);
2417
2418 if (Content->BufferOverridden || Content->IsTransient)
2419 EmitBlob = true;
2420 } else {
2421 // The source location entry is a buffer. The blob associated
2422 // with this entry contains the contents of the buffer.
2423
2424 // We add one to the size so that we capture the trailing NULL
2425 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2426 // the reader side).
2427 std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(
2428 Diag&: SourceMgr.getDiagnostics(), FM&: SourceMgr.getFileManager());
2429 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2430 Stream.EmitRecordWithBlob(Abbrev: SLocBufferAbbrv, Vals: Record,
2431 Blob: StringRef(Name.data(), Name.size() + 1));
2432 EmitBlob = true;
2433 }
2434
2435 if (EmitBlob) {
2436 // Include the implicit terminating null character in the on-disk buffer
2437 // if we're writing it uncompressed.
2438 std::optional<llvm::MemoryBufferRef> Buffer = Content->getBufferOrNone(
2439 Diag&: SourceMgr.getDiagnostics(), FM&: SourceMgr.getFileManager());
2440 if (!Buffer)
2441 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2442 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2443 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2444 SLocBufferBlobAbbrv);
2445 }
2446 } else {
2447 // The source location entry is a macro expansion.
2448 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2449 SLocEntryOffsets.push_back(x: Offset);
2450 // Starting offset of this entry within this module, so skip the dummy.
2451 Record.push_back(Elt: getAdjustedOffset(Offset: SLoc->getOffset()) - 2);
2452 LocSeq::State Seq;
2453 AddSourceLocation(Loc: Expansion.getSpellingLoc(), Record, Seq);
2454 AddSourceLocation(Loc: Expansion.getExpansionLocStart(), Record, Seq);
2455 AddSourceLocation(Loc: Expansion.isMacroArgExpansion()
2456 ? SourceLocation()
2457 : Expansion.getExpansionLocEnd(),
2458 Record, Seq);
2459 Record.push_back(Elt: Expansion.isExpansionTokenRange());
2460
2461 // Compute the token length for this macro expansion.
2462 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2463 if (I + 1 != N)
2464 NextOffset = SourceMgr.getLocalSLocEntry(Index: I + 1).getOffset();
2465 Record.push_back(Elt: getAdjustedOffset(Offset: NextOffset - SLoc->getOffset()) - 1);
2466 Stream.EmitRecordWithAbbrev(Abbrev: SLocExpansionAbbrv, Vals: Record);
2467 }
2468 }
2469
2470 Stream.ExitBlock();
2471
2472 if (SLocEntryOffsets.empty())
2473 return;
2474
2475 // Write the source-location offsets table into the AST block. This
2476 // table is used for lazily loading source-location information.
2477 using namespace llvm;
2478
2479 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2480 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2481 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2482 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2483 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2484 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2485 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2486 {
2487 RecordData::value_type Record[] = {
2488 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2489 getAdjustedOffset(Offset: SourceMgr.getNextLocalOffset()) - 1 /* skip dummy */,
2490 SLocEntryOffsetsBase - SourceManagerBlockOffset};
2491 Stream.EmitRecordWithBlob(Abbrev: SLocOffsetsAbbrev, Vals: Record,
2492 Blob: bytes(v: SLocEntryOffsets));
2493 }
2494
2495 // Write the line table. It depends on remapping working, so it must come
2496 // after the source location offsets.
2497 if (SourceMgr.hasLineTable()) {
2498 LineTableInfo &LineTable = SourceMgr.getLineTable();
2499
2500 Record.clear();
2501
2502 // Emit the needed file names.
2503 llvm::DenseMap<int, int> FilenameMap;
2504 FilenameMap[-1] = -1; // For unspecified filenames.
2505 for (const auto &L : LineTable) {
2506 if (L.first.ID < 0)
2507 continue;
2508 for (auto &LE : L.second) {
2509 if (FilenameMap.insert(KV: std::make_pair(x: LE.FilenameID,
2510 y: FilenameMap.size() - 1)).second)
2511 AddPath(Path: LineTable.getFilename(ID: LE.FilenameID), Record);
2512 }
2513 }
2514 Record.push_back(Elt: 0);
2515
2516 // Emit the line entries
2517 for (const auto &L : LineTable) {
2518 // Only emit entries for local files.
2519 if (L.first.ID < 0)
2520 continue;
2521
2522 AddFileID(FID: L.first, Record);
2523
2524 // Emit the line entries
2525 Record.push_back(Elt: L.second.size());
2526 for (const auto &LE : L.second) {
2527 Record.push_back(Elt: LE.FileOffset);
2528 Record.push_back(Elt: LE.LineNo);
2529 Record.push_back(Elt: FilenameMap[LE.FilenameID]);
2530 Record.push_back(Elt: (unsigned)LE.FileKind);
2531 Record.push_back(Elt: LE.IncludeOffset);
2532 }
2533 }
2534
2535 Stream.EmitRecord(Code: SOURCE_MANAGER_LINE_TABLE, Vals: Record);
2536 }
2537}
2538
2539//===----------------------------------------------------------------------===//
2540// Preprocessor Serialization
2541//===----------------------------------------------------------------------===//
2542
2543static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2544 const Preprocessor &PP) {
2545 if (MacroInfo *MI = MD->getMacroInfo())
2546 if (MI->isBuiltinMacro())
2547 return true;
2548
2549 if (IsModule) {
2550 SourceLocation Loc = MD->getLocation();
2551 if (Loc.isInvalid())
2552 return true;
2553 if (PP.getSourceManager().getFileID(SpellingLoc: Loc) == PP.getPredefinesFileID())
2554 return true;
2555 }
2556
2557 return false;
2558}
2559
2560/// Writes the block containing the serialized form of the
2561/// preprocessor.
2562void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2563 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2564
2565 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2566 if (PPRec)
2567 WritePreprocessorDetail(PPRec&: *PPRec, MacroOffsetsBase);
2568
2569 RecordData Record;
2570 RecordData ModuleMacroRecord;
2571
2572 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2573 if (PP.getCounterValue() != 0) {
2574 RecordData::value_type Record[] = {PP.getCounterValue()};
2575 Stream.EmitRecord(Code: PP_COUNTER_VALUE, Vals: Record);
2576 }
2577
2578 // If we have a recorded #pragma assume_nonnull, remember it so it can be
2579 // replayed when the preamble terminates into the main file.
2580 SourceLocation AssumeNonNullLoc =
2581 PP.getPreambleRecordedPragmaAssumeNonNullLoc();
2582 if (AssumeNonNullLoc.isValid()) {
2583 assert(PP.isRecordingPreamble());
2584 AddSourceLocation(Loc: AssumeNonNullLoc, Record);
2585 Stream.EmitRecord(Code: PP_ASSUME_NONNULL_LOC, Vals: Record);
2586 Record.clear();
2587 }
2588
2589 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2590 assert(!IsModule);
2591 auto SkipInfo = PP.getPreambleSkipInfo();
2592 if (SkipInfo) {
2593 Record.push_back(Elt: true);
2594 AddSourceLocation(Loc: SkipInfo->HashTokenLoc, Record);
2595 AddSourceLocation(Loc: SkipInfo->IfTokenLoc, Record);
2596 Record.push_back(Elt: SkipInfo->FoundNonSkipPortion);
2597 Record.push_back(Elt: SkipInfo->FoundElse);
2598 AddSourceLocation(Loc: SkipInfo->ElseLoc, Record);
2599 } else {
2600 Record.push_back(Elt: false);
2601 }
2602 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2603 AddSourceLocation(Loc: Cond.IfLoc, Record);
2604 Record.push_back(Elt: Cond.WasSkipping);
2605 Record.push_back(Elt: Cond.FoundNonSkip);
2606 Record.push_back(Elt: Cond.FoundElse);
2607 }
2608 Stream.EmitRecord(Code: PP_CONDITIONAL_STACK, Vals: Record);
2609 Record.clear();
2610 }
2611
2612 // Write the safe buffer opt-out region map in PP
2613 for (SourceLocation &S : PP.serializeSafeBufferOptOutMap())
2614 AddSourceLocation(Loc: S, Record);
2615 Stream.EmitRecord(Code: PP_UNSAFE_BUFFER_USAGE, Vals: Record);
2616 Record.clear();
2617
2618 // Enter the preprocessor block.
2619 Stream.EnterSubblock(BlockID: PREPROCESSOR_BLOCK_ID, CodeLen: 3);
2620
2621 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2622 // FIXME: Include a location for the use, and say which one was used.
2623 if (PP.SawDateOrTime())
2624 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2625
2626 // Loop over all the macro directives that are live at the end of the file,
2627 // emitting each to the PP section.
2628
2629 // Construct the list of identifiers with macro directives that need to be
2630 // serialized.
2631 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2632 // It is meaningless to emit macros for named modules. It only wastes times
2633 // and spaces.
2634 if (!isWritingStdCXXNamedModules())
2635 for (auto &Id : PP.getIdentifierTable())
2636 if (Id.second->hadMacroDefinition() &&
2637 (!Id.second->isFromAST() ||
2638 Id.second->hasChangedSinceDeserialization()))
2639 MacroIdentifiers.push_back(Id.second);
2640 // Sort the set of macro definitions that need to be serialized by the
2641 // name of the macro, to provide a stable ordering.
2642 llvm::sort(C&: MacroIdentifiers, Comp: llvm::deref<std::less<>>());
2643
2644 // Emit the macro directives as a list and associate the offset with the
2645 // identifier they belong to.
2646 for (const IdentifierInfo *Name : MacroIdentifiers) {
2647 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(II: Name);
2648 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2649 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2650
2651 // Write out any exported module macros.
2652 bool EmittedModuleMacros = false;
2653 // C+=20 Header Units are compiled module interfaces, but they preserve
2654 // macros that are live (i.e. have a defined value) at the end of the
2655 // compilation. So when writing a header unit, we preserve only the final
2656 // value of each macro (and discard any that are undefined). Header units
2657 // do not have sub-modules (although they might import other header units).
2658 // PCH files, conversely, retain the history of each macro's define/undef
2659 // and of leaf macros in sub modules.
2660 if (IsModule && WritingModule->isHeaderUnit()) {
2661 // This is for the main TU when it is a C++20 header unit.
2662 // We preserve the final state of defined macros, and we do not emit ones
2663 // that are undefined.
2664 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2665 MD->getKind() == MacroDirective::MD_Undefine)
2666 continue;
2667 AddSourceLocation(Loc: MD->getLocation(), Record);
2668 Record.push_back(Elt: MD->getKind());
2669 if (auto *DefMD = dyn_cast<DefMacroDirective>(Val: MD)) {
2670 Record.push_back(Elt: getMacroRef(MI: DefMD->getInfo(), Name));
2671 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(Val: MD)) {
2672 Record.push_back(Elt: VisMD->isPublic());
2673 }
2674 ModuleMacroRecord.push_back(Elt: getSubmoduleID(Mod: WritingModule));
2675 ModuleMacroRecord.push_back(Elt: getMacroRef(MI: MD->getMacroInfo(), Name));
2676 Stream.EmitRecord(Code: PP_MODULE_MACRO, Vals: ModuleMacroRecord);
2677 ModuleMacroRecord.clear();
2678 EmittedModuleMacros = true;
2679 } else {
2680 // Emit the macro directives in reverse source order.
2681 for (; MD; MD = MD->getPrevious()) {
2682 // Once we hit an ignored macro, we're done: the rest of the chain
2683 // will all be ignored macros.
2684 if (shouldIgnoreMacro(MD, IsModule, PP))
2685 break;
2686 AddSourceLocation(Loc: MD->getLocation(), Record);
2687 Record.push_back(Elt: MD->getKind());
2688 if (auto *DefMD = dyn_cast<DefMacroDirective>(Val: MD)) {
2689 Record.push_back(Elt: getMacroRef(MI: DefMD->getInfo(), Name));
2690 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(Val: MD)) {
2691 Record.push_back(Elt: VisMD->isPublic());
2692 }
2693 }
2694
2695 // We write out exported module macros for PCH as well.
2696 auto Leafs = PP.getLeafModuleMacros(II: Name);
2697 SmallVector<ModuleMacro *, 8> Worklist(Leafs);
2698 llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2699 while (!Worklist.empty()) {
2700 auto *Macro = Worklist.pop_back_val();
2701
2702 // Emit a record indicating this submodule exports this macro.
2703 ModuleMacroRecord.push_back(Elt: getSubmoduleID(Mod: Macro->getOwningModule()));
2704 ModuleMacroRecord.push_back(Elt: getMacroRef(MI: Macro->getMacroInfo(), Name));
2705 for (auto *M : Macro->overrides())
2706 ModuleMacroRecord.push_back(Elt: getSubmoduleID(Mod: M->getOwningModule()));
2707
2708 Stream.EmitRecord(Code: PP_MODULE_MACRO, Vals: ModuleMacroRecord);
2709 ModuleMacroRecord.clear();
2710
2711 // Enqueue overridden macros once we've visited all their ancestors.
2712 for (auto *M : Macro->overrides())
2713 if (++Visits[M] == M->getNumOverridingMacros())
2714 Worklist.push_back(Elt: M);
2715
2716 EmittedModuleMacros = true;
2717 }
2718 }
2719 if (Record.empty() && !EmittedModuleMacros)
2720 continue;
2721
2722 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2723 Stream.EmitRecord(Code: PP_MACRO_DIRECTIVE_HISTORY, Vals: Record);
2724 Record.clear();
2725 }
2726
2727 /// Offsets of each of the macros into the bitstream, indexed by
2728 /// the local macro ID
2729 ///
2730 /// For each identifier that is associated with a macro, this map
2731 /// provides the offset into the bitstream where that macro is
2732 /// defined.
2733 std::vector<uint32_t> MacroOffsets;
2734
2735 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2736 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2737 MacroInfo *MI = MacroInfosToEmit[I].MI;
2738 MacroID ID = MacroInfosToEmit[I].ID;
2739
2740 if (ID < FirstMacroID) {
2741 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2742 continue;
2743 }
2744
2745 // Record the local offset of this macro.
2746 unsigned Index = ID - FirstMacroID;
2747 if (Index >= MacroOffsets.size())
2748 MacroOffsets.resize(new_size: Index + 1);
2749
2750 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2751 assert((Offset >> 32) == 0 && "Macro offset too large");
2752 MacroOffsets[Index] = Offset;
2753
2754 AddIdentifierRef(II: Name, Record);
2755 AddSourceLocation(Loc: MI->getDefinitionLoc(), Record);
2756 AddSourceLocation(Loc: MI->getDefinitionEndLoc(), Record);
2757 Record.push_back(Elt: MI->isUsed());
2758 Record.push_back(Elt: MI->isUsedForHeaderGuard());
2759 Record.push_back(Elt: MI->getNumTokens());
2760 unsigned Code;
2761 if (MI->isObjectLike()) {
2762 Code = PP_MACRO_OBJECT_LIKE;
2763 } else {
2764 Code = PP_MACRO_FUNCTION_LIKE;
2765
2766 Record.push_back(Elt: MI->isC99Varargs());
2767 Record.push_back(Elt: MI->isGNUVarargs());
2768 Record.push_back(Elt: MI->hasCommaPasting());
2769 Record.push_back(Elt: MI->getNumParams());
2770 for (const IdentifierInfo *Param : MI->params())
2771 AddIdentifierRef(II: Param, Record);
2772 }
2773
2774 // If we have a detailed preprocessing record, record the macro definition
2775 // ID that corresponds to this macro.
2776 if (PPRec)
2777 Record.push_back(Elt: MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2778
2779 Stream.EmitRecord(Code, Vals: Record);
2780 Record.clear();
2781
2782 // Emit the tokens array.
2783 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2784 // Note that we know that the preprocessor does not have any annotation
2785 // tokens in it because they are created by the parser, and thus can't
2786 // be in a macro definition.
2787 const Token &Tok = MI->getReplacementToken(Tok: TokNo);
2788 AddToken(Tok, Record);
2789 Stream.EmitRecord(Code: PP_TOKEN, Vals: Record);
2790 Record.clear();
2791 }
2792 ++NumMacros;
2793 }
2794
2795 Stream.ExitBlock();
2796
2797 // Write the offsets table for macro IDs.
2798 using namespace llvm;
2799
2800 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2801 Abbrev->Add(OpInfo: BitCodeAbbrevOp(MACRO_OFFSET));
2802 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2803 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2804 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2805 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2806
2807 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2808 {
2809 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2810 FirstMacroID - NUM_PREDEF_MACRO_IDS,
2811 MacroOffsetsBase - ASTBlockStartOffset};
2812 Stream.EmitRecordWithBlob(Abbrev: MacroOffsetAbbrev, Vals: Record, Blob: bytes(v: MacroOffsets));
2813 }
2814}
2815
2816void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2817 uint64_t MacroOffsetsBase) {
2818 if (PPRec.local_begin() == PPRec.local_end())
2819 return;
2820
2821 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2822
2823 // Enter the preprocessor block.
2824 Stream.EnterSubblock(BlockID: PREPROCESSOR_DETAIL_BLOCK_ID, CodeLen: 3);
2825
2826 // If the preprocessor has a preprocessing record, emit it.
2827 unsigned NumPreprocessingRecords = 0;
2828 using namespace llvm;
2829
2830 // Set up the abbreviation for
2831 unsigned InclusionAbbrev = 0;
2832 {
2833 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2834 Abbrev->Add(OpInfo: BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2835 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2836 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2837 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2838 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2839 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2840 InclusionAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2841 }
2842
2843 unsigned FirstPreprocessorEntityID
2844 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2845 + NUM_PREDEF_PP_ENTITY_IDS;
2846 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2847 RecordData Record;
2848 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2849 EEnd = PPRec.local_end();
2850 E != EEnd;
2851 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2852 Record.clear();
2853
2854 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2855 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2856 SourceRange R = getAdjustedRange(Range: (*E)->getSourceRange());
2857 PreprocessedEntityOffsets.emplace_back(
2858 Args: getRawSourceLocationEncoding(Loc: R.getBegin()),
2859 Args: getRawSourceLocationEncoding(Loc: R.getEnd()), Args&: Offset);
2860
2861 if (auto *MD = dyn_cast<MacroDefinitionRecord>(Val: *E)) {
2862 // Record this macro definition's ID.
2863 MacroDefinitions[MD] = NextPreprocessorEntityID;
2864
2865 AddIdentifierRef(II: MD->getName(), Record);
2866 Stream.EmitRecord(Code: PPD_MACRO_DEFINITION, Vals: Record);
2867 continue;
2868 }
2869
2870 if (auto *ME = dyn_cast<MacroExpansion>(Val: *E)) {
2871 Record.push_back(Elt: ME->isBuiltinMacro());
2872 if (ME->isBuiltinMacro())
2873 AddIdentifierRef(II: ME->getName(), Record);
2874 else
2875 Record.push_back(Elt: MacroDefinitions[ME->getDefinition()]);
2876 Stream.EmitRecord(Code: PPD_MACRO_EXPANSION, Vals: Record);
2877 continue;
2878 }
2879
2880 if (auto *ID = dyn_cast<InclusionDirective>(Val: *E)) {
2881 Record.push_back(Elt: PPD_INCLUSION_DIRECTIVE);
2882 Record.push_back(Elt: ID->getFileName().size());
2883 Record.push_back(Elt: ID->wasInQuotes());
2884 Record.push_back(Elt: static_cast<unsigned>(ID->getKind()));
2885 Record.push_back(Elt: ID->importedModule());
2886 SmallString<64> Buffer;
2887 Buffer += ID->getFileName();
2888 // Check that the FileEntry is not null because it was not resolved and
2889 // we create a PCH even with compiler errors.
2890 if (ID->getFile())
2891 Buffer += ID->getFile()->getName();
2892 Stream.EmitRecordWithBlob(Abbrev: InclusionAbbrev, Vals: Record, Blob: Buffer);
2893 continue;
2894 }
2895
2896 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2897 }
2898 Stream.ExitBlock();
2899
2900 // Write the offsets table for the preprocessing record.
2901 if (NumPreprocessingRecords > 0) {
2902 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2903
2904 // Write the offsets table for identifier IDs.
2905 using namespace llvm;
2906
2907 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2908 Abbrev->Add(OpInfo: BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2909 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2910 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2911 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2912
2913 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2914 FirstPreprocessorEntityID -
2915 NUM_PREDEF_PP_ENTITY_IDS};
2916 Stream.EmitRecordWithBlob(Abbrev: PPEOffsetAbbrev, Vals: Record,
2917 Blob: bytes(v: PreprocessedEntityOffsets));
2918 }
2919
2920 // Write the skipped region table for the preprocessing record.
2921 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2922 if (SkippedRanges.size() > 0) {
2923 std::vector<PPSkippedRange> SerializedSkippedRanges;
2924 SerializedSkippedRanges.reserve(n: SkippedRanges.size());
2925 for (auto const& Range : SkippedRanges)
2926 SerializedSkippedRanges.emplace_back(
2927 args: getRawSourceLocationEncoding(Loc: Range.getBegin()),
2928 args: getRawSourceLocationEncoding(Loc: Range.getEnd()));
2929
2930 using namespace llvm;
2931 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2932 Abbrev->Add(OpInfo: BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2933 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2934 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
2935
2936 Record.clear();
2937 Record.push_back(Elt: PPD_SKIPPED_RANGES);
2938 Stream.EmitRecordWithBlob(Abbrev: PPESkippedRangeAbbrev, Vals: Record,
2939 Blob: bytes(v: SerializedSkippedRanges));
2940 }
2941}
2942
2943unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2944 if (!Mod)
2945 return 0;
2946
2947 auto Known = SubmoduleIDs.find(Val: Mod);
2948 if (Known != SubmoduleIDs.end())
2949 return Known->second;
2950
2951 auto *Top = Mod->getTopLevelModule();
2952 if (Top != WritingModule &&
2953 (getLangOpts().CompilingPCH ||
2954 !Top->fullModuleNameIs(nameParts: StringRef(getLangOpts().CurrentModule))))
2955 return 0;
2956
2957 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2958}
2959
2960unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2961 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2962 // FIXME: This can easily happen, if we have a reference to a submodule that
2963 // did not result in us loading a module file for that submodule. For
2964 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2965 // assert((ID || !Mod) &&
2966 // "asked for module ID for non-local, non-imported module");
2967 return ID;
2968}
2969
2970/// Compute the number of modules within the given tree (including the
2971/// given module).
2972static unsigned getNumberOfModules(Module *Mod) {
2973 unsigned ChildModules = 0;
2974 for (auto *Submodule : Mod->submodules())
2975 ChildModules += getNumberOfModules(Mod: Submodule);
2976
2977 return ChildModules + 1;
2978}
2979
2980void ASTWriter::WriteSubmodules(Module *WritingModule, ASTContext *Context) {
2981 // Enter the submodule description block.
2982 Stream.EnterSubblock(BlockID: SUBMODULE_BLOCK_ID, /*bits for abbreviations*/CodeLen: 5);
2983
2984 // Write the abbreviations needed for the submodules block.
2985 using namespace llvm;
2986
2987 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2988 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2989 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2990 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2991 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Kind
2992 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Definition location
2993 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Inferred allowed by
2994 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2995 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2996 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2997 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2998 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2999 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
3000 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
3001 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
3002 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
3003 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NamedModuleHasN...
3004 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3005 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3006
3007 Abbrev = std::make_shared<BitCodeAbbrev>();
3008 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
3009 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3010 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3011
3012 Abbrev = std::make_shared<BitCodeAbbrev>();
3013 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_HEADER));
3014 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3015 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3016
3017 Abbrev = std::make_shared<BitCodeAbbrev>();
3018 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
3019 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3020 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3021
3022 Abbrev = std::make_shared<BitCodeAbbrev>();
3023 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
3024 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3025 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3026
3027 Abbrev = std::make_shared<BitCodeAbbrev>();
3028 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_REQUIRES));
3029 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
3030 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
3031 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3032
3033 Abbrev = std::make_shared<BitCodeAbbrev>();
3034 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
3035 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3036 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3037
3038 Abbrev = std::make_shared<BitCodeAbbrev>();
3039 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
3040 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3041 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3042
3043 Abbrev = std::make_shared<BitCodeAbbrev>();
3044 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
3045 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3046 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3047
3048 Abbrev = std::make_shared<BitCodeAbbrev>();
3049 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
3050 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3051 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3052
3053 Abbrev = std::make_shared<BitCodeAbbrev>();
3054 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
3055 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
3056 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
3057 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3058
3059 Abbrev = std::make_shared<BitCodeAbbrev>();
3060 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
3061 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
3062 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3063
3064 Abbrev = std::make_shared<BitCodeAbbrev>();
3065 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_CONFLICT));
3066 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
3067 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
3068 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3069
3070 Abbrev = std::make_shared<BitCodeAbbrev>();
3071 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
3072 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
3073 unsigned ExportAsAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3074
3075 // Write the submodule metadata block.
3076 RecordData::value_type Record[] = {
3077 getNumberOfModules(Mod: WritingModule),
3078 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
3079 Stream.EmitRecord(Code: SUBMODULE_METADATA, Vals: Record);
3080
3081 // Write all of the submodules.
3082 std::queue<Module *> Q;
3083 Q.push(x: WritingModule);
3084 while (!Q.empty()) {
3085 Module *Mod = Q.front();
3086 Q.pop();
3087 unsigned ID = getSubmoduleID(Mod);
3088
3089 uint64_t ParentID = 0;
3090 if (Mod->Parent) {
3091 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
3092 ParentID = SubmoduleIDs[Mod->Parent];
3093 }
3094
3095 SourceLocationEncoding::RawLocEncoding DefinitionLoc =
3096 getRawSourceLocationEncoding(Loc: getAdjustedLocation(Loc: Mod->DefinitionLoc));
3097
3098 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
3099 FileID UnadjustedInferredFID;
3100 if (Mod->IsInferred)
3101 UnadjustedInferredFID = ModMap.getModuleMapFileIDForUniquing(M: Mod);
3102 int InferredFID = getAdjustedFileID(FID: UnadjustedInferredFID).getOpaqueValue();
3103
3104 // Emit the definition of the block.
3105 {
3106 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
3107 ID,
3108 ParentID,
3109 (RecordData::value_type)Mod->Kind,
3110 DefinitionLoc,
3111 (RecordData::value_type)InferredFID,
3112 Mod->IsFramework,
3113 Mod->IsExplicit,
3114 Mod->IsSystem,
3115 Mod->IsExternC,
3116 Mod->InferSubmodules,
3117 Mod->InferExplicitSubmodules,
3118 Mod->InferExportWildcard,
3119 Mod->ConfigMacrosExhaustive,
3120 Mod->ModuleMapIsPrivate,
3121 Mod->NamedModuleHasInit};
3122 Stream.EmitRecordWithBlob(Abbrev: DefinitionAbbrev, Vals: Record, Blob: Mod->Name);
3123 }
3124
3125 // Emit the requirements.
3126 for (const auto &R : Mod->Requirements) {
3127 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.RequiredState};
3128 Stream.EmitRecordWithBlob(Abbrev: RequiresAbbrev, Vals: Record, Blob: R.FeatureName);
3129 }
3130
3131 // Emit the umbrella header, if there is one.
3132 if (std::optional<Module::Header> UmbrellaHeader =
3133 Mod->getUmbrellaHeaderAsWritten()) {
3134 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
3135 Stream.EmitRecordWithBlob(Abbrev: UmbrellaAbbrev, Vals: Record,
3136 Blob: UmbrellaHeader->NameAsWritten);
3137 } else if (std::optional<Module::DirectoryName> UmbrellaDir =
3138 Mod->getUmbrellaDirAsWritten()) {
3139 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
3140 Stream.EmitRecordWithBlob(Abbrev: UmbrellaDirAbbrev, Vals: Record,
3141 Blob: UmbrellaDir->NameAsWritten);
3142 }
3143
3144 // Emit the headers.
3145 struct {
3146 unsigned RecordKind;
3147 unsigned Abbrev;
3148 Module::HeaderKind HeaderKind;
3149 } HeaderLists[] = {
3150 {.RecordKind: SUBMODULE_HEADER, .Abbrev: HeaderAbbrev, .HeaderKind: Module::HK_Normal},
3151 {.RecordKind: SUBMODULE_TEXTUAL_HEADER, .Abbrev: TextualHeaderAbbrev, .HeaderKind: Module::HK_Textual},
3152 {.RecordKind: SUBMODULE_PRIVATE_HEADER, .Abbrev: PrivateHeaderAbbrev, .HeaderKind: Module::HK_Private},
3153 {.RecordKind: SUBMODULE_PRIVATE_TEXTUAL_HEADER, .Abbrev: PrivateTextualHeaderAbbrev,
3154 .HeaderKind: Module::HK_PrivateTextual},
3155 {.RecordKind: SUBMODULE_EXCLUDED_HEADER, .Abbrev: ExcludedHeaderAbbrev, .HeaderKind: Module::HK_Excluded}
3156 };
3157 for (const auto &HL : HeaderLists) {
3158 RecordData::value_type Record[] = {HL.RecordKind};
3159 for (const auto &H : Mod->getHeaders(HK: HL.HeaderKind))
3160 Stream.EmitRecordWithBlob(Abbrev: HL.Abbrev, Vals: Record, Blob: H.NameAsWritten);
3161 }
3162
3163 // Emit the top headers.
3164 {
3165 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
3166 for (FileEntryRef H : Mod->getTopHeaders(FileMgr&: PP->getFileManager())) {
3167 SmallString<128> HeaderName(H.getName());
3168 PreparePathForOutput(Path&: HeaderName);
3169 Stream.EmitRecordWithBlob(Abbrev: TopHeaderAbbrev, Vals: Record, Blob: HeaderName);
3170 }
3171 }
3172
3173 // Emit the imports.
3174 if (!Mod->Imports.empty()) {
3175 RecordData Record;
3176 for (auto *I : Mod->Imports)
3177 Record.push_back(Elt: getSubmoduleID(Mod: I));
3178 Stream.EmitRecord(Code: SUBMODULE_IMPORTS, Vals: Record);
3179 }
3180
3181 // Emit the modules affecting compilation that were not imported.
3182 if (!Mod->AffectingClangModules.empty()) {
3183 RecordData Record;
3184 for (auto *I : Mod->AffectingClangModules)
3185 Record.push_back(Elt: getSubmoduleID(Mod: I));
3186 Stream.EmitRecord(Code: SUBMODULE_AFFECTING_MODULES, Vals: Record);
3187 }
3188
3189 // Emit the exports.
3190 if (!Mod->Exports.empty()) {
3191 RecordData Record;
3192 for (const auto &E : Mod->Exports) {
3193 // FIXME: This may fail; we don't require that all exported modules
3194 // are local or imported.
3195 Record.push_back(Elt: getSubmoduleID(Mod: E.getPointer()));
3196 Record.push_back(Elt: E.getInt());
3197 }
3198 Stream.EmitRecord(Code: SUBMODULE_EXPORTS, Vals: Record);
3199 }
3200
3201 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
3202 // Might be unnecessary as use declarations are only used to build the
3203 // module itself.
3204
3205 // TODO: Consider serializing undeclared uses of modules.
3206
3207 // Emit the link libraries.
3208 for (const auto &LL : Mod->LinkLibraries) {
3209 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3210 LL.IsFramework};
3211 Stream.EmitRecordWithBlob(Abbrev: LinkLibraryAbbrev, Vals: Record, Blob: LL.Library);
3212 }
3213
3214 // Emit the conflicts.
3215 for (const auto &C : Mod->Conflicts) {
3216 // FIXME: This may fail; we don't require that all conflicting modules
3217 // are local or imported.
3218 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3219 getSubmoduleID(Mod: C.Other)};
3220 Stream.EmitRecordWithBlob(Abbrev: ConflictAbbrev, Vals: Record, Blob: C.Message);
3221 }
3222
3223 // Emit the configuration macros.
3224 for (const auto &CM : Mod->ConfigMacros) {
3225 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3226 Stream.EmitRecordWithBlob(Abbrev: ConfigMacroAbbrev, Vals: Record, Blob: CM);
3227 }
3228
3229 // Emit the reachable initializers.
3230 // The initializer may only be unreachable in reduced BMI.
3231 if (Context) {
3232 RecordData Inits;
3233 for (Decl *D : Context->getModuleInitializers(M: Mod))
3234 if (wasDeclEmitted(D))
3235 AddDeclRef(D, Record&: Inits);
3236 if (!Inits.empty())
3237 Stream.EmitRecord(Code: SUBMODULE_INITIALIZERS, Vals: Inits);
3238 }
3239
3240 // Emit the name of the re-exported module, if any.
3241 if (!Mod->ExportAsModule.empty()) {
3242 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3243 Stream.EmitRecordWithBlob(Abbrev: ExportAsAbbrev, Vals: Record, Blob: Mod->ExportAsModule);
3244 }
3245
3246 // Queue up the submodules of this module.
3247 for (auto *M : Mod->submodules())
3248 Q.push(x: M);
3249 }
3250
3251 Stream.ExitBlock();
3252
3253 assert((NextSubmoduleID - FirstSubmoduleID ==
3254 getNumberOfModules(WritingModule)) &&
3255 "Wrong # of submodules; found a reference to a non-local, "
3256 "non-imported submodule?");
3257}
3258
3259void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3260 bool isModule) {
3261 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3262 DiagStateIDMap;
3263 unsigned CurrID = 0;
3264 RecordData Record;
3265
3266 auto EncodeDiagStateFlags =
3267 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3268 unsigned Result = (unsigned)DS->ExtBehavior;
3269 for (unsigned Val :
3270 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3271 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3272 (unsigned)DS->SuppressSystemWarnings})
3273 Result = (Result << 1) | Val;
3274 return Result;
3275 };
3276
3277 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3278 Record.push_back(Elt: Flags);
3279
3280 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3281 bool IncludeNonPragmaStates) {
3282 // Ensure that the diagnostic state wasn't modified since it was created.
3283 // We will not correctly round-trip this information otherwise.
3284 assert(Flags == EncodeDiagStateFlags(State) &&
3285 "diag state flags vary in single AST file");
3286
3287 // If we ever serialize non-pragma mappings outside the initial state, the
3288 // code below will need to consider more than getDefaultMapping.
3289 assert(!IncludeNonPragmaStates ||
3290 State == Diag.DiagStatesByLoc.FirstDiagState);
3291
3292 unsigned &DiagStateID = DiagStateIDMap[State];
3293 Record.push_back(Elt: DiagStateID);
3294
3295 if (DiagStateID == 0) {
3296 DiagStateID = ++CurrID;
3297 SmallVector<std::pair<unsigned, DiagnosticMapping>> Mappings;
3298
3299 // Add a placeholder for the number of mappings.
3300 auto SizeIdx = Record.size();
3301 Record.emplace_back();
3302 for (const auto &I : *State) {
3303 // Maybe skip non-pragmas.
3304 if (!I.second.isPragma() && !IncludeNonPragmaStates)
3305 continue;
3306 // Skip default mappings. We have a mapping for every diagnostic ever
3307 // emitted, regardless of whether it was customized.
3308 if (!I.second.isPragma() &&
3309 I.second == Diag.getDiagnosticIDs()->getDefaultMapping(DiagID: I.first))
3310 continue;
3311 Mappings.push_back(Elt: I);
3312 }
3313
3314 // Sort by diag::kind for deterministic output.
3315 llvm::sort(C&: Mappings, Comp: llvm::less_first());
3316
3317 for (const auto &I : Mappings) {
3318 Record.push_back(Elt: I.first);
3319 Record.push_back(Elt: I.second.serialize());
3320 }
3321 // Update the placeholder.
3322 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3323 }
3324 };
3325
3326 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3327
3328 // Reserve a spot for the number of locations with state transitions.
3329 auto NumLocationsIdx = Record.size();
3330 Record.emplace_back();
3331
3332 // Emit the state transitions.
3333 unsigned NumLocations = 0;
3334 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3335 if (!FileIDAndFile.first.isValid() ||
3336 !FileIDAndFile.second.HasLocalTransitions)
3337 continue;
3338 ++NumLocations;
3339
3340 AddFileID(FID: FileIDAndFile.first, Record);
3341
3342 Record.push_back(Elt: FileIDAndFile.second.StateTransitions.size());
3343 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3344 Record.push_back(Elt: getAdjustedOffset(Offset: StatePoint.Offset));
3345 AddDiagState(StatePoint.State, false);
3346 }
3347 }
3348
3349 // Backpatch the number of locations.
3350 Record[NumLocationsIdx] = NumLocations;
3351
3352 // Emit CurDiagStateLoc. Do it last in order to match source order.
3353 //
3354 // This also protects against a hypothetical corner case with simulating
3355 // -Werror settings for implicit modules in the ASTReader, where reading
3356 // CurDiagState out of context could change whether warning pragmas are
3357 // treated as errors.
3358 AddSourceLocation(Loc: Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3359 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3360
3361 Stream.EmitRecord(Code: DIAG_PRAGMA_MAPPINGS, Vals: Record);
3362}
3363
3364//===----------------------------------------------------------------------===//
3365// Type Serialization
3366//===----------------------------------------------------------------------===//
3367
3368/// Write the representation of a type to the AST stream.
3369void ASTWriter::WriteType(ASTContext &Context, QualType T) {
3370 TypeIdx &IdxRef = TypeIdxs[T];
3371 if (IdxRef.getValue() == 0) // we haven't seen this type before.
3372 IdxRef = TypeIdx(0, NextTypeID++);
3373 TypeIdx Idx = IdxRef;
3374
3375 assert(Idx.getModuleFileIndex() == 0 && "Re-writing a type from a prior AST");
3376 assert(Idx.getValue() >= FirstTypeID && "Writing predefined type");
3377
3378 // Emit the type's representation.
3379 uint64_t Offset =
3380 ASTTypeWriter(Context, *this).write(T) - DeclTypesBlockStartOffset;
3381
3382 // Record the offset for this type.
3383 uint64_t Index = Idx.getValue() - FirstTypeID;
3384 if (TypeOffsets.size() == Index)
3385 TypeOffsets.emplace_back(args&: Offset);
3386 else if (TypeOffsets.size() < Index) {
3387 TypeOffsets.resize(new_size: Index + 1);
3388 TypeOffsets[Index].set(Offset);
3389 } else {
3390 llvm_unreachable("Types emitted in wrong order");
3391 }
3392}
3393
3394//===----------------------------------------------------------------------===//
3395// Declaration Serialization
3396//===----------------------------------------------------------------------===//
3397
3398static bool IsInternalDeclFromFileContext(const Decl *D) {
3399 auto *ND = dyn_cast<NamedDecl>(Val: D);
3400 if (!ND)
3401 return false;
3402
3403 if (!D->getDeclContext()->getRedeclContext()->isFileContext())
3404 return false;
3405
3406 return ND->getFormalLinkage() == Linkage::Internal;
3407}
3408
3409/// Write the block containing all of the declaration IDs
3410/// lexically declared within the given DeclContext.
3411///
3412/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3413/// bitstream, or 0 if no block was written.
3414uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3415 const DeclContext *DC) {
3416 if (DC->decls_empty())
3417 return 0;
3418
3419 // In reduced BMI, we don't care the declarations in functions.
3420 if (GeneratingReducedBMI && DC->isFunctionOrMethod())
3421 return 0;
3422
3423 uint64_t Offset = Stream.GetCurrentBitNo();
3424 SmallVector<DeclID, 128> KindDeclPairs;
3425 for (const auto *D : DC->decls()) {
3426 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(D))
3427 continue;
3428
3429 // We don't need to write decls with internal linkage into reduced BMI.
3430 // If such decls gets emitted due to it get used from inline functions,
3431 // the program illegal. However, there are too many use of static inline
3432 // functions in the global module fragment and it will be breaking change
3433 // to forbid that. So we have to allow to emit such declarations from GMF.
3434 if (GeneratingReducedBMI && !D->isFromExplicitGlobalModule() &&
3435 IsInternalDeclFromFileContext(D))
3436 continue;
3437
3438 KindDeclPairs.push_back(Elt: D->getKind());
3439 KindDeclPairs.push_back(Elt: GetDeclRef(D).getRawValue());
3440 }
3441
3442 ++NumLexicalDeclContexts;
3443 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3444 Stream.EmitRecordWithBlob(Abbrev: DeclContextLexicalAbbrev, Vals: Record,
3445 Blob: bytes(v: KindDeclPairs));
3446 return Offset;
3447}
3448
3449void ASTWriter::WriteTypeDeclOffsets() {
3450 using namespace llvm;
3451
3452 // Write the type offsets array
3453 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3454 Abbrev->Add(OpInfo: BitCodeAbbrevOp(TYPE_OFFSET));
3455 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3456 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3457 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3458 {
3459 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size()};
3460 Stream.EmitRecordWithBlob(Abbrev: TypeOffsetAbbrev, Vals: Record, Blob: bytes(v: TypeOffsets));
3461 }
3462
3463 // Write the declaration offsets array
3464 Abbrev = std::make_shared<BitCodeAbbrev>();
3465 Abbrev->Add(OpInfo: BitCodeAbbrevOp(DECL_OFFSET));
3466 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3467 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3468 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3469 {
3470 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size()};
3471 Stream.EmitRecordWithBlob(Abbrev: DeclOffsetAbbrev, Vals: Record, Blob: bytes(v: DeclOffsets));
3472 }
3473}
3474
3475void ASTWriter::WriteFileDeclIDsMap() {
3476 using namespace llvm;
3477
3478 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3479 SortedFileDeclIDs.reserve(N: FileDeclIDs.size());
3480 for (const auto &P : FileDeclIDs)
3481 SortedFileDeclIDs.push_back(Elt: std::make_pair(x: P.first, y: P.second.get()));
3482 llvm::sort(C&: SortedFileDeclIDs, Comp: llvm::less_first());
3483
3484 // Join the vectors of DeclIDs from all files.
3485 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3486 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3487 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3488 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3489 llvm::stable_sort(Range&: Info.DeclIDs);
3490 for (auto &LocDeclEntry : Info.DeclIDs)
3491 FileGroupedDeclIDs.push_back(Elt: LocDeclEntry.second.getRawValue());
3492 }
3493
3494 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3495 Abbrev->Add(OpInfo: BitCodeAbbrevOp(FILE_SORTED_DECLS));
3496 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3497 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3498 unsigned AbbrevCode = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3499 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3500 FileGroupedDeclIDs.size()};
3501 Stream.EmitRecordWithBlob(Abbrev: AbbrevCode, Vals: Record, Blob: bytes(v: FileGroupedDeclIDs));
3502}
3503
3504void ASTWriter::WriteComments(ASTContext &Context) {
3505 Stream.EnterSubblock(BlockID: COMMENTS_BLOCK_ID, CodeLen: 3);
3506 auto _ = llvm::make_scope_exit(F: [this] { Stream.ExitBlock(); });
3507 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3508 return;
3509
3510 // Don't write comments to BMI to reduce the size of BMI.
3511 // If language services (e.g., clangd) want such abilities,
3512 // we can offer a special option then.
3513 if (isWritingStdCXXNamedModules())
3514 return;
3515
3516 RecordData Record;
3517 for (const auto &FO : Context.Comments.OrderedComments) {
3518 for (const auto &OC : FO.second) {
3519 const RawComment *I = OC.second;
3520 Record.clear();
3521 AddSourceRange(Range: I->getSourceRange(), Record);
3522 Record.push_back(Elt: I->getKind());
3523 Record.push_back(Elt: I->isTrailingComment());
3524 Record.push_back(Elt: I->isAlmostTrailingComment());
3525 Stream.EmitRecord(Code: COMMENTS_RAW_COMMENT, Vals: Record);
3526 }
3527 }
3528}
3529
3530//===----------------------------------------------------------------------===//
3531// Global Method Pool and Selector Serialization
3532//===----------------------------------------------------------------------===//
3533
3534namespace {
3535
3536// Trait used for the on-disk hash table used in the method pool.
3537class ASTMethodPoolTrait {
3538 ASTWriter &Writer;
3539
3540public:
3541 using key_type = Selector;
3542 using key_type_ref = key_type;
3543
3544 struct data_type {
3545 SelectorID ID;
3546 ObjCMethodList Instance, Factory;
3547 };
3548 using data_type_ref = const data_type &;
3549
3550 using hash_value_type = unsigned;
3551 using offset_type = unsigned;
3552
3553 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3554
3555 static hash_value_type ComputeHash(Selector Sel) {
3556 return serialization::ComputeHash(Sel);
3557 }
3558
3559 std::pair<unsigned, unsigned>
3560 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3561 data_type_ref Methods) {
3562 unsigned KeyLen =
3563 2 + (Sel.getNumArgs() ? Sel.getNumArgs() * sizeof(IdentifierID)
3564 : sizeof(IdentifierID));
3565 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3566 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3567 Method = Method->getNext())
3568 if (ShouldWriteMethodListNode(Node: Method))
3569 DataLen += sizeof(DeclID);
3570 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3571 Method = Method->getNext())
3572 if (ShouldWriteMethodListNode(Node: Method))
3573 DataLen += sizeof(DeclID);
3574 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3575 }
3576
3577 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3578 using namespace llvm::support;
3579
3580 endian::Writer LE(Out, llvm::endianness::little);
3581 uint64_t Start = Out.tell();
3582 assert((Start >> 32) == 0 && "Selector key offset too large");
3583 Writer.SetSelectorOffset(Sel, Offset: Start);
3584 unsigned N = Sel.getNumArgs();
3585 LE.write<uint16_t>(Val: N);
3586 if (N == 0)
3587 N = 1;
3588 for (unsigned I = 0; I != N; ++I)
3589 LE.write<IdentifierID>(
3590 Val: Writer.getIdentifierRef(II: Sel.getIdentifierInfoForSlot(argIndex: I)));
3591 }
3592
3593 void EmitData(raw_ostream& Out, key_type_ref,
3594 data_type_ref Methods, unsigned DataLen) {
3595 using namespace llvm::support;
3596
3597 endian::Writer LE(Out, llvm::endianness::little);
3598 uint64_t Start = Out.tell(); (void)Start;
3599 LE.write<uint32_t>(Val: Methods.ID);
3600 unsigned NumInstanceMethods = 0;
3601 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3602 Method = Method->getNext())
3603 if (ShouldWriteMethodListNode(Node: Method))
3604 ++NumInstanceMethods;
3605
3606 unsigned NumFactoryMethods = 0;
3607 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3608 Method = Method->getNext())
3609 if (ShouldWriteMethodListNode(Node: Method))
3610 ++NumFactoryMethods;
3611
3612 unsigned InstanceBits = Methods.Instance.getBits();
3613 assert(InstanceBits < 4);
3614 unsigned InstanceHasMoreThanOneDeclBit =
3615 Methods.Instance.hasMoreThanOneDecl();
3616 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3617 (InstanceHasMoreThanOneDeclBit << 2) |
3618 InstanceBits;
3619 unsigned FactoryBits = Methods.Factory.getBits();
3620 assert(FactoryBits < 4);
3621 unsigned FactoryHasMoreThanOneDeclBit =
3622 Methods.Factory.hasMoreThanOneDecl();
3623 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3624 (FactoryHasMoreThanOneDeclBit << 2) |
3625 FactoryBits;
3626 LE.write<uint16_t>(Val: FullInstanceBits);
3627 LE.write<uint16_t>(Val: FullFactoryBits);
3628 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3629 Method = Method->getNext())
3630 if (ShouldWriteMethodListNode(Node: Method))
3631 LE.write<DeclID>(Val: (DeclID)Writer.getDeclID(Method->getMethod()));
3632 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3633 Method = Method->getNext())
3634 if (ShouldWriteMethodListNode(Node: Method))
3635 LE.write<DeclID>(Val: (DeclID)Writer.getDeclID(Method->getMethod()));
3636
3637 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3638 }
3639
3640private:
3641 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3642 return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3643 }
3644};
3645
3646} // namespace
3647
3648/// Write ObjC data: selectors and the method pool.
3649///
3650/// The method pool contains both instance and factory methods, stored
3651/// in an on-disk hash table indexed by the selector. The hash table also
3652/// contains an empty entry for every other selector known to Sema.
3653void ASTWriter::WriteSelectors(Sema &SemaRef) {
3654 using namespace llvm;
3655
3656 // Do we have to do anything at all?
3657 if (SemaRef.ObjC().MethodPool.empty() && SelectorIDs.empty())
3658 return;
3659 unsigned NumTableEntries = 0;
3660 // Create and write out the blob that contains selectors and the method pool.
3661 {
3662 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3663 ASTMethodPoolTrait Trait(*this);
3664
3665 // Create the on-disk hash table representation. We walk through every
3666 // selector we've seen and look it up in the method pool.
3667 SelectorOffsets.resize(new_size: NextSelectorID - FirstSelectorID);
3668 for (auto &SelectorAndID : SelectorIDs) {
3669 Selector S = SelectorAndID.first;
3670 SelectorID ID = SelectorAndID.second;
3671 SemaObjC::GlobalMethodPool::iterator F =
3672 SemaRef.ObjC().MethodPool.find(Val: S);
3673 ASTMethodPoolTrait::data_type Data = {
3674 .ID: ID,
3675 .Instance: ObjCMethodList(),
3676 .Factory: ObjCMethodList()
3677 };
3678 if (F != SemaRef.ObjC().MethodPool.end()) {
3679 Data.Instance = F->second.first;
3680 Data.Factory = F->second.second;
3681 }
3682 // Only write this selector if it's not in an existing AST or something
3683 // changed.
3684 if (Chain && ID < FirstSelectorID) {
3685 // Selector already exists. Did it change?
3686 bool changed = false;
3687 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3688 M = M->getNext()) {
3689 if (!M->getMethod()->isFromASTFile()) {
3690 changed = true;
3691 Data.Instance = *M;
3692 break;
3693 }
3694 }
3695 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3696 M = M->getNext()) {
3697 if (!M->getMethod()->isFromASTFile()) {
3698 changed = true;
3699 Data.Factory = *M;
3700 break;
3701 }
3702 }
3703 if (!changed)
3704 continue;
3705 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3706 // A new method pool entry.
3707 ++NumTableEntries;
3708 }
3709 Generator.insert(Key: S, Data, InfoObj&: Trait);
3710 }
3711
3712 // Create the on-disk hash table in a buffer.
3713 SmallString<4096> MethodPool;
3714 uint32_t BucketOffset;
3715 {
3716 using namespace llvm::support;
3717
3718 ASTMethodPoolTrait Trait(*this);
3719 llvm::raw_svector_ostream Out(MethodPool);
3720 // Make sure that no bucket is at offset 0
3721 endian::write<uint32_t>(os&: Out, value: 0, endian: llvm::endianness::little);
3722 BucketOffset = Generator.Emit(Out, InfoObj&: Trait);
3723 }
3724
3725 // Create a blob abbreviation
3726 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3727 Abbrev->Add(OpInfo: BitCodeAbbrevOp(METHOD_POOL));
3728 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3729 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3730 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3731 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3732
3733 // Write the method pool
3734 {
3735 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3736 NumTableEntries};
3737 Stream.EmitRecordWithBlob(Abbrev: MethodPoolAbbrev, Vals: Record, Blob: MethodPool);
3738 }
3739
3740 // Create a blob abbreviation for the selector table offsets.
3741 Abbrev = std::make_shared<BitCodeAbbrev>();
3742 Abbrev->Add(OpInfo: BitCodeAbbrevOp(SELECTOR_OFFSETS));
3743 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3744 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3745 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3746 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
3747
3748 // Write the selector offsets table.
3749 {
3750 RecordData::value_type Record[] = {
3751 SELECTOR_OFFSETS, SelectorOffsets.size(),
3752 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3753 Stream.EmitRecordWithBlob(Abbrev: SelectorOffsetAbbrev, Vals: Record,
3754 Blob: bytes(v: SelectorOffsets));
3755 }
3756 }
3757}
3758
3759/// Write the selectors referenced in @selector expression into AST file.
3760void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3761 using namespace llvm;
3762
3763 if (SemaRef.ObjC().ReferencedSelectors.empty())
3764 return;
3765
3766 RecordData Record;
3767 ASTRecordWriter Writer(SemaRef.Context, *this, Record);
3768
3769 // Note: this writes out all references even for a dependent AST. But it is
3770 // very tricky to fix, and given that @selector shouldn't really appear in
3771 // headers, probably not worth it. It's not a correctness issue.
3772 for (auto &SelectorAndLocation : SemaRef.ObjC().ReferencedSelectors) {
3773 Selector Sel = SelectorAndLocation.first;
3774 SourceLocation Loc = SelectorAndLocation.second;
3775 Writer.AddSelectorRef(S: Sel);
3776 Writer.AddSourceLocation(Loc);
3777 }
3778 Writer.Emit(Code: REFERENCED_SELECTOR_POOL);
3779}
3780
3781//===----------------------------------------------------------------------===//
3782// Identifier Table Serialization
3783//===----------------------------------------------------------------------===//
3784
3785/// Determine the declaration that should be put into the name lookup table to
3786/// represent the given declaration in this module. This is usually D itself,
3787/// but if D was imported and merged into a local declaration, we want the most
3788/// recent local declaration instead. The chosen declaration will be the most
3789/// recent declaration in any module that imports this one.
3790static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3791 NamedDecl *D) {
3792 if (!LangOpts.Modules || !D->isFromASTFile())
3793 return D;
3794
3795 if (Decl *Redecl = D->getPreviousDecl()) {
3796 // For Redeclarable decls, a prior declaration might be local.
3797 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3798 // If we find a local decl, we're done.
3799 if (!Redecl->isFromASTFile()) {
3800 // Exception: in very rare cases (for injected-class-names), not all
3801 // redeclarations are in the same semantic context. Skip ones in a
3802 // different context. They don't go in this lookup table at all.
3803 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3804 DC: D->getDeclContext()->getRedeclContext()))
3805 continue;
3806 return cast<NamedDecl>(Val: Redecl);
3807 }
3808
3809 // If we find a decl from a (chained-)PCH stop since we won't find a
3810 // local one.
3811 if (Redecl->getOwningModuleID() == 0)
3812 break;
3813 }
3814 } else if (Decl *First = D->getCanonicalDecl()) {
3815 // For Mergeable decls, the first decl might be local.
3816 if (!First->isFromASTFile())
3817 return cast<NamedDecl>(Val: First);
3818 }
3819
3820 // All declarations are imported. Our most recent declaration will also be
3821 // the most recent one in anyone who imports us.
3822 return D;
3823}
3824
3825namespace {
3826
3827bool IsInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset,
3828 bool IsModule, bool IsCPlusPlus) {
3829 bool NeedDecls = !IsModule || !IsCPlusPlus;
3830
3831 bool IsInteresting =
3832 II->getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
3833 II->getBuiltinID() != Builtin::ID::NotBuiltin ||
3834 II->getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
3835 if (MacroOffset ||
3836 (II->hasMacroDefinition() &&
3837 II->hasFETokenInfoChangedSinceDeserialization()) ||
3838 II->isPoisoned() || (!IsModule && IsInteresting) ||
3839 II->hasRevertedTokenIDToIdentifier() ||
3840 (NeedDecls && II->getFETokenInfo()))
3841 return true;
3842
3843 return false;
3844}
3845
3846bool IsInterestingNonMacroIdentifier(const IdentifierInfo *II,
3847 ASTWriter &Writer) {
3848 bool IsModule = Writer.isWritingModule();
3849 bool IsCPlusPlus = Writer.getLangOpts().CPlusPlus;
3850 return IsInterestingIdentifier(II, /*MacroOffset=*/0, IsModule, IsCPlusPlus);
3851}
3852
3853class ASTIdentifierTableTrait {
3854 ASTWriter &Writer;
3855 Preprocessor &PP;
3856 IdentifierResolver *IdResolver;
3857 bool IsModule;
3858 bool NeedDecls;
3859 ASTWriter::RecordData *InterestingIdentifierOffsets;
3860
3861 /// Determines whether this is an "interesting" identifier that needs a
3862 /// full IdentifierInfo structure written into the hash table. Notably, this
3863 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3864 /// to check that.
3865 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3866 return IsInterestingIdentifier(II, MacroOffset, IsModule,
3867 IsCPlusPlus: Writer.getLangOpts().CPlusPlus);
3868 }
3869
3870public:
3871 using key_type = const IdentifierInfo *;
3872 using key_type_ref = key_type;
3873
3874 using data_type = IdentifierID;
3875 using data_type_ref = data_type;
3876
3877 using hash_value_type = unsigned;
3878 using offset_type = unsigned;
3879
3880 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3881 IdentifierResolver *IdResolver, bool IsModule,
3882 ASTWriter::RecordData *InterestingIdentifierOffsets)
3883 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3884 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3885 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3886
3887 bool needDecls() const { return NeedDecls; }
3888
3889 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3890 return llvm::djbHash(Buffer: II->getName());
3891 }
3892
3893 bool isInterestingIdentifier(const IdentifierInfo *II) {
3894 auto MacroOffset = Writer.getMacroDirectivesOffset(Name: II);
3895 return isInterestingIdentifier(II, MacroOffset);
3896 }
3897
3898 std::pair<unsigned, unsigned>
3899 EmitKeyDataLength(raw_ostream &Out, const IdentifierInfo *II, IdentifierID ID) {
3900 // Record the location of the identifier data. This is used when generating
3901 // the mapping from persistent IDs to strings.
3902 Writer.SetIdentifierOffset(II, Offset: Out.tell());
3903
3904 auto MacroOffset = Writer.getMacroDirectivesOffset(Name: II);
3905
3906 // Emit the offset of the key/data length information to the interesting
3907 // identifiers table if necessary.
3908 if (InterestingIdentifierOffsets &&
3909 isInterestingIdentifier(II, MacroOffset))
3910 InterestingIdentifierOffsets->push_back(Elt: Out.tell());
3911
3912 unsigned KeyLen = II->getLength() + 1;
3913 unsigned DataLen = sizeof(IdentifierID); // bytes for the persistent ID << 1
3914 if (isInterestingIdentifier(II, MacroOffset)) {
3915 DataLen += 2; // 2 bytes for builtin ID
3916 DataLen += 2; // 2 bytes for flags
3917 if (MacroOffset || (II->hasMacroDefinition() &&
3918 II->hasFETokenInfoChangedSinceDeserialization()))
3919 DataLen += 4; // MacroDirectives offset.
3920
3921 if (NeedDecls && IdResolver)
3922 DataLen += std::distance(first: IdResolver->begin(Name: II), last: IdResolver->end()) *
3923 sizeof(DeclID);
3924 }
3925 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3926 }
3927
3928 void EmitKey(raw_ostream &Out, const IdentifierInfo *II, unsigned KeyLen) {
3929 Out.write(Ptr: II->getNameStart(), Size: KeyLen);
3930 }
3931
3932 void EmitData(raw_ostream &Out, const IdentifierInfo *II, IdentifierID ID,
3933 unsigned) {
3934 using namespace llvm::support;
3935
3936 endian::Writer LE(Out, llvm::endianness::little);
3937
3938 auto MacroOffset = Writer.getMacroDirectivesOffset(Name: II);
3939 if (!isInterestingIdentifier(II, MacroOffset)) {
3940 LE.write<IdentifierID>(Val: ID << 1);
3941 return;
3942 }
3943
3944 LE.write<IdentifierID>(Val: (ID << 1) | 0x01);
3945 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3946 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3947 LE.write<uint16_t>(Val: Bits);
3948 Bits = 0;
3949 bool HasMacroDefinition =
3950 (MacroOffset != 0) || (II->hasMacroDefinition() &&
3951 II->hasFETokenInfoChangedSinceDeserialization());
3952 Bits = (Bits << 1) | unsigned(HasMacroDefinition);
3953 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3954 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3955 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3956 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3957 LE.write<uint16_t>(Val: Bits);
3958
3959 if (HasMacroDefinition)
3960 LE.write<uint32_t>(Val: MacroOffset);
3961
3962 if (NeedDecls && IdResolver) {
3963 // Emit the declaration IDs in reverse order, because the
3964 // IdentifierResolver provides the declarations as they would be
3965 // visible (e.g., the function "stat" would come before the struct
3966 // "stat"), but the ASTReader adds declarations to the end of the list
3967 // (so we need to see the struct "stat" before the function "stat").
3968 // Only emit declarations that aren't from a chained PCH, though.
3969 SmallVector<NamedDecl *, 16> Decls(IdResolver->decls(Name: II));
3970 for (NamedDecl *D : llvm::reverse(C&: Decls))
3971 LE.write<DeclID>(Val: (DeclID)Writer.getDeclID(
3972 getDeclForLocalLookup(LangOpts: PP.getLangOpts(), D)));
3973 }
3974 }
3975};
3976
3977} // namespace
3978
3979/// If the \param IdentifierID ID is a local Identifier ID. If the higher
3980/// bits of ID is 0, it implies that the ID doesn't come from AST files.
3981static bool isLocalIdentifierID(IdentifierID ID) { return !(ID >> 32); }
3982
3983/// Write the identifier table into the AST file.
3984///
3985/// The identifier table consists of a blob containing string data
3986/// (the actual identifiers themselves) and a separate "offsets" index
3987/// that maps identifier IDs to locations within the blob.
3988void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3989 IdentifierResolver *IdResolver,
3990 bool IsModule) {
3991 using namespace llvm;
3992
3993 RecordData InterestingIdents;
3994
3995 // Create and write out the blob that contains the identifier
3996 // strings.
3997 {
3998 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3999 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule,
4000 IsModule ? &InterestingIdents : nullptr);
4001
4002 // Create the on-disk hash table representation. We only store offsets
4003 // for identifiers that appear here for the first time.
4004 IdentifierOffsets.resize(new_size: NextIdentID - FirstIdentID);
4005 for (auto IdentIDPair : IdentifierIDs) {
4006 const IdentifierInfo *II = IdentIDPair.first;
4007 IdentifierID ID = IdentIDPair.second;
4008 assert(II && "NULL identifier in identifier table");
4009
4010 // Write out identifiers if either the ID is local or the identifier has
4011 // changed since it was loaded.
4012 if (isLocalIdentifierID(ID) || II->hasChangedSinceDeserialization() ||
4013 (Trait.needDecls() &&
4014 II->hasFETokenInfoChangedSinceDeserialization()))
4015 Generator.insert(Key: II, Data: ID, InfoObj&: Trait);
4016 }
4017
4018 // Create the on-disk hash table in a buffer.
4019 SmallString<4096> IdentifierTable;
4020 uint32_t BucketOffset;
4021 {
4022 using namespace llvm::support;
4023
4024 llvm::raw_svector_ostream Out(IdentifierTable);
4025 // Make sure that no bucket is at offset 0
4026 endian::write<uint32_t>(os&: Out, value: 0, endian: llvm::endianness::little);
4027 BucketOffset = Generator.Emit(Out, InfoObj&: Trait);
4028 }
4029
4030 // Create a blob abbreviation
4031 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4032 Abbrev->Add(OpInfo: BitCodeAbbrevOp(IDENTIFIER_TABLE));
4033 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4034 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4035 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
4036
4037 // Write the identifier table
4038 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
4039 Stream.EmitRecordWithBlob(Abbrev: IDTableAbbrev, Vals: Record, Blob: IdentifierTable);
4040 }
4041
4042 // Write the offsets table for identifier IDs.
4043 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4044 Abbrev->Add(OpInfo: BitCodeAbbrevOp(IDENTIFIER_OFFSET));
4045 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
4046 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4047 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
4048
4049#ifndef NDEBUG
4050 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
4051 assert(IdentifierOffsets[I] && "Missing identifier offset?");
4052#endif
4053
4054 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
4055 IdentifierOffsets.size()};
4056 Stream.EmitRecordWithBlob(Abbrev: IdentifierOffsetAbbrev, Vals: Record,
4057 Blob: bytes(v: IdentifierOffsets));
4058
4059 // In C++, write the list of interesting identifiers (those that are
4060 // defined as macros, poisoned, or similar unusual things).
4061 if (!InterestingIdents.empty())
4062 Stream.EmitRecord(Code: INTERESTING_IDENTIFIERS, Vals: InterestingIdents);
4063}
4064
4065void ASTWriter::handleVTable(CXXRecordDecl *RD) {
4066 if (!RD->isInNamedModule())
4067 return;
4068
4069 PendingEmittingVTables.push_back(Elt: RD);
4070}
4071
4072//===----------------------------------------------------------------------===//
4073// DeclContext's Name Lookup Table Serialization
4074//===----------------------------------------------------------------------===//
4075
4076namespace {
4077
4078class ASTDeclContextNameLookupTraitBase {
4079protected:
4080 ASTWriter &Writer;
4081 using DeclIDsTy = llvm::SmallVector<LocalDeclID, 64>;
4082 DeclIDsTy DeclIDs;
4083
4084public:
4085 /// A start and end index into DeclIDs, representing a sequence of decls.
4086 using data_type = std::pair<unsigned, unsigned>;
4087 using data_type_ref = const data_type &;
4088
4089 using hash_value_type = unsigned;
4090 using offset_type = unsigned;
4091
4092protected:
4093 explicit ASTDeclContextNameLookupTraitBase(ASTWriter &Writer)
4094 : Writer(Writer) {}
4095
4096public:
4097 data_type getData(const DeclIDsTy &LocalIDs) {
4098 unsigned Start = DeclIDs.size();
4099 for (auto ID : LocalIDs)
4100 DeclIDs.push_back(Elt: ID);
4101 return std::make_pair(x&: Start, y: DeclIDs.size());
4102 }
4103
4104 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
4105 unsigned Start = DeclIDs.size();
4106 DeclIDs.insert(
4107 DeclIDs.end(),
4108 DeclIDIterator<GlobalDeclID, LocalDeclID>(FromReader.begin()),
4109 DeclIDIterator<GlobalDeclID, LocalDeclID>(FromReader.end()));
4110 return std::make_pair(x&: Start, y: DeclIDs.size());
4111 }
4112
4113 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
4114 assert(Writer.hasChain() &&
4115 "have reference to loaded module file but no chain?");
4116
4117 using namespace llvm::support;
4118
4119 endian::write<uint32_t>(os&: Out, value: Writer.getChain()->getModuleFileID(M: F),
4120 endian: llvm::endianness::little);
4121 }
4122
4123 std::pair<unsigned, unsigned> EmitKeyDataLengthBase(raw_ostream &Out,
4124 DeclarationNameKey Name,
4125 data_type_ref Lookup) {
4126 unsigned KeyLen = 1;
4127 switch (Name.getKind()) {
4128 case DeclarationName::Identifier:
4129 case DeclarationName::CXXLiteralOperatorName:
4130 case DeclarationName::CXXDeductionGuideName:
4131 KeyLen += sizeof(IdentifierID);
4132 break;
4133 case DeclarationName::ObjCZeroArgSelector:
4134 case DeclarationName::ObjCOneArgSelector:
4135 case DeclarationName::ObjCMultiArgSelector:
4136 KeyLen += 4;
4137 break;
4138 case DeclarationName::CXXOperatorName:
4139 KeyLen += 1;
4140 break;
4141 case DeclarationName::CXXConstructorName:
4142 case DeclarationName::CXXDestructorName:
4143 case DeclarationName::CXXConversionFunctionName:
4144 case DeclarationName::CXXUsingDirective:
4145 break;
4146 }
4147
4148 // length of DeclIDs.
4149 unsigned DataLen = sizeof(DeclID) * (Lookup.second - Lookup.first);
4150
4151 return {KeyLen, DataLen};
4152 }
4153
4154 void EmitKeyBase(raw_ostream &Out, DeclarationNameKey Name) {
4155 using namespace llvm::support;
4156
4157 endian::Writer LE(Out, llvm::endianness::little);
4158 LE.write<uint8_t>(Val: Name.getKind());
4159 switch (Name.getKind()) {
4160 case DeclarationName::Identifier:
4161 case DeclarationName::CXXLiteralOperatorName:
4162 case DeclarationName::CXXDeductionGuideName:
4163 LE.write<IdentifierID>(Val: Writer.getIdentifierRef(II: Name.getIdentifier()));
4164 return;
4165 case DeclarationName::ObjCZeroArgSelector:
4166 case DeclarationName::ObjCOneArgSelector:
4167 case DeclarationName::ObjCMultiArgSelector:
4168 LE.write<uint32_t>(Val: Writer.getSelectorRef(Sel: Name.getSelector()));
4169 return;
4170 case DeclarationName::CXXOperatorName:
4171 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
4172 "Invalid operator?");
4173 LE.write<uint8_t>(Val: Name.getOperatorKind());
4174 return;
4175 case DeclarationName::CXXConstructorName:
4176 case DeclarationName::CXXDestructorName:
4177 case DeclarationName::CXXConversionFunctionName:
4178 case DeclarationName::CXXUsingDirective:
4179 return;
4180 }
4181
4182 llvm_unreachable("Invalid name kind?");
4183 }
4184
4185 void EmitDataBase(raw_ostream &Out, data_type Lookup, unsigned DataLen) {
4186 using namespace llvm::support;
4187
4188 endian::Writer LE(Out, llvm::endianness::little);
4189 uint64_t Start = Out.tell(); (void)Start;
4190 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
4191 LE.write<DeclID>(Val: (DeclID)DeclIDs[I]);
4192 assert(Out.tell() - Start == DataLen && "Data length is wrong");
4193 }
4194};
4195
4196class ModuleLevelNameLookupTrait : public ASTDeclContextNameLookupTraitBase {
4197public:
4198 using primary_module_hash_type = unsigned;
4199
4200 using key_type = std::pair<DeclarationNameKey, primary_module_hash_type>;
4201 using key_type_ref = key_type;
4202
4203 explicit ModuleLevelNameLookupTrait(ASTWriter &Writer)
4204 : ASTDeclContextNameLookupTraitBase(Writer) {}
4205
4206 static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4207
4208 hash_value_type ComputeHash(key_type Key) {
4209 llvm::FoldingSetNodeID ID;
4210 ID.AddInteger(I: Key.first.getHash());
4211 ID.AddInteger(I: Key.second);
4212 return ID.computeStableHash();
4213 }
4214
4215 std::pair<unsigned, unsigned>
4216 EmitKeyDataLength(raw_ostream &Out, key_type Key, data_type_ref Lookup) {
4217 auto [KeyLen, DataLen] = EmitKeyDataLengthBase(Out, Name: Key.first, Lookup);
4218 KeyLen += sizeof(Key.second);
4219 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4220 }
4221
4222 void EmitKey(raw_ostream &Out, key_type Key, unsigned) {
4223 EmitKeyBase(Out, Name: Key.first);
4224 llvm::support::endian::Writer LE(Out, llvm::endianness::little);
4225 LE.write<primary_module_hash_type>(Val: Key.second);
4226 }
4227
4228 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4229 unsigned DataLen) {
4230 EmitDataBase(Out, Lookup, DataLen);
4231 }
4232};
4233
4234static bool isModuleLocalDecl(NamedDecl *D) {
4235 // For decls not in a file context, they should have the same visibility
4236 // with their parent.
4237 if (auto *Parent = dyn_cast<NamedDecl>(D->getNonTransparentDeclContext());
4238 Parent && !D->getNonTransparentDeclContext()->isFileContext())
4239 return isModuleLocalDecl(Parent);
4240
4241 // Deduction Guide are special here. Since their logical parent context are
4242 // not their actual parent.
4243 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
4244 if (auto *CDGD = dyn_cast<CXXDeductionGuideDecl>(Val: FTD->getTemplatedDecl()))
4245 return isModuleLocalDecl(CDGD->getDeducedTemplate());
4246
4247 if (D->getFormalLinkage() == Linkage::Module)
4248 return true;
4249
4250 return false;
4251}
4252
4253static bool isTULocalInNamedModules(NamedDecl *D) {
4254 Module *NamedModule = D->getTopLevelOwningNamedModule();
4255 if (!NamedModule)
4256 return false;
4257
4258 // For none-top level decls, we choose to move it to the general visible
4259 // lookup table. Since the consumer may get its parent somehow and performs
4260 // a lookup in it (considering looking up the operator function in lambda).
4261 // The difference between module local lookup table and TU local lookup table
4262 // is, the consumers still have a chance to lookup in the module local lookup
4263 // table but **now** the consumers won't read the TU local lookup table if
4264 // the consumer is not the original TU.
4265 //
4266 // FIXME: It seems to be an optimization chance (and also a more correct
4267 // semantics) to remain the TULocal lookup table and performing similar lookup
4268 // with the module local lookup table except that we only allow the lookups
4269 // with the same module unit.
4270 if (!D->getNonTransparentDeclContext()->isFileContext())
4271 return false;
4272
4273 return D->getLinkageInternal() == Linkage::Internal;
4274}
4275
4276// Trait used for the on-disk hash table used in the method pool.
4277template <bool CollectingTULocalDecls>
4278class ASTDeclContextNameLookupTrait : public ASTDeclContextNameLookupTraitBase {
4279public:
4280 using ModuleLevelDeclsMapTy =
4281 llvm::DenseMap<ModuleLevelNameLookupTrait::key_type, DeclIDsTy>;
4282
4283 using key_type = DeclarationNameKey;
4284 using key_type_ref = key_type;
4285
4286 using TULocalDeclsMapTy = llvm::DenseMap<key_type, DeclIDsTy>;
4287
4288private:
4289 ModuleLevelDeclsMapTy ModuleLocalDeclsMap;
4290 TULocalDeclsMapTy TULocalDeclsMap;
4291
4292public:
4293 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer)
4294 : ASTDeclContextNameLookupTraitBase(Writer) {}
4295
4296 template <typename Coll> data_type getData(const Coll &Decls) {
4297 unsigned Start = DeclIDs.size();
4298 for (NamedDecl *D : Decls) {
4299 NamedDecl *DeclForLocalLookup =
4300 getDeclForLocalLookup(Writer.getLangOpts(), D);
4301
4302 if (Writer.getDoneWritingDeclsAndTypes() &&
4303 !Writer.wasDeclEmitted(D: DeclForLocalLookup))
4304 continue;
4305
4306 // Try to avoid writing internal decls to reduced BMI.
4307 // See comments in ASTWriter::WriteDeclContextLexicalBlock for details.
4308 if (Writer.isGeneratingReducedBMI() &&
4309 !DeclForLocalLookup->isFromExplicitGlobalModule() &&
4310 IsInternalDeclFromFileContext(DeclForLocalLookup))
4311 continue;
4312
4313 auto ID = Writer.GetDeclRef(D: DeclForLocalLookup);
4314
4315 if (isModuleLocalDecl(D)) {
4316 if (UnsignedOrNone PrimaryModuleHash =
4317 getPrimaryModuleHash(D->getOwningModule())) {
4318 auto Key = std::make_pair(x: D->getDeclName(), y: *PrimaryModuleHash);
4319 auto Iter = ModuleLocalDeclsMap.find(Key);
4320 if (Iter == ModuleLocalDeclsMap.end())
4321 ModuleLocalDeclsMap.insert({Key, DeclIDsTy{ID}});
4322 else
4323 Iter->second.push_back(ID);
4324 continue;
4325 }
4326 }
4327
4328 if constexpr (CollectingTULocalDecls) {
4329 if (isTULocalInNamedModules(D)) {
4330 auto Iter = TULocalDeclsMap.find(Val: D->getDeclName());
4331 if (Iter == TULocalDeclsMap.end())
4332 TULocalDeclsMap.insert(KV: {D->getDeclName(), DeclIDsTy{ID}});
4333 else
4334 Iter->second.push_back(Elt: ID);
4335 continue;
4336 }
4337 }
4338
4339 DeclIDs.push_back(Elt: ID);
4340 }
4341 return std::make_pair(Start, DeclIDs.size());
4342 }
4343
4344 using ASTDeclContextNameLookupTraitBase::getData;
4345
4346 const ModuleLevelDeclsMapTy &getModuleLocalDecls() {
4347 return ModuleLocalDeclsMap;
4348 }
4349
4350 const TULocalDeclsMapTy &getTULocalDecls() { return TULocalDeclsMap; }
4351
4352 static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4353
4354 hash_value_type ComputeHash(key_type Name) { return Name.getHash(); }
4355
4356 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
4357 DeclarationNameKey Name,
4358 data_type_ref Lookup) {
4359 auto [KeyLen, DataLen] = EmitKeyDataLengthBase(Out, Name, Lookup);
4360 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4361 }
4362
4363 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
4364 return EmitKeyBase(Out, Name);
4365 }
4366
4367 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4368 unsigned DataLen) {
4369 EmitDataBase(Out, Lookup, DataLen);
4370 }
4371};
4372
4373} // namespace
4374
4375namespace {
4376class LazySpecializationInfoLookupTrait {
4377 ASTWriter &Writer;
4378 llvm::SmallVector<serialization::reader::LazySpecializationInfo, 64> Specs;
4379
4380public:
4381 using key_type = unsigned;
4382 using key_type_ref = key_type;
4383
4384 /// A start and end index into Specs, representing a sequence of decls.
4385 using data_type = std::pair<unsigned, unsigned>;
4386 using data_type_ref = const data_type &;
4387
4388 using hash_value_type = unsigned;
4389 using offset_type = unsigned;
4390
4391 explicit LazySpecializationInfoLookupTrait(ASTWriter &Writer)
4392 : Writer(Writer) {}
4393
4394 template <typename Col, typename Col2>
4395 data_type getData(Col &&C, Col2 &ExistingInfo) {
4396 unsigned Start = Specs.size();
4397 for (auto *D : C) {
4398 NamedDecl *ND = getDeclForLocalLookup(LangOpts: Writer.getLangOpts(),
4399 D: const_cast<NamedDecl *>(D));
4400 Specs.push_back(Elt: GlobalDeclID(Writer.GetDeclRef(ND).getRawValue()));
4401 }
4402 for (const serialization::reader::LazySpecializationInfo &Info :
4403 ExistingInfo)
4404 Specs.push_back(Elt: Info);
4405 return std::make_pair(x&: Start, y: Specs.size());
4406 }
4407
4408 data_type ImportData(
4409 const reader::LazySpecializationInfoLookupTrait::data_type &FromReader) {
4410 unsigned Start = Specs.size();
4411 for (auto ID : FromReader)
4412 Specs.push_back(Elt: ID);
4413 return std::make_pair(x&: Start, y: Specs.size());
4414 }
4415
4416 static bool EqualKey(key_type_ref a, key_type_ref b) { return a == b; }
4417
4418 hash_value_type ComputeHash(key_type Name) { return Name; }
4419
4420 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
4421 assert(Writer.hasChain() &&
4422 "have reference to loaded module file but no chain?");
4423
4424 using namespace llvm::support;
4425 endian::write<uint32_t>(os&: Out, value: Writer.getChain()->getModuleFileID(M: F),
4426 endian: llvm::endianness::little);
4427 }
4428
4429 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
4430 key_type HashValue,
4431 data_type_ref Lookup) {
4432 // 4 bytes for each slot.
4433 unsigned KeyLen = 4;
4434 unsigned DataLen = sizeof(serialization::reader::LazySpecializationInfo) *
4435 (Lookup.second - Lookup.first);
4436
4437 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
4438 }
4439
4440 void EmitKey(raw_ostream &Out, key_type HashValue, unsigned) {
4441 using namespace llvm::support;
4442
4443 endian::Writer LE(Out, llvm::endianness::little);
4444 LE.write<uint32_t>(Val: HashValue);
4445 }
4446
4447 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
4448 unsigned DataLen) {
4449 using namespace llvm::support;
4450
4451 endian::Writer LE(Out, llvm::endianness::little);
4452 uint64_t Start = Out.tell();
4453 (void)Start;
4454 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) {
4455 LE.write<DeclID>(Val: Specs[I].getRawValue());
4456 }
4457 assert(Out.tell() - Start == DataLen && "Data length is wrong");
4458 }
4459};
4460
4461unsigned CalculateODRHashForSpecs(const Decl *Spec) {
4462 ArrayRef<TemplateArgument> Args;
4463 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Spec))
4464 Args = CTSD->getTemplateArgs().asArray();
4465 else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Spec))
4466 Args = VTSD->getTemplateArgs().asArray();
4467 else if (auto *FD = dyn_cast<FunctionDecl>(Val: Spec))
4468 Args = FD->getTemplateSpecializationArgs()->asArray();
4469 else
4470 llvm_unreachable("New Specialization Kind?");
4471
4472 return StableHashForTemplateArguments(Args);
4473}
4474} // namespace
4475
4476void ASTWriter::GenerateSpecializationInfoLookupTable(
4477 const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
4478 llvm::SmallVectorImpl<char> &LookupTable, bool IsPartial) {
4479 assert(D->isFirstDecl());
4480
4481 // Create the on-disk hash table representation.
4482 MultiOnDiskHashTableGenerator<reader::LazySpecializationInfoLookupTrait,
4483 LazySpecializationInfoLookupTrait>
4484 Generator;
4485 LazySpecializationInfoLookupTrait Trait(*this);
4486
4487 llvm::MapVector<unsigned, llvm::SmallVector<const NamedDecl *, 4>>
4488 SpecializationMaps;
4489
4490 for (auto *Specialization : Specializations) {
4491 unsigned HashedValue = CalculateODRHashForSpecs(Spec: Specialization);
4492
4493 auto Iter = SpecializationMaps.find(Key: HashedValue);
4494 if (Iter == SpecializationMaps.end())
4495 Iter = SpecializationMaps
4496 .try_emplace(Key: HashedValue,
4497 Args: llvm::SmallVector<const NamedDecl *, 4>())
4498 .first;
4499
4500 Iter->second.push_back(Elt: cast<NamedDecl>(Val: Specialization));
4501 }
4502
4503 auto *Lookups =
4504 Chain ? Chain->getLoadedSpecializationsLookupTables(D, IsPartial)
4505 : nullptr;
4506
4507 for (auto &[HashValue, Specs] : SpecializationMaps) {
4508 SmallVector<serialization::reader::LazySpecializationInfo, 16>
4509 ExisitingSpecs;
4510 // We have to merge the lookup table manually here. We can't depend on the
4511 // merge mechanism offered by
4512 // clang::serialization::MultiOnDiskHashTableGenerator since that generator
4513 // assumes the we'll get the same value with the same key.
4514 // And also underlying llvm::OnDiskChainedHashTableGenerator assumes that we
4515 // won't insert the values with the same key twice. So we have to merge the
4516 // lookup table here manually.
4517 if (Lookups)
4518 ExisitingSpecs = Lookups->Table.find(HashValue);
4519
4520 Generator.insert(Key: HashValue, Data: Trait.getData(C&: Specs, ExistingInfo&: ExisitingSpecs), Info&: Trait);
4521 }
4522
4523 Generator.emit(Out&: LookupTable, Info&: Trait, Base: Lookups ? &Lookups->Table : nullptr);
4524}
4525
4526uint64_t ASTWriter::WriteSpecializationInfoLookupTable(
4527 const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
4528 bool IsPartial) {
4529
4530 llvm::SmallString<4096> LookupTable;
4531 GenerateSpecializationInfoLookupTable(D, Specializations, LookupTable,
4532 IsPartial);
4533
4534 uint64_t Offset = Stream.GetCurrentBitNo();
4535 RecordData::value_type Record[] = {static_cast<RecordData::value_type>(
4536 IsPartial ? DECL_PARTIAL_SPECIALIZATIONS : DECL_SPECIALIZATIONS)};
4537 Stream.EmitRecordWithBlob(Abbrev: IsPartial ? DeclPartialSpecializationsAbbrev
4538 : DeclSpecializationsAbbrev,
4539 Vals: Record, Blob: LookupTable);
4540
4541 return Offset;
4542}
4543
4544/// Returns ture if all of the lookup result are either external, not emitted or
4545/// predefined. In such cases, the lookup result is not interesting and we don't
4546/// need to record the result in the current being written module. Return false
4547/// otherwise.
4548static bool isLookupResultNotInteresting(ASTWriter &Writer,
4549 StoredDeclsList &Result) {
4550 for (auto *D : Result.getLookupResult()) {
4551 auto *LocalD = getDeclForLocalLookup(LangOpts: Writer.getLangOpts(), D);
4552 if (LocalD->isFromASTFile())
4553 continue;
4554
4555 // We can only be sure whether the local declaration is reachable
4556 // after we done writing the declarations and types.
4557 if (Writer.getDoneWritingDeclsAndTypes() && !Writer.wasDeclEmitted(LocalD))
4558 continue;
4559
4560 // We don't need to emit the predefined decls.
4561 if (Writer.isDeclPredefined(LocalD))
4562 continue;
4563
4564 return false;
4565 }
4566
4567 return true;
4568}
4569
4570void ASTWriter::GenerateNameLookupTable(
4571 ASTContext &Context, const DeclContext *ConstDC,
4572 llvm::SmallVectorImpl<char> &LookupTable,
4573 llvm::SmallVectorImpl<char> &ModuleLocalLookupTable,
4574 llvm::SmallVectorImpl<char> &TULookupTable) {
4575 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
4576 !ConstDC->hasLazyExternalLexicalLookups() &&
4577 "must call buildLookups first");
4578
4579 // FIXME: We need to build the lookups table, which is logically const.
4580 auto *DC = const_cast<DeclContext*>(ConstDC);
4581 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
4582
4583 // Create the on-disk hash table representation.
4584 MultiOnDiskHashTableGenerator<
4585 reader::ASTDeclContextNameLookupTrait,
4586 ASTDeclContextNameLookupTrait</*CollectingTULocal=*/true>>
4587 Generator;
4588 ASTDeclContextNameLookupTrait</*CollectingTULocal=*/true> Trait(*this);
4589
4590 // The first step is to collect the declaration names which we need to
4591 // serialize into the name lookup table, and to collect them in a stable
4592 // order.
4593 SmallVector<DeclarationName, 16> Names;
4594
4595 // We also track whether we're writing out the DeclarationNameKey for
4596 // constructors or conversion functions.
4597 bool IncludeConstructorNames = false;
4598 bool IncludeConversionNames = false;
4599
4600 for (auto &[Name, Result] : *DC->buildLookup()) {
4601 // If there are no local declarations in our lookup result, we
4602 // don't need to write an entry for the name at all. If we can't
4603 // write out a lookup set without performing more deserialization,
4604 // just skip this entry.
4605 //
4606 // Also in reduced BMI, we'd like to avoid writing unreachable
4607 // declarations in GMF, so we need to avoid writing declarations
4608 // that entirely external or unreachable.
4609 if (GeneratingReducedBMI && isLookupResultNotInteresting(Writer&: *this, Result))
4610 continue;
4611 // We also skip empty results. If any of the results could be external and
4612 // the currently available results are empty, then all of the results are
4613 // external and we skip it above. So the only way we get here with an empty
4614 // results is when no results could have been external *and* we have
4615 // external results.
4616 //
4617 // FIXME: While we might want to start emitting on-disk entries for negative
4618 // lookups into a decl context as an optimization, today we *have* to skip
4619 // them because there are names with empty lookup results in decl contexts
4620 // which we can't emit in any stable ordering: we lookup constructors and
4621 // conversion functions in the enclosing namespace scope creating empty
4622 // results for them. This in almost certainly a bug in Clang's name lookup,
4623 // but that is likely to be hard or impossible to fix and so we tolerate it
4624 // here by omitting lookups with empty results.
4625 if (Result.getLookupResult().empty())
4626 continue;
4627
4628 switch (Name.getNameKind()) {
4629 default:
4630 Names.push_back(Elt: Name);
4631 break;
4632
4633 case DeclarationName::CXXConstructorName:
4634 IncludeConstructorNames = true;
4635 break;
4636
4637 case DeclarationName::CXXConversionFunctionName:
4638 IncludeConversionNames = true;
4639 break;
4640 }
4641 }
4642
4643 // Sort the names into a stable order.
4644 llvm::sort(C&: Names);
4645
4646 if (IncludeConstructorNames || IncludeConversionNames) {
4647 // We need to establish an ordering of constructor and conversion function
4648 // names, and they don't have an intrinsic ordering. We also need to write
4649 // out all constructor and conversion function results if we write out any
4650 // of them, because they're all tracked under the same lookup key.
4651 llvm::SmallPtrSet<DeclarationName, 8> AddedNames;
4652 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) {
4653 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4654 auto Name = ChildND->getDeclName();
4655 switch (Name.getNameKind()) {
4656 default:
4657 continue;
4658
4659 case DeclarationName::CXXConstructorName:
4660 if (!IncludeConstructorNames)
4661 continue;
4662 break;
4663
4664 case DeclarationName::CXXConversionFunctionName:
4665 if (!IncludeConversionNames)
4666 continue;
4667 break;
4668 }
4669 if (AddedNames.insert(Name).second)
4670 Names.push_back(Name);
4671 }
4672 }
4673 }
4674 // Next we need to do a lookup with each name into this decl context to fully
4675 // populate any results from external sources. We don't actually use the
4676 // results of these lookups because we only want to use the results after all
4677 // results have been loaded and the pointers into them will be stable.
4678 for (auto &Name : Names)
4679 DC->lookup(Name);
4680
4681 // Now we need to insert the results for each name into the hash table. For
4682 // constructor names and conversion function names, we actually need to merge
4683 // all of the results for them into one list of results each and insert
4684 // those.
4685 SmallVector<NamedDecl *, 8> ConstructorDecls;
4686 SmallVector<NamedDecl *, 8> ConversionDecls;
4687
4688 // Now loop over the names, either inserting them or appending for the two
4689 // special cases.
4690 for (auto &Name : Names) {
4691 DeclContext::lookup_result Result = DC->noload_lookup(Name);
4692
4693 switch (Name.getNameKind()) {
4694 default:
4695 Generator.insert(Key: Name, Data: Trait.getData(Decls: Result), Info&: Trait);
4696 break;
4697
4698 case DeclarationName::CXXConstructorName:
4699 ConstructorDecls.append(in_start: Result.begin(), in_end: Result.end());
4700 break;
4701
4702 case DeclarationName::CXXConversionFunctionName:
4703 ConversionDecls.append(in_start: Result.begin(), in_end: Result.end());
4704 break;
4705 }
4706 }
4707
4708 // Handle our two special cases if we ended up having any. We arbitrarily use
4709 // the first declaration's name here because the name itself isn't part of
4710 // the key, only the kind of name is used.
4711 if (!ConstructorDecls.empty())
4712 Generator.insert(Key: ConstructorDecls.front()->getDeclName(),
4713 Data: Trait.getData(Decls: ConstructorDecls), Info&: Trait);
4714 if (!ConversionDecls.empty())
4715 Generator.insert(Key: ConversionDecls.front()->getDeclName(),
4716 Data: Trait.getData(Decls: ConversionDecls), Info&: Trait);
4717
4718 // Create the on-disk hash table. Also emit the existing imported and
4719 // merged table if there is one.
4720 auto *Lookups = Chain ? Chain->getLoadedLookupTables(Primary: DC) : nullptr;
4721 Generator.emit(Out&: LookupTable, Info&: Trait, Base: Lookups ? &Lookups->Table : nullptr);
4722
4723 const auto &ModuleLocalDecls = Trait.getModuleLocalDecls();
4724 if (!ModuleLocalDecls.empty()) {
4725 MultiOnDiskHashTableGenerator<reader::ModuleLocalNameLookupTrait,
4726 ModuleLevelNameLookupTrait>
4727 ModuleLocalLookupGenerator;
4728 ModuleLevelNameLookupTrait ModuleLocalTrait(*this);
4729
4730 for (const auto &ModuleLocalIter : ModuleLocalDecls) {
4731 const auto &Key = ModuleLocalIter.first;
4732 const auto &IDs = ModuleLocalIter.second;
4733 ModuleLocalLookupGenerator.insert(Key, Data: ModuleLocalTrait.getData(LocalIDs: IDs),
4734 Info&: ModuleLocalTrait);
4735 }
4736
4737 auto *ModuleLocalLookups =
4738 Chain ? Chain->getModuleLocalLookupTables(Primary: DC) : nullptr;
4739 ModuleLocalLookupGenerator.emit(
4740 Out&: ModuleLocalLookupTable, Info&: ModuleLocalTrait,
4741 Base: ModuleLocalLookups ? &ModuleLocalLookups->Table : nullptr);
4742 }
4743
4744 const auto &TULocalDecls = Trait.getTULocalDecls();
4745 if (!TULocalDecls.empty() && !isGeneratingReducedBMI()) {
4746 MultiOnDiskHashTableGenerator<
4747 reader::ASTDeclContextNameLookupTrait,
4748 ASTDeclContextNameLookupTrait</*CollectingTULocal=*/false>>
4749 TULookupGenerator;
4750 ASTDeclContextNameLookupTrait</*CollectingTULocal=*/false> TULocalTrait(
4751 *this);
4752
4753 for (const auto &TULocalIter : TULocalDecls) {
4754 const auto &Key = TULocalIter.first;
4755 const auto &IDs = TULocalIter.second;
4756 TULookupGenerator.insert(Key, Data: TULocalTrait.getData(LocalIDs: IDs), Info&: TULocalTrait);
4757 }
4758
4759 auto *TULocalLookups = Chain ? Chain->getTULocalLookupTables(Primary: DC) : nullptr;
4760 TULookupGenerator.emit(Out&: TULookupTable, Info&: TULocalTrait,
4761 Base: TULocalLookups ? &TULocalLookups->Table : nullptr);
4762 }
4763}
4764
4765/// Write the block containing all of the declaration IDs
4766/// visible from the given DeclContext.
4767///
4768/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4769/// bitstream, or 0 if no block was written.
4770void ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4771 DeclContext *DC,
4772 uint64_t &VisibleBlockOffset,
4773 uint64_t &ModuleLocalBlockOffset,
4774 uint64_t &TULocalBlockOffset) {
4775 assert(VisibleBlockOffset == 0);
4776 assert(ModuleLocalBlockOffset == 0);
4777 assert(TULocalBlockOffset == 0);
4778
4779 // If we imported a key declaration of this namespace, write the visible
4780 // lookup results as an update record for it rather than including them
4781 // on this declaration. We will only look at key declarations on reload.
4782 if (isa<NamespaceDecl>(Val: DC) && Chain &&
4783 Chain->getKeyDeclaration(D: cast<Decl>(Val: DC))->isFromASTFile()) {
4784 // Only do this once, for the first local declaration of the namespace.
4785 for (auto *Prev = cast<NamespaceDecl>(Val: DC)->getPreviousDecl(); Prev;
4786 Prev = Prev->getPreviousDecl())
4787 if (!Prev->isFromASTFile())
4788 return;
4789
4790 // Note that we need to emit an update record for the primary context.
4791 UpdatedDeclContexts.insert(X: DC->getPrimaryContext());
4792
4793 // Make sure all visible decls are written. They will be recorded later. We
4794 // do this using a side data structure so we can sort the names into
4795 // a deterministic order.
4796 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4797 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4798 LookupResults;
4799 if (Map) {
4800 LookupResults.reserve(N: Map->size());
4801 for (auto &Entry : *Map)
4802 LookupResults.push_back(
4803 Elt: std::make_pair(x&: Entry.first, y: Entry.second.getLookupResult()));
4804 }
4805
4806 llvm::sort(C&: LookupResults, Comp: llvm::less_first());
4807 for (auto &NameAndResult : LookupResults) {
4808 DeclarationName Name = NameAndResult.first;
4809 DeclContext::lookup_result Result = NameAndResult.second;
4810 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4811 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4812 // We have to work around a name lookup bug here where negative lookup
4813 // results for these names get cached in namespace lookup tables (these
4814 // names should never be looked up in a namespace).
4815 assert(Result.empty() && "Cannot have a constructor or conversion "
4816 "function name in a namespace!");
4817 continue;
4818 }
4819
4820 for (NamedDecl *ND : Result) {
4821 if (ND->isFromASTFile())
4822 continue;
4823
4824 if (DoneWritingDeclsAndTypes && !wasDeclEmitted(ND))
4825 continue;
4826
4827 // We don't need to force emitting internal decls into reduced BMI.
4828 // See comments in ASTWriter::WriteDeclContextLexicalBlock for details.
4829 if (GeneratingReducedBMI && !ND->isFromExplicitGlobalModule() &&
4830 IsInternalDeclFromFileContext(ND))
4831 continue;
4832
4833 GetDeclRef(ND);
4834 }
4835 }
4836
4837 return;
4838 }
4839
4840 if (DC->getPrimaryContext() != DC)
4841 return;
4842
4843 // Skip contexts which don't support name lookup.
4844 if (!DC->isLookupContext())
4845 return;
4846
4847 // If not in C++, we perform name lookup for the translation unit via the
4848 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4849 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4850 return;
4851
4852 // Serialize the contents of the mapping used for lookup. Note that,
4853 // although we have two very different code paths, the serialized
4854 // representation is the same for both cases: a declaration name,
4855 // followed by a size, followed by references to the visible
4856 // declarations that have that name.
4857 StoredDeclsMap *Map = DC->buildLookup();
4858 if (!Map || Map->empty())
4859 return;
4860
4861 VisibleBlockOffset = Stream.GetCurrentBitNo();
4862 // Create the on-disk hash table in a buffer.
4863 SmallString<4096> LookupTable;
4864 SmallString<4096> ModuleLocalLookupTable;
4865 SmallString<4096> TULookupTable;
4866 GenerateNameLookupTable(Context, ConstDC: DC, LookupTable, ModuleLocalLookupTable,
4867 TULookupTable);
4868
4869 // Write the lookup table
4870 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4871 Stream.EmitRecordWithBlob(Abbrev: DeclContextVisibleLookupAbbrev, Vals: Record,
4872 Blob: LookupTable);
4873 ++NumVisibleDeclContexts;
4874
4875 if (!ModuleLocalLookupTable.empty()) {
4876 ModuleLocalBlockOffset = Stream.GetCurrentBitNo();
4877 assert(ModuleLocalBlockOffset > VisibleBlockOffset);
4878 // Write the lookup table
4879 RecordData::value_type ModuleLocalRecord[] = {
4880 DECL_CONTEXT_MODULE_LOCAL_VISIBLE};
4881 Stream.EmitRecordWithBlob(Abbrev: DeclModuleLocalVisibleLookupAbbrev,
4882 Vals: ModuleLocalRecord, Blob: ModuleLocalLookupTable);
4883 ++NumModuleLocalDeclContexts;
4884 }
4885
4886 if (!TULookupTable.empty()) {
4887 TULocalBlockOffset = Stream.GetCurrentBitNo();
4888 // Write the lookup table
4889 RecordData::value_type TULocalDeclsRecord[] = {
4890 DECL_CONTEXT_TU_LOCAL_VISIBLE};
4891 Stream.EmitRecordWithBlob(Abbrev: DeclTULocalLookupAbbrev, Vals: TULocalDeclsRecord,
4892 Blob: TULookupTable);
4893 ++NumTULocalDeclContexts;
4894 }
4895}
4896
4897/// Write an UPDATE_VISIBLE block for the given context.
4898///
4899/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4900/// DeclContext in a dependent AST file. As such, they only exist for the TU
4901/// (in C++), for namespaces, and for classes with forward-declared unscoped
4902/// enumeration members (in C++11).
4903void ASTWriter::WriteDeclContextVisibleUpdate(ASTContext &Context,
4904 const DeclContext *DC) {
4905 StoredDeclsMap *Map = DC->getLookupPtr();
4906 if (!Map || Map->empty())
4907 return;
4908
4909 // Create the on-disk hash table in a buffer.
4910 SmallString<4096> LookupTable;
4911 SmallString<4096> ModuleLocalLookupTable;
4912 SmallString<4096> TULookupTable;
4913 GenerateNameLookupTable(Context, ConstDC: DC, LookupTable, ModuleLocalLookupTable,
4914 TULookupTable);
4915
4916 // If we're updating a namespace, select a key declaration as the key for the
4917 // update record; those are the only ones that will be checked on reload.
4918 if (isa<NamespaceDecl>(Val: DC))
4919 DC = cast<DeclContext>(Val: Chain->getKeyDeclaration(D: cast<Decl>(Val: DC)));
4920
4921 // Write the lookup table
4922 RecordData::value_type Record[] = {UPDATE_VISIBLE,
4923 getDeclID(D: cast<Decl>(Val: DC)).getRawValue()};
4924 Stream.EmitRecordWithBlob(Abbrev: UpdateVisibleAbbrev, Vals: Record, Blob: LookupTable);
4925
4926 if (!ModuleLocalLookupTable.empty()) {
4927 // Write the module local lookup table
4928 RecordData::value_type ModuleLocalRecord[] = {
4929 UPDATE_MODULE_LOCAL_VISIBLE, getDeclID(D: cast<Decl>(Val: DC)).getRawValue()};
4930 Stream.EmitRecordWithBlob(Abbrev: ModuleLocalUpdateVisibleAbbrev, Vals: ModuleLocalRecord,
4931 Blob: ModuleLocalLookupTable);
4932 }
4933
4934 if (!TULookupTable.empty()) {
4935 RecordData::value_type GMFRecord[] = {
4936 UPDATE_TU_LOCAL_VISIBLE, getDeclID(D: cast<Decl>(Val: DC)).getRawValue()};
4937 Stream.EmitRecordWithBlob(Abbrev: TULocalUpdateVisibleAbbrev, Vals: GMFRecord,
4938 Blob: TULookupTable);
4939 }
4940}
4941
4942/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4943void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4944 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4945 Stream.EmitRecord(Code: FP_PRAGMA_OPTIONS, Vals: Record);
4946}
4947
4948/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4949void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4950 if (!SemaRef.Context.getLangOpts().OpenCL)
4951 return;
4952
4953 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4954 RecordData Record;
4955 for (const auto &I:Opts.OptMap) {
4956 AddString(Str: I.getKey(), Record);
4957 auto V = I.getValue();
4958 Record.push_back(Elt: V.Supported ? 1 : 0);
4959 Record.push_back(Elt: V.Enabled ? 1 : 0);
4960 Record.push_back(Elt: V.WithPragma ? 1 : 0);
4961 Record.push_back(Elt: V.Avail);
4962 Record.push_back(Elt: V.Core);
4963 Record.push_back(Elt: V.Opt);
4964 }
4965 Stream.EmitRecord(Code: OPENCL_EXTENSIONS, Vals: Record);
4966}
4967void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4968 if (SemaRef.CUDA().ForceHostDeviceDepth > 0) {
4969 RecordData::value_type Record[] = {SemaRef.CUDA().ForceHostDeviceDepth};
4970 Stream.EmitRecord(Code: CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Vals: Record);
4971 }
4972}
4973
4974void ASTWriter::WriteObjCCategories() {
4975 if (ObjCClassesWithCategories.empty())
4976 return;
4977
4978 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4979 RecordData Categories;
4980
4981 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4982 unsigned Size = 0;
4983 unsigned StartIndex = Categories.size();
4984
4985 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4986
4987 // Allocate space for the size.
4988 Categories.push_back(Elt: 0);
4989
4990 // Add the categories.
4991 for (ObjCInterfaceDecl::known_categories_iterator
4992 Cat = Class->known_categories_begin(),
4993 CatEnd = Class->known_categories_end();
4994 Cat != CatEnd; ++Cat, ++Size) {
4995 assert(getDeclID(*Cat).isValid() && "Bogus category");
4996 AddDeclRef(*Cat, Categories);
4997 }
4998
4999 // Update the size.
5000 Categories[StartIndex] = Size;
5001
5002 // Record this interface -> category map.
5003 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
5004 CategoriesMap.push_back(Elt: CatInfo);
5005 }
5006
5007 // Sort the categories map by the definition ID, since the reader will be
5008 // performing binary searches on this information.
5009 llvm::array_pod_sort(Start: CategoriesMap.begin(), End: CategoriesMap.end());
5010
5011 // Emit the categories map.
5012 using namespace llvm;
5013
5014 auto Abbrev = std::make_shared<BitCodeAbbrev>();
5015 Abbrev->Add(OpInfo: BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
5016 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
5017 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5018 unsigned AbbrevID = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
5019
5020 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
5021 Stream.EmitRecordWithBlob(Abbrev: AbbrevID, Vals: Record,
5022 BlobData: reinterpret_cast<char *>(CategoriesMap.data()),
5023 BlobLen: CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
5024
5025 // Emit the category lists.
5026 Stream.EmitRecord(Code: OBJC_CATEGORIES, Vals: Categories);
5027}
5028
5029void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
5030 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
5031
5032 if (LPTMap.empty())
5033 return;
5034
5035 RecordData Record;
5036 for (auto &LPTMapEntry : LPTMap) {
5037 const FunctionDecl *FD = LPTMapEntry.first;
5038 LateParsedTemplate &LPT = *LPTMapEntry.second;
5039 AddDeclRef(FD, Record);
5040 AddDeclRef(D: LPT.D, Record);
5041 Record.push_back(Elt: LPT.FPO.getAsOpaqueInt());
5042 Record.push_back(Elt: LPT.Toks.size());
5043
5044 for (const auto &Tok : LPT.Toks) {
5045 AddToken(Tok, Record);
5046 }
5047 }
5048 Stream.EmitRecord(Code: LATE_PARSED_TEMPLATE, Vals: Record);
5049}
5050
5051/// Write the state of 'pragma clang optimize' at the end of the module.
5052void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
5053 RecordData Record;
5054 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
5055 AddSourceLocation(Loc: PragmaLoc, Record);
5056 Stream.EmitRecord(Code: OPTIMIZE_PRAGMA_OPTIONS, Vals: Record);
5057}
5058
5059/// Write the state of 'pragma ms_struct' at the end of the module.
5060void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
5061 RecordData Record;
5062 Record.push_back(Elt: SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
5063 Stream.EmitRecord(Code: MSSTRUCT_PRAGMA_OPTIONS, Vals: Record);
5064}
5065
5066/// Write the state of 'pragma pointers_to_members' at the end of the
5067//module.
5068void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
5069 RecordData Record;
5070 Record.push_back(Elt: SemaRef.MSPointerToMemberRepresentationMethod);
5071 AddSourceLocation(Loc: SemaRef.ImplicitMSInheritanceAttrLoc, Record);
5072 Stream.EmitRecord(Code: POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Vals: Record);
5073}
5074
5075/// Write the state of 'pragma align/pack' at the end of the module.
5076void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
5077 // Don't serialize pragma align/pack state for modules, since it should only
5078 // take effect on a per-submodule basis.
5079 if (WritingModule)
5080 return;
5081
5082 RecordData Record;
5083 AddAlignPackInfo(Info: SemaRef.AlignPackStack.CurrentValue, Record);
5084 AddSourceLocation(Loc: SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
5085 Record.push_back(Elt: SemaRef.AlignPackStack.Stack.size());
5086 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
5087 AddAlignPackInfo(Info: StackEntry.Value, Record);
5088 AddSourceLocation(Loc: StackEntry.PragmaLocation, Record);
5089 AddSourceLocation(Loc: StackEntry.PragmaPushLocation, Record);
5090 AddString(Str: StackEntry.StackSlotLabel, Record);
5091 }
5092 Stream.EmitRecord(Code: ALIGN_PACK_PRAGMA_OPTIONS, Vals: Record);
5093}
5094
5095/// Write the state of 'pragma float_control' at the end of the module.
5096void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
5097 // Don't serialize pragma float_control state for modules,
5098 // since it should only take effect on a per-submodule basis.
5099 if (WritingModule)
5100 return;
5101
5102 RecordData Record;
5103 Record.push_back(Elt: SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
5104 AddSourceLocation(Loc: SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
5105 Record.push_back(Elt: SemaRef.FpPragmaStack.Stack.size());
5106 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
5107 Record.push_back(Elt: StackEntry.Value.getAsOpaqueInt());
5108 AddSourceLocation(Loc: StackEntry.PragmaLocation, Record);
5109 AddSourceLocation(Loc: StackEntry.PragmaPushLocation, Record);
5110 AddString(Str: StackEntry.StackSlotLabel, Record);
5111 }
5112 Stream.EmitRecord(Code: FLOAT_CONTROL_PRAGMA_OPTIONS, Vals: Record);
5113}
5114
5115/// Write Sema's collected list of declarations with unverified effects.
5116void ASTWriter::WriteDeclsWithEffectsToVerify(Sema &SemaRef) {
5117 if (SemaRef.DeclsWithEffectsToVerify.empty())
5118 return;
5119 RecordData Record;
5120 for (const auto *D : SemaRef.DeclsWithEffectsToVerify) {
5121 AddDeclRef(D, Record);
5122 }
5123 Stream.EmitRecord(Code: DECLS_WITH_EFFECTS_TO_VERIFY, Vals: Record);
5124}
5125
5126void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
5127 ModuleFileExtensionWriter &Writer) {
5128 // Enter the extension block.
5129 Stream.EnterSubblock(BlockID: EXTENSION_BLOCK_ID, CodeLen: 4);
5130
5131 // Emit the metadata record abbreviation.
5132 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
5133 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
5134 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5135 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5136 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5137 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
5138 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
5139 unsigned Abbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
5140
5141 // Emit the metadata record.
5142 RecordData Record;
5143 auto Metadata = Writer.getExtension()->getExtensionMetadata();
5144 Record.push_back(Elt: EXTENSION_METADATA);
5145 Record.push_back(Elt: Metadata.MajorVersion);
5146 Record.push_back(Elt: Metadata.MinorVersion);
5147 Record.push_back(Elt: Metadata.BlockName.size());
5148 Record.push_back(Elt: Metadata.UserInfo.size());
5149 SmallString<64> Buffer;
5150 Buffer += Metadata.BlockName;
5151 Buffer += Metadata.UserInfo;
5152 Stream.EmitRecordWithBlob(Abbrev, Vals: Record, Blob: Buffer);
5153
5154 // Emit the contents of the extension block.
5155 Writer.writeExtensionContents(SemaRef, Stream);
5156
5157 // Exit the extension block.
5158 Stream.ExitBlock();
5159}
5160
5161//===----------------------------------------------------------------------===//
5162// General Serialization Routines
5163//===----------------------------------------------------------------------===//
5164
5165void ASTRecordWriter::AddAttr(const Attr *A) {
5166 auto &Record = *this;
5167 // FIXME: Clang can't handle the serialization/deserialization of
5168 // preferred_name properly now. See
5169 // https://github.com/llvm/llvm-project/issues/56490 for example.
5170 if (!A || (isa<PreferredNameAttr>(A) &&
5171 Writer->isWritingStdCXXNamedModules()))
5172 return Record.push_back(N: 0);
5173
5174 Record.push_back(N: A->getKind() + 1); // FIXME: stable encoding, target attrs
5175
5176 Record.AddIdentifierRef(II: A->getAttrName());
5177 Record.AddIdentifierRef(II: A->getScopeName());
5178 Record.AddSourceRange(Range: A->getRange());
5179 Record.AddSourceLocation(Loc: A->getScopeLoc());
5180 Record.push_back(N: A->getParsedKind());
5181 Record.push_back(N: A->getSyntax());
5182 Record.push_back(N: A->getAttributeSpellingListIndexRaw());
5183 Record.push_back(N: A->isRegularKeywordAttribute());
5184
5185#include "clang/Serialization/AttrPCHWrite.inc"
5186}
5187
5188/// Emit the list of attributes to the specified record.
5189void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
5190 push_back(N: Attrs.size());
5191 for (const auto *A : Attrs)
5192 AddAttr(A);
5193}
5194
5195void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
5196 AddSourceLocation(Loc: Tok.getLocation(), Record);
5197 // FIXME: Should translate token kind to a stable encoding.
5198 Record.push_back(Elt: Tok.getKind());
5199 // FIXME: Should translate token flags to a stable encoding.
5200 Record.push_back(Elt: Tok.getFlags());
5201
5202 if (Tok.isAnnotation()) {
5203 AddSourceLocation(Loc: Tok.getAnnotationEndLoc(), Record);
5204 switch (Tok.getKind()) {
5205 case tok::annot_pragma_loop_hint: {
5206 auto *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
5207 AddToken(Tok: Info->PragmaName, Record);
5208 AddToken(Tok: Info->Option, Record);
5209 Record.push_back(Elt: Info->Toks.size());
5210 for (const auto &T : Info->Toks)
5211 AddToken(Tok: T, Record);
5212 break;
5213 }
5214 case tok::annot_pragma_pack: {
5215 auto *Info =
5216 static_cast<Sema::PragmaPackInfo *>(Tok.getAnnotationValue());
5217 Record.push_back(Elt: static_cast<unsigned>(Info->Action));
5218 AddString(Str: Info->SlotLabel, Record);
5219 AddToken(Tok: Info->Alignment, Record);
5220 break;
5221 }
5222 // Some annotation tokens do not use the PtrData field.
5223 case tok::annot_pragma_openmp:
5224 case tok::annot_pragma_openmp_end:
5225 case tok::annot_pragma_unused:
5226 case tok::annot_pragma_openacc:
5227 case tok::annot_pragma_openacc_end:
5228 case tok::annot_repl_input_end:
5229 break;
5230 default:
5231 llvm_unreachable("missing serialization code for annotation token");
5232 }
5233 } else {
5234 Record.push_back(Elt: Tok.getLength());
5235 // FIXME: When reading literal tokens, reconstruct the literal pointer if it
5236 // is needed.
5237 AddIdentifierRef(II: Tok.getIdentifierInfo(), Record);
5238 }
5239}
5240
5241void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
5242 Record.push_back(Elt: Str.size());
5243 llvm::append_range(C&: Record, R&: Str);
5244}
5245
5246void ASTWriter::AddStringBlob(StringRef Str, RecordDataImpl &Record,
5247 SmallVectorImpl<char> &Blob) {
5248 Record.push_back(Elt: Str.size());
5249 llvm::append_range(C&: Blob, R&: Str);
5250}
5251
5252bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
5253 assert(WritingAST && "can't prepare path for output when not writing AST");
5254
5255 // Leave special file names as they are.
5256 StringRef PathStr(Path.data(), Path.size());
5257 if (PathStr == "<built-in>" || PathStr == "<command line>")
5258 return false;
5259
5260 bool Changed = cleanPathForOutput(FileMgr&: PP->getFileManager(), Path);
5261
5262 // Remove a prefix to make the path relative, if relevant.
5263 const char *PathBegin = Path.data();
5264 const char *PathPtr =
5265 adjustFilenameForRelocatableAST(Filename: PathBegin, BaseDir: BaseDirectory);
5266 if (PathPtr != PathBegin) {
5267 Path.erase(CS: Path.begin(), CE: Path.begin() + (PathPtr - PathBegin));
5268 Changed = true;
5269 }
5270
5271 return Changed;
5272}
5273
5274void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
5275 SmallString<128> FilePath(Path);
5276 PreparePathForOutput(Path&: FilePath);
5277 AddString(Str: FilePath, Record);
5278}
5279
5280void ASTWriter::AddPathBlob(StringRef Path, RecordDataImpl &Record,
5281 SmallVectorImpl<char> &Blob) {
5282 SmallString<128> FilePath(Path);
5283 PreparePathForOutput(Path&: FilePath);
5284 AddStringBlob(Str: FilePath, Record, Blob);
5285}
5286
5287void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
5288 StringRef Path) {
5289 SmallString<128> FilePath(Path);
5290 PreparePathForOutput(Path&: FilePath);
5291 Stream.EmitRecordWithBlob(Abbrev, Vals: Record, Blob: FilePath);
5292}
5293
5294void ASTWriter::AddVersionTuple(const VersionTuple &Version,
5295 RecordDataImpl &Record) {
5296 Record.push_back(Elt: Version.getMajor());
5297 if (std::optional<unsigned> Minor = Version.getMinor())
5298 Record.push_back(Elt: *Minor + 1);
5299 else
5300 Record.push_back(Elt: 0);
5301 if (std::optional<unsigned> Subminor = Version.getSubminor())
5302 Record.push_back(Elt: *Subminor + 1);
5303 else
5304 Record.push_back(Elt: 0);
5305}
5306
5307/// Note that the identifier II occurs at the given offset
5308/// within the identifier table.
5309void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
5310 IdentifierID ID = IdentifierIDs[II];
5311 // Only store offsets new to this AST file. Other identifier names are looked
5312 // up earlier in the chain and thus don't need an offset.
5313 if (!isLocalIdentifierID(ID))
5314 return;
5315
5316 // For local identifiers, the module file index must be 0.
5317
5318 assert(ID != 0);
5319 ID -= NUM_PREDEF_IDENT_IDS;
5320 assert(ID < IdentifierOffsets.size());
5321 IdentifierOffsets[ID] = Offset;
5322}
5323
5324/// Note that the selector Sel occurs at the given offset
5325/// within the method pool/selector table.
5326void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
5327 unsigned ID = SelectorIDs[Sel];
5328 assert(ID && "Unknown selector");
5329 // Don't record offsets for selectors that are also available in a different
5330 // file.
5331 if (ID < FirstSelectorID)
5332 return;
5333 SelectorOffsets[ID - FirstSelectorID] = Offset;
5334}
5335
5336ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
5337 SmallVectorImpl<char> &Buffer, ModuleCache &ModCache,
5338 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
5339 bool IncludeTimestamps, bool BuildingImplicitModule,
5340 bool GeneratingReducedBMI)
5341 : Stream(Stream), Buffer(Buffer), ModCache(ModCache),
5342 IncludeTimestamps(IncludeTimestamps),
5343 BuildingImplicitModule(BuildingImplicitModule),
5344 GeneratingReducedBMI(GeneratingReducedBMI) {
5345 for (const auto &Ext : Extensions) {
5346 if (auto Writer = Ext->createExtensionWriter(Writer&: *this))
5347 ModuleFileExtensionWriters.push_back(x: std::move(Writer));
5348 }
5349}
5350
5351ASTWriter::~ASTWriter() = default;
5352
5353const LangOptions &ASTWriter::getLangOpts() const {
5354 assert(WritingAST && "can't determine lang opts when not writing AST");
5355 return PP->getLangOpts();
5356}
5357
5358time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
5359 return IncludeTimestamps ? E->getModificationTime() : 0;
5360}
5361
5362ASTFileSignature
5363ASTWriter::WriteAST(llvm::PointerUnion<Sema *, Preprocessor *> Subject,
5364 StringRef OutputFile, Module *WritingModule,
5365 StringRef isysroot, bool ShouldCacheASTInMemory) {
5366 llvm::TimeTraceScope scope("WriteAST", OutputFile);
5367 WritingAST = true;
5368
5369 Sema *SemaPtr = dyn_cast<Sema *>(Val&: Subject);
5370 Preprocessor &PPRef =
5371 SemaPtr ? SemaPtr->getPreprocessor() : *cast<Preprocessor *>(Val&: Subject);
5372
5373 ASTHasCompilerErrors = PPRef.getDiagnostics().hasUncompilableErrorOccurred();
5374
5375 // Emit the file header.
5376 Stream.Emit(Val: (unsigned)'C', NumBits: 8);
5377 Stream.Emit(Val: (unsigned)'P', NumBits: 8);
5378 Stream.Emit(Val: (unsigned)'C', NumBits: 8);
5379 Stream.Emit(Val: (unsigned)'H', NumBits: 8);
5380
5381 WriteBlockInfoBlock();
5382
5383 PP = &PPRef;
5384 this->WritingModule = WritingModule;
5385 ASTFileSignature Signature = WriteASTCore(SemaPtr, isysroot, WritingModule);
5386 PP = nullptr;
5387 this->WritingModule = nullptr;
5388 this->BaseDirectory.clear();
5389
5390 WritingAST = false;
5391
5392 if (WritingModule && PPRef.getHeaderSearchInfo()
5393 .getHeaderSearchOpts()
5394 .ModulesValidateOncePerBuildSession)
5395 ModCache.updateModuleTimestamp(ModuleFilename: OutputFile);
5396
5397 if (ShouldCacheASTInMemory) {
5398 // Construct MemoryBuffer and update buffer manager.
5399 ModCache.getInMemoryModuleCache().addBuiltPCM(
5400 Filename: OutputFile, Buffer: llvm::MemoryBuffer::getMemBufferCopy(
5401 InputData: StringRef(Buffer.begin(), Buffer.size())));
5402 }
5403 return Signature;
5404}
5405
5406template<typename Vector>
5407static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec) {
5408 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
5409 I != E; ++I) {
5410 Writer.GetDeclRef(D: *I);
5411 }
5412}
5413
5414template <typename Vector>
5415static void AddLazyVectorEmiitedDecls(ASTWriter &Writer, Vector &Vec,
5416 ASTWriter::RecordData &Record) {
5417 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
5418 I != E; ++I) {
5419 Writer.AddEmittedDeclRef(D: *I, Record);
5420 }
5421}
5422
5423void ASTWriter::computeNonAffectingInputFiles() {
5424 SourceManager &SrcMgr = PP->getSourceManager();
5425 unsigned N = SrcMgr.local_sloc_entry_size();
5426
5427 IsSLocAffecting.resize(N, t: true);
5428 IsSLocFileEntryAffecting.resize(N, t: true);
5429
5430 if (!WritingModule)
5431 return;
5432
5433 auto AffectingModuleMaps = GetAffectingModuleMaps(PP: *PP, RootModule: WritingModule);
5434
5435 unsigned FileIDAdjustment = 0;
5436 unsigned OffsetAdjustment = 0;
5437
5438 NonAffectingFileIDAdjustments.reserve(n: N);
5439 NonAffectingOffsetAdjustments.reserve(n: N);
5440
5441 NonAffectingFileIDAdjustments.push_back(x: FileIDAdjustment);
5442 NonAffectingOffsetAdjustments.push_back(x: OffsetAdjustment);
5443
5444 for (unsigned I = 1; I != N; ++I) {
5445 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(Index: I);
5446 FileID FID = FileID::get(V: I);
5447 assert(&SrcMgr.getSLocEntry(FID) == SLoc);
5448
5449 if (!SLoc->isFile())
5450 continue;
5451 const SrcMgr::FileInfo &File = SLoc->getFile();
5452 const SrcMgr::ContentCache *Cache = &File.getContentCache();
5453 if (!Cache->OrigEntry)
5454 continue;
5455
5456 // Don't prune anything other than module maps.
5457 if (!isModuleMap(CK: File.getFileCharacteristic()))
5458 continue;
5459
5460 // Don't prune module maps if all are guaranteed to be affecting.
5461 if (!AffectingModuleMaps)
5462 continue;
5463
5464 // Don't prune module maps that are affecting.
5465 if (AffectingModuleMaps->DefinitionFileIDs.contains(V: FID))
5466 continue;
5467
5468 IsSLocAffecting[I] = false;
5469 IsSLocFileEntryAffecting[I] =
5470 AffectingModuleMaps->DefinitionFiles.contains(V: *Cache->OrigEntry);
5471
5472 FileIDAdjustment += 1;
5473 // Even empty files take up one element in the offset table.
5474 OffsetAdjustment += SrcMgr.getFileIDSize(FID) + 1;
5475
5476 // If the previous file was non-affecting as well, just extend its entry
5477 // with our information.
5478 if (!NonAffectingFileIDs.empty() &&
5479 NonAffectingFileIDs.back().ID == FID.ID - 1) {
5480 NonAffectingFileIDs.back() = FID;
5481 NonAffectingRanges.back().setEnd(SrcMgr.getLocForEndOfFile(FID));
5482 NonAffectingFileIDAdjustments.back() = FileIDAdjustment;
5483 NonAffectingOffsetAdjustments.back() = OffsetAdjustment;
5484 continue;
5485 }
5486
5487 NonAffectingFileIDs.push_back(x: FID);
5488 NonAffectingRanges.emplace_back(args: SrcMgr.getLocForStartOfFile(FID),
5489 args: SrcMgr.getLocForEndOfFile(FID));
5490 NonAffectingFileIDAdjustments.push_back(x: FileIDAdjustment);
5491 NonAffectingOffsetAdjustments.push_back(x: OffsetAdjustment);
5492 }
5493
5494 if (!PP->getHeaderSearchInfo().getHeaderSearchOpts().ModulesIncludeVFSUsage)
5495 return;
5496
5497 FileManager &FileMgr = PP->getFileManager();
5498 FileMgr.trackVFSUsage(Active: true);
5499 // Lookup the paths in the VFS to trigger `-ivfsoverlay` usage tracking.
5500 for (StringRef Path :
5501 PP->getHeaderSearchInfo().getHeaderSearchOpts().VFSOverlayFiles)
5502 FileMgr.getVirtualFileSystem().exists(Path);
5503 for (unsigned I = 1; I != N; ++I) {
5504 if (IsSLocAffecting[I]) {
5505 const SrcMgr::SLocEntry *SLoc = &SrcMgr.getLocalSLocEntry(Index: I);
5506 if (!SLoc->isFile())
5507 continue;
5508 const SrcMgr::FileInfo &File = SLoc->getFile();
5509 const SrcMgr::ContentCache *Cache = &File.getContentCache();
5510 if (!Cache->OrigEntry)
5511 continue;
5512 FileMgr.getVirtualFileSystem().exists(
5513 Path: Cache->OrigEntry->getNameAsRequested());
5514 }
5515 }
5516 FileMgr.trackVFSUsage(Active: false);
5517}
5518
5519void ASTWriter::PrepareWritingSpecialDecls(Sema &SemaRef) {
5520 ASTContext &Context = SemaRef.Context;
5521
5522 bool isModule = WritingModule != nullptr;
5523
5524 // Set up predefined declaration IDs.
5525 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
5526 if (D) {
5527 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
5528 DeclIDs[D] = ID;
5529 PredefinedDecls.insert(Ptr: D);
5530 }
5531 };
5532 RegisterPredefDecl(Context.getTranslationUnitDecl(),
5533 PREDEF_DECL_TRANSLATION_UNIT_ID);
5534 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
5535 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
5536 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
5537 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
5538 PREDEF_DECL_OBJC_PROTOCOL_ID);
5539 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
5540 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
5541 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
5542 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
5543 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
5544 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
5545 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
5546 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
5547 RegisterPredefDecl(Context.MSGuidTagDecl,
5548 PREDEF_DECL_BUILTIN_MS_GUID_ID);
5549 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
5550 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
5551 PREDEF_DECL_CF_CONSTANT_STRING_ID);
5552 RegisterPredefDecl(Context.CFConstantStringTagDecl,
5553 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
5554#define BuiltinTemplate(BTName) \
5555 RegisterPredefDecl(Context.Decl##BTName, PREDEF_DECL##BTName##_ID);
5556#include "clang/Basic/BuiltinTemplates.inc"
5557
5558 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5559
5560 // Force all top level declarations to be emitted.
5561 //
5562 // We start emitting top level declarations from the module purview to
5563 // implement the eliding unreachable declaration feature.
5564 for (const auto *D : TU->noload_decls()) {
5565 if (D->isFromASTFile())
5566 continue;
5567
5568 if (GeneratingReducedBMI) {
5569 if (D->isFromExplicitGlobalModule())
5570 continue;
5571
5572 // Don't force emitting static entities.
5573 //
5574 // Technically, all static entities shouldn't be in reduced BMI. The
5575 // language also specifies that the program exposes TU-local entities
5576 // is ill-formed. However, in practice, there are a lot of projects
5577 // uses `static inline` in the headers. So we can't get rid of all
5578 // static entities in reduced BMI now.
5579 if (IsInternalDeclFromFileContext(D))
5580 continue;
5581 }
5582
5583 // If we're writing C++ named modules, don't emit declarations which are
5584 // not from modules by default. They may be built in declarations (be
5585 // handled above) or implcit declarations (see the implementation of
5586 // `Sema::Initialize()` for example).
5587 if (isWritingStdCXXNamedModules() && !D->getOwningModule() &&
5588 D->isImplicit())
5589 continue;
5590
5591 GetDeclRef(D);
5592 }
5593
5594 if (GeneratingReducedBMI)
5595 return;
5596
5597 // Writing all of the tentative definitions in this file, in
5598 // TentativeDefinitions order. Generally, this record will be empty for
5599 // headers.
5600 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions);
5601
5602 // Writing all of the file scoped decls in this file.
5603 if (!isModule)
5604 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls);
5605
5606 // Writing all of the delegating constructors we still need
5607 // to resolve.
5608 if (!isModule)
5609 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls);
5610
5611 // Writing all of the ext_vector declarations.
5612 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls);
5613
5614 // Writing all of the VTable uses information.
5615 if (!SemaRef.VTableUses.empty())
5616 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I)
5617 GetDeclRef(SemaRef.VTableUses[I].first);
5618
5619 // Writing all of the UnusedLocalTypedefNameCandidates.
5620 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
5621 GetDeclRef(TD);
5622
5623 // Writing all of pending implicit instantiations.
5624 for (const auto &I : SemaRef.PendingInstantiations)
5625 GetDeclRef(I.first);
5626 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
5627 "There are local ones at end of translation unit!");
5628
5629 // Writing some declaration references.
5630 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
5631 GetDeclRef(SemaRef.getStdNamespace());
5632 GetDeclRef(SemaRef.getStdBadAlloc());
5633 GetDeclRef(SemaRef.getStdAlignValT());
5634 }
5635
5636 if (Context.getcudaConfigureCallDecl())
5637 GetDeclRef(Context.getcudaConfigureCallDecl());
5638
5639 // Writing all of the known namespaces.
5640 for (const auto &I : SemaRef.KnownNamespaces)
5641 if (!I.second)
5642 GetDeclRef(I.first);
5643
5644 // Writing all used, undefined objects that require definitions.
5645 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
5646 SemaRef.getUndefinedButUsed(Undefined&: Undefined);
5647 for (const auto &I : Undefined)
5648 GetDeclRef(I.first);
5649
5650 // Writing all delete-expressions that we would like to
5651 // analyze later in AST.
5652 if (!isModule)
5653 for (const auto &DeleteExprsInfo :
5654 SemaRef.getMismatchingDeleteExpressions())
5655 GetDeclRef(DeleteExprsInfo.first);
5656
5657 // Make sure visible decls, added to DeclContexts previously loaded from
5658 // an AST file, are registered for serialization. Likewise for template
5659 // specializations added to imported templates.
5660 for (const auto *I : DeclsToEmitEvenIfUnreferenced)
5661 GetDeclRef(D: I);
5662 DeclsToEmitEvenIfUnreferenced.clear();
5663
5664 // Make sure all decls associated with an identifier are registered for
5665 // serialization, if we're storing decls with identifiers.
5666 if (!WritingModule || !getLangOpts().CPlusPlus) {
5667 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
5668 for (const auto &ID : SemaRef.PP.getIdentifierTable()) {
5669 const IdentifierInfo *II = ID.second;
5670 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization() ||
5671 II->hasFETokenInfoChangedSinceDeserialization())
5672 IIs.push_back(II);
5673 }
5674 // Sort the identifiers to visit based on their name.
5675 llvm::sort(IIs, llvm::deref<std::less<>>());
5676 const LangOptions &LangOpts = getLangOpts();
5677 for (const IdentifierInfo *II : IIs)
5678 for (NamedDecl *D : SemaRef.IdResolver.decls(II))
5679 GetDeclRef(getDeclForLocalLookup(LangOpts, D));
5680 }
5681
5682 // Write all of the DeclsToCheckForDeferredDiags.
5683 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5684 GetDeclRef(D);
5685
5686 // Write all classes that need to emit the vtable definitions if required.
5687 if (isWritingStdCXXNamedModules())
5688 for (CXXRecordDecl *RD : PendingEmittingVTables)
5689 GetDeclRef(RD);
5690 else
5691 PendingEmittingVTables.clear();
5692}
5693
5694void ASTWriter::WriteSpecialDeclRecords(Sema &SemaRef) {
5695 ASTContext &Context = SemaRef.Context;
5696
5697 bool isModule = WritingModule != nullptr;
5698
5699 // Write the record containing external, unnamed definitions.
5700 if (!EagerlyDeserializedDecls.empty())
5701 Stream.EmitRecord(Code: EAGERLY_DESERIALIZED_DECLS, Vals: EagerlyDeserializedDecls);
5702
5703 if (!ModularCodegenDecls.empty())
5704 Stream.EmitRecord(Code: MODULAR_CODEGEN_DECLS, Vals: ModularCodegenDecls);
5705
5706 // Write the record containing tentative definitions.
5707 RecordData TentativeDefinitions;
5708 AddLazyVectorEmiitedDecls(Writer&: *this, Vec&: SemaRef.TentativeDefinitions,
5709 Record&: TentativeDefinitions);
5710 if (!TentativeDefinitions.empty())
5711 Stream.EmitRecord(Code: TENTATIVE_DEFINITIONS, Vals: TentativeDefinitions);
5712
5713 // Write the record containing unused file scoped decls.
5714 RecordData UnusedFileScopedDecls;
5715 if (!isModule)
5716 AddLazyVectorEmiitedDecls(Writer&: *this, Vec&: SemaRef.UnusedFileScopedDecls,
5717 Record&: UnusedFileScopedDecls);
5718 if (!UnusedFileScopedDecls.empty())
5719 Stream.EmitRecord(Code: UNUSED_FILESCOPED_DECLS, Vals: UnusedFileScopedDecls);
5720
5721 // Write the record containing ext_vector type names.
5722 RecordData ExtVectorDecls;
5723 AddLazyVectorEmiitedDecls(Writer&: *this, Vec&: SemaRef.ExtVectorDecls, Record&: ExtVectorDecls);
5724 if (!ExtVectorDecls.empty())
5725 Stream.EmitRecord(Code: EXT_VECTOR_DECLS, Vals: ExtVectorDecls);
5726
5727 // Write the record containing VTable uses information.
5728 RecordData VTableUses;
5729 if (!SemaRef.VTableUses.empty()) {
5730 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
5731 CXXRecordDecl *D = SemaRef.VTableUses[I].first;
5732 if (!wasDeclEmitted(D))
5733 continue;
5734
5735 AddDeclRef(D, VTableUses);
5736 AddSourceLocation(Loc: SemaRef.VTableUses[I].second, Record&: VTableUses);
5737 VTableUses.push_back(Elt: SemaRef.VTablesUsed[D]);
5738 }
5739 Stream.EmitRecord(Code: VTABLE_USES, Vals: VTableUses);
5740 }
5741
5742 // Write the record containing potentially unused local typedefs.
5743 RecordData UnusedLocalTypedefNameCandidates;
5744 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
5745 AddEmittedDeclRef(TD, UnusedLocalTypedefNameCandidates);
5746 if (!UnusedLocalTypedefNameCandidates.empty())
5747 Stream.EmitRecord(Code: UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5748 Vals: UnusedLocalTypedefNameCandidates);
5749
5750 // Write the record containing pending implicit instantiations.
5751 RecordData PendingInstantiations;
5752 for (const auto &I : SemaRef.PendingInstantiations) {
5753 if (!wasDeclEmitted(I.first))
5754 continue;
5755
5756 AddDeclRef(I.first, PendingInstantiations);
5757 AddSourceLocation(Loc: I.second, Record&: PendingInstantiations);
5758 }
5759 if (!PendingInstantiations.empty())
5760 Stream.EmitRecord(Code: PENDING_IMPLICIT_INSTANTIATIONS, Vals: PendingInstantiations);
5761
5762 // Write the record containing declaration references of Sema.
5763 RecordData SemaDeclRefs;
5764 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
5765 auto AddEmittedDeclRefOrZero = [this, &SemaDeclRefs](Decl *D) {
5766 if (!D || !wasDeclEmitted(D))
5767 SemaDeclRefs.push_back(Elt: 0);
5768 else
5769 AddDeclRef(D, Record&: SemaDeclRefs);
5770 };
5771
5772 AddEmittedDeclRefOrZero(SemaRef.getStdNamespace());
5773 AddEmittedDeclRefOrZero(SemaRef.getStdBadAlloc());
5774 AddEmittedDeclRefOrZero(SemaRef.getStdAlignValT());
5775 }
5776 if (!SemaDeclRefs.empty())
5777 Stream.EmitRecord(Code: SEMA_DECL_REFS, Vals: SemaDeclRefs);
5778
5779 // Write the record containing decls to be checked for deferred diags.
5780 RecordData DeclsToCheckForDeferredDiags;
5781 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
5782 if (wasDeclEmitted(D))
5783 AddDeclRef(D, Record&: DeclsToCheckForDeferredDiags);
5784 if (!DeclsToCheckForDeferredDiags.empty())
5785 Stream.EmitRecord(Code: DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
5786 Vals: DeclsToCheckForDeferredDiags);
5787
5788 // Write the record containing CUDA-specific declaration references.
5789 RecordData CUDASpecialDeclRefs;
5790 if (auto *CudaCallDecl = Context.getcudaConfigureCallDecl();
5791 CudaCallDecl && wasDeclEmitted(CudaCallDecl)) {
5792 AddDeclRef(CudaCallDecl, CUDASpecialDeclRefs);
5793 Stream.EmitRecord(Code: CUDA_SPECIAL_DECL_REFS, Vals: CUDASpecialDeclRefs);
5794 }
5795
5796 // Write the delegating constructors.
5797 RecordData DelegatingCtorDecls;
5798 if (!isModule)
5799 AddLazyVectorEmiitedDecls(Writer&: *this, Vec&: SemaRef.DelegatingCtorDecls,
5800 Record&: DelegatingCtorDecls);
5801 if (!DelegatingCtorDecls.empty())
5802 Stream.EmitRecord(Code: DELEGATING_CTORS, Vals: DelegatingCtorDecls);
5803
5804 // Write the known namespaces.
5805 RecordData KnownNamespaces;
5806 for (const auto &I : SemaRef.KnownNamespaces) {
5807 if (!I.second && wasDeclEmitted(I.first))
5808 AddDeclRef(I.first, KnownNamespaces);
5809 }
5810 if (!KnownNamespaces.empty())
5811 Stream.EmitRecord(Code: KNOWN_NAMESPACES, Vals: KnownNamespaces);
5812
5813 // Write the undefined internal functions and variables, and inline functions.
5814 RecordData UndefinedButUsed;
5815 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
5816 SemaRef.getUndefinedButUsed(Undefined);
5817 for (const auto &I : Undefined) {
5818 if (!wasDeclEmitted(I.first))
5819 continue;
5820
5821 AddDeclRef(I.first, UndefinedButUsed);
5822 AddSourceLocation(Loc: I.second, Record&: UndefinedButUsed);
5823 }
5824 if (!UndefinedButUsed.empty())
5825 Stream.EmitRecord(Code: UNDEFINED_BUT_USED, Vals: UndefinedButUsed);
5826
5827 // Write all delete-expressions that we would like to
5828 // analyze later in AST.
5829 RecordData DeleteExprsToAnalyze;
5830 if (!isModule) {
5831 for (const auto &DeleteExprsInfo :
5832 SemaRef.getMismatchingDeleteExpressions()) {
5833 if (!wasDeclEmitted(DeleteExprsInfo.first))
5834 continue;
5835
5836 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
5837 DeleteExprsToAnalyze.push_back(Elt: DeleteExprsInfo.second.size());
5838 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
5839 AddSourceLocation(Loc: DeleteLoc.first, Record&: DeleteExprsToAnalyze);
5840 DeleteExprsToAnalyze.push_back(Elt: DeleteLoc.second);
5841 }
5842 }
5843 }
5844 if (!DeleteExprsToAnalyze.empty())
5845 Stream.EmitRecord(Code: DELETE_EXPRS_TO_ANALYZE, Vals: DeleteExprsToAnalyze);
5846
5847 RecordData VTablesToEmit;
5848 for (CXXRecordDecl *RD : PendingEmittingVTables) {
5849 if (!wasDeclEmitted(RD))
5850 continue;
5851
5852 AddDeclRef(RD, VTablesToEmit);
5853 }
5854
5855 if (!VTablesToEmit.empty())
5856 Stream.EmitRecord(Code: VTABLES_TO_EMIT, Vals: VTablesToEmit);
5857}
5858
5859ASTFileSignature ASTWriter::WriteASTCore(Sema *SemaPtr, StringRef isysroot,
5860 Module *WritingModule) {
5861 using namespace llvm;
5862
5863 bool isModule = WritingModule != nullptr;
5864
5865 // Make sure that the AST reader knows to finalize itself.
5866 if (Chain)
5867 Chain->finalizeForWriting();
5868
5869 // This needs to be done very early, since everything that writes
5870 // SourceLocations or FileIDs depends on it.
5871 computeNonAffectingInputFiles();
5872
5873 writeUnhashedControlBlock(PP&: *PP);
5874
5875 // Don't reuse type ID and Identifier ID from readers for C++ standard named
5876 // modules since we want to support no-transitive-change model for named
5877 // modules. The theory for no-transitive-change model is,
5878 // for a user of a named module, the user can only access the indirectly
5879 // imported decls via the directly imported module. So that it is possible to
5880 // control what matters to the users when writing the module. It would be
5881 // problematic if the users can reuse the type IDs and identifier IDs from
5882 // indirectly imported modules arbitrarily. So we choose to clear these ID
5883 // here.
5884 if (isWritingStdCXXNamedModules()) {
5885 TypeIdxs.clear();
5886 IdentifierIDs.clear();
5887 }
5888
5889 // Look for any identifiers that were named while processing the
5890 // headers, but are otherwise not needed. We add these to the hash
5891 // table to enable checking of the predefines buffer in the case
5892 // where the user adds new macro definitions when building the AST
5893 // file.
5894 //
5895 // We do this before emitting any Decl and Types to make sure the
5896 // Identifier ID is stable.
5897 SmallVector<const IdentifierInfo *, 128> IIs;
5898 for (const auto &ID : PP->getIdentifierTable())
5899 if (IsInterestingNonMacroIdentifier(ID.second, *this))
5900 IIs.push_back(ID.second);
5901 // Sort the identifiers lexicographically before getting the references so
5902 // that their order is stable.
5903 llvm::sort(C&: IIs, Comp: llvm::deref<std::less<>>());
5904 for (const IdentifierInfo *II : IIs)
5905 getIdentifierRef(II);
5906
5907 // Write the set of weak, undeclared identifiers. We always write the
5908 // entire table, since later PCH files in a PCH chain are only interested in
5909 // the results at the end of the chain.
5910 RecordData WeakUndeclaredIdentifiers;
5911 if (SemaPtr) {
5912 for (const auto &WeakUndeclaredIdentifierList :
5913 SemaPtr->WeakUndeclaredIdentifiers) {
5914 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
5915 for (const auto &WI : WeakUndeclaredIdentifierList.second) {
5916 AddIdentifierRef(II, Record&: WeakUndeclaredIdentifiers);
5917 AddIdentifierRef(II: WI.getAlias(), Record&: WeakUndeclaredIdentifiers);
5918 AddSourceLocation(Loc: WI.getLocation(), Record&: WeakUndeclaredIdentifiers);
5919 }
5920 }
5921 }
5922
5923 // Form the record of special types.
5924 RecordData SpecialTypes;
5925 if (SemaPtr) {
5926 ASTContext &Context = SemaPtr->Context;
5927 AddTypeRef(Context, T: Context.getRawCFConstantStringType(), Record&: SpecialTypes);
5928 AddTypeRef(Context, T: Context.getFILEType(), Record&: SpecialTypes);
5929 AddTypeRef(Context, T: Context.getjmp_bufType(), Record&: SpecialTypes);
5930 AddTypeRef(Context, T: Context.getsigjmp_bufType(), Record&: SpecialTypes);
5931 AddTypeRef(Context, T: Context.ObjCIdRedefinitionType, Record&: SpecialTypes);
5932 AddTypeRef(Context, T: Context.ObjCClassRedefinitionType, Record&: SpecialTypes);
5933 AddTypeRef(Context, T: Context.ObjCSelRedefinitionType, Record&: SpecialTypes);
5934 AddTypeRef(Context, T: Context.getucontext_tType(), Record&: SpecialTypes);
5935 }
5936
5937 if (SemaPtr)
5938 PrepareWritingSpecialDecls(SemaRef&: *SemaPtr);
5939
5940 // Write the control block
5941 WriteControlBlock(PP&: *PP, isysroot);
5942
5943 // Write the remaining AST contents.
5944 Stream.FlushToWord();
5945 ASTBlockRange.first = Stream.GetCurrentBitNo() >> 3;
5946 Stream.EnterSubblock(BlockID: AST_BLOCK_ID, CodeLen: 5);
5947 ASTBlockStartOffset = Stream.GetCurrentBitNo();
5948
5949 // This is so that older clang versions, before the introduction
5950 // of the control block, can read and reject the newer PCH format.
5951 {
5952 RecordData Record = {VERSION_MAJOR};
5953 Stream.EmitRecord(Code: METADATA_OLD_FORMAT, Vals: Record);
5954 }
5955
5956 // For method pool in the module, if it contains an entry for a selector,
5957 // the entry should be complete, containing everything introduced by that
5958 // module and all modules it imports. It's possible that the entry is out of
5959 // date, so we need to pull in the new content here.
5960
5961 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
5962 // safe, we copy all selectors out.
5963 if (SemaPtr) {
5964 llvm::SmallVector<Selector, 256> AllSelectors;
5965 for (auto &SelectorAndID : SelectorIDs)
5966 AllSelectors.push_back(Elt: SelectorAndID.first);
5967 for (auto &Selector : AllSelectors)
5968 SemaPtr->ObjC().updateOutOfDateSelector(Sel: Selector);
5969 }
5970
5971 if (Chain) {
5972 // Write the mapping information describing our module dependencies and how
5973 // each of those modules were mapped into our own offset/ID space, so that
5974 // the reader can build the appropriate mapping to its own offset/ID space.
5975 // The map consists solely of a blob with the following format:
5976 // *(module-kind:i8
5977 // module-name-len:i16 module-name:len*i8
5978 // source-location-offset:i32
5979 // identifier-id:i32
5980 // preprocessed-entity-id:i32
5981 // macro-definition-id:i32
5982 // submodule-id:i32
5983 // selector-id:i32
5984 // declaration-id:i32
5985 // c++-base-specifiers-id:i32
5986 // type-id:i32)
5987 //
5988 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
5989 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
5990 // module name. Otherwise, it is the module file name.
5991 auto Abbrev = std::make_shared<BitCodeAbbrev>();
5992 Abbrev->Add(OpInfo: BitCodeAbbrevOp(MODULE_OFFSET_MAP));
5993 Abbrev->Add(OpInfo: BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
5994 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abbrev));
5995 SmallString<2048> Buffer;
5996 {
5997 llvm::raw_svector_ostream Out(Buffer);
5998 for (ModuleFile &M : Chain->ModuleMgr) {
5999 using namespace llvm::support;
6000
6001 endian::Writer LE(Out, llvm::endianness::little);
6002 LE.write<uint8_t>(Val: static_cast<uint8_t>(M.Kind));
6003 StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
6004 LE.write<uint16_t>(Val: Name.size());
6005 Out.write(Ptr: Name.data(), Size: Name.size());
6006
6007 // Note: if a base ID was uint max, it would not be possible to load
6008 // another module after it or have more than one entity inside it.
6009 uint32_t None = std::numeric_limits<uint32_t>::max();
6010
6011 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
6012 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
6013 if (ShouldWrite)
6014 LE.write<uint32_t>(BaseID);
6015 else
6016 LE.write<uint32_t>(Val: None);
6017 };
6018
6019 // These values should be unique within a chain, since they will be read
6020 // as keys into ContinuousRangeMaps.
6021 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
6022 writeBaseIDOrNone(M.BasePreprocessedEntityID,
6023 M.NumPreprocessedEntities);
6024 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
6025 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
6026 }
6027 }
6028 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
6029 Stream.EmitRecordWithBlob(Abbrev: ModuleOffsetMapAbbrev, Vals: Record,
6030 BlobData: Buffer.data(), BlobLen: Buffer.size());
6031 }
6032
6033 if (SemaPtr)
6034 WriteDeclAndTypes(Context&: SemaPtr->Context);
6035
6036 WriteFileDeclIDsMap();
6037 WriteSourceManagerBlock(SourceMgr&: PP->getSourceManager());
6038 if (SemaPtr)
6039 WriteComments(Context&: SemaPtr->Context);
6040 WritePreprocessor(PP: *PP, IsModule: isModule);
6041 WriteHeaderSearch(HS: PP->getHeaderSearchInfo());
6042 if (SemaPtr) {
6043 WriteSelectors(SemaRef&: *SemaPtr);
6044 WriteReferencedSelectorsPool(SemaRef&: *SemaPtr);
6045 WriteLateParsedTemplates(SemaRef&: *SemaPtr);
6046 }
6047 WriteIdentifierTable(PP&: *PP, IdResolver: SemaPtr ? &SemaPtr->IdResolver : nullptr, IsModule: isModule);
6048 if (SemaPtr) {
6049 WriteFPPragmaOptions(Opts: SemaPtr->CurFPFeatureOverrides());
6050 WriteOpenCLExtensions(SemaRef&: *SemaPtr);
6051 WriteCUDAPragmas(SemaRef&: *SemaPtr);
6052 }
6053
6054 // If we're emitting a module, write out the submodule information.
6055 if (WritingModule)
6056 WriteSubmodules(WritingModule, Context: SemaPtr ? &SemaPtr->Context : nullptr);
6057
6058 Stream.EmitRecord(Code: SPECIAL_TYPES, Vals: SpecialTypes);
6059
6060 if (SemaPtr)
6061 WriteSpecialDeclRecords(SemaRef&: *SemaPtr);
6062
6063 // Write the record containing weak undeclared identifiers.
6064 if (!WeakUndeclaredIdentifiers.empty())
6065 Stream.EmitRecord(Code: WEAK_UNDECLARED_IDENTIFIERS,
6066 Vals: WeakUndeclaredIdentifiers);
6067
6068 if (!WritingModule) {
6069 // Write the submodules that were imported, if any.
6070 struct ModuleInfo {
6071 uint64_t ID;
6072 Module *M;
6073 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
6074 };
6075 llvm::SmallVector<ModuleInfo, 64> Imports;
6076 if (SemaPtr) {
6077 for (const auto *I : SemaPtr->Context.local_imports()) {
6078 assert(SubmoduleIDs.contains(I->getImportedModule()));
6079 Imports.push_back(Elt: ModuleInfo(SubmoduleIDs[I->getImportedModule()],
6080 I->getImportedModule()));
6081 }
6082 }
6083
6084 if (!Imports.empty()) {
6085 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
6086 return A.ID < B.ID;
6087 };
6088 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
6089 return A.ID == B.ID;
6090 };
6091
6092 // Sort and deduplicate module IDs.
6093 llvm::sort(C&: Imports, Comp: Cmp);
6094 Imports.erase(CS: llvm::unique(R&: Imports, P: Eq), CE: Imports.end());
6095
6096 RecordData ImportedModules;
6097 for (const auto &Import : Imports) {
6098 ImportedModules.push_back(Elt: Import.ID);
6099 // FIXME: If the module has macros imported then later has declarations
6100 // imported, this location won't be the right one as a location for the
6101 // declaration imports.
6102 AddSourceLocation(Loc: PP->getModuleImportLoc(M: Import.M), Record&: ImportedModules);
6103 }
6104
6105 Stream.EmitRecord(Code: IMPORTED_MODULES, Vals: ImportedModules);
6106 }
6107 }
6108
6109 WriteObjCCategories();
6110 if (SemaPtr) {
6111 if (!WritingModule) {
6112 WriteOptimizePragmaOptions(SemaRef&: *SemaPtr);
6113 WriteMSStructPragmaOptions(SemaRef&: *SemaPtr);
6114 WriteMSPointersToMembersPragmaOptions(SemaRef&: *SemaPtr);
6115 }
6116 WritePackPragmaOptions(SemaRef&: *SemaPtr);
6117 WriteFloatControlPragmaOptions(SemaRef&: *SemaPtr);
6118 WriteDeclsWithEffectsToVerify(SemaRef&: *SemaPtr);
6119 }
6120
6121 // Some simple statistics
6122 RecordData::value_type Record[] = {NumStatements,
6123 NumMacros,
6124 NumLexicalDeclContexts,
6125 NumVisibleDeclContexts,
6126 NumModuleLocalDeclContexts,
6127 NumTULocalDeclContexts};
6128 Stream.EmitRecord(Code: STATISTICS, Vals: Record);
6129 Stream.ExitBlock();
6130 Stream.FlushToWord();
6131 ASTBlockRange.second = Stream.GetCurrentBitNo() >> 3;
6132
6133 // Write the module file extension blocks.
6134 if (SemaPtr)
6135 for (const auto &ExtWriter : ModuleFileExtensionWriters)
6136 WriteModuleFileExtension(SemaRef&: *SemaPtr, Writer&: *ExtWriter);
6137
6138 return backpatchSignature();
6139}
6140
6141void ASTWriter::EnteringModulePurview() {
6142 // In C++20 named modules, all entities before entering the module purview
6143 // lives in the GMF.
6144 if (GeneratingReducedBMI)
6145 DeclUpdatesFromGMF.swap(RHS&: DeclUpdates);
6146}
6147
6148// Add update records for all mangling numbers and static local numbers.
6149// These aren't really update records, but this is a convenient way of
6150// tagging this rare extra data onto the declarations.
6151void ASTWriter::AddedManglingNumber(const Decl *D, unsigned Number) {
6152 if (D->isFromASTFile())
6153 return;
6154
6155 DeclUpdates[D].push_back(Elt: DeclUpdate(DeclUpdateKind::ManglingNumber, Number));
6156}
6157void ASTWriter::AddedStaticLocalNumbers(const Decl *D, unsigned Number) {
6158 if (D->isFromASTFile())
6159 return;
6160
6161 DeclUpdates[D].push_back(
6162 Elt: DeclUpdate(DeclUpdateKind::StaticLocalNumber, Number));
6163}
6164
6165void ASTWriter::AddedAnonymousNamespace(const TranslationUnitDecl *TU,
6166 NamespaceDecl *AnonNamespace) {
6167 // If the translation unit has an anonymous namespace, and we don't already
6168 // have an update block for it, write it as an update block.
6169 // FIXME: Why do we not do this if there's already an update block?
6170 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
6171 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
6172 if (Record.empty())
6173 Record.push_back(
6174 Elt: DeclUpdate(DeclUpdateKind::CXXAddedAnonymousNamespace, NS));
6175 }
6176}
6177
6178void ASTWriter::WriteDeclAndTypes(ASTContext &Context) {
6179 // Keep writing types, declarations, and declaration update records
6180 // until we've emitted all of them.
6181 RecordData DeclUpdatesOffsetsRecord;
6182 Stream.EnterSubblock(BlockID: DECLTYPES_BLOCK_ID, /*bits for abbreviations*/ CodeLen: 6);
6183 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
6184 WriteTypeAbbrevs();
6185 WriteDeclAbbrevs();
6186 do {
6187 WriteDeclUpdatesBlocks(Context, OffsetsRecord&: DeclUpdatesOffsetsRecord);
6188 while (!DeclTypesToEmit.empty()) {
6189 DeclOrType DOT = DeclTypesToEmit.front();
6190 DeclTypesToEmit.pop();
6191 if (DOT.isType())
6192 WriteType(Context, T: DOT.getType());
6193 else
6194 WriteDecl(Context, D: DOT.getDecl());
6195 }
6196 } while (!DeclUpdates.empty());
6197
6198 DoneWritingDeclsAndTypes = true;
6199
6200 // DelayedNamespace is only meaningful in reduced BMI.
6201 // See the comments of DelayedNamespace for details.
6202 assert(DelayedNamespace.empty() || GeneratingReducedBMI);
6203 RecordData DelayedNamespaceRecord;
6204 for (NamespaceDecl *NS : DelayedNamespace) {
6205 uint64_t LexicalOffset = WriteDeclContextLexicalBlock(Context, NS);
6206 uint64_t VisibleOffset = 0;
6207 uint64_t ModuleLocalOffset = 0;
6208 uint64_t TULocalOffset = 0;
6209 WriteDeclContextVisibleBlock(Context, NS, VisibleOffset, ModuleLocalOffset,
6210 TULocalOffset);
6211
6212 // Write the offset relative to current block.
6213 if (LexicalOffset)
6214 LexicalOffset -= DeclTypesBlockStartOffset;
6215
6216 if (VisibleOffset)
6217 VisibleOffset -= DeclTypesBlockStartOffset;
6218
6219 if (ModuleLocalOffset)
6220 ModuleLocalOffset -= DeclTypesBlockStartOffset;
6221
6222 if (TULocalOffset)
6223 TULocalOffset -= DeclTypesBlockStartOffset;
6224
6225 AddDeclRef(NS, DelayedNamespaceRecord);
6226 DelayedNamespaceRecord.push_back(Elt: LexicalOffset);
6227 DelayedNamespaceRecord.push_back(Elt: VisibleOffset);
6228 DelayedNamespaceRecord.push_back(Elt: ModuleLocalOffset);
6229 DelayedNamespaceRecord.push_back(Elt: TULocalOffset);
6230 }
6231
6232 // The process of writing lexical and visible block for delayed namespace
6233 // shouldn't introduce any new decls, types or update to emit.
6234 assert(DeclTypesToEmit.empty());
6235 assert(DeclUpdates.empty());
6236
6237 Stream.ExitBlock();
6238
6239 // These things can only be done once we've written out decls and types.
6240 WriteTypeDeclOffsets();
6241 if (!DeclUpdatesOffsetsRecord.empty())
6242 Stream.EmitRecord(Code: DECL_UPDATE_OFFSETS, Vals: DeclUpdatesOffsetsRecord);
6243
6244 if (!DelayedNamespaceRecord.empty())
6245 Stream.EmitRecord(Code: DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD,
6246 Vals: DelayedNamespaceRecord);
6247
6248 if (!RelatedDeclsMap.empty()) {
6249 // TODO: on disk hash table for related decls mapping might be more
6250 // efficent becuase it allows lazy deserialization.
6251 RecordData RelatedDeclsMapRecord;
6252 for (const auto &Pair : RelatedDeclsMap) {
6253 RelatedDeclsMapRecord.push_back(Elt: Pair.first.getRawValue());
6254 RelatedDeclsMapRecord.push_back(Elt: Pair.second.size());
6255 for (const auto &Lambda : Pair.second)
6256 RelatedDeclsMapRecord.push_back(Elt: Lambda.getRawValue());
6257 }
6258
6259 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6260 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(RELATED_DECLS_MAP));
6261 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Array));
6262 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6263 unsigned FunctionToLambdaMapAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
6264 Stream.EmitRecord(Code: RELATED_DECLS_MAP, Vals: RelatedDeclsMapRecord,
6265 Abbrev: FunctionToLambdaMapAbbrev);
6266 }
6267
6268 if (!SpecializationsUpdates.empty()) {
6269 WriteSpecializationsUpdates(/*IsPartial=*/false);
6270 SpecializationsUpdates.clear();
6271 }
6272
6273 if (!PartialSpecializationsUpdates.empty()) {
6274 WriteSpecializationsUpdates(/*IsPartial=*/true);
6275 PartialSpecializationsUpdates.clear();
6276 }
6277
6278 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6279 // Create a lexical update block containing all of the declarations in the
6280 // translation unit that do not come from other AST files.
6281 SmallVector<DeclID, 128> NewGlobalKindDeclPairs;
6282 for (const auto *D : TU->noload_decls()) {
6283 if (D->isFromASTFile())
6284 continue;
6285
6286 // In reduced BMI, skip unreached declarations.
6287 if (!wasDeclEmitted(D))
6288 continue;
6289
6290 NewGlobalKindDeclPairs.push_back(D->getKind());
6291 NewGlobalKindDeclPairs.push_back(GetDeclRef(D).getRawValue());
6292 }
6293
6294 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6295 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
6296 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6297 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
6298
6299 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
6300 Stream.EmitRecordWithBlob(Abbrev: TuUpdateLexicalAbbrev, Vals: Record,
6301 Blob: bytes(v: NewGlobalKindDeclPairs));
6302
6303 Abv = std::make_shared<llvm::BitCodeAbbrev>();
6304 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
6305 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6306 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6307 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
6308
6309 Abv = std::make_shared<llvm::BitCodeAbbrev>();
6310 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(UPDATE_MODULE_LOCAL_VISIBLE));
6311 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6312 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6313 ModuleLocalUpdateVisibleAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
6314
6315 Abv = std::make_shared<llvm::BitCodeAbbrev>();
6316 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(UPDATE_TU_LOCAL_VISIBLE));
6317 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6318 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6319 TULocalUpdateVisibleAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
6320
6321 // And a visible updates block for the translation unit.
6322 WriteDeclContextVisibleUpdate(Context, TU);
6323
6324 // If we have any extern "C" names, write out a visible update for them.
6325 if (Context.ExternCContext)
6326 WriteDeclContextVisibleUpdate(Context, Context.ExternCContext);
6327
6328 // Write the visible updates to DeclContexts.
6329 for (auto *DC : UpdatedDeclContexts)
6330 WriteDeclContextVisibleUpdate(Context, DC);
6331}
6332
6333void ASTWriter::WriteSpecializationsUpdates(bool IsPartial) {
6334 auto RecordType = IsPartial ? CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
6335 : CXX_ADDED_TEMPLATE_SPECIALIZATION;
6336
6337 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
6338 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(RecordType));
6339 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
6340 Abv->Add(OpInfo: llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
6341 auto UpdateSpecializationAbbrev = Stream.EmitAbbrev(Abbv: std::move(Abv));
6342
6343 auto &SpecUpdates =
6344 IsPartial ? PartialSpecializationsUpdates : SpecializationsUpdates;
6345 for (auto &SpecializationUpdate : SpecUpdates) {
6346 const NamedDecl *D = SpecializationUpdate.first;
6347
6348 llvm::SmallString<4096> LookupTable;
6349 GenerateSpecializationInfoLookupTable(D, Specializations&: SpecializationUpdate.second,
6350 LookupTable, IsPartial);
6351
6352 // Write the lookup table
6353 RecordData::value_type Record[] = {
6354 static_cast<RecordData::value_type>(RecordType),
6355 getDeclID(D).getRawValue()};
6356 Stream.EmitRecordWithBlob(Abbrev: UpdateSpecializationAbbrev, Vals: Record, Blob: LookupTable);
6357 }
6358}
6359
6360void ASTWriter::WriteDeclUpdatesBlocks(ASTContext &Context,
6361 RecordDataImpl &OffsetsRecord) {
6362 if (DeclUpdates.empty())
6363 return;
6364
6365 DeclUpdateMap LocalUpdates;
6366 LocalUpdates.swap(RHS&: DeclUpdates);
6367
6368 for (auto &DeclUpdate : LocalUpdates) {
6369 const Decl *D = DeclUpdate.first;
6370
6371 bool HasUpdatedBody = false;
6372 bool HasAddedVarDefinition = false;
6373 RecordData RecordData;
6374 ASTRecordWriter Record(Context, *this, RecordData);
6375 for (auto &Update : DeclUpdate.second) {
6376 DeclUpdateKind Kind = Update.getKind();
6377
6378 // An updated body is emitted last, so that the reader doesn't need
6379 // to skip over the lazy body to reach statements for other records.
6380 if (Kind == DeclUpdateKind::CXXAddedFunctionDefinition)
6381 HasUpdatedBody = true;
6382 else if (Kind == DeclUpdateKind::CXXAddedVarDefinition)
6383 HasAddedVarDefinition = true;
6384 else
6385 Record.push_back(N: llvm::to_underlying(E: Kind));
6386
6387 switch (Kind) {
6388 case DeclUpdateKind::CXXAddedImplicitMember:
6389 case DeclUpdateKind::CXXAddedAnonymousNamespace:
6390 assert(Update.getDecl() && "no decl to add?");
6391 Record.AddDeclRef(D: Update.getDecl());
6392 break;
6393 case DeclUpdateKind::CXXAddedFunctionDefinition:
6394 case DeclUpdateKind::CXXAddedVarDefinition:
6395 break;
6396
6397 case DeclUpdateKind::CXXPointOfInstantiation:
6398 // FIXME: Do we need to also save the template specialization kind here?
6399 Record.AddSourceLocation(Loc: Update.getLoc());
6400 break;
6401
6402 case DeclUpdateKind::CXXInstantiatedDefaultArgument:
6403 Record.writeStmtRef(
6404 cast<ParmVarDecl>(Val: Update.getDecl())->getDefaultArg());
6405 break;
6406
6407 case DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer:
6408 Record.AddStmt(
6409 cast<FieldDecl>(Val: Update.getDecl())->getInClassInitializer());
6410 break;
6411
6412 case DeclUpdateKind::CXXInstantiatedClassDefinition: {
6413 auto *RD = cast<CXXRecordDecl>(Val: D);
6414 UpdatedDeclContexts.insert(RD->getPrimaryContext());
6415 Record.push_back(N: RD->isParamDestroyedInCallee());
6416 Record.push_back(N: llvm::to_underlying(RD->getArgPassingRestrictions()));
6417 Record.AddCXXDefinitionData(D: RD);
6418 Record.AddOffset(BitOffset: WriteDeclContextLexicalBlock(Context, RD));
6419
6420 // This state is sometimes updated by template instantiation, when we
6421 // switch from the specialization referring to the template declaration
6422 // to it referring to the template definition.
6423 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
6424 Record.push_back(N: MSInfo->getTemplateSpecializationKind());
6425 Record.AddSourceLocation(Loc: MSInfo->getPointOfInstantiation());
6426 } else {
6427 auto *Spec = cast<ClassTemplateSpecializationDecl>(Val: RD);
6428 Record.push_back(N: Spec->getTemplateSpecializationKind());
6429 Record.AddSourceLocation(Loc: Spec->getPointOfInstantiation());
6430
6431 // The instantiation might have been resolved to a partial
6432 // specialization. If so, record which one.
6433 auto From = Spec->getInstantiatedFrom();
6434 if (auto PartialSpec =
6435 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
6436 Record.push_back(N: true);
6437 Record.AddDeclRef(PartialSpec);
6438 Record.AddTemplateArgumentList(
6439 TemplateArgs: &Spec->getTemplateInstantiationArgs());
6440 } else {
6441 Record.push_back(N: false);
6442 }
6443 }
6444 Record.push_back(N: llvm::to_underlying(RD->getTagKind()));
6445 Record.AddSourceLocation(Loc: RD->getLocation());
6446 Record.AddSourceLocation(Loc: RD->getBeginLoc());
6447 Record.AddSourceRange(Range: RD->getBraceRange());
6448
6449 // Instantiation may change attributes; write them all out afresh.
6450 Record.push_back(N: D->hasAttrs());
6451 if (D->hasAttrs())
6452 Record.AddAttributes(Attrs: D->getAttrs());
6453
6454 // FIXME: Ensure we don't get here for explicit instantiations.
6455 break;
6456 }
6457
6458 case DeclUpdateKind::CXXResolvedDtorDelete:
6459 Record.AddDeclRef(D: Update.getDecl());
6460 Record.AddStmt(cast<CXXDestructorDecl>(Val: D)->getOperatorDeleteThisArg());
6461 break;
6462
6463 case DeclUpdateKind::CXXResolvedExceptionSpec: {
6464 auto prototype =
6465 cast<FunctionDecl>(Val: D)->getType()->castAs<FunctionProtoType>();
6466 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
6467 break;
6468 }
6469
6470 case DeclUpdateKind::CXXDeducedReturnType:
6471 Record.push_back(N: GetOrCreateTypeID(Context, T: Update.getType()));
6472 break;
6473
6474 case DeclUpdateKind::DeclMarkedUsed:
6475 break;
6476
6477 case DeclUpdateKind::ManglingNumber:
6478 case DeclUpdateKind::StaticLocalNumber:
6479 Record.push_back(N: Update.getNumber());
6480 break;
6481
6482 case DeclUpdateKind::DeclMarkedOpenMPThreadPrivate:
6483 Record.AddSourceRange(
6484 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
6485 break;
6486
6487 case DeclUpdateKind::DeclMarkedOpenMPAllocate: {
6488 auto *A = D->getAttr<OMPAllocateDeclAttr>();
6489 Record.push_back(N: A->getAllocatorType());
6490 Record.AddStmt(S: A->getAllocator());
6491 Record.AddStmt(S: A->getAlignment());
6492 Record.AddSourceRange(Range: A->getRange());
6493 break;
6494 }
6495
6496 case DeclUpdateKind::DeclMarkedOpenMPDeclareTarget:
6497 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
6498 Record.AddSourceRange(
6499 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
6500 break;
6501
6502 case DeclUpdateKind::DeclExported:
6503 Record.push_back(N: getSubmoduleID(Mod: Update.getModule()));
6504 break;
6505
6506 case DeclUpdateKind::AddedAttrToRecord:
6507 Record.AddAttributes(Attrs: llvm::ArrayRef(Update.getAttr()));
6508 break;
6509 }
6510 }
6511
6512 // Add a trailing update record, if any. These must go last because we
6513 // lazily load their attached statement.
6514 if (!GeneratingReducedBMI || !CanElideDeclDef(D)) {
6515 if (HasUpdatedBody) {
6516 const auto *Def = cast<FunctionDecl>(Val: D);
6517 Record.push_back(
6518 N: llvm::to_underlying(E: DeclUpdateKind::CXXAddedFunctionDefinition));
6519 Record.push_back(N: Def->isInlined());
6520 Record.AddSourceLocation(Loc: Def->getInnerLocStart());
6521 Record.AddFunctionDefinition(FD: Def);
6522 } else if (HasAddedVarDefinition) {
6523 const auto *VD = cast<VarDecl>(Val: D);
6524 Record.push_back(
6525 N: llvm::to_underlying(E: DeclUpdateKind::CXXAddedVarDefinition));
6526 Record.push_back(N: VD->isInline());
6527 Record.push_back(N: VD->isInlineSpecified());
6528 Record.AddVarDeclInit(VD);
6529 }
6530 }
6531
6532 AddDeclRef(D, Record&: OffsetsRecord);
6533 OffsetsRecord.push_back(Elt: Record.Emit(Code: DECL_UPDATES));
6534 }
6535}
6536
6537void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
6538 RecordDataImpl &Record) {
6539 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
6540 Record.push_back(Elt: Raw);
6541}
6542
6543FileID ASTWriter::getAdjustedFileID(FileID FID) const {
6544 if (FID.isInvalid() || PP->getSourceManager().isLoadedFileID(FID) ||
6545 NonAffectingFileIDs.empty())
6546 return FID;
6547 auto It = llvm::lower_bound(Range: NonAffectingFileIDs, Value&: FID);
6548 unsigned Idx = std::distance(first: NonAffectingFileIDs.begin(), last: It);
6549 unsigned Offset = NonAffectingFileIDAdjustments[Idx];
6550 return FileID::get(V: FID.getOpaqueValue() - Offset);
6551}
6552
6553unsigned ASTWriter::getAdjustedNumCreatedFIDs(FileID FID) const {
6554 unsigned NumCreatedFIDs = PP->getSourceManager()
6555 .getLocalSLocEntry(Index: FID.ID)
6556 .getFile()
6557 .NumCreatedFIDs;
6558
6559 unsigned AdjustedNumCreatedFIDs = 0;
6560 for (unsigned I = FID.ID, N = I + NumCreatedFIDs; I != N; ++I)
6561 if (IsSLocAffecting[I])
6562 ++AdjustedNumCreatedFIDs;
6563 return AdjustedNumCreatedFIDs;
6564}
6565
6566SourceLocation ASTWriter::getAdjustedLocation(SourceLocation Loc) const {
6567 if (Loc.isInvalid())
6568 return Loc;
6569 return Loc.getLocWithOffset(Offset: -getAdjustment(Offset: Loc.getOffset()));
6570}
6571
6572SourceRange ASTWriter::getAdjustedRange(SourceRange Range) const {
6573 return SourceRange(getAdjustedLocation(Loc: Range.getBegin()),
6574 getAdjustedLocation(Loc: Range.getEnd()));
6575}
6576
6577SourceLocation::UIntTy
6578ASTWriter::getAdjustedOffset(SourceLocation::UIntTy Offset) const {
6579 return Offset - getAdjustment(Offset);
6580}
6581
6582SourceLocation::UIntTy
6583ASTWriter::getAdjustment(SourceLocation::UIntTy Offset) const {
6584 if (NonAffectingRanges.empty())
6585 return 0;
6586
6587 if (PP->getSourceManager().isLoadedOffset(SLocOffset: Offset))
6588 return 0;
6589
6590 if (Offset > NonAffectingRanges.back().getEnd().getOffset())
6591 return NonAffectingOffsetAdjustments.back();
6592
6593 if (Offset < NonAffectingRanges.front().getBegin().getOffset())
6594 return 0;
6595
6596 auto Contains = [](const SourceRange &Range, SourceLocation::UIntTy Offset) {
6597 return Range.getEnd().getOffset() < Offset;
6598 };
6599
6600 auto It = llvm::lower_bound(Range: NonAffectingRanges, Value&: Offset, C: Contains);
6601 unsigned Idx = std::distance(first: NonAffectingRanges.begin(), last: It);
6602 return NonAffectingOffsetAdjustments[Idx];
6603}
6604
6605void ASTWriter::AddFileID(FileID FID, RecordDataImpl &Record) {
6606 Record.push_back(Elt: getAdjustedFileID(FID).getOpaqueValue());
6607}
6608
6609SourceLocationEncoding::RawLocEncoding
6610ASTWriter::getRawSourceLocationEncoding(SourceLocation Loc, LocSeq *Seq) {
6611 unsigned BaseOffset = 0;
6612 unsigned ModuleFileIndex = 0;
6613
6614 // See SourceLocationEncoding.h for the encoding details.
6615 if (PP->getSourceManager().isLoadedSourceLocation(Loc) && Loc.isValid()) {
6616 assert(getChain());
6617 auto SLocMapI = getChain()->GlobalSLocOffsetMap.find(
6618 K: SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6619 assert(SLocMapI != getChain()->GlobalSLocOffsetMap.end() &&
6620 "Corrupted global sloc offset map");
6621 ModuleFile *F = SLocMapI->second;
6622 BaseOffset = F->SLocEntryBaseOffset - 2;
6623 // 0 means the location is not loaded. So we need to add 1 to the index to
6624 // make it clear.
6625 ModuleFileIndex = F->Index + 1;
6626 assert(&getChain()->getModuleManager()[F->Index] == F);
6627 }
6628
6629 return SourceLocationEncoding::encode(Loc, BaseOffset, BaseModuleFileIndex: ModuleFileIndex, Seq);
6630}
6631
6632void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record,
6633 SourceLocationSequence *Seq) {
6634 Loc = getAdjustedLocation(Loc);
6635 Record.push_back(Elt: getRawSourceLocationEncoding(Loc, Seq));
6636}
6637
6638void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record,
6639 SourceLocationSequence *Seq) {
6640 AddSourceLocation(Loc: Range.getBegin(), Record, Seq);
6641 AddSourceLocation(Loc: Range.getEnd(), Record, Seq);
6642}
6643
6644void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
6645 AddAPInt(Value: Value.bitcastToAPInt());
6646}
6647
6648void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
6649 Record.push_back(Elt: getIdentifierRef(II));
6650}
6651
6652IdentifierID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
6653 if (!II)
6654 return 0;
6655
6656 IdentifierID &ID = IdentifierIDs[II];
6657 if (ID == 0)
6658 ID = NextIdentID++;
6659 return ID;
6660}
6661
6662MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
6663 // Don't emit builtin macros like __LINE__ to the AST file unless they
6664 // have been redefined by the header (in which case they are not
6665 // isBuiltinMacro).
6666 if (!MI || MI->isBuiltinMacro())
6667 return 0;
6668
6669 MacroID &ID = MacroIDs[MI];
6670 if (ID == 0) {
6671 ID = NextMacroID++;
6672 MacroInfoToEmitData Info = { .Name: Name, .MI: MI, .ID: ID };
6673 MacroInfosToEmit.push_back(x: Info);
6674 }
6675 return ID;
6676}
6677
6678uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
6679 return IdentMacroDirectivesOffsetMap.lookup(Val: Name);
6680}
6681
6682void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
6683 Record->push_back(Elt: Writer->getSelectorRef(Sel: SelRef));
6684}
6685
6686SelectorID ASTWriter::getSelectorRef(Selector Sel) {
6687 if (Sel.getAsOpaquePtr() == nullptr) {
6688 return 0;
6689 }
6690
6691 SelectorID SID = SelectorIDs[Sel];
6692 if (SID == 0 && Chain) {
6693 // This might trigger a ReadSelector callback, which will set the ID for
6694 // this selector.
6695 Chain->LoadSelector(Sel);
6696 SID = SelectorIDs[Sel];
6697 }
6698 if (SID == 0) {
6699 SID = NextSelectorID++;
6700 SelectorIDs[Sel] = SID;
6701 }
6702 return SID;
6703}
6704
6705void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
6706 AddDeclRef(Temp->getDestructor());
6707}
6708
6709void ASTRecordWriter::AddTemplateArgumentLocInfo(
6710 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
6711 switch (Kind) {
6712 case TemplateArgument::Expression:
6713 AddStmt(Arg.getAsExpr());
6714 break;
6715 case TemplateArgument::Type:
6716 AddTypeSourceInfo(TInfo: Arg.getAsTypeSourceInfo());
6717 break;
6718 case TemplateArgument::Template:
6719 AddNestedNameSpecifierLoc(NNS: Arg.getTemplateQualifierLoc());
6720 AddSourceLocation(Loc: Arg.getTemplateNameLoc());
6721 break;
6722 case TemplateArgument::TemplateExpansion:
6723 AddNestedNameSpecifierLoc(NNS: Arg.getTemplateQualifierLoc());
6724 AddSourceLocation(Loc: Arg.getTemplateNameLoc());
6725 AddSourceLocation(Loc: Arg.getTemplateEllipsisLoc());
6726 break;
6727 case TemplateArgument::Null:
6728 case TemplateArgument::Integral:
6729 case TemplateArgument::Declaration:
6730 case TemplateArgument::NullPtr:
6731 case TemplateArgument::StructuralValue:
6732 case TemplateArgument::Pack:
6733 // FIXME: Is this right?
6734 break;
6735 }
6736}
6737
6738void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
6739 AddTemplateArgument(Arg: Arg.getArgument());
6740
6741 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
6742 bool InfoHasSameExpr
6743 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
6744 Record->push_back(Elt: InfoHasSameExpr);
6745 if (InfoHasSameExpr)
6746 return; // Avoid storing the same expr twice.
6747 }
6748 AddTemplateArgumentLocInfo(Kind: Arg.getArgument().getKind(), Arg: Arg.getLocInfo());
6749}
6750
6751void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
6752 if (!TInfo) {
6753 AddTypeRef(T: QualType());
6754 return;
6755 }
6756
6757 AddTypeRef(T: TInfo->getType());
6758 AddTypeLoc(TL: TInfo->getTypeLoc());
6759}
6760
6761void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) {
6762 LocSeq::State Seq(OuterSeq);
6763 TypeLocWriter TLW(*this, Seq);
6764 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6765 TLW.Visit(TyLoc: TL);
6766}
6767
6768void ASTWriter::AddTypeRef(ASTContext &Context, QualType T,
6769 RecordDataImpl &Record) {
6770 Record.push_back(Elt: GetOrCreateTypeID(Context, T));
6771}
6772
6773template <typename IdxForTypeTy>
6774static TypeID MakeTypeID(ASTContext &Context, QualType T,
6775 IdxForTypeTy IdxForType) {
6776 if (T.isNull())
6777 return PREDEF_TYPE_NULL_ID;
6778
6779 unsigned FastQuals = T.getLocalFastQualifiers();
6780 T.removeLocalFastQualifiers();
6781
6782 if (T.hasLocalNonFastQualifiers())
6783 return IdxForType(T).asTypeID(FastQuals);
6784
6785 assert(!T.hasLocalQualifiers());
6786
6787 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Val: T.getTypePtr()))
6788 return TypeIdxFromBuiltin(BT).asTypeID(FastQuals);
6789
6790 if (T == Context.AutoDeductTy)
6791 return TypeIdx(0, PREDEF_TYPE_AUTO_DEDUCT).asTypeID(FastQuals);
6792 if (T == Context.AutoRRefDeductTy)
6793 return TypeIdx(0, PREDEF_TYPE_AUTO_RREF_DEDUCT).asTypeID(FastQuals);
6794
6795 return IdxForType(T).asTypeID(FastQuals);
6796}
6797
6798TypeID ASTWriter::GetOrCreateTypeID(ASTContext &Context, QualType T) {
6799 return MakeTypeID(Context, T, IdxForType: [&](QualType T) -> TypeIdx {
6800 if (T.isNull())
6801 return TypeIdx();
6802 assert(!T.getLocalFastQualifiers());
6803
6804 TypeIdx &Idx = TypeIdxs[T];
6805 if (Idx.getValue() == 0) {
6806 if (DoneWritingDeclsAndTypes) {
6807 assert(0 && "New type seen after serializing all the types to emit!");
6808 return TypeIdx();
6809 }
6810
6811 // We haven't seen this type before. Assign it a new ID and put it
6812 // into the queue of types to emit.
6813 Idx = TypeIdx(0, NextTypeID++);
6814 DeclTypesToEmit.push(T);
6815 }
6816 return Idx;
6817 });
6818}
6819
6820void ASTWriter::AddEmittedDeclRef(const Decl *D, RecordDataImpl &Record) {
6821 if (!wasDeclEmitted(D))
6822 return;
6823
6824 AddDeclRef(D, Record);
6825}
6826
6827void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
6828 Record.push_back(Elt: GetDeclRef(D).getRawValue());
6829}
6830
6831LocalDeclID ASTWriter::GetDeclRef(const Decl *D) {
6832 assert(WritingAST && "Cannot request a declaration ID before AST writing");
6833
6834 if (!D) {
6835 return LocalDeclID();
6836 }
6837
6838 // If the DeclUpdate from the GMF gets touched, emit it.
6839 if (auto *Iter = DeclUpdatesFromGMF.find(Key: D);
6840 Iter != DeclUpdatesFromGMF.end()) {
6841 for (DeclUpdate &Update : Iter->second)
6842 DeclUpdates[D].push_back(Elt: Update);
6843 DeclUpdatesFromGMF.erase(Iterator: Iter);
6844 }
6845
6846 // If D comes from an AST file, its declaration ID is already known and
6847 // fixed.
6848 if (D->isFromASTFile()) {
6849 if (isWritingStdCXXNamedModules() && D->getOwningModule())
6850 TouchedTopLevelModules.insert(X: D->getOwningModule()->getTopLevelModule());
6851
6852 return LocalDeclID(D->getGlobalID());
6853 }
6854
6855 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
6856 LocalDeclID &ID = DeclIDs[D];
6857 if (ID.isInvalid()) {
6858 if (DoneWritingDeclsAndTypes) {
6859 assert(0 && "New decl seen after serializing all the decls to emit!");
6860 return LocalDeclID();
6861 }
6862
6863 // We haven't seen this declaration before. Give it a new ID and
6864 // enqueue it in the list of declarations to emit.
6865 ID = NextDeclID++;
6866 DeclTypesToEmit.push(x: const_cast<Decl *>(D));
6867 }
6868
6869 return ID;
6870}
6871
6872LocalDeclID ASTWriter::getDeclID(const Decl *D) {
6873 if (!D)
6874 return LocalDeclID();
6875
6876 // If D comes from an AST file, its declaration ID is already known and
6877 // fixed.
6878 if (D->isFromASTFile())
6879 return LocalDeclID(D->getGlobalID());
6880
6881 assert(DeclIDs.contains(D) && "Declaration not emitted!");
6882 return DeclIDs[D];
6883}
6884
6885bool ASTWriter::wasDeclEmitted(const Decl *D) const {
6886 assert(D);
6887
6888 assert(DoneWritingDeclsAndTypes &&
6889 "wasDeclEmitted should only be called after writing declarations");
6890
6891 if (D->isFromASTFile())
6892 return true;
6893
6894 bool Emitted = DeclIDs.contains(Val: D);
6895 assert((Emitted || (!D->getOwningModule() && isWritingStdCXXNamedModules()) ||
6896 GeneratingReducedBMI) &&
6897 "The declaration within modules can only be omitted in reduced BMI.");
6898 return Emitted;
6899}
6900
6901void ASTWriter::associateDeclWithFile(const Decl *D, LocalDeclID ID) {
6902 assert(ID.isValid());
6903 assert(D);
6904
6905 SourceLocation Loc = D->getLocation();
6906 if (Loc.isInvalid())
6907 return;
6908
6909 // We only keep track of the file-level declarations of each file.
6910 if (!D->getLexicalDeclContext()->isFileContext())
6911 return;
6912 // FIXME: ParmVarDecls that are part of a function type of a parameter of
6913 // a function/objc method, should not have TU as lexical context.
6914 // TemplateTemplateParmDecls that are part of an alias template, should not
6915 // have TU as lexical context.
6916 if (isa<ParmVarDecl, TemplateTemplateParmDecl>(Val: D))
6917 return;
6918
6919 SourceManager &SM = PP->getSourceManager();
6920 SourceLocation FileLoc = SM.getFileLoc(Loc);
6921 assert(SM.isLocalSourceLocation(FileLoc));
6922 FileID FID;
6923 unsigned Offset;
6924 std::tie(args&: FID, args&: Offset) = SM.getDecomposedLoc(Loc: FileLoc);
6925 if (FID.isInvalid())
6926 return;
6927 assert(SM.getSLocEntry(FID).isFile());
6928 assert(IsSLocAffecting[FID.ID]);
6929
6930 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
6931 if (!Info)
6932 Info = std::make_unique<DeclIDInFileInfo>();
6933
6934 std::pair<unsigned, LocalDeclID> LocDecl(Offset, ID);
6935 LocDeclIDsTy &Decls = Info->DeclIDs;
6936 Decls.push_back(Elt: LocDecl);
6937}
6938
6939unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
6940 assert(needsAnonymousDeclarationNumber(D) &&
6941 "expected an anonymous declaration");
6942
6943 // Number the anonymous declarations within this context, if we've not
6944 // already done so.
6945 auto It = AnonymousDeclarationNumbers.find(D);
6946 if (It == AnonymousDeclarationNumbers.end()) {
6947 auto *DC = D->getLexicalDeclContext();
6948 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
6949 AnonymousDeclarationNumbers[ND] = Number;
6950 });
6951
6952 It = AnonymousDeclarationNumbers.find(D);
6953 assert(It != AnonymousDeclarationNumbers.end() &&
6954 "declaration not found within its lexical context");
6955 }
6956
6957 return It->second;
6958}
6959
6960void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
6961 DeclarationName Name) {
6962 switch (Name.getNameKind()) {
6963 case DeclarationName::CXXConstructorName:
6964 case DeclarationName::CXXDestructorName:
6965 case DeclarationName::CXXConversionFunctionName:
6966 AddTypeSourceInfo(TInfo: DNLoc.getNamedTypeInfo());
6967 break;
6968
6969 case DeclarationName::CXXOperatorName:
6970 AddSourceRange(Range: DNLoc.getCXXOperatorNameRange());
6971 break;
6972
6973 case DeclarationName::CXXLiteralOperatorName:
6974 AddSourceLocation(Loc: DNLoc.getCXXLiteralOperatorNameLoc());
6975 break;
6976
6977 case DeclarationName::Identifier:
6978 case DeclarationName::ObjCZeroArgSelector:
6979 case DeclarationName::ObjCOneArgSelector:
6980 case DeclarationName::ObjCMultiArgSelector:
6981 case DeclarationName::CXXUsingDirective:
6982 case DeclarationName::CXXDeductionGuideName:
6983 break;
6984 }
6985}
6986
6987void ASTRecordWriter::AddDeclarationNameInfo(
6988 const DeclarationNameInfo &NameInfo) {
6989 AddDeclarationName(Name: NameInfo.getName());
6990 AddSourceLocation(Loc: NameInfo.getLoc());
6991 AddDeclarationNameLoc(DNLoc: NameInfo.getInfo(), Name: NameInfo.getName());
6992}
6993
6994void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
6995 AddNestedNameSpecifierLoc(NNS: Info.QualifierLoc);
6996 Record->push_back(Elt: Info.NumTemplParamLists);
6997 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
6998 AddTemplateParameterList(TemplateParams: Info.TemplParamLists[i]);
6999}
7000
7001void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
7002 // Nested name specifiers usually aren't too long. I think that 8 would
7003 // typically accommodate the vast majority.
7004 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
7005
7006 // Push each of the nested-name-specifiers's onto a stack for
7007 // serialization in reverse order.
7008 while (NNS) {
7009 NestedNames.push_back(Elt: NNS);
7010 NNS = NNS.getPrefix();
7011 }
7012
7013 Record->push_back(Elt: NestedNames.size());
7014 while(!NestedNames.empty()) {
7015 NNS = NestedNames.pop_back_val();
7016 NestedNameSpecifier::SpecifierKind Kind
7017 = NNS.getNestedNameSpecifier()->getKind();
7018 Record->push_back(Elt: Kind);
7019 switch (Kind) {
7020 case NestedNameSpecifier::Identifier:
7021 AddIdentifierRef(II: NNS.getNestedNameSpecifier()->getAsIdentifier());
7022 AddSourceRange(Range: NNS.getLocalSourceRange());
7023 break;
7024
7025 case NestedNameSpecifier::Namespace:
7026 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
7027 AddSourceRange(Range: NNS.getLocalSourceRange());
7028 break;
7029
7030 case NestedNameSpecifier::NamespaceAlias:
7031 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
7032 AddSourceRange(Range: NNS.getLocalSourceRange());
7033 break;
7034
7035 case NestedNameSpecifier::TypeSpec:
7036 AddTypeRef(T: NNS.getTypeLoc().getType());
7037 AddTypeLoc(TL: NNS.getTypeLoc());
7038 AddSourceLocation(Loc: NNS.getLocalSourceRange().getEnd());
7039 break;
7040
7041 case NestedNameSpecifier::Global:
7042 AddSourceLocation(Loc: NNS.getLocalSourceRange().getEnd());
7043 break;
7044
7045 case NestedNameSpecifier::Super:
7046 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
7047 AddSourceRange(Range: NNS.getLocalSourceRange());
7048 break;
7049 }
7050 }
7051}
7052
7053void ASTRecordWriter::AddTemplateParameterList(
7054 const TemplateParameterList *TemplateParams) {
7055 assert(TemplateParams && "No TemplateParams!");
7056 AddSourceLocation(Loc: TemplateParams->getTemplateLoc());
7057 AddSourceLocation(Loc: TemplateParams->getLAngleLoc());
7058 AddSourceLocation(Loc: TemplateParams->getRAngleLoc());
7059
7060 Record->push_back(Elt: TemplateParams->size());
7061 for (const auto &P : *TemplateParams)
7062 AddDeclRef(P);
7063 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
7064 Record->push_back(Elt: true);
7065 writeStmtRef(RequiresClause);
7066 } else {
7067 Record->push_back(Elt: false);
7068 }
7069}
7070
7071/// Emit a template argument list.
7072void ASTRecordWriter::AddTemplateArgumentList(
7073 const TemplateArgumentList *TemplateArgs) {
7074 assert(TemplateArgs && "No TemplateArgs!");
7075 Record->push_back(Elt: TemplateArgs->size());
7076 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
7077 AddTemplateArgument(Arg: TemplateArgs->get(Idx: i));
7078}
7079
7080void ASTRecordWriter::AddASTTemplateArgumentListInfo(
7081 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
7082 assert(ASTTemplArgList && "No ASTTemplArgList!");
7083 AddSourceLocation(Loc: ASTTemplArgList->LAngleLoc);
7084 AddSourceLocation(Loc: ASTTemplArgList->RAngleLoc);
7085 Record->push_back(Elt: ASTTemplArgList->NumTemplateArgs);
7086 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
7087 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
7088 AddTemplateArgumentLoc(Arg: TemplArgs[i]);
7089}
7090
7091void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
7092 Record->push_back(Elt: Set.size());
7093 for (ASTUnresolvedSet::const_iterator
7094 I = Set.begin(), E = Set.end(); I != E; ++I) {
7095 AddDeclRef(I.getDecl());
7096 Record->push_back(Elt: I.getAccess());
7097 }
7098}
7099
7100// FIXME: Move this out of the main ASTRecordWriter interface.
7101void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
7102 Record->push_back(Elt: Base.isVirtual());
7103 Record->push_back(Elt: Base.isBaseOfClass());
7104 Record->push_back(Elt: Base.getAccessSpecifierAsWritten());
7105 Record->push_back(Elt: Base.getInheritConstructors());
7106 AddTypeSourceInfo(TInfo: Base.getTypeSourceInfo());
7107 AddSourceRange(Range: Base.getSourceRange());
7108 AddSourceLocation(Loc: Base.isPackExpansion()? Base.getEllipsisLoc()
7109 : SourceLocation());
7110}
7111
7112static uint64_t EmitCXXBaseSpecifiers(ASTContext &Context, ASTWriter &W,
7113 ArrayRef<CXXBaseSpecifier> Bases) {
7114 ASTWriter::RecordData Record;
7115 ASTRecordWriter Writer(Context, W, Record);
7116 Writer.push_back(N: Bases.size());
7117
7118 for (auto &Base : Bases)
7119 Writer.AddCXXBaseSpecifier(Base);
7120
7121 return Writer.Emit(Code: serialization::DECL_CXX_BASE_SPECIFIERS);
7122}
7123
7124// FIXME: Move this out of the main ASTRecordWriter interface.
7125void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
7126 AddOffset(BitOffset: EmitCXXBaseSpecifiers(getASTContext(), *Writer, Bases));
7127}
7128
7129static uint64_t
7130EmitCXXCtorInitializers(ASTContext &Context, ASTWriter &W,
7131 ArrayRef<CXXCtorInitializer *> CtorInits) {
7132 ASTWriter::RecordData Record;
7133 ASTRecordWriter Writer(Context, W, Record);
7134 Writer.push_back(N: CtorInits.size());
7135
7136 for (auto *Init : CtorInits) {
7137 if (Init->isBaseInitializer()) {
7138 Writer.push_back(N: CTOR_INITIALIZER_BASE);
7139 Writer.AddTypeSourceInfo(TInfo: Init->getTypeSourceInfo());
7140 Writer.push_back(N: Init->isBaseVirtual());
7141 } else if (Init->isDelegatingInitializer()) {
7142 Writer.push_back(N: CTOR_INITIALIZER_DELEGATING);
7143 Writer.AddTypeSourceInfo(TInfo: Init->getTypeSourceInfo());
7144 } else if (Init->isMemberInitializer()){
7145 Writer.push_back(N: CTOR_INITIALIZER_MEMBER);
7146 Writer.AddDeclRef(Init->getMember());
7147 } else {
7148 Writer.push_back(N: CTOR_INITIALIZER_INDIRECT_MEMBER);
7149 Writer.AddDeclRef(Init->getIndirectMember());
7150 }
7151
7152 Writer.AddSourceLocation(Loc: Init->getMemberLocation());
7153 Writer.AddStmt(Init->getInit());
7154 Writer.AddSourceLocation(Loc: Init->getLParenLoc());
7155 Writer.AddSourceLocation(Loc: Init->getRParenLoc());
7156 Writer.push_back(N: Init->isWritten());
7157 if (Init->isWritten())
7158 Writer.push_back(N: Init->getSourceOrder());
7159 }
7160
7161 return Writer.Emit(Code: serialization::DECL_CXX_CTOR_INITIALIZERS);
7162}
7163
7164// FIXME: Move this out of the main ASTRecordWriter interface.
7165void ASTRecordWriter::AddCXXCtorInitializers(
7166 ArrayRef<CXXCtorInitializer *> CtorInits) {
7167 AddOffset(BitOffset: EmitCXXCtorInitializers(getASTContext(), *Writer, CtorInits));
7168}
7169
7170void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
7171 auto &Data = D->data();
7172
7173 Record->push_back(Elt: Data.IsLambda);
7174
7175 BitsPacker DefinitionBits;
7176
7177#define FIELD(Name, Width, Merge) \
7178 if (!DefinitionBits.canWriteNextNBits(Width)) { \
7179 Record->push_back(DefinitionBits); \
7180 DefinitionBits.reset(0); \
7181 } \
7182 DefinitionBits.addBits(Data.Name, Width);
7183
7184#include "clang/AST/CXXRecordDeclDefinitionBits.def"
7185#undef FIELD
7186
7187 Record->push_back(Elt: DefinitionBits);
7188
7189 // getODRHash will compute the ODRHash if it has not been previously
7190 // computed.
7191 Record->push_back(Elt: D->getODRHash());
7192
7193 bool ModulesCodegen =
7194 !D->isDependentType() &&
7195 D->getTemplateSpecializationKind() !=
7196 TSK_ExplicitInstantiationDeclaration &&
7197 (Writer->getLangOpts().ModulesDebugInfo || D->isInNamedModule());
7198 Record->push_back(Elt: ModulesCodegen);
7199 if (ModulesCodegen)
7200 Writer->AddDeclRef(D, Writer->ModularCodegenDecls);
7201
7202 // IsLambda bit is already saved.
7203
7204 AddUnresolvedSet(Set: Data.Conversions.get(C&: getASTContext()));
7205 Record->push_back(Elt: Data.ComputedVisibleConversions);
7206 if (Data.ComputedVisibleConversions)
7207 AddUnresolvedSet(Set: Data.VisibleConversions.get(C&: getASTContext()));
7208 // Data.Definition is the owning decl, no need to write it.
7209
7210 if (!Data.IsLambda) {
7211 Record->push_back(Elt: Data.NumBases);
7212 if (Data.NumBases > 0)
7213 AddCXXBaseSpecifiers(Bases: Data.bases());
7214
7215 // FIXME: Make VBases lazily computed when needed to avoid storing them.
7216 Record->push_back(Elt: Data.NumVBases);
7217 if (Data.NumVBases > 0)
7218 AddCXXBaseSpecifiers(Bases: Data.vbases());
7219
7220 AddDeclRef(D->getFirstFriend());
7221 } else {
7222 auto &Lambda = D->getLambdaData();
7223
7224 BitsPacker LambdaBits;
7225 LambdaBits.addBits(Value: Lambda.DependencyKind, /*Width=*/BitsWidth: 2);
7226 LambdaBits.addBit(Value: Lambda.IsGenericLambda);
7227 LambdaBits.addBits(Value: Lambda.CaptureDefault, /*Width=*/BitsWidth: 2);
7228 LambdaBits.addBits(Value: Lambda.NumCaptures, /*Width=*/BitsWidth: 15);
7229 LambdaBits.addBit(Value: Lambda.HasKnownInternalLinkage);
7230 Record->push_back(Elt: LambdaBits);
7231
7232 Record->push_back(Elt: Lambda.NumExplicitCaptures);
7233 Record->push_back(Elt: Lambda.ManglingNumber);
7234 Record->push_back(Elt: D->getDeviceLambdaManglingNumber());
7235 // The lambda context declaration and index within the context are provided
7236 // separately, so that they can be used for merging.
7237 AddTypeSourceInfo(TInfo: Lambda.MethodTyInfo);
7238 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
7239 const LambdaCapture &Capture = Lambda.Captures.front()[I];
7240 AddSourceLocation(Loc: Capture.getLocation());
7241
7242 BitsPacker CaptureBits;
7243 CaptureBits.addBit(Value: Capture.isImplicit());
7244 CaptureBits.addBits(Value: Capture.getCaptureKind(), /*Width=*/BitsWidth: 3);
7245 Record->push_back(Elt: CaptureBits);
7246
7247 switch (Capture.getCaptureKind()) {
7248 case LCK_StarThis:
7249 case LCK_This:
7250 case LCK_VLAType:
7251 break;
7252 case LCK_ByCopy:
7253 case LCK_ByRef:
7254 ValueDecl *Var =
7255 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
7256 AddDeclRef(Var);
7257 AddSourceLocation(Loc: Capture.isPackExpansion() ? Capture.getEllipsisLoc()
7258 : SourceLocation());
7259 break;
7260 }
7261 }
7262 }
7263}
7264
7265void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
7266 const Expr *Init = VD->getInit();
7267 if (!Init) {
7268 push_back(N: 0);
7269 return;
7270 }
7271
7272 uint64_t Val = 1;
7273 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
7274 Val |= (ES->HasConstantInitialization ? 2 : 0);
7275 Val |= (ES->HasConstantDestruction ? 4 : 0);
7276 APValue *Evaluated = VD->getEvaluatedValue();
7277 // If the evaluated result is constant, emit it.
7278 if (Evaluated && (Evaluated->isInt() || Evaluated->isFloat()))
7279 Val |= 8;
7280 }
7281 push_back(N: Val);
7282 if (Val & 8) {
7283 AddAPValue(Value: *VD->getEvaluatedValue());
7284 }
7285
7286 writeStmtRef(Init);
7287}
7288
7289void ASTWriter::ReaderInitialized(ASTReader *Reader) {
7290 assert(Reader && "Cannot remove chain");
7291 assert((!Chain || Chain == Reader) && "Cannot replace chain");
7292 assert(FirstDeclID == NextDeclID &&
7293 FirstTypeID == NextTypeID &&
7294 FirstIdentID == NextIdentID &&
7295 FirstMacroID == NextMacroID &&
7296 FirstSubmoduleID == NextSubmoduleID &&
7297 FirstSelectorID == NextSelectorID &&
7298 "Setting chain after writing has started.");
7299
7300 Chain = Reader;
7301
7302 // Note, this will get called multiple times, once one the reader starts up
7303 // and again each time it's done reading a PCH or module.
7304 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
7305 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
7306 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
7307 NextMacroID = FirstMacroID;
7308 NextSelectorID = FirstSelectorID;
7309 NextSubmoduleID = FirstSubmoduleID;
7310}
7311
7312void ASTWriter::IdentifierRead(IdentifierID ID, IdentifierInfo *II) {
7313 // Don't reuse Type ID from external modules for named modules. See the
7314 // comments in WriteASTCore for details.
7315 if (isWritingStdCXXNamedModules())
7316 return;
7317
7318 IdentifierID &StoredID = IdentifierIDs[II];
7319 unsigned OriginalModuleFileIndex = StoredID >> 32;
7320
7321 // Always keep the local identifier ID. See \p TypeRead() for more
7322 // information.
7323 if (OriginalModuleFileIndex == 0 && StoredID)
7324 return;
7325
7326 // Otherwise, keep the highest ID since the module file comes later has
7327 // higher module file indexes.
7328 if (ID > StoredID)
7329 StoredID = ID;
7330}
7331
7332void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
7333 // Always keep the highest ID. See \p TypeRead() for more information.
7334 MacroID &StoredID = MacroIDs[MI];
7335 if (ID > StoredID)
7336 StoredID = ID;
7337}
7338
7339void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
7340 // Don't reuse Type ID from external modules for named modules. See the
7341 // comments in WriteASTCore for details.
7342 if (isWritingStdCXXNamedModules())
7343 return;
7344
7345 // Always take the type index that comes in later module files.
7346 // This copes with an interesting
7347 // case for chained AST writing where we schedule writing the type and then,
7348 // later, deserialize the type from another AST. In this case, we want to
7349 // keep the entry from a later module so that we can properly write it out to
7350 // the AST file.
7351 TypeIdx &StoredIdx = TypeIdxs[T];
7352
7353 // Ignore it if the type comes from the current being written module file.
7354 // Since the current module file being written logically has the highest
7355 // index.
7356 unsigned ModuleFileIndex = StoredIdx.getModuleFileIndex();
7357 if (ModuleFileIndex == 0 && StoredIdx.getValue())
7358 return;
7359
7360 // Otherwise, keep the highest ID since the module file comes later has
7361 // higher module file indexes.
7362 if (Idx.getModuleFileIndex() >= StoredIdx.getModuleFileIndex())
7363 StoredIdx = Idx;
7364}
7365
7366void ASTWriter::PredefinedDeclBuilt(PredefinedDeclIDs ID, const Decl *D) {
7367 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
7368 DeclIDs[D] = LocalDeclID(ID);
7369 PredefinedDecls.insert(Ptr: D);
7370}
7371
7372void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
7373 // Always keep the highest ID. See \p TypeRead() for more information.
7374 SelectorID &StoredID = SelectorIDs[S];
7375 if (ID > StoredID)
7376 StoredID = ID;
7377}
7378
7379void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
7380 MacroDefinitionRecord *MD) {
7381 assert(!MacroDefinitions.contains(MD));
7382 MacroDefinitions[MD] = ID;
7383}
7384
7385void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
7386 assert(!SubmoduleIDs.contains(Mod));
7387 SubmoduleIDs[Mod] = ID;
7388}
7389
7390void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
7391 if (Chain && Chain->isProcessingUpdateRecords()) return;
7392 assert(D->isCompleteDefinition());
7393 assert(!WritingAST && "Already writing the AST!");
7394 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
7395 // We are interested when a PCH decl is modified.
7396 if (RD->isFromASTFile()) {
7397 // A forward reference was mutated into a definition. Rewrite it.
7398 // FIXME: This happens during template instantiation, should we
7399 // have created a new definition decl instead ?
7400 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
7401 "completed a tag from another module but not by instantiation?");
7402 DeclUpdates[RD].push_back(
7403 DeclUpdate(DeclUpdateKind::CXXInstantiatedClassDefinition));
7404 }
7405 }
7406}
7407
7408static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
7409 if (D->isFromASTFile())
7410 return true;
7411
7412 // The predefined __va_list_tag struct is imported if we imported any decls.
7413 // FIXME: This is a gross hack.
7414 return D == D->getASTContext().getVaListTagDecl();
7415}
7416
7417void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
7418 if (Chain && Chain->isProcessingUpdateRecords()) return;
7419 assert(DC->isLookupContext() &&
7420 "Should not add lookup results to non-lookup contexts!");
7421
7422 // TU is handled elsewhere.
7423 if (isa<TranslationUnitDecl>(Val: DC))
7424 return;
7425
7426 // Namespaces are handled elsewhere, except for template instantiations of
7427 // FunctionTemplateDecls in namespaces. We are interested in cases where the
7428 // local instantiations are added to an imported context. Only happens when
7429 // adding ADL lookup candidates, for example templated friends.
7430 if (isa<NamespaceDecl>(Val: DC) && D->getFriendObjectKind() == Decl::FOK_None &&
7431 !isa<FunctionTemplateDecl>(Val: D))
7432 return;
7433
7434 // We're only interested in cases where a local declaration is added to an
7435 // imported context.
7436 if (D->isFromASTFile() || !isImportedDeclContext(Chain, D: cast<Decl>(Val: DC)))
7437 return;
7438
7439 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
7440 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
7441 assert(!WritingAST && "Already writing the AST!");
7442 if (UpdatedDeclContexts.insert(X: DC) && !cast<Decl>(Val: DC)->isFromASTFile()) {
7443 // We're adding a visible declaration to a predefined decl context. Ensure
7444 // that we write out all of its lookup results so we don't get a nasty
7445 // surprise when we try to emit its lookup table.
7446 llvm::append_range(C&: DeclsToEmitEvenIfUnreferenced, R: DC->decls());
7447 }
7448 DeclsToEmitEvenIfUnreferenced.push_back(Elt: D);
7449}
7450
7451void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
7452 if (Chain && Chain->isProcessingUpdateRecords()) return;
7453 assert(D->isImplicit());
7454
7455 // We're only interested in cases where a local declaration is added to an
7456 // imported context.
7457 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
7458 return;
7459
7460 if (!isa<CXXMethodDecl>(Val: D))
7461 return;
7462
7463 // A decl coming from PCH was modified.
7464 assert(RD->isCompleteDefinition());
7465 assert(!WritingAST && "Already writing the AST!");
7466 DeclUpdates[RD].push_back(
7467 DeclUpdate(DeclUpdateKind::CXXAddedImplicitMember, D));
7468}
7469
7470void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
7471 if (Chain && Chain->isProcessingUpdateRecords()) return;
7472 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
7473 if (!Chain) return;
7474 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
7475 // If we don't already know the exception specification for this redecl
7476 // chain, add an update record for it.
7477 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(Val: D)
7478 ->getType()
7479 ->castAs<FunctionProtoType>()
7480 ->getExceptionSpecType()))
7481 DeclUpdates[D].push_back(Elt: DeclUpdateKind::CXXResolvedExceptionSpec);
7482 });
7483}
7484
7485void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
7486 if (Chain && Chain->isProcessingUpdateRecords()) return;
7487 assert(!WritingAST && "Already writing the AST!");
7488 if (!Chain) return;
7489 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
7490 DeclUpdates[D].push_back(
7491 Elt: DeclUpdate(DeclUpdateKind::CXXDeducedReturnType, ReturnType));
7492 });
7493}
7494
7495void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
7496 const FunctionDecl *Delete,
7497 Expr *ThisArg) {
7498 if (Chain && Chain->isProcessingUpdateRecords()) return;
7499 assert(!WritingAST && "Already writing the AST!");
7500 assert(Delete && "Not given an operator delete");
7501 if (!Chain) return;
7502 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
7503 DeclUpdates[D].push_back(
7504 Elt: DeclUpdate(DeclUpdateKind::CXXResolvedDtorDelete, Delete));
7505 });
7506}
7507
7508void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
7509 if (Chain && Chain->isProcessingUpdateRecords()) return;
7510 assert(!WritingAST && "Already writing the AST!");
7511 if (!D->isFromASTFile())
7512 return; // Declaration not imported from PCH.
7513
7514 // The function definition may not have a body due to parsing errors.
7515 if (!D->doesThisDeclarationHaveABody())
7516 return;
7517
7518 // Implicit function decl from a PCH was defined.
7519 DeclUpdates[D].push_back(
7520 DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
7521}
7522
7523void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
7524 if (Chain && Chain->isProcessingUpdateRecords()) return;
7525 assert(!WritingAST && "Already writing the AST!");
7526 if (!D->isFromASTFile())
7527 return;
7528
7529 DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::CXXAddedVarDefinition));
7530}
7531
7532void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
7533 if (Chain && Chain->isProcessingUpdateRecords()) return;
7534 assert(!WritingAST && "Already writing the AST!");
7535 if (!D->isFromASTFile())
7536 return;
7537
7538 // The function definition may not have a body due to parsing errors.
7539 if (!D->doesThisDeclarationHaveABody())
7540 return;
7541
7542 DeclUpdates[D].push_back(
7543 DeclUpdate(DeclUpdateKind::CXXAddedFunctionDefinition));
7544}
7545
7546void ASTWriter::InstantiationRequested(const ValueDecl *D) {
7547 if (Chain && Chain->isProcessingUpdateRecords()) return;
7548 assert(!WritingAST && "Already writing the AST!");
7549 if (!D->isFromASTFile())
7550 return;
7551
7552 // Since the actual instantiation is delayed, this really means that we need
7553 // to update the instantiation location.
7554 SourceLocation POI;
7555 if (auto *VD = dyn_cast<VarDecl>(Val: D))
7556 POI = VD->getPointOfInstantiation();
7557 else
7558 POI = cast<FunctionDecl>(Val: D)->getPointOfInstantiation();
7559 DeclUpdates[D].push_back(
7560 DeclUpdate(DeclUpdateKind::CXXPointOfInstantiation, POI));
7561}
7562
7563void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
7564 if (Chain && Chain->isProcessingUpdateRecords()) return;
7565 assert(!WritingAST && "Already writing the AST!");
7566 if (!D->isFromASTFile())
7567 return;
7568
7569 DeclUpdates[D].push_back(
7570 DeclUpdate(DeclUpdateKind::CXXInstantiatedDefaultArgument, D));
7571}
7572
7573void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
7574 assert(!WritingAST && "Already writing the AST!");
7575 if (!D->isFromASTFile())
7576 return;
7577
7578 DeclUpdates[D].push_back(
7579 DeclUpdate(DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer, D));
7580}
7581
7582void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
7583 const ObjCInterfaceDecl *IFD) {
7584 if (Chain && Chain->isProcessingUpdateRecords()) return;
7585 assert(!WritingAST && "Already writing the AST!");
7586 if (!IFD->isFromASTFile())
7587 return; // Declaration not imported from PCH.
7588
7589 assert(IFD->getDefinition() && "Category on a class without a definition?");
7590 ObjCClassesWithCategories.insert(
7591 X: const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
7592}
7593
7594void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
7595 if (Chain && Chain->isProcessingUpdateRecords()) return;
7596 assert(!WritingAST && "Already writing the AST!");
7597
7598 // If there is *any* declaration of the entity that's not from an AST file,
7599 // we can skip writing the update record. We make sure that isUsed() triggers
7600 // completion of the redeclaration chain of the entity.
7601 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
7602 if (IsLocalDecl(D: Prev))
7603 return;
7604
7605 DeclUpdates[D].push_back(Elt: DeclUpdate(DeclUpdateKind::DeclMarkedUsed));
7606}
7607
7608void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
7609 if (Chain && Chain->isProcessingUpdateRecords()) return;
7610 assert(!WritingAST && "Already writing the AST!");
7611 if (!D->isFromASTFile())
7612 return;
7613
7614 DeclUpdates[D].push_back(
7615 Elt: DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPThreadPrivate));
7616}
7617
7618void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
7619 if (Chain && Chain->isProcessingUpdateRecords()) return;
7620 assert(!WritingAST && "Already writing the AST!");
7621 if (!D->isFromASTFile())
7622 return;
7623
7624 DeclUpdates[D].push_back(
7625 Elt: DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPAllocate, A));
7626}
7627
7628void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
7629 const Attr *Attr) {
7630 if (Chain && Chain->isProcessingUpdateRecords()) return;
7631 assert(!WritingAST && "Already writing the AST!");
7632 if (!D->isFromASTFile())
7633 return;
7634
7635 DeclUpdates[D].push_back(
7636 Elt: DeclUpdate(DeclUpdateKind::DeclMarkedOpenMPDeclareTarget, Attr));
7637}
7638
7639void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
7640 if (Chain && Chain->isProcessingUpdateRecords()) return;
7641 assert(!WritingAST && "Already writing the AST!");
7642 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
7643 DeclUpdates[D].push_back(DeclUpdate(DeclUpdateKind::DeclExported, M));
7644}
7645
7646void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
7647 const RecordDecl *Record) {
7648 if (Chain && Chain->isProcessingUpdateRecords()) return;
7649 assert(!WritingAST && "Already writing the AST!");
7650 if (!Record->isFromASTFile())
7651 return;
7652 DeclUpdates[Record].push_back(
7653 DeclUpdate(DeclUpdateKind::AddedAttrToRecord, Attr));
7654}
7655
7656void ASTWriter::AddedCXXTemplateSpecialization(
7657 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
7658 assert(!WritingAST && "Already writing the AST!");
7659
7660 if (!TD->getFirstDecl()->isFromASTFile())
7661 return;
7662 if (Chain && Chain->isProcessingUpdateRecords())
7663 return;
7664
7665 DeclsToEmitEvenIfUnreferenced.push_back(D);
7666}
7667
7668void ASTWriter::AddedCXXTemplateSpecialization(
7669 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
7670 assert(!WritingAST && "Already writing the AST!");
7671
7672 if (!TD->getFirstDecl()->isFromASTFile())
7673 return;
7674 if (Chain && Chain->isProcessingUpdateRecords())
7675 return;
7676
7677 DeclsToEmitEvenIfUnreferenced.push_back(D);
7678}
7679
7680void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
7681 const FunctionDecl *D) {
7682 assert(!WritingAST && "Already writing the AST!");
7683
7684 if (!TD->getFirstDecl()->isFromASTFile())
7685 return;
7686 if (Chain && Chain->isProcessingUpdateRecords())
7687 return;
7688
7689 DeclsToEmitEvenIfUnreferenced.push_back(D);
7690}
7691
7692//===----------------------------------------------------------------------===//
7693//// OMPClause Serialization
7694////===----------------------------------------------------------------------===//
7695
7696namespace {
7697
7698class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
7699 ASTRecordWriter &Record;
7700
7701public:
7702 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
7703#define GEN_CLANG_CLAUSE_CLASS
7704#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
7705#include "llvm/Frontend/OpenMP/OMP.inc"
7706 void writeClause(OMPClause *C);
7707 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
7708 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
7709};
7710
7711}
7712
7713void ASTRecordWriter::writeOMPClause(OMPClause *C) {
7714 OMPClauseWriter(*this).writeClause(C);
7715}
7716
7717void OMPClauseWriter::writeClause(OMPClause *C) {
7718 Record.push_back(N: unsigned(C->getClauseKind()));
7719 Visit(C);
7720 Record.AddSourceLocation(Loc: C->getBeginLoc());
7721 Record.AddSourceLocation(Loc: C->getEndLoc());
7722}
7723
7724void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
7725 Record.push_back(N: uint64_t(C->getCaptureRegion()));
7726 Record.AddStmt(S: C->getPreInitStmt());
7727}
7728
7729void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
7730 VisitOMPClauseWithPreInit(C);
7731 Record.AddStmt(C->getPostUpdateExpr());
7732}
7733
7734void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
7735 VisitOMPClauseWithPreInit(C);
7736 Record.push_back(N: uint64_t(C->getNameModifier()));
7737 Record.AddSourceLocation(Loc: C->getNameModifierLoc());
7738 Record.AddSourceLocation(Loc: C->getColonLoc());
7739 Record.AddStmt(C->getCondition());
7740 Record.AddSourceLocation(Loc: C->getLParenLoc());
7741}
7742
7743void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
7744 VisitOMPClauseWithPreInit(C);
7745 Record.AddStmt(C->getCondition());
7746 Record.AddSourceLocation(Loc: C->getLParenLoc());
7747}
7748
7749void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
7750 VisitOMPClauseWithPreInit(C);
7751 Record.AddStmt(C->getNumThreads());
7752 Record.AddSourceLocation(Loc: C->getLParenLoc());
7753}
7754
7755void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
7756 Record.AddStmt(C->getSafelen());
7757 Record.AddSourceLocation(Loc: C->getLParenLoc());
7758}
7759
7760void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
7761 Record.AddStmt(C->getSimdlen());
7762 Record.AddSourceLocation(Loc: C->getLParenLoc());
7763}
7764
7765void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
7766 Record.push_back(N: C->getNumSizes());
7767 for (Expr *Size : C->getSizesRefs())
7768 Record.AddStmt(Size);
7769 Record.AddSourceLocation(Loc: C->getLParenLoc());
7770}
7771
7772void OMPClauseWriter::VisitOMPPermutationClause(OMPPermutationClause *C) {
7773 Record.push_back(N: C->getNumLoops());
7774 for (Expr *Size : C->getArgsRefs())
7775 Record.AddStmt(Size);
7776 Record.AddSourceLocation(Loc: C->getLParenLoc());
7777}
7778
7779void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
7780
7781void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
7782 Record.AddStmt(C->getFactor());
7783 Record.AddSourceLocation(Loc: C->getLParenLoc());
7784}
7785
7786void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
7787 Record.AddStmt(C->getAllocator());
7788 Record.AddSourceLocation(Loc: C->getLParenLoc());
7789}
7790
7791void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
7792 Record.AddStmt(C->getNumForLoops());
7793 Record.AddSourceLocation(Loc: C->getLParenLoc());
7794}
7795
7796void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
7797 Record.AddStmt(C->getEventHandler());
7798 Record.AddSourceLocation(Loc: C->getLParenLoc());
7799}
7800
7801void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
7802 Record.push_back(N: unsigned(C->getDefaultKind()));
7803 Record.AddSourceLocation(Loc: C->getLParenLoc());
7804 Record.AddSourceLocation(Loc: C->getDefaultKindKwLoc());
7805}
7806
7807void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
7808 Record.push_back(N: unsigned(C->getProcBindKind()));
7809 Record.AddSourceLocation(Loc: C->getLParenLoc());
7810 Record.AddSourceLocation(Loc: C->getProcBindKindKwLoc());
7811}
7812
7813void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
7814 VisitOMPClauseWithPreInit(C);
7815 Record.push_back(N: C->getScheduleKind());
7816 Record.push_back(N: C->getFirstScheduleModifier());
7817 Record.push_back(N: C->getSecondScheduleModifier());
7818 Record.AddStmt(C->getChunkSize());
7819 Record.AddSourceLocation(Loc: C->getLParenLoc());
7820 Record.AddSourceLocation(Loc: C->getFirstScheduleModifierLoc());
7821 Record.AddSourceLocation(Loc: C->getSecondScheduleModifierLoc());
7822 Record.AddSourceLocation(Loc: C->getScheduleKindLoc());
7823 Record.AddSourceLocation(Loc: C->getCommaLoc());
7824}
7825
7826void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
7827 Record.push_back(N: C->getLoopNumIterations().size());
7828 Record.AddStmt(C->getNumForLoops());
7829 for (Expr *NumIter : C->getLoopNumIterations())
7830 Record.AddStmt(NumIter);
7831 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
7832 Record.AddStmt(C->getLoopCounter(NumLoop: I));
7833 Record.AddSourceLocation(Loc: C->getLParenLoc());
7834}
7835
7836void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
7837
7838void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
7839
7840void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
7841
7842void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
7843
7844void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
7845
7846void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
7847 Record.push_back(N: C->isExtended() ? 1 : 0);
7848 if (C->isExtended()) {
7849 Record.AddSourceLocation(Loc: C->getLParenLoc());
7850 Record.AddSourceLocation(Loc: C->getArgumentLoc());
7851 Record.writeEnum(C->getDependencyKind());
7852 }
7853}
7854
7855void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
7856
7857void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
7858
7859// Save the parameter of fail clause.
7860void OMPClauseWriter::VisitOMPFailClause(OMPFailClause *C) {
7861 Record.AddSourceLocation(Loc: C->getLParenLoc());
7862 Record.AddSourceLocation(Loc: C->getFailParameterLoc());
7863 Record.writeEnum(C->getFailParameter());
7864}
7865
7866void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
7867
7868void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
7869
7870void OMPClauseWriter::VisitOMPAbsentClause(OMPAbsentClause *C) {
7871 Record.push_back(N: static_cast<uint64_t>(C->getDirectiveKinds().size()));
7872 Record.AddSourceLocation(Loc: C->getLParenLoc());
7873 for (auto K : C->getDirectiveKinds()) {
7874 Record.writeEnum(K);
7875 }
7876}
7877
7878void OMPClauseWriter::VisitOMPHoldsClause(OMPHoldsClause *C) {
7879 Record.AddStmt(C->getExpr());
7880 Record.AddSourceLocation(Loc: C->getLParenLoc());
7881}
7882
7883void OMPClauseWriter::VisitOMPContainsClause(OMPContainsClause *C) {
7884 Record.push_back(N: static_cast<uint64_t>(C->getDirectiveKinds().size()));
7885 Record.AddSourceLocation(Loc: C->getLParenLoc());
7886 for (auto K : C->getDirectiveKinds()) {
7887 Record.writeEnum(K);
7888 }
7889}
7890
7891void OMPClauseWriter::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
7892
7893void OMPClauseWriter::VisitOMPNoOpenMPRoutinesClause(
7894 OMPNoOpenMPRoutinesClause *) {}
7895
7896void OMPClauseWriter::VisitOMPNoOpenMPConstructsClause(
7897 OMPNoOpenMPConstructsClause *) {}
7898
7899void OMPClauseWriter::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
7900
7901void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
7902
7903void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
7904
7905void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
7906
7907void OMPClauseWriter::VisitOMPWeakClause(OMPWeakClause *) {}
7908
7909void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
7910
7911void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
7912
7913void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
7914
7915void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
7916 Record.push_back(N: C->varlist_size());
7917 for (Expr *VE : C->varlist())
7918 Record.AddStmt(VE);
7919 Record.writeBool(Value: C->getIsTarget());
7920 Record.writeBool(Value: C->getIsTargetSync());
7921 Record.AddSourceLocation(Loc: C->getLParenLoc());
7922 Record.AddSourceLocation(Loc: C->getVarLoc());
7923}
7924
7925void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
7926 Record.AddStmt(C->getInteropVar());
7927 Record.AddSourceLocation(Loc: C->getLParenLoc());
7928 Record.AddSourceLocation(Loc: C->getVarLoc());
7929}
7930
7931void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
7932 Record.AddStmt(C->getInteropVar());
7933 Record.AddSourceLocation(Loc: C->getLParenLoc());
7934 Record.AddSourceLocation(Loc: C->getVarLoc());
7935}
7936
7937void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
7938 VisitOMPClauseWithPreInit(C);
7939 Record.AddStmt(C->getCondition());
7940 Record.AddSourceLocation(Loc: C->getLParenLoc());
7941}
7942
7943void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
7944 VisitOMPClauseWithPreInit(C);
7945 Record.AddStmt(C->getCondition());
7946 Record.AddSourceLocation(Loc: C->getLParenLoc());
7947}
7948
7949void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
7950 VisitOMPClauseWithPreInit(C);
7951 Record.AddStmt(C->getThreadID());
7952 Record.AddSourceLocation(Loc: C->getLParenLoc());
7953}
7954
7955void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
7956 Record.AddStmt(C->getAlignment());
7957 Record.AddSourceLocation(Loc: C->getLParenLoc());
7958}
7959
7960void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
7961 Record.push_back(N: C->varlist_size());
7962 Record.AddSourceLocation(Loc: C->getLParenLoc());
7963 for (auto *VE : C->varlist()) {
7964 Record.AddStmt(VE);
7965 }
7966 for (auto *VE : C->private_copies()) {
7967 Record.AddStmt(VE);
7968 }
7969}
7970
7971void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
7972 Record.push_back(N: C->varlist_size());
7973 VisitOMPClauseWithPreInit(C);
7974 Record.AddSourceLocation(Loc: C->getLParenLoc());
7975 for (auto *VE : C->varlist()) {
7976 Record.AddStmt(VE);
7977 }
7978 for (auto *VE : C->private_copies()) {
7979 Record.AddStmt(VE);
7980 }
7981 for (auto *VE : C->inits()) {
7982 Record.AddStmt(VE);
7983 }
7984}
7985
7986void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
7987 Record.push_back(N: C->varlist_size());
7988 VisitOMPClauseWithPostUpdate(C);
7989 Record.AddSourceLocation(Loc: C->getLParenLoc());
7990 Record.writeEnum(C->getKind());
7991 Record.AddSourceLocation(Loc: C->getKindLoc());
7992 Record.AddSourceLocation(Loc: C->getColonLoc());
7993 for (auto *VE : C->varlist())
7994 Record.AddStmt(VE);
7995 for (auto *E : C->private_copies())
7996 Record.AddStmt(E);
7997 for (auto *E : C->source_exprs())
7998 Record.AddStmt(E);
7999 for (auto *E : C->destination_exprs())
8000 Record.AddStmt(E);
8001 for (auto *E : C->assignment_ops())
8002 Record.AddStmt(E);
8003}
8004
8005void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
8006 Record.push_back(N: C->varlist_size());
8007 Record.AddSourceLocation(Loc: C->getLParenLoc());
8008 for (auto *VE : C->varlist())
8009 Record.AddStmt(VE);
8010}
8011
8012void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
8013 Record.push_back(N: C->varlist_size());
8014 Record.writeEnum(C->getModifier());
8015 VisitOMPClauseWithPostUpdate(C);
8016 Record.AddSourceLocation(Loc: C->getLParenLoc());
8017 Record.AddSourceLocation(Loc: C->getModifierLoc());
8018 Record.AddSourceLocation(Loc: C->getColonLoc());
8019 Record.AddNestedNameSpecifierLoc(NNS: C->getQualifierLoc());
8020 Record.AddDeclarationNameInfo(NameInfo: C->getNameInfo());
8021 for (auto *VE : C->varlist())
8022 Record.AddStmt(VE);
8023 for (auto *VE : C->privates())
8024 Record.AddStmt(VE);
8025 for (auto *E : C->lhs_exprs())
8026 Record.AddStmt(E);
8027 for (auto *E : C->rhs_exprs())
8028 Record.AddStmt(E);
8029 for (auto *E : C->reduction_ops())
8030 Record.AddStmt(E);
8031 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
8032 for (auto *E : C->copy_ops())
8033 Record.AddStmt(E);
8034 for (auto *E : C->copy_array_temps())
8035 Record.AddStmt(E);
8036 for (auto *E : C->copy_array_elems())
8037 Record.AddStmt(E);
8038 }
8039 auto PrivateFlags = C->private_var_reduction_flags();
8040 Record.push_back(N: std::distance(first: PrivateFlags.begin(), last: PrivateFlags.end()));
8041 for (bool Flag : PrivateFlags)
8042 Record.push_back(N: Flag);
8043}
8044
8045void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
8046 Record.push_back(N: C->varlist_size());
8047 VisitOMPClauseWithPostUpdate(C);
8048 Record.AddSourceLocation(Loc: C->getLParenLoc());
8049 Record.AddSourceLocation(Loc: C->getColonLoc());
8050 Record.AddNestedNameSpecifierLoc(NNS: C->getQualifierLoc());
8051 Record.AddDeclarationNameInfo(NameInfo: C->getNameInfo());
8052 for (auto *VE : C->varlist())
8053 Record.AddStmt(VE);
8054 for (auto *VE : C->privates())
8055 Record.AddStmt(VE);
8056 for (auto *E : C->lhs_exprs())
8057 Record.AddStmt(E);
8058 for (auto *E : C->rhs_exprs())
8059 Record.AddStmt(E);
8060 for (auto *E : C->reduction_ops())
8061 Record.AddStmt(E);
8062}
8063
8064void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
8065 Record.push_back(N: C->varlist_size());
8066 VisitOMPClauseWithPostUpdate(C);
8067 Record.AddSourceLocation(Loc: C->getLParenLoc());
8068 Record.AddSourceLocation(Loc: C->getColonLoc());
8069 Record.AddNestedNameSpecifierLoc(NNS: C->getQualifierLoc());
8070 Record.AddDeclarationNameInfo(NameInfo: C->getNameInfo());
8071 for (auto *VE : C->varlist())
8072 Record.AddStmt(VE);
8073 for (auto *VE : C->privates())
8074 Record.AddStmt(VE);
8075 for (auto *E : C->lhs_exprs())
8076 Record.AddStmt(E);
8077 for (auto *E : C->rhs_exprs())
8078 Record.AddStmt(E);
8079 for (auto *E : C->reduction_ops())
8080 Record.AddStmt(E);
8081 for (auto *E : C->taskgroup_descriptors())
8082 Record.AddStmt(E);
8083}
8084
8085void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
8086 Record.push_back(N: C->varlist_size());
8087 VisitOMPClauseWithPostUpdate(C);
8088 Record.AddSourceLocation(Loc: C->getLParenLoc());
8089 Record.AddSourceLocation(Loc: C->getColonLoc());
8090 Record.push_back(N: C->getModifier());
8091 Record.AddSourceLocation(Loc: C->getModifierLoc());
8092 for (auto *VE : C->varlist()) {
8093 Record.AddStmt(VE);
8094 }
8095 for (auto *VE : C->privates()) {
8096 Record.AddStmt(VE);
8097 }
8098 for (auto *VE : C->inits()) {
8099 Record.AddStmt(VE);
8100 }
8101 for (auto *VE : C->updates()) {
8102 Record.AddStmt(VE);
8103 }
8104 for (auto *VE : C->finals()) {
8105 Record.AddStmt(VE);
8106 }
8107 Record.AddStmt(C->getStep());
8108 Record.AddStmt(C->getCalcStep());
8109 for (auto *VE : C->used_expressions())
8110 Record.AddStmt(VE);
8111}
8112
8113void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
8114 Record.push_back(N: C->varlist_size());
8115 Record.AddSourceLocation(Loc: C->getLParenLoc());
8116 Record.AddSourceLocation(Loc: C->getColonLoc());
8117 for (auto *VE : C->varlist())
8118 Record.AddStmt(VE);
8119 Record.AddStmt(C->getAlignment());
8120}
8121
8122void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
8123 Record.push_back(N: C->varlist_size());
8124 Record.AddSourceLocation(Loc: C->getLParenLoc());
8125 for (auto *VE : C->varlist())
8126 Record.AddStmt(VE);
8127 for (auto *E : C->source_exprs())
8128 Record.AddStmt(E);
8129 for (auto *E : C->destination_exprs())
8130 Record.AddStmt(E);
8131 for (auto *E : C->assignment_ops())
8132 Record.AddStmt(E);
8133}
8134
8135void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
8136 Record.push_back(N: C->varlist_size());
8137 Record.AddSourceLocation(Loc: C->getLParenLoc());
8138 for (auto *VE : C->varlist())
8139 Record.AddStmt(VE);
8140 for (auto *E : C->source_exprs())
8141 Record.AddStmt(E);
8142 for (auto *E : C->destination_exprs())
8143 Record.AddStmt(E);
8144 for (auto *E : C->assignment_ops())
8145 Record.AddStmt(E);
8146}
8147
8148void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
8149 Record.push_back(N: C->varlist_size());
8150 Record.AddSourceLocation(Loc: C->getLParenLoc());
8151 for (auto *VE : C->varlist())
8152 Record.AddStmt(VE);
8153}
8154
8155void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
8156 Record.AddStmt(C->getDepobj());
8157 Record.AddSourceLocation(Loc: C->getLParenLoc());
8158}
8159
8160void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
8161 Record.push_back(N: C->varlist_size());
8162 Record.push_back(N: C->getNumLoops());
8163 Record.AddSourceLocation(Loc: C->getLParenLoc());
8164 Record.AddStmt(C->getModifier());
8165 Record.push_back(N: C->getDependencyKind());
8166 Record.AddSourceLocation(Loc: C->getDependencyLoc());
8167 Record.AddSourceLocation(Loc: C->getColonLoc());
8168 Record.AddSourceLocation(Loc: C->getOmpAllMemoryLoc());
8169 for (auto *VE : C->varlist())
8170 Record.AddStmt(VE);
8171 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
8172 Record.AddStmt(C->getLoopData(NumLoop: I));
8173}
8174
8175void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
8176 VisitOMPClauseWithPreInit(C);
8177 Record.writeEnum(C->getModifier());
8178 Record.AddStmt(C->getDevice());
8179 Record.AddSourceLocation(Loc: C->getModifierLoc());
8180 Record.AddSourceLocation(Loc: C->getLParenLoc());
8181}
8182
8183void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
8184 Record.push_back(N: C->varlist_size());
8185 Record.push_back(N: C->getUniqueDeclarationsNum());
8186 Record.push_back(N: C->getTotalComponentListNum());
8187 Record.push_back(N: C->getTotalComponentsNum());
8188 Record.AddSourceLocation(Loc: C->getLParenLoc());
8189 bool HasIteratorModifier = false;
8190 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
8191 Record.push_back(N: C->getMapTypeModifier(Cnt: I));
8192 Record.AddSourceLocation(Loc: C->getMapTypeModifierLoc(Cnt: I));
8193 if (C->getMapTypeModifier(Cnt: I) == OMPC_MAP_MODIFIER_iterator)
8194 HasIteratorModifier = true;
8195 }
8196 Record.AddNestedNameSpecifierLoc(NNS: C->getMapperQualifierLoc());
8197 Record.AddDeclarationNameInfo(NameInfo: C->getMapperIdInfo());
8198 Record.push_back(N: C->getMapType());
8199 Record.AddSourceLocation(Loc: C->getMapLoc());
8200 Record.AddSourceLocation(Loc: C->getColonLoc());
8201 for (auto *E : C->varlist())
8202 Record.AddStmt(E);
8203 for (auto *E : C->mapperlists())
8204 Record.AddStmt(E);
8205 if (HasIteratorModifier)
8206 Record.AddStmt(C->getIteratorModifier());
8207 for (auto *D : C->all_decls())
8208 Record.AddDeclRef(D);
8209 for (auto N : C->all_num_lists())
8210 Record.push_back(N);
8211 for (auto N : C->all_lists_sizes())
8212 Record.push_back(N);
8213 for (auto &M : C->all_components()) {
8214 Record.AddStmt(M.getAssociatedExpression());
8215 Record.AddDeclRef(M.getAssociatedDeclaration());
8216 }
8217}
8218
8219void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
8220 Record.push_back(N: C->varlist_size());
8221 Record.writeEnum(C->getFirstAllocateModifier());
8222 Record.writeEnum(C->getSecondAllocateModifier());
8223 Record.AddSourceLocation(Loc: C->getLParenLoc());
8224 Record.AddSourceLocation(Loc: C->getColonLoc());
8225 Record.AddStmt(C->getAllocator());
8226 Record.AddStmt(C->getAlignment());
8227 for (auto *VE : C->varlist())
8228 Record.AddStmt(VE);
8229}
8230
8231void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
8232 Record.push_back(N: C->varlist_size());
8233 VisitOMPClauseWithPreInit(C);
8234 Record.AddSourceLocation(Loc: C->getLParenLoc());
8235 for (auto *VE : C->varlist())
8236 Record.AddStmt(VE);
8237}
8238
8239void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
8240 Record.push_back(N: C->varlist_size());
8241 VisitOMPClauseWithPreInit(C);
8242 Record.AddSourceLocation(Loc: C->getLParenLoc());
8243 for (auto *VE : C->varlist())
8244 Record.AddStmt(VE);
8245}
8246
8247void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
8248 VisitOMPClauseWithPreInit(C);
8249 Record.AddStmt(C->getPriority());
8250 Record.AddSourceLocation(Loc: C->getLParenLoc());
8251}
8252
8253void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
8254 VisitOMPClauseWithPreInit(C);
8255 Record.writeEnum(C->getModifier());
8256 Record.AddStmt(C->getGrainsize());
8257 Record.AddSourceLocation(Loc: C->getModifierLoc());
8258 Record.AddSourceLocation(Loc: C->getLParenLoc());
8259}
8260
8261void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
8262 VisitOMPClauseWithPreInit(C);
8263 Record.writeEnum(C->getModifier());
8264 Record.AddStmt(C->getNumTasks());
8265 Record.AddSourceLocation(Loc: C->getModifierLoc());
8266 Record.AddSourceLocation(Loc: C->getLParenLoc());
8267}
8268
8269void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
8270 Record.AddStmt(C->getHint());
8271 Record.AddSourceLocation(Loc: C->getLParenLoc());
8272}
8273
8274void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
8275 VisitOMPClauseWithPreInit(C);
8276 Record.push_back(N: C->getDistScheduleKind());
8277 Record.AddStmt(C->getChunkSize());
8278 Record.AddSourceLocation(Loc: C->getLParenLoc());
8279 Record.AddSourceLocation(Loc: C->getDistScheduleKindLoc());
8280 Record.AddSourceLocation(Loc: C->getCommaLoc());
8281}
8282
8283void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
8284 Record.push_back(N: C->getDefaultmapKind());
8285 Record.push_back(N: C->getDefaultmapModifier());
8286 Record.AddSourceLocation(Loc: C->getLParenLoc());
8287 Record.AddSourceLocation(Loc: C->getDefaultmapModifierLoc());
8288 Record.AddSourceLocation(Loc: C->getDefaultmapKindLoc());
8289}
8290
8291void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
8292 Record.push_back(N: C->varlist_size());
8293 Record.push_back(N: C->getUniqueDeclarationsNum());
8294 Record.push_back(N: C->getTotalComponentListNum());
8295 Record.push_back(N: C->getTotalComponentsNum());
8296 Record.AddSourceLocation(Loc: C->getLParenLoc());
8297 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
8298 Record.push_back(N: C->getMotionModifier(Cnt: I));
8299 Record.AddSourceLocation(Loc: C->getMotionModifierLoc(Cnt: I));
8300 }
8301 Record.AddNestedNameSpecifierLoc(NNS: C->getMapperQualifierLoc());
8302 Record.AddDeclarationNameInfo(NameInfo: C->getMapperIdInfo());
8303 Record.AddSourceLocation(Loc: C->getColonLoc());
8304 for (auto *E : C->varlist())
8305 Record.AddStmt(E);
8306 for (auto *E : C->mapperlists())
8307 Record.AddStmt(E);
8308 for (auto *D : C->all_decls())
8309 Record.AddDeclRef(D);
8310 for (auto N : C->all_num_lists())
8311 Record.push_back(N);
8312 for (auto N : C->all_lists_sizes())
8313 Record.push_back(N);
8314 for (auto &M : C->all_components()) {
8315 Record.AddStmt(M.getAssociatedExpression());
8316 Record.writeBool(M.isNonContiguous());
8317 Record.AddDeclRef(M.getAssociatedDeclaration());
8318 }
8319}
8320
8321void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
8322 Record.push_back(N: C->varlist_size());
8323 Record.push_back(N: C->getUniqueDeclarationsNum());
8324 Record.push_back(N: C->getTotalComponentListNum());
8325 Record.push_back(N: C->getTotalComponentsNum());
8326 Record.AddSourceLocation(Loc: C->getLParenLoc());
8327 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
8328 Record.push_back(N: C->getMotionModifier(Cnt: I));
8329 Record.AddSourceLocation(Loc: C->getMotionModifierLoc(Cnt: I));
8330 }
8331 Record.AddNestedNameSpecifierLoc(NNS: C->getMapperQualifierLoc());
8332 Record.AddDeclarationNameInfo(NameInfo: C->getMapperIdInfo());
8333 Record.AddSourceLocation(Loc: C->getColonLoc());
8334 for (auto *E : C->varlist())
8335 Record.AddStmt(E);
8336 for (auto *E : C->mapperlists())
8337 Record.AddStmt(E);
8338 for (auto *D : C->all_decls())
8339 Record.AddDeclRef(D);
8340 for (auto N : C->all_num_lists())
8341 Record.push_back(N);
8342 for (auto N : C->all_lists_sizes())
8343 Record.push_back(N);
8344 for (auto &M : C->all_components()) {
8345 Record.AddStmt(M.getAssociatedExpression());
8346 Record.writeBool(M.isNonContiguous());
8347 Record.AddDeclRef(M.getAssociatedDeclaration());
8348 }
8349}
8350
8351void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
8352 Record.push_back(N: C->varlist_size());
8353 Record.push_back(N: C->getUniqueDeclarationsNum());
8354 Record.push_back(N: C->getTotalComponentListNum());
8355 Record.push_back(N: C->getTotalComponentsNum());
8356 Record.AddSourceLocation(Loc: C->getLParenLoc());
8357 for (auto *E : C->varlist())
8358 Record.AddStmt(E);
8359 for (auto *VE : C->private_copies())
8360 Record.AddStmt(VE);
8361 for (auto *VE : C->inits())
8362 Record.AddStmt(VE);
8363 for (auto *D : C->all_decls())
8364 Record.AddDeclRef(D);
8365 for (auto N : C->all_num_lists())
8366 Record.push_back(N);
8367 for (auto N : C->all_lists_sizes())
8368 Record.push_back(N);
8369 for (auto &M : C->all_components()) {
8370 Record.AddStmt(M.getAssociatedExpression());
8371 Record.AddDeclRef(M.getAssociatedDeclaration());
8372 }
8373}
8374
8375void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
8376 Record.push_back(N: C->varlist_size());
8377 Record.push_back(N: C->getUniqueDeclarationsNum());
8378 Record.push_back(N: C->getTotalComponentListNum());
8379 Record.push_back(N: C->getTotalComponentsNum());
8380 Record.AddSourceLocation(Loc: C->getLParenLoc());
8381 for (auto *E : C->varlist())
8382 Record.AddStmt(E);
8383 for (auto *D : C->all_decls())
8384 Record.AddDeclRef(D);
8385 for (auto N : C->all_num_lists())
8386 Record.push_back(N);
8387 for (auto N : C->all_lists_sizes())
8388 Record.push_back(N);
8389 for (auto &M : C->all_components()) {
8390 Record.AddStmt(M.getAssociatedExpression());
8391 Record.AddDeclRef(M.getAssociatedDeclaration());
8392 }
8393}
8394
8395void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8396 Record.push_back(N: C->varlist_size());
8397 Record.push_back(N: C->getUniqueDeclarationsNum());
8398 Record.push_back(N: C->getTotalComponentListNum());
8399 Record.push_back(N: C->getTotalComponentsNum());
8400 Record.AddSourceLocation(Loc: C->getLParenLoc());
8401 for (auto *E : C->varlist())
8402 Record.AddStmt(E);
8403 for (auto *D : C->all_decls())
8404 Record.AddDeclRef(D);
8405 for (auto N : C->all_num_lists())
8406 Record.push_back(N);
8407 for (auto N : C->all_lists_sizes())
8408 Record.push_back(N);
8409 for (auto &M : C->all_components()) {
8410 Record.AddStmt(M.getAssociatedExpression());
8411 Record.AddDeclRef(M.getAssociatedDeclaration());
8412 }
8413}
8414
8415void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
8416 Record.push_back(N: C->varlist_size());
8417 Record.push_back(N: C->getUniqueDeclarationsNum());
8418 Record.push_back(N: C->getTotalComponentListNum());
8419 Record.push_back(N: C->getTotalComponentsNum());
8420 Record.AddSourceLocation(Loc: C->getLParenLoc());
8421 for (auto *E : C->varlist())
8422 Record.AddStmt(E);
8423 for (auto *D : C->all_decls())
8424 Record.AddDeclRef(D);
8425 for (auto N : C->all_num_lists())
8426 Record.push_back(N);
8427 for (auto N : C->all_lists_sizes())
8428 Record.push_back(N);
8429 for (auto &M : C->all_components()) {
8430 Record.AddStmt(M.getAssociatedExpression());
8431 Record.AddDeclRef(M.getAssociatedDeclaration());
8432 }
8433}
8434
8435void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
8436
8437void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
8438 OMPUnifiedSharedMemoryClause *) {}
8439
8440void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
8441
8442void
8443OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
8444}
8445
8446void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
8447 OMPAtomicDefaultMemOrderClause *C) {
8448 Record.push_back(N: C->getAtomicDefaultMemOrderKind());
8449 Record.AddSourceLocation(Loc: C->getLParenLoc());
8450 Record.AddSourceLocation(Loc: C->getAtomicDefaultMemOrderKindKwLoc());
8451}
8452
8453void OMPClauseWriter::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
8454
8455void OMPClauseWriter::VisitOMPAtClause(OMPAtClause *C) {
8456 Record.push_back(N: C->getAtKind());
8457 Record.AddSourceLocation(Loc: C->getLParenLoc());
8458 Record.AddSourceLocation(Loc: C->getAtKindKwLoc());
8459}
8460
8461void OMPClauseWriter::VisitOMPSeverityClause(OMPSeverityClause *C) {
8462 Record.push_back(N: C->getSeverityKind());
8463 Record.AddSourceLocation(Loc: C->getLParenLoc());
8464 Record.AddSourceLocation(Loc: C->getSeverityKindKwLoc());
8465}
8466
8467void OMPClauseWriter::VisitOMPMessageClause(OMPMessageClause *C) {
8468 Record.AddStmt(C->getMessageString());
8469 Record.AddSourceLocation(Loc: C->getLParenLoc());
8470}
8471
8472void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
8473 Record.push_back(N: C->varlist_size());
8474 Record.AddSourceLocation(Loc: C->getLParenLoc());
8475 for (auto *VE : C->varlist())
8476 Record.AddStmt(VE);
8477 for (auto *E : C->private_refs())
8478 Record.AddStmt(E);
8479}
8480
8481void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
8482 Record.push_back(N: C->varlist_size());
8483 Record.AddSourceLocation(Loc: C->getLParenLoc());
8484 for (auto *VE : C->varlist())
8485 Record.AddStmt(VE);
8486}
8487
8488void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
8489 Record.push_back(N: C->varlist_size());
8490 Record.AddSourceLocation(Loc: C->getLParenLoc());
8491 for (auto *VE : C->varlist())
8492 Record.AddStmt(VE);
8493}
8494
8495void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
8496 Record.writeEnum(C->getKind());
8497 Record.writeEnum(C->getModifier());
8498 Record.AddSourceLocation(Loc: C->getLParenLoc());
8499 Record.AddSourceLocation(Loc: C->getKindKwLoc());
8500 Record.AddSourceLocation(Loc: C->getModifierKwLoc());
8501}
8502
8503void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
8504 Record.push_back(N: C->getNumberOfAllocators());
8505 Record.AddSourceLocation(Loc: C->getLParenLoc());
8506 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
8507 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
8508 Record.AddStmt(Data.Allocator);
8509 Record.AddStmt(Data.AllocatorTraits);
8510 Record.AddSourceLocation(Loc: Data.LParenLoc);
8511 Record.AddSourceLocation(Loc: Data.RParenLoc);
8512 }
8513}
8514
8515void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
8516 Record.push_back(N: C->varlist_size());
8517 Record.AddSourceLocation(Loc: C->getLParenLoc());
8518 Record.AddStmt(C->getModifier());
8519 Record.AddSourceLocation(Loc: C->getColonLoc());
8520 for (Expr *E : C->varlist())
8521 Record.AddStmt(E);
8522}
8523
8524void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
8525 Record.writeEnum(C->getBindKind());
8526 Record.AddSourceLocation(Loc: C->getLParenLoc());
8527 Record.AddSourceLocation(Loc: C->getBindKindLoc());
8528}
8529
8530void OMPClauseWriter::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
8531 VisitOMPClauseWithPreInit(C);
8532 Record.AddStmt(C->getSize());
8533 Record.AddSourceLocation(Loc: C->getLParenLoc());
8534}
8535
8536void OMPClauseWriter::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
8537 Record.push_back(N: C->varlist_size());
8538 Record.push_back(N: C->getNumLoops());
8539 Record.AddSourceLocation(Loc: C->getLParenLoc());
8540 Record.push_back(N: C->getDependenceType());
8541 Record.AddSourceLocation(Loc: C->getDependenceLoc());
8542 Record.AddSourceLocation(Loc: C->getColonLoc());
8543 for (auto *VE : C->varlist())
8544 Record.AddStmt(VE);
8545 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
8546 Record.AddStmt(C->getLoopData(NumLoop: I));
8547}
8548
8549void OMPClauseWriter::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
8550 Record.AddAttributes(Attrs: C->getAttrs());
8551 Record.AddSourceLocation(Loc: C->getBeginLoc());
8552 Record.AddSourceLocation(Loc: C->getLParenLoc());
8553 Record.AddSourceLocation(Loc: C->getEndLoc());
8554}
8555
8556void OMPClauseWriter::VisitOMPXBareClause(OMPXBareClause *C) {}
8557
8558void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
8559 writeUInt32(Value: TI->Sets.size());
8560 for (const auto &Set : TI->Sets) {
8561 writeEnum(Set.Kind);
8562 writeUInt32(Set.Selectors.size());
8563 for (const auto &Selector : Set.Selectors) {
8564 writeEnum(Selector.Kind);
8565 writeBool(Selector.ScoreOrCondition);
8566 if (Selector.ScoreOrCondition)
8567 writeExprRef(Selector.ScoreOrCondition);
8568 writeUInt32(Selector.Properties.size());
8569 for (const auto &Property : Selector.Properties)
8570 writeEnum(Property.Kind);
8571 }
8572 }
8573}
8574
8575void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) {
8576 if (!Data)
8577 return;
8578 writeUInt32(Value: Data->getNumClauses());
8579 writeUInt32(Value: Data->getNumChildren());
8580 writeBool(Value: Data->hasAssociatedStmt());
8581 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
8582 writeOMPClause(C: Data->getClauses()[I]);
8583 if (Data->hasAssociatedStmt())
8584 AddStmt(S: Data->getAssociatedStmt());
8585 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
8586 AddStmt(S: Data->getChildren()[I]);
8587}
8588
8589void ASTRecordWriter::writeOpenACCVarList(const OpenACCClauseWithVarList *C) {
8590 writeUInt32(Value: C->getVarList().size());
8591 for (Expr *E : C->getVarList())
8592 AddStmt(E);
8593}
8594
8595void ASTRecordWriter::writeOpenACCIntExprList(ArrayRef<Expr *> Exprs) {
8596 writeUInt32(Value: Exprs.size());
8597 for (Expr *E : Exprs)
8598 AddStmt(E);
8599}
8600
8601void ASTRecordWriter::writeOpenACCClause(const OpenACCClause *C) {
8602 writeEnum(C->getClauseKind());
8603 writeSourceLocation(Loc: C->getBeginLoc());
8604 writeSourceLocation(Loc: C->getEndLoc());
8605
8606 switch (C->getClauseKind()) {
8607 case OpenACCClauseKind::Default: {
8608 const auto *DC = cast<OpenACCDefaultClause>(Val: C);
8609 writeSourceLocation(Loc: DC->getLParenLoc());
8610 writeEnum(DC->getDefaultClauseKind());
8611 return;
8612 }
8613 case OpenACCClauseKind::If: {
8614 const auto *IC = cast<OpenACCIfClause>(Val: C);
8615 writeSourceLocation(Loc: IC->getLParenLoc());
8616 AddStmt(const_cast<Expr*>(IC->getConditionExpr()));
8617 return;
8618 }
8619 case OpenACCClauseKind::Self: {
8620 const auto *SC = cast<OpenACCSelfClause>(Val: C);
8621 writeSourceLocation(Loc: SC->getLParenLoc());
8622 writeBool(Value: SC->isConditionExprClause());
8623 if (SC->isConditionExprClause()) {
8624 writeBool(Value: SC->hasConditionExpr());
8625 if (SC->hasConditionExpr())
8626 AddStmt(const_cast<Expr *>(SC->getConditionExpr()));
8627 } else {
8628 writeUInt32(Value: SC->getVarList().size());
8629 for (Expr *E : SC->getVarList())
8630 AddStmt(E);
8631 }
8632 return;
8633 }
8634 case OpenACCClauseKind::NumGangs: {
8635 const auto *NGC = cast<OpenACCNumGangsClause>(Val: C);
8636 writeSourceLocation(Loc: NGC->getLParenLoc());
8637 writeUInt32(Value: NGC->getIntExprs().size());
8638 for (Expr *E : NGC->getIntExprs())
8639 AddStmt(E);
8640 return;
8641 }
8642 case OpenACCClauseKind::DeviceNum: {
8643 const auto *DNC = cast<OpenACCDeviceNumClause>(Val: C);
8644 writeSourceLocation(Loc: DNC->getLParenLoc());
8645 AddStmt(const_cast<Expr*>(DNC->getIntExpr()));
8646 return;
8647 }
8648 case OpenACCClauseKind::DefaultAsync: {
8649 const auto *DAC = cast<OpenACCDefaultAsyncClause>(Val: C);
8650 writeSourceLocation(Loc: DAC->getLParenLoc());
8651 AddStmt(const_cast<Expr *>(DAC->getIntExpr()));
8652 return;
8653 }
8654 case OpenACCClauseKind::NumWorkers: {
8655 const auto *NWC = cast<OpenACCNumWorkersClause>(Val: C);
8656 writeSourceLocation(Loc: NWC->getLParenLoc());
8657 AddStmt(const_cast<Expr*>(NWC->getIntExpr()));
8658 return;
8659 }
8660 case OpenACCClauseKind::VectorLength: {
8661 const auto *NWC = cast<OpenACCVectorLengthClause>(Val: C);
8662 writeSourceLocation(Loc: NWC->getLParenLoc());
8663 AddStmt(const_cast<Expr*>(NWC->getIntExpr()));
8664 return;
8665 }
8666 case OpenACCClauseKind::Private: {
8667 const auto *PC = cast<OpenACCPrivateClause>(Val: C);
8668 writeSourceLocation(Loc: PC->getLParenLoc());
8669 writeOpenACCVarList(C: PC);
8670 return;
8671 }
8672 case OpenACCClauseKind::Host: {
8673 const auto *HC = cast<OpenACCHostClause>(Val: C);
8674 writeSourceLocation(Loc: HC->getLParenLoc());
8675 writeOpenACCVarList(C: HC);
8676 return;
8677 }
8678 case OpenACCClauseKind::Device: {
8679 const auto *DC = cast<OpenACCDeviceClause>(Val: C);
8680 writeSourceLocation(Loc: DC->getLParenLoc());
8681 writeOpenACCVarList(C: DC);
8682 return;
8683 }
8684 case OpenACCClauseKind::FirstPrivate: {
8685 const auto *FPC = cast<OpenACCFirstPrivateClause>(Val: C);
8686 writeSourceLocation(Loc: FPC->getLParenLoc());
8687 writeOpenACCVarList(C: FPC);
8688 return;
8689 }
8690 case OpenACCClauseKind::Attach: {
8691 const auto *AC = cast<OpenACCAttachClause>(Val: C);
8692 writeSourceLocation(Loc: AC->getLParenLoc());
8693 writeOpenACCVarList(C: AC);
8694 return;
8695 }
8696 case OpenACCClauseKind::Detach: {
8697 const auto *DC = cast<OpenACCDetachClause>(Val: C);
8698 writeSourceLocation(Loc: DC->getLParenLoc());
8699 writeOpenACCVarList(C: DC);
8700 return;
8701 }
8702 case OpenACCClauseKind::Delete: {
8703 const auto *DC = cast<OpenACCDeleteClause>(Val: C);
8704 writeSourceLocation(Loc: DC->getLParenLoc());
8705 writeOpenACCVarList(C: DC);
8706 return;
8707 }
8708 case OpenACCClauseKind::UseDevice: {
8709 const auto *UDC = cast<OpenACCUseDeviceClause>(Val: C);
8710 writeSourceLocation(Loc: UDC->getLParenLoc());
8711 writeOpenACCVarList(C: UDC);
8712 return;
8713 }
8714 case OpenACCClauseKind::DevicePtr: {
8715 const auto *DPC = cast<OpenACCDevicePtrClause>(Val: C);
8716 writeSourceLocation(Loc: DPC->getLParenLoc());
8717 writeOpenACCVarList(C: DPC);
8718 return;
8719 }
8720 case OpenACCClauseKind::NoCreate: {
8721 const auto *NCC = cast<OpenACCNoCreateClause>(Val: C);
8722 writeSourceLocation(Loc: NCC->getLParenLoc());
8723 writeOpenACCVarList(C: NCC);
8724 return;
8725 }
8726 case OpenACCClauseKind::Present: {
8727 const auto *PC = cast<OpenACCPresentClause>(Val: C);
8728 writeSourceLocation(Loc: PC->getLParenLoc());
8729 writeOpenACCVarList(C: PC);
8730 return;
8731 }
8732 case OpenACCClauseKind::Copy:
8733 case OpenACCClauseKind::PCopy:
8734 case OpenACCClauseKind::PresentOrCopy: {
8735 const auto *CC = cast<OpenACCCopyClause>(Val: C);
8736 writeSourceLocation(Loc: CC->getLParenLoc());
8737 writeEnum(CC->getModifierList());
8738 writeOpenACCVarList(C: CC);
8739 return;
8740 }
8741 case OpenACCClauseKind::CopyIn:
8742 case OpenACCClauseKind::PCopyIn:
8743 case OpenACCClauseKind::PresentOrCopyIn: {
8744 const auto *CIC = cast<OpenACCCopyInClause>(Val: C);
8745 writeSourceLocation(Loc: CIC->getLParenLoc());
8746 writeEnum(CIC->getModifierList());
8747 writeOpenACCVarList(C: CIC);
8748 return;
8749 }
8750 case OpenACCClauseKind::CopyOut:
8751 case OpenACCClauseKind::PCopyOut:
8752 case OpenACCClauseKind::PresentOrCopyOut: {
8753 const auto *COC = cast<OpenACCCopyOutClause>(Val: C);
8754 writeSourceLocation(Loc: COC->getLParenLoc());
8755 writeEnum(COC->getModifierList());
8756 writeOpenACCVarList(C: COC);
8757 return;
8758 }
8759 case OpenACCClauseKind::Create:
8760 case OpenACCClauseKind::PCreate:
8761 case OpenACCClauseKind::PresentOrCreate: {
8762 const auto *CC = cast<OpenACCCreateClause>(Val: C);
8763 writeSourceLocation(Loc: CC->getLParenLoc());
8764 writeEnum(CC->getModifierList());
8765 writeOpenACCVarList(C: CC);
8766 return;
8767 }
8768 case OpenACCClauseKind::Async: {
8769 const auto *AC = cast<OpenACCAsyncClause>(Val: C);
8770 writeSourceLocation(Loc: AC->getLParenLoc());
8771 writeBool(Value: AC->hasIntExpr());
8772 if (AC->hasIntExpr())
8773 AddStmt(const_cast<Expr*>(AC->getIntExpr()));
8774 return;
8775 }
8776 case OpenACCClauseKind::Wait: {
8777 const auto *WC = cast<OpenACCWaitClause>(Val: C);
8778 writeSourceLocation(Loc: WC->getLParenLoc());
8779 writeBool(Value: WC->getDevNumExpr());
8780 if (Expr *DNE = WC->getDevNumExpr())
8781 AddStmt(DNE);
8782 writeSourceLocation(Loc: WC->getQueuesLoc());
8783
8784 writeOpenACCIntExprList(Exprs: WC->getQueueIdExprs());
8785 return;
8786 }
8787 case OpenACCClauseKind::DeviceType:
8788 case OpenACCClauseKind::DType: {
8789 const auto *DTC = cast<OpenACCDeviceTypeClause>(Val: C);
8790 writeSourceLocation(Loc: DTC->getLParenLoc());
8791 writeUInt32(Value: DTC->getArchitectures().size());
8792 for (const DeviceTypeArgument &Arg : DTC->getArchitectures()) {
8793 writeBool(Value: Arg.getIdentifierInfo());
8794 if (Arg.getIdentifierInfo())
8795 AddIdentifierRef(II: Arg.getIdentifierInfo());
8796 writeSourceLocation(Loc: Arg.getLoc());
8797 }
8798 return;
8799 }
8800 case OpenACCClauseKind::Reduction: {
8801 const auto *RC = cast<OpenACCReductionClause>(Val: C);
8802 writeSourceLocation(Loc: RC->getLParenLoc());
8803 writeEnum(RC->getReductionOp());
8804 writeOpenACCVarList(C: RC);
8805 return;
8806 }
8807 case OpenACCClauseKind::Seq:
8808 case OpenACCClauseKind::Independent:
8809 case OpenACCClauseKind::NoHost:
8810 case OpenACCClauseKind::Auto:
8811 case OpenACCClauseKind::Finalize:
8812 case OpenACCClauseKind::IfPresent:
8813 // Nothing to do here, there is no additional information beyond the
8814 // begin/end loc and clause kind.
8815 return;
8816 case OpenACCClauseKind::Collapse: {
8817 const auto *CC = cast<OpenACCCollapseClause>(Val: C);
8818 writeSourceLocation(Loc: CC->getLParenLoc());
8819 writeBool(Value: CC->hasForce());
8820 AddStmt(const_cast<Expr *>(CC->getLoopCount()));
8821 return;
8822 }
8823 case OpenACCClauseKind::Tile: {
8824 const auto *TC = cast<OpenACCTileClause>(Val: C);
8825 writeSourceLocation(Loc: TC->getLParenLoc());
8826 writeUInt32(Value: TC->getSizeExprs().size());
8827 for (Expr *E : TC->getSizeExprs())
8828 AddStmt(E);
8829 return;
8830 }
8831 case OpenACCClauseKind::Gang: {
8832 const auto *GC = cast<OpenACCGangClause>(Val: C);
8833 writeSourceLocation(Loc: GC->getLParenLoc());
8834 writeUInt32(Value: GC->getNumExprs());
8835 for (unsigned I = 0; I < GC->getNumExprs(); ++I) {
8836 writeEnum(GC->getExpr(I).first);
8837 AddStmt(const_cast<Expr *>(GC->getExpr(I).second));
8838 }
8839 return;
8840 }
8841 case OpenACCClauseKind::Worker: {
8842 const auto *WC = cast<OpenACCWorkerClause>(Val: C);
8843 writeSourceLocation(Loc: WC->getLParenLoc());
8844 writeBool(Value: WC->hasIntExpr());
8845 if (WC->hasIntExpr())
8846 AddStmt(const_cast<Expr *>(WC->getIntExpr()));
8847 return;
8848 }
8849 case OpenACCClauseKind::Vector: {
8850 const auto *VC = cast<OpenACCVectorClause>(Val: C);
8851 writeSourceLocation(Loc: VC->getLParenLoc());
8852 writeBool(Value: VC->hasIntExpr());
8853 if (VC->hasIntExpr())
8854 AddStmt(const_cast<Expr *>(VC->getIntExpr()));
8855 return;
8856 }
8857 case OpenACCClauseKind::Link: {
8858 const auto *LC = cast<OpenACCLinkClause>(Val: C);
8859 writeSourceLocation(Loc: LC->getLParenLoc());
8860 writeOpenACCVarList(C: LC);
8861 return;
8862 }
8863 case OpenACCClauseKind::DeviceResident: {
8864 const auto *DRC = cast<OpenACCDeviceResidentClause>(Val: C);
8865 writeSourceLocation(Loc: DRC->getLParenLoc());
8866 writeOpenACCVarList(C: DRC);
8867 return;
8868 }
8869
8870 case OpenACCClauseKind::Bind: {
8871 const auto *BC = cast<OpenACCBindClause>(Val: C);
8872 writeSourceLocation(Loc: BC->getLParenLoc());
8873 writeBool(Value: BC->isStringArgument());
8874 if (BC->isStringArgument())
8875 AddStmt(const_cast<StringLiteral *>(BC->getStringArgument()));
8876 else
8877 AddIdentifierRef(II: BC->getIdentifierArgument());
8878
8879 return;
8880 }
8881 case OpenACCClauseKind::Invalid:
8882 case OpenACCClauseKind::Shortloop:
8883 llvm_unreachable("Clause serialization not yet implemented");
8884 }
8885 llvm_unreachable("Invalid Clause Kind");
8886}
8887
8888void ASTRecordWriter::writeOpenACCClauseList(
8889 ArrayRef<const OpenACCClause *> Clauses) {
8890 for (const OpenACCClause *Clause : Clauses)
8891 writeOpenACCClause(C: Clause);
8892}
8893void ASTRecordWriter::AddOpenACCRoutineDeclAttr(
8894 const OpenACCRoutineDeclAttr *A) {
8895 // We have to write the size so that the reader can do a resize. Unlike the
8896 // Decl version of this, we can't count on trailing storage to get this right.
8897 writeUInt32(Value: A->Clauses.size());
8898 writeOpenACCClauseList(Clauses: A->Clauses);
8899}
8900

source code of clang/lib/Serialization/ASTWriter.cpp