xref: /freebsd/contrib/llvm-project/clang/lib/Serialization/ASTWriterDecl.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===--- ASTWriterDecl.cpp - Declaration Serialization --------------------===//
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 implements serialization for Declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ASTCommon.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/OpenMPClause.h"
20 #include "clang/AST/PrettyDeclStackTrace.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Serialization/ASTReader.h"
23 #include "clang/Serialization/ASTRecordWriter.h"
24 #include "llvm/Bitstream/BitstreamWriter.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include <optional>
27 using namespace clang;
28 using namespace serialization;
29 
30 //===----------------------------------------------------------------------===//
31 // Declaration serialization
32 //===----------------------------------------------------------------------===//
33 
34 namespace clang {
35   class ASTDeclWriter : public DeclVisitor<ASTDeclWriter, void> {
36     ASTWriter &Writer;
37     ASTContext &Context;
38     ASTRecordWriter Record;
39 
40     serialization::DeclCode Code;
41     unsigned AbbrevToUse;
42 
43   public:
44     ASTDeclWriter(ASTWriter &Writer, ASTContext &Context,
45                   ASTWriter::RecordDataImpl &Record)
46         : Writer(Writer), Context(Context), Record(Writer, Record),
47           Code((serialization::DeclCode)0), AbbrevToUse(0) {}
48 
49     uint64_t Emit(Decl *D) {
50       if (!Code)
51         llvm::report_fatal_error(StringRef("unexpected declaration kind '") +
52             D->getDeclKindName() + "'");
53       return Record.Emit(Code, AbbrevToUse);
54     }
55 
56     void Visit(Decl *D);
57 
58     void VisitDecl(Decl *D);
59     void VisitPragmaCommentDecl(PragmaCommentDecl *D);
60     void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
61     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
62     void VisitNamedDecl(NamedDecl *D);
63     void VisitLabelDecl(LabelDecl *LD);
64     void VisitNamespaceDecl(NamespaceDecl *D);
65     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
66     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
67     void VisitTypeDecl(TypeDecl *D);
68     void VisitTypedefNameDecl(TypedefNameDecl *D);
69     void VisitTypedefDecl(TypedefDecl *D);
70     void VisitTypeAliasDecl(TypeAliasDecl *D);
71     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
72     void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);
73     void VisitTagDecl(TagDecl *D);
74     void VisitEnumDecl(EnumDecl *D);
75     void VisitRecordDecl(RecordDecl *D);
76     void VisitCXXRecordDecl(CXXRecordDecl *D);
77     void VisitClassTemplateSpecializationDecl(
78                                             ClassTemplateSpecializationDecl *D);
79     void VisitClassTemplatePartialSpecializationDecl(
80                                      ClassTemplatePartialSpecializationDecl *D);
81     void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
82     void VisitVarTemplatePartialSpecializationDecl(
83         VarTemplatePartialSpecializationDecl *D);
84     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
85     void VisitValueDecl(ValueDecl *D);
86     void VisitEnumConstantDecl(EnumConstantDecl *D);
87     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
88     void VisitDeclaratorDecl(DeclaratorDecl *D);
89     void VisitFunctionDecl(FunctionDecl *D);
90     void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
91     void VisitCXXMethodDecl(CXXMethodDecl *D);
92     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
93     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
94     void VisitCXXConversionDecl(CXXConversionDecl *D);
95     void VisitFieldDecl(FieldDecl *D);
96     void VisitMSPropertyDecl(MSPropertyDecl *D);
97     void VisitMSGuidDecl(MSGuidDecl *D);
98     void VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl *D);
99     void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);
100     void VisitIndirectFieldDecl(IndirectFieldDecl *D);
101     void VisitVarDecl(VarDecl *D);
102     void VisitImplicitParamDecl(ImplicitParamDecl *D);
103     void VisitParmVarDecl(ParmVarDecl *D);
104     void VisitDecompositionDecl(DecompositionDecl *D);
105     void VisitBindingDecl(BindingDecl *D);
106     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
107     void VisitTemplateDecl(TemplateDecl *D);
108     void VisitConceptDecl(ConceptDecl *D);
109     void VisitImplicitConceptSpecializationDecl(
110         ImplicitConceptSpecializationDecl *D);
111     void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
112     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
113     void VisitClassTemplateDecl(ClassTemplateDecl *D);
114     void VisitVarTemplateDecl(VarTemplateDecl *D);
115     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
116     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
117     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
118     void VisitUsingDecl(UsingDecl *D);
119     void VisitUsingEnumDecl(UsingEnumDecl *D);
120     void VisitUsingPackDecl(UsingPackDecl *D);
121     void VisitUsingShadowDecl(UsingShadowDecl *D);
122     void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
123     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
124     void VisitExportDecl(ExportDecl *D);
125     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
126     void VisitTopLevelStmtDecl(TopLevelStmtDecl *D);
127     void VisitImportDecl(ImportDecl *D);
128     void VisitAccessSpecDecl(AccessSpecDecl *D);
129     void VisitFriendDecl(FriendDecl *D);
130     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
131     void VisitStaticAssertDecl(StaticAssertDecl *D);
132     void VisitBlockDecl(BlockDecl *D);
133     void VisitCapturedDecl(CapturedDecl *D);
134     void VisitEmptyDecl(EmptyDecl *D);
135     void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
136     void VisitDeclContext(DeclContext *DC);
137     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
138     void VisitHLSLBufferDecl(HLSLBufferDecl *D);
139 
140     // FIXME: Put in the same order is DeclNodes.td?
141     void VisitObjCMethodDecl(ObjCMethodDecl *D);
142     void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
143     void VisitObjCContainerDecl(ObjCContainerDecl *D);
144     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
145     void VisitObjCIvarDecl(ObjCIvarDecl *D);
146     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
147     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
148     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
149     void VisitObjCImplDecl(ObjCImplDecl *D);
150     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
151     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
152     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
153     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
154     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
155     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
156     void VisitOMPAllocateDecl(OMPAllocateDecl *D);
157     void VisitOMPRequiresDecl(OMPRequiresDecl *D);
158     void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
159     void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
160     void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
161 
162     /// Add an Objective-C type parameter list to the given record.
163     void AddObjCTypeParamList(ObjCTypeParamList *typeParams) {
164       // Empty type parameter list.
165       if (!typeParams) {
166         Record.push_back(0);
167         return;
168       }
169 
170       Record.push_back(typeParams->size());
171       for (auto *typeParam : *typeParams) {
172         Record.AddDeclRef(typeParam);
173       }
174       Record.AddSourceLocation(typeParams->getLAngleLoc());
175       Record.AddSourceLocation(typeParams->getRAngleLoc());
176     }
177 
178     /// Add to the record the first declaration from each module file that
179     /// provides a declaration of D. The intent is to provide a sufficient
180     /// set such that reloading this set will load all current redeclarations.
181     void AddFirstDeclFromEachModule(const Decl *D, bool IncludeLocal) {
182       llvm::MapVector<ModuleFile*, const Decl*> Firsts;
183       // FIXME: We can skip entries that we know are implied by others.
184       for (const Decl *R = D->getMostRecentDecl(); R; R = R->getPreviousDecl()) {
185         if (R->isFromASTFile())
186           Firsts[Writer.Chain->getOwningModuleFile(R)] = R;
187         else if (IncludeLocal)
188           Firsts[nullptr] = R;
189       }
190       for (const auto &F : Firsts)
191         Record.AddDeclRef(F.second);
192     }
193 
194     /// Get the specialization decl from an entry in the specialization list.
195     template <typename EntryType>
196     typename RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::DeclType *
197     getSpecializationDecl(EntryType &T) {
198       return RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::getDecl(&T);
199     }
200 
201     /// Get the list of partial specializations from a template's common ptr.
202     template<typename T>
203     decltype(T::PartialSpecializations) &getPartialSpecializations(T *Common) {
204       return Common->PartialSpecializations;
205     }
206     ArrayRef<Decl> getPartialSpecializations(FunctionTemplateDecl::Common *) {
207       return std::nullopt;
208     }
209 
210     template<typename DeclTy>
211     void AddTemplateSpecializations(DeclTy *D) {
212       auto *Common = D->getCommonPtr();
213 
214       // If we have any lazy specializations, and the external AST source is
215       // our chained AST reader, we can just write out the DeclIDs. Otherwise,
216       // we need to resolve them to actual declarations.
217       if (Writer.Chain != Writer.Context->getExternalSource() &&
218           Common->LazySpecializations) {
219         D->LoadLazySpecializations();
220         assert(!Common->LazySpecializations);
221       }
222 
223       ArrayRef<DeclID> LazySpecializations;
224       if (auto *LS = Common->LazySpecializations)
225         LazySpecializations = llvm::ArrayRef(LS + 1, LS[0]);
226 
227       // Add a slot to the record for the number of specializations.
228       unsigned I = Record.size();
229       Record.push_back(0);
230 
231       // AddFirstDeclFromEachModule might trigger deserialization, invalidating
232       // *Specializations iterators.
233       llvm::SmallVector<const Decl*, 16> Specs;
234       for (auto &Entry : Common->Specializations)
235         Specs.push_back(getSpecializationDecl(Entry));
236       for (auto &Entry : getPartialSpecializations(Common))
237         Specs.push_back(getSpecializationDecl(Entry));
238 
239       for (auto *D : Specs) {
240         assert(D->isCanonicalDecl() && "non-canonical decl in set");
241         AddFirstDeclFromEachModule(D, /*IncludeLocal*/true);
242       }
243       Record.append(LazySpecializations.begin(), LazySpecializations.end());
244 
245       // Update the size entry we added earlier.
246       Record[I] = Record.size() - I - 1;
247     }
248 
249     /// Ensure that this template specialization is associated with the specified
250     /// template on reload.
251     void RegisterTemplateSpecialization(const Decl *Template,
252                                         const Decl *Specialization) {
253       Template = Template->getCanonicalDecl();
254 
255       // If the canonical template is local, we'll write out this specialization
256       // when we emit it.
257       // FIXME: We can do the same thing if there is any local declaration of
258       // the template, to avoid emitting an update record.
259       if (!Template->isFromASTFile())
260         return;
261 
262       // We only need to associate the first local declaration of the
263       // specialization. The other declarations will get pulled in by it.
264       if (Writer.getFirstLocalDecl(Specialization) != Specialization)
265         return;
266 
267       Writer.DeclUpdates[Template].push_back(ASTWriter::DeclUpdate(
268           UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION, Specialization));
269     }
270   };
271 }
272 
273 void ASTDeclWriter::Visit(Decl *D) {
274   DeclVisitor<ASTDeclWriter>::Visit(D);
275 
276   // Source locations require array (variable-length) abbreviations.  The
277   // abbreviation infrastructure requires that arrays are encoded last, so
278   // we handle it here in the case of those classes derived from DeclaratorDecl
279   if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
280     if (auto *TInfo = DD->getTypeSourceInfo())
281       Record.AddTypeLoc(TInfo->getTypeLoc());
282   }
283 
284   // Handle FunctionDecl's body here and write it after all other Stmts/Exprs
285   // have been written. We want it last because we will not read it back when
286   // retrieving it from the AST, we'll just lazily set the offset.
287   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
288     Record.push_back(FD->doesThisDeclarationHaveABody());
289     if (FD->doesThisDeclarationHaveABody())
290       Record.AddFunctionDefinition(FD);
291   }
292 
293   // Similar to FunctionDecls, handle VarDecl's initializer here and write it
294   // after all other Stmts/Exprs. We will not read the initializer until after
295   // we have finished recursive deserialization, because it can recursively
296   // refer back to the variable.
297   if (auto *VD = dyn_cast<VarDecl>(D)) {
298     Record.AddVarDeclInit(VD);
299   }
300 
301   // And similarly for FieldDecls. We already serialized whether there is a
302   // default member initializer.
303   if (auto *FD = dyn_cast<FieldDecl>(D)) {
304     if (FD->hasInClassInitializer()) {
305       if (Expr *Init = FD->getInClassInitializer()) {
306         Record.push_back(1);
307         Record.AddStmt(Init);
308       } else {
309         Record.push_back(0);
310         // Initializer has not been instantiated yet.
311       }
312     }
313   }
314 
315   // If this declaration is also a DeclContext, write blocks for the
316   // declarations that lexically stored inside its context and those
317   // declarations that are visible from its context.
318   if (auto *DC = dyn_cast<DeclContext>(D))
319     VisitDeclContext(DC);
320 }
321 
322 void ASTDeclWriter::VisitDecl(Decl *D) {
323   BitsPacker DeclBits;
324 
325   // The order matters here. It will be better to put the bit with higher
326   // probability to be 0 in the end of the bits.
327   //
328   // Since we're using VBR6 format to store it.
329   // It will be pretty effient if all the higher bits are 0.
330   // For example, if we need to pack 8 bits into a value and the stored value
331   // is 0xf0, the actual stored value will be 0b000111'110000, which takes 12
332   // bits actually. However, if we changed the order to be 0x0f, then we can
333   // store it as 0b001111, which takes 6 bits only now.
334   DeclBits.addBits((uint64_t)D->getModuleOwnershipKind(), /*BitWidth=*/3);
335   DeclBits.addBit(D->isReferenced());
336   DeclBits.addBit(D->isUsed(false));
337   DeclBits.addBits(D->getAccess(), /*BitWidth=*/2);
338   DeclBits.addBit(D->isImplicit());
339   DeclBits.addBit(D->getDeclContext() != D->getLexicalDeclContext());
340   DeclBits.addBit(D->hasAttrs());
341   DeclBits.addBit(D->isTopLevelDeclInObjCContainer());
342   DeclBits.addBit(D->isInvalidDecl());
343   Record.push_back(DeclBits);
344 
345   Record.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()));
346   if (D->getDeclContext() != D->getLexicalDeclContext())
347     Record.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()));
348 
349   if (D->hasAttrs())
350     Record.AddAttributes(D->getAttrs());
351 
352   Record.push_back(Writer.getSubmoduleID(D->getOwningModule()));
353 
354   // If this declaration injected a name into a context different from its
355   // lexical context, and that context is an imported namespace, we need to
356   // update its visible declarations to include this name.
357   //
358   // This happens when we instantiate a class with a friend declaration or a
359   // function with a local extern declaration, for instance.
360   //
361   // FIXME: Can we handle this in AddedVisibleDecl instead?
362   if (D->isOutOfLine()) {
363     auto *DC = D->getDeclContext();
364     while (auto *NS = dyn_cast<NamespaceDecl>(DC->getRedeclContext())) {
365       if (!NS->isFromASTFile())
366         break;
367       Writer.UpdatedDeclContexts.insert(NS->getPrimaryContext());
368       if (!NS->isInlineNamespace())
369         break;
370       DC = NS->getParent();
371     }
372   }
373 }
374 
375 void ASTDeclWriter::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
376   StringRef Arg = D->getArg();
377   Record.push_back(Arg.size());
378   VisitDecl(D);
379   Record.AddSourceLocation(D->getBeginLoc());
380   Record.push_back(D->getCommentKind());
381   Record.AddString(Arg);
382   Code = serialization::DECL_PRAGMA_COMMENT;
383 }
384 
385 void ASTDeclWriter::VisitPragmaDetectMismatchDecl(
386     PragmaDetectMismatchDecl *D) {
387   StringRef Name = D->getName();
388   StringRef Value = D->getValue();
389   Record.push_back(Name.size() + 1 + Value.size());
390   VisitDecl(D);
391   Record.AddSourceLocation(D->getBeginLoc());
392   Record.AddString(Name);
393   Record.AddString(Value);
394   Code = serialization::DECL_PRAGMA_DETECT_MISMATCH;
395 }
396 
397 void ASTDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
398   llvm_unreachable("Translation units aren't directly serialized");
399 }
400 
401 void ASTDeclWriter::VisitNamedDecl(NamedDecl *D) {
402   VisitDecl(D);
403   Record.AddDeclarationName(D->getDeclName());
404   Record.push_back(needsAnonymousDeclarationNumber(D)
405                        ? Writer.getAnonymousDeclarationNumber(D)
406                        : 0);
407 }
408 
409 void ASTDeclWriter::VisitTypeDecl(TypeDecl *D) {
410   VisitNamedDecl(D);
411   Record.AddSourceLocation(D->getBeginLoc());
412   Record.AddTypeRef(QualType(D->getTypeForDecl(), 0));
413 }
414 
415 void ASTDeclWriter::VisitTypedefNameDecl(TypedefNameDecl *D) {
416   VisitRedeclarable(D);
417   VisitTypeDecl(D);
418   Record.AddTypeSourceInfo(D->getTypeSourceInfo());
419   Record.push_back(D->isModed());
420   if (D->isModed())
421     Record.AddTypeRef(D->getUnderlyingType());
422   Record.AddDeclRef(D->getAnonDeclWithTypedefName(false));
423 }
424 
425 void ASTDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
426   VisitTypedefNameDecl(D);
427   if (D->getDeclContext() == D->getLexicalDeclContext() &&
428       !D->hasAttrs() &&
429       !D->isImplicit() &&
430       D->getFirstDecl() == D->getMostRecentDecl() &&
431       !D->isInvalidDecl() &&
432       !D->isTopLevelDeclInObjCContainer() &&
433       !D->isModulePrivate() &&
434       !needsAnonymousDeclarationNumber(D) &&
435       D->getDeclName().getNameKind() == DeclarationName::Identifier)
436     AbbrevToUse = Writer.getDeclTypedefAbbrev();
437 
438   Code = serialization::DECL_TYPEDEF;
439 }
440 
441 void ASTDeclWriter::VisitTypeAliasDecl(TypeAliasDecl *D) {
442   VisitTypedefNameDecl(D);
443   Record.AddDeclRef(D->getDescribedAliasTemplate());
444   Code = serialization::DECL_TYPEALIAS;
445 }
446 
447 void ASTDeclWriter::VisitTagDecl(TagDecl *D) {
448   static_assert(DeclContext::NumTagDeclBits == 23,
449                 "You need to update the serializer after you change the "
450                 "TagDeclBits");
451 
452   VisitRedeclarable(D);
453   VisitTypeDecl(D);
454   Record.push_back(D->getIdentifierNamespace());
455 
456   BitsPacker TagDeclBits;
457   TagDeclBits.addBits(llvm::to_underlying(D->getTagKind()), /*BitWidth=*/3);
458   TagDeclBits.addBit(!isa<CXXRecordDecl>(D) ? D->isCompleteDefinition() : 0);
459   TagDeclBits.addBit(D->isEmbeddedInDeclarator());
460   TagDeclBits.addBit(D->isFreeStanding());
461   TagDeclBits.addBit(D->isCompleteDefinitionRequired());
462   TagDeclBits.addBits(
463       D->hasExtInfo() ? 1 : (D->getTypedefNameForAnonDecl() ? 2 : 0),
464       /*BitWidth=*/2);
465   Record.push_back(TagDeclBits);
466 
467   Record.AddSourceRange(D->getBraceRange());
468 
469   if (D->hasExtInfo()) {
470     Record.AddQualifierInfo(*D->getExtInfo());
471   } else if (auto *TD = D->getTypedefNameForAnonDecl()) {
472     Record.AddDeclRef(TD);
473     Record.AddIdentifierRef(TD->getDeclName().getAsIdentifierInfo());
474   }
475 }
476 
477 void ASTDeclWriter::VisitEnumDecl(EnumDecl *D) {
478   static_assert(DeclContext::NumEnumDeclBits == 43,
479                 "You need to update the serializer after you change the "
480                 "EnumDeclBits");
481 
482   VisitTagDecl(D);
483   Record.AddTypeSourceInfo(D->getIntegerTypeSourceInfo());
484   if (!D->getIntegerTypeSourceInfo())
485     Record.AddTypeRef(D->getIntegerType());
486   Record.AddTypeRef(D->getPromotionType());
487 
488   BitsPacker EnumDeclBits;
489   EnumDeclBits.addBits(D->getNumPositiveBits(), /*BitWidth=*/8);
490   EnumDeclBits.addBits(D->getNumNegativeBits(), /*BitWidth=*/8);
491   EnumDeclBits.addBit(D->isScoped());
492   EnumDeclBits.addBit(D->isScopedUsingClassTag());
493   EnumDeclBits.addBit(D->isFixed());
494   Record.push_back(EnumDeclBits);
495 
496   Record.push_back(D->getODRHash());
497 
498   if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
499     Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
500     Record.push_back(MemberInfo->getTemplateSpecializationKind());
501     Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
502   } else {
503     Record.AddDeclRef(nullptr);
504   }
505 
506   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
507       !D->isInvalidDecl() && !D->isImplicit() && !D->hasExtInfo() &&
508       !D->getTypedefNameForAnonDecl() &&
509       D->getFirstDecl() == D->getMostRecentDecl() &&
510       !D->isTopLevelDeclInObjCContainer() &&
511       !CXXRecordDecl::classofKind(D->getKind()) &&
512       !D->getIntegerTypeSourceInfo() && !D->getMemberSpecializationInfo() &&
513       !needsAnonymousDeclarationNumber(D) &&
514       D->getDeclName().getNameKind() == DeclarationName::Identifier)
515     AbbrevToUse = Writer.getDeclEnumAbbrev();
516 
517   Code = serialization::DECL_ENUM;
518 }
519 
520 void ASTDeclWriter::VisitRecordDecl(RecordDecl *D) {
521   static_assert(DeclContext::NumRecordDeclBits == 64,
522                 "You need to update the serializer after you change the "
523                 "RecordDeclBits");
524 
525   VisitTagDecl(D);
526 
527   BitsPacker RecordDeclBits;
528   RecordDeclBits.addBit(D->hasFlexibleArrayMember());
529   RecordDeclBits.addBit(D->isAnonymousStructOrUnion());
530   RecordDeclBits.addBit(D->hasObjectMember());
531   RecordDeclBits.addBit(D->hasVolatileMember());
532   RecordDeclBits.addBit(D->isNonTrivialToPrimitiveDefaultInitialize());
533   RecordDeclBits.addBit(D->isNonTrivialToPrimitiveCopy());
534   RecordDeclBits.addBit(D->isNonTrivialToPrimitiveDestroy());
535   RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveDefaultInitializeCUnion());
536   RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveDestructCUnion());
537   RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveCopyCUnion());
538   RecordDeclBits.addBit(D->isParamDestroyedInCallee());
539   RecordDeclBits.addBits(llvm::to_underlying(D->getArgPassingRestrictions()), 2);
540   Record.push_back(RecordDeclBits);
541 
542   // Only compute this for C/Objective-C, in C++ this is computed as part
543   // of CXXRecordDecl.
544   if (!isa<CXXRecordDecl>(D))
545     Record.push_back(D->getODRHash());
546 
547   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
548       !D->isImplicit() && !D->isInvalidDecl() && !D->hasExtInfo() &&
549       !D->getTypedefNameForAnonDecl() &&
550       D->getFirstDecl() == D->getMostRecentDecl() &&
551       !D->isTopLevelDeclInObjCContainer() &&
552       !CXXRecordDecl::classofKind(D->getKind()) &&
553       !needsAnonymousDeclarationNumber(D) &&
554       D->getDeclName().getNameKind() == DeclarationName::Identifier)
555     AbbrevToUse = Writer.getDeclRecordAbbrev();
556 
557   Code = serialization::DECL_RECORD;
558 }
559 
560 void ASTDeclWriter::VisitValueDecl(ValueDecl *D) {
561   VisitNamedDecl(D);
562   Record.AddTypeRef(D->getType());
563 }
564 
565 void ASTDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
566   VisitValueDecl(D);
567   Record.push_back(D->getInitExpr()? 1 : 0);
568   if (D->getInitExpr())
569     Record.AddStmt(D->getInitExpr());
570   Record.AddAPSInt(D->getInitVal());
571 
572   Code = serialization::DECL_ENUM_CONSTANT;
573 }
574 
575 void ASTDeclWriter::VisitDeclaratorDecl(DeclaratorDecl *D) {
576   VisitValueDecl(D);
577   Record.AddSourceLocation(D->getInnerLocStart());
578   Record.push_back(D->hasExtInfo());
579   if (D->hasExtInfo()) {
580     DeclaratorDecl::ExtInfo *Info = D->getExtInfo();
581     Record.AddQualifierInfo(*Info);
582     Record.AddStmt(Info->TrailingRequiresClause);
583   }
584   // The location information is deferred until the end of the record.
585   Record.AddTypeRef(D->getTypeSourceInfo() ? D->getTypeSourceInfo()->getType()
586                                            : QualType());
587 }
588 
589 void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
590   static_assert(DeclContext::NumFunctionDeclBits == 44,
591                 "You need to update the serializer after you change the "
592                 "FunctionDeclBits");
593 
594   VisitRedeclarable(D);
595 
596   Record.push_back(D->getTemplatedKind());
597   switch (D->getTemplatedKind()) {
598   case FunctionDecl::TK_NonTemplate:
599     break;
600   case FunctionDecl::TK_DependentNonTemplate:
601     Record.AddDeclRef(D->getInstantiatedFromDecl());
602     break;
603   case FunctionDecl::TK_FunctionTemplate:
604     Record.AddDeclRef(D->getDescribedFunctionTemplate());
605     break;
606   case FunctionDecl::TK_MemberSpecialization: {
607     MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo();
608     Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
609     Record.push_back(MemberInfo->getTemplateSpecializationKind());
610     Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
611     break;
612   }
613   case FunctionDecl::TK_FunctionTemplateSpecialization: {
614     FunctionTemplateSpecializationInfo *
615       FTSInfo = D->getTemplateSpecializationInfo();
616 
617     RegisterTemplateSpecialization(FTSInfo->getTemplate(), D);
618 
619     Record.AddDeclRef(FTSInfo->getTemplate());
620     Record.push_back(FTSInfo->getTemplateSpecializationKind());
621 
622     // Template arguments.
623     Record.AddTemplateArgumentList(FTSInfo->TemplateArguments);
624 
625     // Template args as written.
626     Record.push_back(FTSInfo->TemplateArgumentsAsWritten != nullptr);
627     if (FTSInfo->TemplateArgumentsAsWritten)
628       Record.AddASTTemplateArgumentListInfo(
629           FTSInfo->TemplateArgumentsAsWritten);
630 
631     Record.AddSourceLocation(FTSInfo->getPointOfInstantiation());
632 
633     if (MemberSpecializationInfo *MemberInfo =
634         FTSInfo->getMemberSpecializationInfo()) {
635       Record.push_back(1);
636       Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
637       Record.push_back(MemberInfo->getTemplateSpecializationKind());
638       Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
639     } else {
640       Record.push_back(0);
641     }
642 
643     if (D->isCanonicalDecl()) {
644       // Write the template that contains the specializations set. We will
645       // add a FunctionTemplateSpecializationInfo to it when reading.
646       Record.AddDeclRef(FTSInfo->getTemplate()->getCanonicalDecl());
647     }
648     break;
649   }
650   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
651     DependentFunctionTemplateSpecializationInfo *
652       DFTSInfo = D->getDependentSpecializationInfo();
653 
654     // Candidates.
655     Record.push_back(DFTSInfo->getCandidates().size());
656     for (FunctionTemplateDecl *FTD : DFTSInfo->getCandidates())
657       Record.AddDeclRef(FTD);
658 
659     // Templates args.
660     Record.push_back(DFTSInfo->TemplateArgumentsAsWritten != nullptr);
661     if (DFTSInfo->TemplateArgumentsAsWritten)
662       Record.AddASTTemplateArgumentListInfo(
663           DFTSInfo->TemplateArgumentsAsWritten);
664     break;
665   }
666   }
667 
668   VisitDeclaratorDecl(D);
669   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
670   Record.push_back(D->getIdentifierNamespace());
671 
672   // The order matters here. It will be better to put the bit with higher
673   // probability to be 0 in the end of the bits. See the comments in VisitDecl
674   // for details.
675   BitsPacker FunctionDeclBits;
676   // FIXME: stable encoding
677   FunctionDeclBits.addBits(llvm::to_underlying(D->getLinkageInternal()), 3);
678   FunctionDeclBits.addBits((uint32_t)D->getStorageClass(), /*BitWidth=*/3);
679   FunctionDeclBits.addBit(D->isInlineSpecified());
680   FunctionDeclBits.addBit(D->isInlined());
681   FunctionDeclBits.addBit(D->hasSkippedBody());
682   FunctionDeclBits.addBit(D->isVirtualAsWritten());
683   FunctionDeclBits.addBit(D->isPure());
684   FunctionDeclBits.addBit(D->hasInheritedPrototype());
685   FunctionDeclBits.addBit(D->hasWrittenPrototype());
686   FunctionDeclBits.addBit(D->isDeletedBit());
687   FunctionDeclBits.addBit(D->isTrivial());
688   FunctionDeclBits.addBit(D->isTrivialForCall());
689   FunctionDeclBits.addBit(D->isDefaulted());
690   FunctionDeclBits.addBit(D->isExplicitlyDefaulted());
691   FunctionDeclBits.addBit(D->isIneligibleOrNotSelected());
692   FunctionDeclBits.addBits((uint64_t)(D->getConstexprKind()), /*BitWidth=*/2);
693   FunctionDeclBits.addBit(D->hasImplicitReturnZero());
694   FunctionDeclBits.addBit(D->isMultiVersion());
695   FunctionDeclBits.addBit(D->isLateTemplateParsed());
696   FunctionDeclBits.addBit(D->FriendConstraintRefersToEnclosingTemplate());
697   FunctionDeclBits.addBit(D->usesSEHTry());
698   Record.push_back(FunctionDeclBits);
699 
700   Record.AddSourceLocation(D->getEndLoc());
701   if (D->isExplicitlyDefaulted())
702     Record.AddSourceLocation(D->getDefaultLoc());
703 
704   Record.push_back(D->getODRHash());
705 
706   if (D->isDefaulted()) {
707     if (auto *FDI = D->getDefaultedFunctionInfo()) {
708       Record.push_back(FDI->getUnqualifiedLookups().size());
709       for (DeclAccessPair P : FDI->getUnqualifiedLookups()) {
710         Record.AddDeclRef(P.getDecl());
711         Record.push_back(P.getAccess());
712       }
713     } else {
714       Record.push_back(0);
715     }
716   }
717 
718   Record.push_back(D->param_size());
719   for (auto *P : D->parameters())
720     Record.AddDeclRef(P);
721   Code = serialization::DECL_FUNCTION;
722 }
723 
724 static void addExplicitSpecifier(ExplicitSpecifier ES,
725                                  ASTRecordWriter &Record) {
726   uint64_t Kind = static_cast<uint64_t>(ES.getKind());
727   Kind = Kind << 1 | static_cast<bool>(ES.getExpr());
728   Record.push_back(Kind);
729   if (ES.getExpr()) {
730     Record.AddStmt(ES.getExpr());
731   }
732 }
733 
734 void ASTDeclWriter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
735   addExplicitSpecifier(D->getExplicitSpecifier(), Record);
736   Record.AddDeclRef(D->Ctor);
737   VisitFunctionDecl(D);
738   Record.push_back(static_cast<unsigned char>(D->getDeductionCandidateKind()));
739   Code = serialization::DECL_CXX_DEDUCTION_GUIDE;
740 }
741 
742 void ASTDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
743   static_assert(DeclContext::NumObjCMethodDeclBits == 37,
744                 "You need to update the serializer after you change the "
745                 "ObjCMethodDeclBits");
746 
747   VisitNamedDecl(D);
748   // FIXME: convert to LazyStmtPtr?
749   // Unlike C/C++, method bodies will never be in header files.
750   bool HasBodyStuff = D->getBody() != nullptr;
751   Record.push_back(HasBodyStuff);
752   if (HasBodyStuff) {
753     Record.AddStmt(D->getBody());
754   }
755   Record.AddDeclRef(D->getSelfDecl());
756   Record.AddDeclRef(D->getCmdDecl());
757   Record.push_back(D->isInstanceMethod());
758   Record.push_back(D->isVariadic());
759   Record.push_back(D->isPropertyAccessor());
760   Record.push_back(D->isSynthesizedAccessorStub());
761   Record.push_back(D->isDefined());
762   Record.push_back(D->isOverriding());
763   Record.push_back(D->hasSkippedBody());
764 
765   Record.push_back(D->isRedeclaration());
766   Record.push_back(D->hasRedeclaration());
767   if (D->hasRedeclaration()) {
768     assert(Context.getObjCMethodRedeclaration(D));
769     Record.AddDeclRef(Context.getObjCMethodRedeclaration(D));
770   }
771 
772   // FIXME: stable encoding for @required/@optional
773   Record.push_back(llvm::to_underlying(D->getImplementationControl()));
774   // FIXME: stable encoding for in/out/inout/bycopy/byref/oneway/nullability
775   Record.push_back(D->getObjCDeclQualifier());
776   Record.push_back(D->hasRelatedResultType());
777   Record.AddTypeRef(D->getReturnType());
778   Record.AddTypeSourceInfo(D->getReturnTypeSourceInfo());
779   Record.AddSourceLocation(D->getEndLoc());
780   Record.push_back(D->param_size());
781   for (const auto *P : D->parameters())
782     Record.AddDeclRef(P);
783 
784   Record.push_back(D->getSelLocsKind());
785   unsigned NumStoredSelLocs = D->getNumStoredSelLocs();
786   SourceLocation *SelLocs = D->getStoredSelLocs();
787   Record.push_back(NumStoredSelLocs);
788   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
789     Record.AddSourceLocation(SelLocs[i]);
790 
791   Code = serialization::DECL_OBJC_METHOD;
792 }
793 
794 void ASTDeclWriter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
795   VisitTypedefNameDecl(D);
796   Record.push_back(D->Variance);
797   Record.push_back(D->Index);
798   Record.AddSourceLocation(D->VarianceLoc);
799   Record.AddSourceLocation(D->ColonLoc);
800 
801   Code = serialization::DECL_OBJC_TYPE_PARAM;
802 }
803 
804 void ASTDeclWriter::VisitObjCContainerDecl(ObjCContainerDecl *D) {
805   static_assert(DeclContext::NumObjCContainerDeclBits == 64,
806                 "You need to update the serializer after you change the "
807                 "ObjCContainerDeclBits");
808 
809   VisitNamedDecl(D);
810   Record.AddSourceLocation(D->getAtStartLoc());
811   Record.AddSourceRange(D->getAtEndRange());
812   // Abstract class (no need to define a stable serialization::DECL code).
813 }
814 
815 void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
816   VisitRedeclarable(D);
817   VisitObjCContainerDecl(D);
818   Record.AddTypeRef(QualType(D->getTypeForDecl(), 0));
819   AddObjCTypeParamList(D->TypeParamList);
820 
821   Record.push_back(D->isThisDeclarationADefinition());
822   if (D->isThisDeclarationADefinition()) {
823     // Write the DefinitionData
824     ObjCInterfaceDecl::DefinitionData &Data = D->data();
825 
826     Record.AddTypeSourceInfo(D->getSuperClassTInfo());
827     Record.AddSourceLocation(D->getEndOfDefinitionLoc());
828     Record.push_back(Data.HasDesignatedInitializers);
829     Record.push_back(D->getODRHash());
830 
831     // Write out the protocols that are directly referenced by the @interface.
832     Record.push_back(Data.ReferencedProtocols.size());
833     for (const auto *P : D->protocols())
834       Record.AddDeclRef(P);
835     for (const auto &PL : D->protocol_locs())
836       Record.AddSourceLocation(PL);
837 
838     // Write out the protocols that are transitively referenced.
839     Record.push_back(Data.AllReferencedProtocols.size());
840     for (ObjCList<ObjCProtocolDecl>::iterator
841               P = Data.AllReferencedProtocols.begin(),
842            PEnd = Data.AllReferencedProtocols.end();
843          P != PEnd; ++P)
844       Record.AddDeclRef(*P);
845 
846 
847     if (ObjCCategoryDecl *Cat = D->getCategoryListRaw()) {
848       // Ensure that we write out the set of categories for this class.
849       Writer.ObjCClassesWithCategories.insert(D);
850 
851       // Make sure that the categories get serialized.
852       for (; Cat; Cat = Cat->getNextClassCategoryRaw())
853         (void)Writer.GetDeclRef(Cat);
854     }
855   }
856 
857   Code = serialization::DECL_OBJC_INTERFACE;
858 }
859 
860 void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
861   VisitFieldDecl(D);
862   // FIXME: stable encoding for @public/@private/@protected/@package
863   Record.push_back(D->getAccessControl());
864   Record.push_back(D->getSynthesize());
865 
866   if (D->getDeclContext() == D->getLexicalDeclContext() &&
867       !D->hasAttrs() &&
868       !D->isImplicit() &&
869       !D->isUsed(false) &&
870       !D->isInvalidDecl() &&
871       !D->isReferenced() &&
872       !D->isModulePrivate() &&
873       !D->getBitWidth() &&
874       !D->hasExtInfo() &&
875       D->getDeclName())
876     AbbrevToUse = Writer.getDeclObjCIvarAbbrev();
877 
878   Code = serialization::DECL_OBJC_IVAR;
879 }
880 
881 void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
882   VisitRedeclarable(D);
883   VisitObjCContainerDecl(D);
884 
885   Record.push_back(D->isThisDeclarationADefinition());
886   if (D->isThisDeclarationADefinition()) {
887     Record.push_back(D->protocol_size());
888     for (const auto *I : D->protocols())
889       Record.AddDeclRef(I);
890     for (const auto &PL : D->protocol_locs())
891       Record.AddSourceLocation(PL);
892     Record.push_back(D->getODRHash());
893   }
894 
895   Code = serialization::DECL_OBJC_PROTOCOL;
896 }
897 
898 void ASTDeclWriter::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
899   VisitFieldDecl(D);
900   Code = serialization::DECL_OBJC_AT_DEFS_FIELD;
901 }
902 
903 void ASTDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
904   VisitObjCContainerDecl(D);
905   Record.AddSourceLocation(D->getCategoryNameLoc());
906   Record.AddSourceLocation(D->getIvarLBraceLoc());
907   Record.AddSourceLocation(D->getIvarRBraceLoc());
908   Record.AddDeclRef(D->getClassInterface());
909   AddObjCTypeParamList(D->TypeParamList);
910   Record.push_back(D->protocol_size());
911   for (const auto *I : D->protocols())
912     Record.AddDeclRef(I);
913   for (const auto &PL : D->protocol_locs())
914     Record.AddSourceLocation(PL);
915   Code = serialization::DECL_OBJC_CATEGORY;
916 }
917 
918 void ASTDeclWriter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D) {
919   VisitNamedDecl(D);
920   Record.AddDeclRef(D->getClassInterface());
921   Code = serialization::DECL_OBJC_COMPATIBLE_ALIAS;
922 }
923 
924 void ASTDeclWriter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
925   VisitNamedDecl(D);
926   Record.AddSourceLocation(D->getAtLoc());
927   Record.AddSourceLocation(D->getLParenLoc());
928   Record.AddTypeRef(D->getType());
929   Record.AddTypeSourceInfo(D->getTypeSourceInfo());
930   // FIXME: stable encoding
931   Record.push_back((unsigned)D->getPropertyAttributes());
932   Record.push_back((unsigned)D->getPropertyAttributesAsWritten());
933   // FIXME: stable encoding
934   Record.push_back((unsigned)D->getPropertyImplementation());
935   Record.AddDeclarationName(D->getGetterName());
936   Record.AddSourceLocation(D->getGetterNameLoc());
937   Record.AddDeclarationName(D->getSetterName());
938   Record.AddSourceLocation(D->getSetterNameLoc());
939   Record.AddDeclRef(D->getGetterMethodDecl());
940   Record.AddDeclRef(D->getSetterMethodDecl());
941   Record.AddDeclRef(D->getPropertyIvarDecl());
942   Code = serialization::DECL_OBJC_PROPERTY;
943 }
944 
945 void ASTDeclWriter::VisitObjCImplDecl(ObjCImplDecl *D) {
946   VisitObjCContainerDecl(D);
947   Record.AddDeclRef(D->getClassInterface());
948   // Abstract class (no need to define a stable serialization::DECL code).
949 }
950 
951 void ASTDeclWriter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
952   VisitObjCImplDecl(D);
953   Record.AddSourceLocation(D->getCategoryNameLoc());
954   Code = serialization::DECL_OBJC_CATEGORY_IMPL;
955 }
956 
957 void ASTDeclWriter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
958   VisitObjCImplDecl(D);
959   Record.AddDeclRef(D->getSuperClass());
960   Record.AddSourceLocation(D->getSuperClassLoc());
961   Record.AddSourceLocation(D->getIvarLBraceLoc());
962   Record.AddSourceLocation(D->getIvarRBraceLoc());
963   Record.push_back(D->hasNonZeroConstructors());
964   Record.push_back(D->hasDestructors());
965   Record.push_back(D->NumIvarInitializers);
966   if (D->NumIvarInitializers)
967     Record.AddCXXCtorInitializers(
968         llvm::ArrayRef(D->init_begin(), D->init_end()));
969   Code = serialization::DECL_OBJC_IMPLEMENTATION;
970 }
971 
972 void ASTDeclWriter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
973   VisitDecl(D);
974   Record.AddSourceLocation(D->getBeginLoc());
975   Record.AddDeclRef(D->getPropertyDecl());
976   Record.AddDeclRef(D->getPropertyIvarDecl());
977   Record.AddSourceLocation(D->getPropertyIvarDeclLoc());
978   Record.AddDeclRef(D->getGetterMethodDecl());
979   Record.AddDeclRef(D->getSetterMethodDecl());
980   Record.AddStmt(D->getGetterCXXConstructor());
981   Record.AddStmt(D->getSetterCXXAssignment());
982   Code = serialization::DECL_OBJC_PROPERTY_IMPL;
983 }
984 
985 void ASTDeclWriter::VisitFieldDecl(FieldDecl *D) {
986   VisitDeclaratorDecl(D);
987   Record.push_back(D->isMutable());
988 
989   Record.push_back((D->StorageKind << 1) | D->BitField);
990   if (D->StorageKind == FieldDecl::ISK_CapturedVLAType)
991     Record.AddTypeRef(QualType(D->getCapturedVLAType(), 0));
992   else if (D->BitField)
993     Record.AddStmt(D->getBitWidth());
994 
995   if (!D->getDeclName())
996     Record.AddDeclRef(Context.getInstantiatedFromUnnamedFieldDecl(D));
997 
998   if (D->getDeclContext() == D->getLexicalDeclContext() &&
999       !D->hasAttrs() &&
1000       !D->isImplicit() &&
1001       !D->isUsed(false) &&
1002       !D->isInvalidDecl() &&
1003       !D->isReferenced() &&
1004       !D->isTopLevelDeclInObjCContainer() &&
1005       !D->isModulePrivate() &&
1006       !D->getBitWidth() &&
1007       !D->hasInClassInitializer() &&
1008       !D->hasCapturedVLAType() &&
1009       !D->hasExtInfo() &&
1010       !ObjCIvarDecl::classofKind(D->getKind()) &&
1011       !ObjCAtDefsFieldDecl::classofKind(D->getKind()) &&
1012       D->getDeclName())
1013     AbbrevToUse = Writer.getDeclFieldAbbrev();
1014 
1015   Code = serialization::DECL_FIELD;
1016 }
1017 
1018 void ASTDeclWriter::VisitMSPropertyDecl(MSPropertyDecl *D) {
1019   VisitDeclaratorDecl(D);
1020   Record.AddIdentifierRef(D->getGetterId());
1021   Record.AddIdentifierRef(D->getSetterId());
1022   Code = serialization::DECL_MS_PROPERTY;
1023 }
1024 
1025 void ASTDeclWriter::VisitMSGuidDecl(MSGuidDecl *D) {
1026   VisitValueDecl(D);
1027   MSGuidDecl::Parts Parts = D->getParts();
1028   Record.push_back(Parts.Part1);
1029   Record.push_back(Parts.Part2);
1030   Record.push_back(Parts.Part3);
1031   Record.append(std::begin(Parts.Part4And5), std::end(Parts.Part4And5));
1032   Code = serialization::DECL_MS_GUID;
1033 }
1034 
1035 void ASTDeclWriter::VisitUnnamedGlobalConstantDecl(
1036     UnnamedGlobalConstantDecl *D) {
1037   VisitValueDecl(D);
1038   Record.AddAPValue(D->getValue());
1039   Code = serialization::DECL_UNNAMED_GLOBAL_CONSTANT;
1040 }
1041 
1042 void ASTDeclWriter::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1043   VisitValueDecl(D);
1044   Record.AddAPValue(D->getValue());
1045   Code = serialization::DECL_TEMPLATE_PARAM_OBJECT;
1046 }
1047 
1048 void ASTDeclWriter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1049   VisitValueDecl(D);
1050   Record.push_back(D->getChainingSize());
1051 
1052   for (const auto *P : D->chain())
1053     Record.AddDeclRef(P);
1054   Code = serialization::DECL_INDIRECTFIELD;
1055 }
1056 
1057 void ASTDeclWriter::VisitVarDecl(VarDecl *D) {
1058   VisitRedeclarable(D);
1059   VisitDeclaratorDecl(D);
1060 
1061   // The order matters here. It will be better to put the bit with higher
1062   // probability to be 0 in the end of the bits. See the comments in VisitDecl
1063   // for details.
1064   BitsPacker VarDeclBits;
1065   VarDeclBits.addBits(llvm::to_underlying(D->getLinkageInternal()),
1066                       /*BitWidth=*/3);
1067 
1068   bool ModulesCodegen = false;
1069   if (Writer.WritingModule && D->getStorageDuration() == SD_Static &&
1070       !D->getDescribedVarTemplate()) {
1071     // When building a C++20 module interface unit or a partition unit, a
1072     // strong definition in the module interface is provided by the
1073     // compilation of that unit, not by its users. (Inline variables are still
1074     // emitted in module users.)
1075     ModulesCodegen =
1076         (Writer.WritingModule->isInterfaceOrPartition() ||
1077          (D->hasAttr<DLLExportAttr>() &&
1078           Writer.Context->getLangOpts().BuildingPCHWithObjectFile)) &&
1079         Writer.Context->GetGVALinkageForVariable(D) >= GVA_StrongExternal;
1080   }
1081   VarDeclBits.addBit(ModulesCodegen);
1082 
1083   VarDeclBits.addBits(D->getStorageClass(), /*BitWidth=*/3);
1084   VarDeclBits.addBits(D->getTSCSpec(), /*BitWidth=*/2);
1085   VarDeclBits.addBits(D->getInitStyle(), /*BitWidth=*/2);
1086   VarDeclBits.addBit(D->isARCPseudoStrong());
1087 
1088   bool HasDeducedType = false;
1089   if (!isa<ParmVarDecl>(D)) {
1090     VarDeclBits.addBit(D->isThisDeclarationADemotedDefinition());
1091     VarDeclBits.addBit(D->isExceptionVariable());
1092     VarDeclBits.addBit(D->isNRVOVariable());
1093     VarDeclBits.addBit(D->isCXXForRangeDecl());
1094 
1095     VarDeclBits.addBit(D->isInline());
1096     VarDeclBits.addBit(D->isInlineSpecified());
1097     VarDeclBits.addBit(D->isConstexpr());
1098     VarDeclBits.addBit(D->isInitCapture());
1099     VarDeclBits.addBit(D->isPreviousDeclInSameBlockScope());
1100 
1101     VarDeclBits.addBit(D->isEscapingByref());
1102     HasDeducedType = D->getType()->getContainedDeducedType();
1103     VarDeclBits.addBit(HasDeducedType);
1104 
1105     if (const auto *IPD = dyn_cast<ImplicitParamDecl>(D))
1106       VarDeclBits.addBits(llvm::to_underlying(IPD->getParameterKind()),
1107                           /*Width=*/3);
1108     else
1109       VarDeclBits.addBits(0, /*Width=*/3);
1110 
1111     VarDeclBits.addBit(D->isObjCForDecl());
1112   }
1113 
1114   Record.push_back(VarDeclBits);
1115 
1116   if (ModulesCodegen)
1117     Writer.ModularCodegenDecls.push_back(Writer.GetDeclRef(D));
1118 
1119   if (D->hasAttr<BlocksAttr>()) {
1120     BlockVarCopyInit Init = Writer.Context->getBlockVarCopyInit(D);
1121     Record.AddStmt(Init.getCopyExpr());
1122     if (Init.getCopyExpr())
1123       Record.push_back(Init.canThrow());
1124   }
1125 
1126   enum {
1127     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1128   };
1129   if (VarTemplateDecl *TemplD = D->getDescribedVarTemplate()) {
1130     Record.push_back(VarTemplate);
1131     Record.AddDeclRef(TemplD);
1132   } else if (MemberSpecializationInfo *SpecInfo
1133                = D->getMemberSpecializationInfo()) {
1134     Record.push_back(StaticDataMemberSpecialization);
1135     Record.AddDeclRef(SpecInfo->getInstantiatedFrom());
1136     Record.push_back(SpecInfo->getTemplateSpecializationKind());
1137     Record.AddSourceLocation(SpecInfo->getPointOfInstantiation());
1138   } else {
1139     Record.push_back(VarNotTemplate);
1140   }
1141 
1142   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
1143       !D->isTopLevelDeclInObjCContainer() &&
1144       !needsAnonymousDeclarationNumber(D) &&
1145       D->getDeclName().getNameKind() == DeclarationName::Identifier &&
1146       !D->hasExtInfo() && D->getFirstDecl() == D->getMostRecentDecl() &&
1147       D->getKind() == Decl::Var && !D->isInline() && !D->isConstexpr() &&
1148       !D->isInitCapture() && !D->isPreviousDeclInSameBlockScope() &&
1149       !D->isEscapingByref() && !HasDeducedType &&
1150       D->getStorageDuration() != SD_Static && !D->getDescribedVarTemplate() &&
1151       !D->getMemberSpecializationInfo() && !D->isObjCForDecl() &&
1152       !isa<ImplicitParamDecl>(D) && !D->isEscapingByref())
1153     AbbrevToUse = Writer.getDeclVarAbbrev();
1154 
1155   Code = serialization::DECL_VAR;
1156 }
1157 
1158 void ASTDeclWriter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
1159   VisitVarDecl(D);
1160   Code = serialization::DECL_IMPLICIT_PARAM;
1161 }
1162 
1163 void ASTDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
1164   VisitVarDecl(D);
1165 
1166   // See the implementation of `ParmVarDecl::getParameterIndex()`, which may
1167   // exceed the size of the normal bitfield. So it may be better to not pack
1168   // these bits.
1169   Record.push_back(D->getFunctionScopeIndex());
1170 
1171   BitsPacker ParmVarDeclBits;
1172   ParmVarDeclBits.addBit(D->isObjCMethodParameter());
1173   ParmVarDeclBits.addBits(D->getFunctionScopeDepth(), /*BitsWidth=*/7);
1174   // FIXME: stable encoding
1175   ParmVarDeclBits.addBits(D->getObjCDeclQualifier(), /*BitsWidth=*/7);
1176   ParmVarDeclBits.addBit(D->isKNRPromoted());
1177   ParmVarDeclBits.addBit(D->hasInheritedDefaultArg());
1178   ParmVarDeclBits.addBit(D->hasUninstantiatedDefaultArg());
1179   ParmVarDeclBits.addBit(D->getExplicitObjectParamThisLoc().isValid());
1180   Record.push_back(ParmVarDeclBits);
1181 
1182   if (D->hasUninstantiatedDefaultArg())
1183     Record.AddStmt(D->getUninstantiatedDefaultArg());
1184   if (D->getExplicitObjectParamThisLoc().isValid())
1185     Record.AddSourceLocation(D->getExplicitObjectParamThisLoc());
1186   Code = serialization::DECL_PARM_VAR;
1187 
1188   // If the assumptions about the DECL_PARM_VAR abbrev are true, use it.  Here
1189   // we dynamically check for the properties that we optimize for, but don't
1190   // know are true of all PARM_VAR_DECLs.
1191   if (D->getDeclContext() == D->getLexicalDeclContext() && !D->hasAttrs() &&
1192       !D->hasExtInfo() && D->getStorageClass() == 0 && !D->isInvalidDecl() &&
1193       !D->isTopLevelDeclInObjCContainer() &&
1194       D->getInitStyle() == VarDecl::CInit && // Can params have anything else?
1195       D->getInit() == nullptr)               // No default expr.
1196     AbbrevToUse = Writer.getDeclParmVarAbbrev();
1197 
1198   // Check things we know are true of *every* PARM_VAR_DECL, which is more than
1199   // just us assuming it.
1200   assert(!D->getTSCSpec() && "PARM_VAR_DECL can't use TLS");
1201   assert(!D->isThisDeclarationADemotedDefinition()
1202          && "PARM_VAR_DECL can't be demoted definition.");
1203   assert(D->getAccess() == AS_none && "PARM_VAR_DECL can't be public/private");
1204   assert(!D->isExceptionVariable() && "PARM_VAR_DECL can't be exception var");
1205   assert(D->getPreviousDecl() == nullptr && "PARM_VAR_DECL can't be redecl");
1206   assert(!D->isStaticDataMember() &&
1207          "PARM_VAR_DECL can't be static data member");
1208 }
1209 
1210 void ASTDeclWriter::VisitDecompositionDecl(DecompositionDecl *D) {
1211   // Record the number of bindings first to simplify deserialization.
1212   Record.push_back(D->bindings().size());
1213 
1214   VisitVarDecl(D);
1215   for (auto *B : D->bindings())
1216     Record.AddDeclRef(B);
1217   Code = serialization::DECL_DECOMPOSITION;
1218 }
1219 
1220 void ASTDeclWriter::VisitBindingDecl(BindingDecl *D) {
1221   VisitValueDecl(D);
1222   Record.AddStmt(D->getBinding());
1223   Code = serialization::DECL_BINDING;
1224 }
1225 
1226 void ASTDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
1227   VisitDecl(D);
1228   Record.AddStmt(D->getAsmString());
1229   Record.AddSourceLocation(D->getRParenLoc());
1230   Code = serialization::DECL_FILE_SCOPE_ASM;
1231 }
1232 
1233 void ASTDeclWriter::VisitTopLevelStmtDecl(TopLevelStmtDecl *D) {
1234   VisitDecl(D);
1235   Record.AddStmt(D->getStmt());
1236   Code = serialization::DECL_TOP_LEVEL_STMT_DECL;
1237 }
1238 
1239 void ASTDeclWriter::VisitEmptyDecl(EmptyDecl *D) {
1240   VisitDecl(D);
1241   Code = serialization::DECL_EMPTY;
1242 }
1243 
1244 void ASTDeclWriter::VisitLifetimeExtendedTemporaryDecl(
1245     LifetimeExtendedTemporaryDecl *D) {
1246   VisitDecl(D);
1247   Record.AddDeclRef(D->getExtendingDecl());
1248   Record.AddStmt(D->getTemporaryExpr());
1249   Record.push_back(static_cast<bool>(D->getValue()));
1250   if (D->getValue())
1251     Record.AddAPValue(*D->getValue());
1252   Record.push_back(D->getManglingNumber());
1253   Code = serialization::DECL_LIFETIME_EXTENDED_TEMPORARY;
1254 }
1255 void ASTDeclWriter::VisitBlockDecl(BlockDecl *D) {
1256   VisitDecl(D);
1257   Record.AddStmt(D->getBody());
1258   Record.AddTypeSourceInfo(D->getSignatureAsWritten());
1259   Record.push_back(D->param_size());
1260   for (ParmVarDecl *P : D->parameters())
1261     Record.AddDeclRef(P);
1262   Record.push_back(D->isVariadic());
1263   Record.push_back(D->blockMissingReturnType());
1264   Record.push_back(D->isConversionFromLambda());
1265   Record.push_back(D->doesNotEscape());
1266   Record.push_back(D->canAvoidCopyToHeap());
1267   Record.push_back(D->capturesCXXThis());
1268   Record.push_back(D->getNumCaptures());
1269   for (const auto &capture : D->captures()) {
1270     Record.AddDeclRef(capture.getVariable());
1271 
1272     unsigned flags = 0;
1273     if (capture.isByRef()) flags |= 1;
1274     if (capture.isNested()) flags |= 2;
1275     if (capture.hasCopyExpr()) flags |= 4;
1276     Record.push_back(flags);
1277 
1278     if (capture.hasCopyExpr()) Record.AddStmt(capture.getCopyExpr());
1279   }
1280 
1281   Code = serialization::DECL_BLOCK;
1282 }
1283 
1284 void ASTDeclWriter::VisitCapturedDecl(CapturedDecl *CD) {
1285   Record.push_back(CD->getNumParams());
1286   VisitDecl(CD);
1287   Record.push_back(CD->getContextParamPosition());
1288   Record.push_back(CD->isNothrow() ? 1 : 0);
1289   // Body is stored by VisitCapturedStmt.
1290   for (unsigned I = 0; I < CD->getNumParams(); ++I)
1291     Record.AddDeclRef(CD->getParam(I));
1292   Code = serialization::DECL_CAPTURED;
1293 }
1294 
1295 void ASTDeclWriter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1296   static_assert(DeclContext::NumLinkageSpecDeclBits == 17,
1297                 "You need to update the serializer after you change the"
1298                 "LinkageSpecDeclBits");
1299 
1300   VisitDecl(D);
1301   Record.push_back(llvm::to_underlying(D->getLanguage()));
1302   Record.AddSourceLocation(D->getExternLoc());
1303   Record.AddSourceLocation(D->getRBraceLoc());
1304   Code = serialization::DECL_LINKAGE_SPEC;
1305 }
1306 
1307 void ASTDeclWriter::VisitExportDecl(ExportDecl *D) {
1308   VisitDecl(D);
1309   Record.AddSourceLocation(D->getRBraceLoc());
1310   Code = serialization::DECL_EXPORT;
1311 }
1312 
1313 void ASTDeclWriter::VisitLabelDecl(LabelDecl *D) {
1314   VisitNamedDecl(D);
1315   Record.AddSourceLocation(D->getBeginLoc());
1316   Code = serialization::DECL_LABEL;
1317 }
1318 
1319 
1320 void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) {
1321   VisitRedeclarable(D);
1322   VisitNamedDecl(D);
1323 
1324   BitsPacker NamespaceDeclBits;
1325   NamespaceDeclBits.addBit(D->isInline());
1326   NamespaceDeclBits.addBit(D->isNested());
1327   Record.push_back(NamespaceDeclBits);
1328 
1329   Record.AddSourceLocation(D->getBeginLoc());
1330   Record.AddSourceLocation(D->getRBraceLoc());
1331 
1332   if (D->isOriginalNamespace())
1333     Record.AddDeclRef(D->getAnonymousNamespace());
1334   Code = serialization::DECL_NAMESPACE;
1335 
1336   if (Writer.hasChain() && D->isAnonymousNamespace() &&
1337       D == D->getMostRecentDecl()) {
1338     // This is a most recent reopening of the anonymous namespace. If its parent
1339     // is in a previous PCH (or is the TU), mark that parent for update, because
1340     // the original namespace always points to the latest re-opening of its
1341     // anonymous namespace.
1342     Decl *Parent = cast<Decl>(
1343         D->getParent()->getRedeclContext()->getPrimaryContext());
1344     if (Parent->isFromASTFile() || isa<TranslationUnitDecl>(Parent)) {
1345       Writer.DeclUpdates[Parent].push_back(
1346           ASTWriter::DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, D));
1347     }
1348   }
1349 }
1350 
1351 void ASTDeclWriter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1352   VisitRedeclarable(D);
1353   VisitNamedDecl(D);
1354   Record.AddSourceLocation(D->getNamespaceLoc());
1355   Record.AddSourceLocation(D->getTargetNameLoc());
1356   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1357   Record.AddDeclRef(D->getNamespace());
1358   Code = serialization::DECL_NAMESPACE_ALIAS;
1359 }
1360 
1361 void ASTDeclWriter::VisitUsingDecl(UsingDecl *D) {
1362   VisitNamedDecl(D);
1363   Record.AddSourceLocation(D->getUsingLoc());
1364   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1365   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
1366   Record.AddDeclRef(D->FirstUsingShadow.getPointer());
1367   Record.push_back(D->hasTypename());
1368   Record.AddDeclRef(Context.getInstantiatedFromUsingDecl(D));
1369   Code = serialization::DECL_USING;
1370 }
1371 
1372 void ASTDeclWriter::VisitUsingEnumDecl(UsingEnumDecl *D) {
1373   VisitNamedDecl(D);
1374   Record.AddSourceLocation(D->getUsingLoc());
1375   Record.AddSourceLocation(D->getEnumLoc());
1376   Record.AddTypeSourceInfo(D->getEnumType());
1377   Record.AddDeclRef(D->FirstUsingShadow.getPointer());
1378   Record.AddDeclRef(Context.getInstantiatedFromUsingEnumDecl(D));
1379   Code = serialization::DECL_USING_ENUM;
1380 }
1381 
1382 void ASTDeclWriter::VisitUsingPackDecl(UsingPackDecl *D) {
1383   Record.push_back(D->NumExpansions);
1384   VisitNamedDecl(D);
1385   Record.AddDeclRef(D->getInstantiatedFromUsingDecl());
1386   for (auto *E : D->expansions())
1387     Record.AddDeclRef(E);
1388   Code = serialization::DECL_USING_PACK;
1389 }
1390 
1391 void ASTDeclWriter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1392   VisitRedeclarable(D);
1393   VisitNamedDecl(D);
1394   Record.AddDeclRef(D->getTargetDecl());
1395   Record.push_back(D->getIdentifierNamespace());
1396   Record.AddDeclRef(D->UsingOrNextShadow);
1397   Record.AddDeclRef(Context.getInstantiatedFromUsingShadowDecl(D));
1398 
1399   if (D->getDeclContext() == D->getLexicalDeclContext() &&
1400       D->getFirstDecl() == D->getMostRecentDecl() && !D->hasAttrs() &&
1401       !needsAnonymousDeclarationNumber(D) &&
1402       D->getDeclName().getNameKind() == DeclarationName::Identifier)
1403     AbbrevToUse = Writer.getDeclUsingShadowAbbrev();
1404 
1405   Code = serialization::DECL_USING_SHADOW;
1406 }
1407 
1408 void ASTDeclWriter::VisitConstructorUsingShadowDecl(
1409     ConstructorUsingShadowDecl *D) {
1410   VisitUsingShadowDecl(D);
1411   Record.AddDeclRef(D->NominatedBaseClassShadowDecl);
1412   Record.AddDeclRef(D->ConstructedBaseClassShadowDecl);
1413   Record.push_back(D->IsVirtual);
1414   Code = serialization::DECL_CONSTRUCTOR_USING_SHADOW;
1415 }
1416 
1417 void ASTDeclWriter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1418   VisitNamedDecl(D);
1419   Record.AddSourceLocation(D->getUsingLoc());
1420   Record.AddSourceLocation(D->getNamespaceKeyLocation());
1421   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1422   Record.AddDeclRef(D->getNominatedNamespace());
1423   Record.AddDeclRef(dyn_cast<Decl>(D->getCommonAncestor()));
1424   Code = serialization::DECL_USING_DIRECTIVE;
1425 }
1426 
1427 void ASTDeclWriter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1428   VisitValueDecl(D);
1429   Record.AddSourceLocation(D->getUsingLoc());
1430   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1431   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
1432   Record.AddSourceLocation(D->getEllipsisLoc());
1433   Code = serialization::DECL_UNRESOLVED_USING_VALUE;
1434 }
1435 
1436 void ASTDeclWriter::VisitUnresolvedUsingTypenameDecl(
1437                                                UnresolvedUsingTypenameDecl *D) {
1438   VisitTypeDecl(D);
1439   Record.AddSourceLocation(D->getTypenameLoc());
1440   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1441   Record.AddSourceLocation(D->getEllipsisLoc());
1442   Code = serialization::DECL_UNRESOLVED_USING_TYPENAME;
1443 }
1444 
1445 void ASTDeclWriter::VisitUnresolvedUsingIfExistsDecl(
1446     UnresolvedUsingIfExistsDecl *D) {
1447   VisitNamedDecl(D);
1448   Code = serialization::DECL_UNRESOLVED_USING_IF_EXISTS;
1449 }
1450 
1451 void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
1452   VisitRecordDecl(D);
1453 
1454   enum {
1455     CXXRecNotTemplate = 0,
1456     CXXRecTemplate,
1457     CXXRecMemberSpecialization,
1458     CXXLambda
1459   };
1460   if (ClassTemplateDecl *TemplD = D->getDescribedClassTemplate()) {
1461     Record.push_back(CXXRecTemplate);
1462     Record.AddDeclRef(TemplD);
1463   } else if (MemberSpecializationInfo *MSInfo
1464                = D->getMemberSpecializationInfo()) {
1465     Record.push_back(CXXRecMemberSpecialization);
1466     Record.AddDeclRef(MSInfo->getInstantiatedFrom());
1467     Record.push_back(MSInfo->getTemplateSpecializationKind());
1468     Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
1469   } else if (D->isLambda()) {
1470     // For a lambda, we need some information early for merging.
1471     Record.push_back(CXXLambda);
1472     if (auto *Context = D->getLambdaContextDecl()) {
1473       Record.AddDeclRef(Context);
1474       Record.push_back(D->getLambdaIndexInContext());
1475     } else {
1476       Record.push_back(0);
1477     }
1478   } else {
1479     Record.push_back(CXXRecNotTemplate);
1480   }
1481 
1482   Record.push_back(D->isThisDeclarationADefinition());
1483   if (D->isThisDeclarationADefinition())
1484     Record.AddCXXDefinitionData(D);
1485 
1486   // Store (what we currently believe to be) the key function to avoid
1487   // deserializing every method so we can compute it.
1488   if (D->isCompleteDefinition())
1489     Record.AddDeclRef(Context.getCurrentKeyFunction(D));
1490 
1491   Code = serialization::DECL_CXX_RECORD;
1492 }
1493 
1494 void ASTDeclWriter::VisitCXXMethodDecl(CXXMethodDecl *D) {
1495   VisitFunctionDecl(D);
1496   if (D->isCanonicalDecl()) {
1497     Record.push_back(D->size_overridden_methods());
1498     for (const CXXMethodDecl *MD : D->overridden_methods())
1499       Record.AddDeclRef(MD);
1500   } else {
1501     // We only need to record overridden methods once for the canonical decl.
1502     Record.push_back(0);
1503   }
1504 
1505   if (D->getDeclContext() == D->getLexicalDeclContext() &&
1506       D->getFirstDecl() == D->getMostRecentDecl() && !D->isInvalidDecl() &&
1507       !D->hasAttrs() && !D->isTopLevelDeclInObjCContainer() &&
1508       D->getDeclName().getNameKind() == DeclarationName::Identifier &&
1509       !D->hasExtInfo() && !D->isExplicitlyDefaulted()) {
1510     if (D->getTemplatedKind() == FunctionDecl::TK_NonTemplate ||
1511         D->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate ||
1512         D->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization ||
1513         D->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)
1514       AbbrevToUse = Writer.getDeclCXXMethodAbbrev(D->getTemplatedKind());
1515     else if (D->getTemplatedKind() ==
1516              FunctionDecl::TK_FunctionTemplateSpecialization) {
1517       FunctionTemplateSpecializationInfo *FTSInfo =
1518           D->getTemplateSpecializationInfo();
1519 
1520       if (FTSInfo->TemplateArguments->size() == 1) {
1521         const TemplateArgument &TA = FTSInfo->TemplateArguments->get(0);
1522         if (TA.getKind() == TemplateArgument::Type &&
1523             !FTSInfo->TemplateArgumentsAsWritten &&
1524             !FTSInfo->getMemberSpecializationInfo())
1525           AbbrevToUse = Writer.getDeclCXXMethodAbbrev(D->getTemplatedKind());
1526       }
1527     } else if (D->getTemplatedKind() ==
1528                FunctionDecl::TK_DependentFunctionTemplateSpecialization) {
1529       DependentFunctionTemplateSpecializationInfo *DFTSInfo =
1530           D->getDependentSpecializationInfo();
1531       if (!DFTSInfo->TemplateArgumentsAsWritten)
1532         AbbrevToUse = Writer.getDeclCXXMethodAbbrev(D->getTemplatedKind());
1533     }
1534   }
1535 
1536   Code = serialization::DECL_CXX_METHOD;
1537 }
1538 
1539 void ASTDeclWriter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1540   static_assert(DeclContext::NumCXXConstructorDeclBits == 64,
1541                 "You need to update the serializer after you change the "
1542                 "CXXConstructorDeclBits");
1543 
1544   Record.push_back(D->getTrailingAllocKind());
1545   addExplicitSpecifier(D->getExplicitSpecifier(), Record);
1546   if (auto Inherited = D->getInheritedConstructor()) {
1547     Record.AddDeclRef(Inherited.getShadowDecl());
1548     Record.AddDeclRef(Inherited.getConstructor());
1549   }
1550 
1551   VisitCXXMethodDecl(D);
1552   Code = serialization::DECL_CXX_CONSTRUCTOR;
1553 }
1554 
1555 void ASTDeclWriter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1556   VisitCXXMethodDecl(D);
1557 
1558   Record.AddDeclRef(D->getOperatorDelete());
1559   if (D->getOperatorDelete())
1560     Record.AddStmt(D->getOperatorDeleteThisArg());
1561 
1562   Code = serialization::DECL_CXX_DESTRUCTOR;
1563 }
1564 
1565 void ASTDeclWriter::VisitCXXConversionDecl(CXXConversionDecl *D) {
1566   addExplicitSpecifier(D->getExplicitSpecifier(), Record);
1567   VisitCXXMethodDecl(D);
1568   Code = serialization::DECL_CXX_CONVERSION;
1569 }
1570 
1571 void ASTDeclWriter::VisitImportDecl(ImportDecl *D) {
1572   VisitDecl(D);
1573   Record.push_back(Writer.getSubmoduleID(D->getImportedModule()));
1574   ArrayRef<SourceLocation> IdentifierLocs = D->getIdentifierLocs();
1575   Record.push_back(!IdentifierLocs.empty());
1576   if (IdentifierLocs.empty()) {
1577     Record.AddSourceLocation(D->getEndLoc());
1578     Record.push_back(1);
1579   } else {
1580     for (unsigned I = 0, N = IdentifierLocs.size(); I != N; ++I)
1581       Record.AddSourceLocation(IdentifierLocs[I]);
1582     Record.push_back(IdentifierLocs.size());
1583   }
1584   // Note: the number of source locations must always be the last element in
1585   // the record.
1586   Code = serialization::DECL_IMPORT;
1587 }
1588 
1589 void ASTDeclWriter::VisitAccessSpecDecl(AccessSpecDecl *D) {
1590   VisitDecl(D);
1591   Record.AddSourceLocation(D->getColonLoc());
1592   Code = serialization::DECL_ACCESS_SPEC;
1593 }
1594 
1595 void ASTDeclWriter::VisitFriendDecl(FriendDecl *D) {
1596   // Record the number of friend type template parameter lists here
1597   // so as to simplify memory allocation during deserialization.
1598   Record.push_back(D->NumTPLists);
1599   VisitDecl(D);
1600   bool hasFriendDecl = D->Friend.is<NamedDecl*>();
1601   Record.push_back(hasFriendDecl);
1602   if (hasFriendDecl)
1603     Record.AddDeclRef(D->getFriendDecl());
1604   else
1605     Record.AddTypeSourceInfo(D->getFriendType());
1606   for (unsigned i = 0; i < D->NumTPLists; ++i)
1607     Record.AddTemplateParameterList(D->getFriendTypeTemplateParameterList(i));
1608   Record.AddDeclRef(D->getNextFriend());
1609   Record.push_back(D->UnsupportedFriend);
1610   Record.AddSourceLocation(D->FriendLoc);
1611   Code = serialization::DECL_FRIEND;
1612 }
1613 
1614 void ASTDeclWriter::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1615   VisitDecl(D);
1616   Record.push_back(D->getNumTemplateParameters());
1617   for (unsigned i = 0, e = D->getNumTemplateParameters(); i != e; ++i)
1618     Record.AddTemplateParameterList(D->getTemplateParameterList(i));
1619   Record.push_back(D->getFriendDecl() != nullptr);
1620   if (D->getFriendDecl())
1621     Record.AddDeclRef(D->getFriendDecl());
1622   else
1623     Record.AddTypeSourceInfo(D->getFriendType());
1624   Record.AddSourceLocation(D->getFriendLoc());
1625   Code = serialization::DECL_FRIEND_TEMPLATE;
1626 }
1627 
1628 void ASTDeclWriter::VisitTemplateDecl(TemplateDecl *D) {
1629   VisitNamedDecl(D);
1630 
1631   Record.AddTemplateParameterList(D->getTemplateParameters());
1632   Record.AddDeclRef(D->getTemplatedDecl());
1633 }
1634 
1635 void ASTDeclWriter::VisitConceptDecl(ConceptDecl *D) {
1636   VisitTemplateDecl(D);
1637   Record.AddStmt(D->getConstraintExpr());
1638   Code = serialization::DECL_CONCEPT;
1639 }
1640 
1641 void ASTDeclWriter::VisitImplicitConceptSpecializationDecl(
1642     ImplicitConceptSpecializationDecl *D) {
1643   Record.push_back(D->getTemplateArguments().size());
1644   VisitDecl(D);
1645   for (const TemplateArgument &Arg : D->getTemplateArguments())
1646     Record.AddTemplateArgument(Arg);
1647   Code = serialization::DECL_IMPLICIT_CONCEPT_SPECIALIZATION;
1648 }
1649 
1650 void ASTDeclWriter::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
1651   Code = serialization::DECL_REQUIRES_EXPR_BODY;
1652 }
1653 
1654 void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1655   VisitRedeclarable(D);
1656 
1657   // Emit data to initialize CommonOrPrev before VisitTemplateDecl so that
1658   // getCommonPtr() can be used while this is still initializing.
1659   if (D->isFirstDecl()) {
1660     // This declaration owns the 'common' pointer, so serialize that data now.
1661     Record.AddDeclRef(D->getInstantiatedFromMemberTemplate());
1662     if (D->getInstantiatedFromMemberTemplate())
1663       Record.push_back(D->isMemberSpecialization());
1664   }
1665 
1666   VisitTemplateDecl(D);
1667   Record.push_back(D->getIdentifierNamespace());
1668 }
1669 
1670 void ASTDeclWriter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1671   VisitRedeclarableTemplateDecl(D);
1672 
1673   if (D->isFirstDecl())
1674     AddTemplateSpecializations(D);
1675   Code = serialization::DECL_CLASS_TEMPLATE;
1676 }
1677 
1678 void ASTDeclWriter::VisitClassTemplateSpecializationDecl(
1679                                            ClassTemplateSpecializationDecl *D) {
1680   RegisterTemplateSpecialization(D->getSpecializedTemplate(), D);
1681 
1682   VisitCXXRecordDecl(D);
1683 
1684   llvm::PointerUnion<ClassTemplateDecl *,
1685                      ClassTemplatePartialSpecializationDecl *> InstFrom
1686     = D->getSpecializedTemplateOrPartial();
1687   if (Decl *InstFromD = InstFrom.dyn_cast<ClassTemplateDecl *>()) {
1688     Record.AddDeclRef(InstFromD);
1689   } else {
1690     Record.AddDeclRef(InstFrom.get<ClassTemplatePartialSpecializationDecl *>());
1691     Record.AddTemplateArgumentList(&D->getTemplateInstantiationArgs());
1692   }
1693 
1694   Record.AddTemplateArgumentList(&D->getTemplateArgs());
1695   Record.AddSourceLocation(D->getPointOfInstantiation());
1696   Record.push_back(D->getSpecializationKind());
1697   Record.push_back(D->isCanonicalDecl());
1698 
1699   if (D->isCanonicalDecl()) {
1700     // When reading, we'll add it to the folding set of the following template.
1701     Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl());
1702   }
1703 
1704   // Explicit info.
1705   Record.AddTypeSourceInfo(D->getTypeAsWritten());
1706   if (D->getTypeAsWritten()) {
1707     Record.AddSourceLocation(D->getExternLoc());
1708     Record.AddSourceLocation(D->getTemplateKeywordLoc());
1709   }
1710 
1711   Code = serialization::DECL_CLASS_TEMPLATE_SPECIALIZATION;
1712 }
1713 
1714 void ASTDeclWriter::VisitClassTemplatePartialSpecializationDecl(
1715                                     ClassTemplatePartialSpecializationDecl *D) {
1716   Record.AddTemplateParameterList(D->getTemplateParameters());
1717   Record.AddASTTemplateArgumentListInfo(D->getTemplateArgsAsWritten());
1718 
1719   VisitClassTemplateSpecializationDecl(D);
1720 
1721   // These are read/set from/to the first declaration.
1722   if (D->getPreviousDecl() == nullptr) {
1723     Record.AddDeclRef(D->getInstantiatedFromMember());
1724     Record.push_back(D->isMemberSpecialization());
1725   }
1726 
1727   Code = serialization::DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION;
1728 }
1729 
1730 void ASTDeclWriter::VisitVarTemplateDecl(VarTemplateDecl *D) {
1731   VisitRedeclarableTemplateDecl(D);
1732 
1733   if (D->isFirstDecl())
1734     AddTemplateSpecializations(D);
1735   Code = serialization::DECL_VAR_TEMPLATE;
1736 }
1737 
1738 void ASTDeclWriter::VisitVarTemplateSpecializationDecl(
1739     VarTemplateSpecializationDecl *D) {
1740   RegisterTemplateSpecialization(D->getSpecializedTemplate(), D);
1741 
1742   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
1743   InstFrom = D->getSpecializedTemplateOrPartial();
1744   if (Decl *InstFromD = InstFrom.dyn_cast<VarTemplateDecl *>()) {
1745     Record.AddDeclRef(InstFromD);
1746   } else {
1747     Record.AddDeclRef(InstFrom.get<VarTemplatePartialSpecializationDecl *>());
1748     Record.AddTemplateArgumentList(&D->getTemplateInstantiationArgs());
1749   }
1750 
1751   // Explicit info.
1752   Record.AddTypeSourceInfo(D->getTypeAsWritten());
1753   if (D->getTypeAsWritten()) {
1754     Record.AddSourceLocation(D->getExternLoc());
1755     Record.AddSourceLocation(D->getTemplateKeywordLoc());
1756   }
1757 
1758   Record.AddTemplateArgumentList(&D->getTemplateArgs());
1759   Record.AddSourceLocation(D->getPointOfInstantiation());
1760   Record.push_back(D->getSpecializationKind());
1761   Record.push_back(D->IsCompleteDefinition);
1762 
1763   VisitVarDecl(D);
1764 
1765   Record.push_back(D->isCanonicalDecl());
1766 
1767   if (D->isCanonicalDecl()) {
1768     // When reading, we'll add it to the folding set of the following template.
1769     Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl());
1770   }
1771 
1772   Code = serialization::DECL_VAR_TEMPLATE_SPECIALIZATION;
1773 }
1774 
1775 void ASTDeclWriter::VisitVarTemplatePartialSpecializationDecl(
1776     VarTemplatePartialSpecializationDecl *D) {
1777   Record.AddTemplateParameterList(D->getTemplateParameters());
1778   Record.AddASTTemplateArgumentListInfo(D->getTemplateArgsAsWritten());
1779 
1780   VisitVarTemplateSpecializationDecl(D);
1781 
1782   // These are read/set from/to the first declaration.
1783   if (D->getPreviousDecl() == nullptr) {
1784     Record.AddDeclRef(D->getInstantiatedFromMember());
1785     Record.push_back(D->isMemberSpecialization());
1786   }
1787 
1788   Code = serialization::DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION;
1789 }
1790 
1791 void ASTDeclWriter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1792   VisitRedeclarableTemplateDecl(D);
1793 
1794   if (D->isFirstDecl())
1795     AddTemplateSpecializations(D);
1796   Code = serialization::DECL_FUNCTION_TEMPLATE;
1797 }
1798 
1799 void ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1800   Record.push_back(D->hasTypeConstraint());
1801   VisitTypeDecl(D);
1802 
1803   Record.push_back(D->wasDeclaredWithTypename());
1804 
1805   const TypeConstraint *TC = D->getTypeConstraint();
1806   assert((bool)TC == D->hasTypeConstraint());
1807   if (TC) {
1808     auto *CR = TC->getConceptReference();
1809     Record.push_back(CR != nullptr);
1810     if (CR)
1811       Record.AddConceptReference(CR);
1812     Record.AddStmt(TC->getImmediatelyDeclaredConstraint());
1813     Record.push_back(D->isExpandedParameterPack());
1814     if (D->isExpandedParameterPack())
1815       Record.push_back(D->getNumExpansionParameters());
1816   }
1817 
1818   bool OwnsDefaultArg = D->hasDefaultArgument() &&
1819                         !D->defaultArgumentWasInherited();
1820   Record.push_back(OwnsDefaultArg);
1821   if (OwnsDefaultArg)
1822     Record.AddTypeSourceInfo(D->getDefaultArgumentInfo());
1823 
1824   if (!TC && !OwnsDefaultArg &&
1825       D->getDeclContext() == D->getLexicalDeclContext() &&
1826       !D->isInvalidDecl() && !D->hasAttrs() &&
1827       !D->isTopLevelDeclInObjCContainer() && !D->isImplicit() &&
1828       D->getDeclName().getNameKind() == DeclarationName::Identifier)
1829     AbbrevToUse = Writer.getDeclTemplateTypeParmAbbrev();
1830 
1831   Code = serialization::DECL_TEMPLATE_TYPE_PARM;
1832 }
1833 
1834 void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1835   // For an expanded parameter pack, record the number of expansion types here
1836   // so that it's easier for deserialization to allocate the right amount of
1837   // memory.
1838   Expr *TypeConstraint = D->getPlaceholderTypeConstraint();
1839   Record.push_back(!!TypeConstraint);
1840   if (D->isExpandedParameterPack())
1841     Record.push_back(D->getNumExpansionTypes());
1842 
1843   VisitDeclaratorDecl(D);
1844   // TemplateParmPosition.
1845   Record.push_back(D->getDepth());
1846   Record.push_back(D->getPosition());
1847   if (TypeConstraint)
1848     Record.AddStmt(TypeConstraint);
1849 
1850   if (D->isExpandedParameterPack()) {
1851     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1852       Record.AddTypeRef(D->getExpansionType(I));
1853       Record.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I));
1854     }
1855 
1856     Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK;
1857   } else {
1858     // Rest of NonTypeTemplateParmDecl.
1859     Record.push_back(D->isParameterPack());
1860     bool OwnsDefaultArg = D->hasDefaultArgument() &&
1861                           !D->defaultArgumentWasInherited();
1862     Record.push_back(OwnsDefaultArg);
1863     if (OwnsDefaultArg)
1864       Record.AddStmt(D->getDefaultArgument());
1865     Code = serialization::DECL_NON_TYPE_TEMPLATE_PARM;
1866   }
1867 }
1868 
1869 void ASTDeclWriter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1870   // For an expanded parameter pack, record the number of expansion types here
1871   // so that it's easier for deserialization to allocate the right amount of
1872   // memory.
1873   if (D->isExpandedParameterPack())
1874     Record.push_back(D->getNumExpansionTemplateParameters());
1875 
1876   VisitTemplateDecl(D);
1877   // TemplateParmPosition.
1878   Record.push_back(D->getDepth());
1879   Record.push_back(D->getPosition());
1880 
1881   if (D->isExpandedParameterPack()) {
1882     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1883          I != N; ++I)
1884       Record.AddTemplateParameterList(D->getExpansionTemplateParameters(I));
1885     Code = serialization::DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK;
1886   } else {
1887     // Rest of TemplateTemplateParmDecl.
1888     Record.push_back(D->isParameterPack());
1889     bool OwnsDefaultArg = D->hasDefaultArgument() &&
1890                           !D->defaultArgumentWasInherited();
1891     Record.push_back(OwnsDefaultArg);
1892     if (OwnsDefaultArg)
1893       Record.AddTemplateArgumentLoc(D->getDefaultArgument());
1894     Code = serialization::DECL_TEMPLATE_TEMPLATE_PARM;
1895   }
1896 }
1897 
1898 void ASTDeclWriter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1899   VisitRedeclarableTemplateDecl(D);
1900   Code = serialization::DECL_TYPE_ALIAS_TEMPLATE;
1901 }
1902 
1903 void ASTDeclWriter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1904   VisitDecl(D);
1905   Record.AddStmt(D->getAssertExpr());
1906   Record.push_back(D->isFailed());
1907   Record.AddStmt(D->getMessage());
1908   Record.AddSourceLocation(D->getRParenLoc());
1909   Code = serialization::DECL_STATIC_ASSERT;
1910 }
1911 
1912 /// Emit the DeclContext part of a declaration context decl.
1913 void ASTDeclWriter::VisitDeclContext(DeclContext *DC) {
1914   static_assert(DeclContext::NumDeclContextBits == 13,
1915                 "You need to update the serializer after you change the "
1916                 "DeclContextBits");
1917 
1918   Record.AddOffset(Writer.WriteDeclContextLexicalBlock(Context, DC));
1919   Record.AddOffset(Writer.WriteDeclContextVisibleBlock(Context, DC));
1920 }
1921 
1922 const Decl *ASTWriter::getFirstLocalDecl(const Decl *D) {
1923   assert(IsLocalDecl(D) && "expected a local declaration");
1924 
1925   const Decl *Canon = D->getCanonicalDecl();
1926   if (IsLocalDecl(Canon))
1927     return Canon;
1928 
1929   const Decl *&CacheEntry = FirstLocalDeclCache[Canon];
1930   if (CacheEntry)
1931     return CacheEntry;
1932 
1933   for (const Decl *Redecl = D; Redecl; Redecl = Redecl->getPreviousDecl())
1934     if (IsLocalDecl(Redecl))
1935       D = Redecl;
1936   return CacheEntry = D;
1937 }
1938 
1939 template <typename T>
1940 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
1941   T *First = D->getFirstDecl();
1942   T *MostRecent = First->getMostRecentDecl();
1943   T *DAsT = static_cast<T *>(D);
1944   if (MostRecent != First) {
1945     assert(isRedeclarableDeclKind(DAsT->getKind()) &&
1946            "Not considered redeclarable?");
1947 
1948     Record.AddDeclRef(First);
1949 
1950     // Write out a list of local redeclarations of this declaration if it's the
1951     // first local declaration in the chain.
1952     const Decl *FirstLocal = Writer.getFirstLocalDecl(DAsT);
1953     if (DAsT == FirstLocal) {
1954       // Emit a list of all imported first declarations so that we can be sure
1955       // that all redeclarations visible to this module are before D in the
1956       // redecl chain.
1957       unsigned I = Record.size();
1958       Record.push_back(0);
1959       if (Writer.Chain)
1960         AddFirstDeclFromEachModule(DAsT, /*IncludeLocal*/false);
1961       // This is the number of imported first declarations + 1.
1962       Record[I] = Record.size() - I;
1963 
1964       // Collect the set of local redeclarations of this declaration, from
1965       // newest to oldest.
1966       ASTWriter::RecordData LocalRedecls;
1967       ASTRecordWriter LocalRedeclWriter(Record, LocalRedecls);
1968       for (const Decl *Prev = FirstLocal->getMostRecentDecl();
1969            Prev != FirstLocal; Prev = Prev->getPreviousDecl())
1970         if (!Prev->isFromASTFile())
1971           LocalRedeclWriter.AddDeclRef(Prev);
1972 
1973       // If we have any redecls, write them now as a separate record preceding
1974       // the declaration itself.
1975       if (LocalRedecls.empty())
1976         Record.push_back(0);
1977       else
1978         Record.AddOffset(LocalRedeclWriter.Emit(LOCAL_REDECLARATIONS));
1979     } else {
1980       Record.push_back(0);
1981       Record.AddDeclRef(FirstLocal);
1982     }
1983 
1984     // Make sure that we serialize both the previous and the most-recent
1985     // declarations, which (transitively) ensures that all declarations in the
1986     // chain get serialized.
1987     //
1988     // FIXME: This is not correct; when we reach an imported declaration we
1989     // won't emit its previous declaration.
1990     (void)Writer.GetDeclRef(D->getPreviousDecl());
1991     (void)Writer.GetDeclRef(MostRecent);
1992   } else {
1993     // We use the sentinel value 0 to indicate an only declaration.
1994     Record.push_back(0);
1995   }
1996 }
1997 
1998 void ASTDeclWriter::VisitHLSLBufferDecl(HLSLBufferDecl *D) {
1999   VisitNamedDecl(D);
2000   VisitDeclContext(D);
2001   Record.push_back(D->isCBuffer());
2002   Record.AddSourceLocation(D->getLocStart());
2003   Record.AddSourceLocation(D->getLBraceLoc());
2004   Record.AddSourceLocation(D->getRBraceLoc());
2005 
2006   Code = serialization::DECL_HLSL_BUFFER;
2007 }
2008 
2009 void ASTDeclWriter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2010   Record.writeOMPChildren(D->Data);
2011   VisitDecl(D);
2012   Code = serialization::DECL_OMP_THREADPRIVATE;
2013 }
2014 
2015 void ASTDeclWriter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2016   Record.writeOMPChildren(D->Data);
2017   VisitDecl(D);
2018   Code = serialization::DECL_OMP_ALLOCATE;
2019 }
2020 
2021 void ASTDeclWriter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2022   Record.writeOMPChildren(D->Data);
2023   VisitDecl(D);
2024   Code = serialization::DECL_OMP_REQUIRES;
2025 }
2026 
2027 void ASTDeclWriter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2028   static_assert(DeclContext::NumOMPDeclareReductionDeclBits == 15,
2029                 "You need to update the serializer after you change the "
2030                 "NumOMPDeclareReductionDeclBits");
2031 
2032   VisitValueDecl(D);
2033   Record.AddSourceLocation(D->getBeginLoc());
2034   Record.AddStmt(D->getCombinerIn());
2035   Record.AddStmt(D->getCombinerOut());
2036   Record.AddStmt(D->getCombiner());
2037   Record.AddStmt(D->getInitOrig());
2038   Record.AddStmt(D->getInitPriv());
2039   Record.AddStmt(D->getInitializer());
2040   Record.push_back(llvm::to_underlying(D->getInitializerKind()));
2041   Record.AddDeclRef(D->getPrevDeclInScope());
2042   Code = serialization::DECL_OMP_DECLARE_REDUCTION;
2043 }
2044 
2045 void ASTDeclWriter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2046   Record.writeOMPChildren(D->Data);
2047   VisitValueDecl(D);
2048   Record.AddDeclarationName(D->getVarName());
2049   Record.AddDeclRef(D->getPrevDeclInScope());
2050   Code = serialization::DECL_OMP_DECLARE_MAPPER;
2051 }
2052 
2053 void ASTDeclWriter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2054   VisitVarDecl(D);
2055   Code = serialization::DECL_OMP_CAPTUREDEXPR;
2056 }
2057 
2058 //===----------------------------------------------------------------------===//
2059 // ASTWriter Implementation
2060 //===----------------------------------------------------------------------===//
2061 
2062 namespace {
2063 template <FunctionDecl::TemplatedKind Kind>
2064 std::shared_ptr<llvm::BitCodeAbbrev>
2065 getFunctionDeclAbbrev(serialization::DeclCode Code) {
2066   using namespace llvm;
2067 
2068   auto Abv = std::make_shared<BitCodeAbbrev>();
2069   Abv->Add(BitCodeAbbrevOp(Code));
2070   // RedeclarableDecl
2071   Abv->Add(BitCodeAbbrevOp(0)); // CanonicalDecl
2072   Abv->Add(BitCodeAbbrevOp(Kind));
2073   if constexpr (Kind == FunctionDecl::TK_NonTemplate) {
2074 
2075   } else if constexpr (Kind == FunctionDecl::TK_FunctionTemplate) {
2076     // DescribedFunctionTemplate
2077     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2078   } else if constexpr (Kind == FunctionDecl::TK_DependentNonTemplate) {
2079     // Instantiated From Decl
2080     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2081   } else if constexpr (Kind == FunctionDecl::TK_MemberSpecialization) {
2082     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InstantiatedFrom
2083     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2084                              3)); // TemplateSpecializationKind
2085     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Specialized Location
2086   } else if constexpr (Kind ==
2087                        FunctionDecl::TK_FunctionTemplateSpecialization) {
2088     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Template
2089     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2090                              3)); // TemplateSpecializationKind
2091     Abv->Add(BitCodeAbbrevOp(1)); // Template Argument Size
2092     Abv->Add(BitCodeAbbrevOp(TemplateArgument::Type)); // Template Argument Kind
2093     Abv->Add(
2094         BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Template Argument Type
2095     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is Defaulted
2096     Abv->Add(BitCodeAbbrevOp(0)); // TemplateArgumentsAsWritten
2097     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SourceLocation
2098     Abv->Add(BitCodeAbbrevOp(0));
2099     Abv->Add(
2100         BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Canonical Decl of template
2101   } else if constexpr (Kind == FunctionDecl::
2102                                    TK_DependentFunctionTemplateSpecialization) {
2103     // Candidates of specialization
2104     Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2105     Abv->Add(BitCodeAbbrevOp(0)); // TemplateArgumentsAsWritten
2106   } else {
2107     llvm_unreachable("Unknown templated kind?");
2108   }
2109   // Decl
2110   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2111                            8)); // Packed DeclBits: ModuleOwnershipKind,
2112                                 // isUsed, isReferenced,  AccessSpecifier,
2113                                 // isImplicit
2114                                 //
2115                                 // The following bits should be 0:
2116                                 // HasStandaloneLexicalDC, HasAttrs,
2117                                 // TopLevelDeclInObjCContainer,
2118                                 // isInvalidDecl
2119   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2120   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2121   // NamedDecl
2122   Abv->Add(BitCodeAbbrevOp(DeclarationName::Identifier)); // NameKind
2123   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));     // Identifier
2124   Abv->Add(BitCodeAbbrevOp(0));                           // AnonDeclNumber
2125   // ValueDecl
2126   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2127   // DeclaratorDecl
2128   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerLocStart
2129   Abv->Add(BitCodeAbbrevOp(0));                       // HasExtInfo
2130   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2131   // FunctionDecl
2132   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 11)); // IDNS
2133   Abv->Add(BitCodeAbbrevOp(
2134       BitCodeAbbrevOp::Fixed,
2135       27)); // Packed Function Bits: StorageClass, Inline, InlineSpecified,
2136             // VirtualAsWritten, Pure, HasInheritedProto, HasWrittenProto,
2137             // Deleted, Trivial, TrivialForCall, Defaulted, ExplicitlyDefaulted,
2138             // IsIneligibleOrNotSelected, ImplicitReturnZero, Constexpr,
2139             // UsesSEHTry, SkippedBody, MultiVersion, LateParsed,
2140             // FriendConstraintRefersToEnclosingTemplate, Linkage
2141   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // LocEnd
2142   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // ODRHash
2143   // This Array slurps the rest of the record. Fortunately we want to encode
2144   // (nearly) all the remaining (variable number of) fields in the same way.
2145   //
2146   // This is:
2147   //         NumParams and Params[] from FunctionDecl, and
2148   //         NumOverriddenMethods, OverriddenMethods[] from CXXMethodDecl.
2149   //
2150   //  Add an AbbrevOp for 'size then elements' and use it here.
2151   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2152   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2153   return Abv;
2154 }
2155 
2156 template <FunctionDecl::TemplatedKind Kind>
2157 std::shared_ptr<llvm::BitCodeAbbrev> getCXXMethodAbbrev() {
2158   return getFunctionDeclAbbrev<Kind>(serialization::DECL_CXX_METHOD);
2159 }
2160 } // namespace
2161 
2162 void ASTWriter::WriteDeclAbbrevs() {
2163   using namespace llvm;
2164 
2165   std::shared_ptr<BitCodeAbbrev> Abv;
2166 
2167   // Abbreviation for DECL_FIELD
2168   Abv = std::make_shared<BitCodeAbbrev>();
2169   Abv->Add(BitCodeAbbrevOp(serialization::DECL_FIELD));
2170   // Decl
2171   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2172                            7)); // Packed DeclBits: ModuleOwnershipKind,
2173                                 // isUsed, isReferenced,  AccessSpecifier,
2174                                 //
2175                                 // The following bits should be 0:
2176                                 // isImplicit, HasStandaloneLexicalDC, HasAttrs,
2177                                 // TopLevelDeclInObjCContainer,
2178                                 // isInvalidDecl
2179   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2180   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2181   // NamedDecl
2182   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2183   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2184   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2185   // ValueDecl
2186   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2187   // DeclaratorDecl
2188   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2189   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2190   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2191   // FieldDecl
2192   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isMutable
2193   Abv->Add(BitCodeAbbrevOp(0));                       // StorageKind
2194   // Type Source Info
2195   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2196   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2197   DeclFieldAbbrev = Stream.EmitAbbrev(std::move(Abv));
2198 
2199   // Abbreviation for DECL_OBJC_IVAR
2200   Abv = std::make_shared<BitCodeAbbrev>();
2201   Abv->Add(BitCodeAbbrevOp(serialization::DECL_OBJC_IVAR));
2202   // Decl
2203   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2204                            12)); // Packed DeclBits: HasStandaloneLexicalDC,
2205                                  // isInvalidDecl, HasAttrs, isImplicit, isUsed,
2206                                  // isReferenced, TopLevelDeclInObjCContainer,
2207                                  // AccessSpecifier, ModuleOwnershipKind
2208   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2209   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2210   // NamedDecl
2211   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2212   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2213   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2214   // ValueDecl
2215   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2216   // DeclaratorDecl
2217   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2218   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2219   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2220   // FieldDecl
2221   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isMutable
2222   Abv->Add(BitCodeAbbrevOp(0));                       // InitStyle
2223   // ObjC Ivar
2224   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getAccessControl
2225   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getSynthesize
2226   // Type Source Info
2227   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2228   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2229   DeclObjCIvarAbbrev = Stream.EmitAbbrev(std::move(Abv));
2230 
2231   // Abbreviation for DECL_ENUM
2232   Abv = std::make_shared<BitCodeAbbrev>();
2233   Abv->Add(BitCodeAbbrevOp(serialization::DECL_ENUM));
2234   // Redeclarable
2235   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2236   // Decl
2237   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2238                            7)); // Packed DeclBits: ModuleOwnershipKind,
2239                                 // isUsed, isReferenced,  AccessSpecifier,
2240                                 //
2241                                 // The following bits should be 0:
2242                                 // isImplicit, HasStandaloneLexicalDC, HasAttrs,
2243                                 // TopLevelDeclInObjCContainer,
2244                                 // isInvalidDecl
2245   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2246   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2247   // NamedDecl
2248   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2249   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2250   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2251   // TypeDecl
2252   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2253   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2254   // TagDecl
2255   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNamespace
2256   Abv->Add(BitCodeAbbrevOp(
2257       BitCodeAbbrevOp::Fixed,
2258       9)); // Packed Tag Decl Bits: getTagKind, isCompleteDefinition,
2259            // EmbeddedInDeclarator, IsFreeStanding,
2260            // isCompleteDefinitionRequired, ExtInfoKind
2261   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2262   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2263   // EnumDecl
2264   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddTypeRef
2265   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IntegerType
2266   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getPromotionType
2267   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 19)); // Enum Decl Bits
2268   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));// ODRHash
2269   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // InstantiatedMembEnum
2270   // DC
2271   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LexicalOffset
2272   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // VisibleOffset
2273   DeclEnumAbbrev = Stream.EmitAbbrev(std::move(Abv));
2274 
2275   // Abbreviation for DECL_RECORD
2276   Abv = std::make_shared<BitCodeAbbrev>();
2277   Abv->Add(BitCodeAbbrevOp(serialization::DECL_RECORD));
2278   // Redeclarable
2279   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2280   // Decl
2281   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2282                            7)); // Packed DeclBits: ModuleOwnershipKind,
2283                                 // isUsed, isReferenced,  AccessSpecifier,
2284                                 //
2285                                 // The following bits should be 0:
2286                                 // isImplicit, HasStandaloneLexicalDC, HasAttrs,
2287                                 // TopLevelDeclInObjCContainer,
2288                                 // isInvalidDecl
2289   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2290   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2291   // NamedDecl
2292   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2293   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2294   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2295   // TypeDecl
2296   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2297   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2298   // TagDecl
2299   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNamespace
2300   Abv->Add(BitCodeAbbrevOp(
2301       BitCodeAbbrevOp::Fixed,
2302       9)); // Packed Tag Decl Bits: getTagKind, isCompleteDefinition,
2303            // EmbeddedInDeclarator, IsFreeStanding,
2304            // isCompleteDefinitionRequired, ExtInfoKind
2305   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2306   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
2307   // RecordDecl
2308   Abv->Add(BitCodeAbbrevOp(
2309       BitCodeAbbrevOp::Fixed,
2310       13)); // Packed Record Decl Bits: FlexibleArrayMember,
2311             // AnonymousStructUnion, hasObjectMember, hasVolatileMember,
2312             // isNonTrivialToPrimitiveDefaultInitialize,
2313             // isNonTrivialToPrimitiveCopy, isNonTrivialToPrimitiveDestroy,
2314             // hasNonTrivialToPrimitiveDefaultInitializeCUnion,
2315             // hasNonTrivialToPrimitiveDestructCUnion,
2316             // hasNonTrivialToPrimitiveCopyCUnion, isParamDestroyedInCallee,
2317             // getArgPassingRestrictions
2318   // ODRHash
2319   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 26));
2320 
2321   // DC
2322   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LexicalOffset
2323   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // VisibleOffset
2324   DeclRecordAbbrev = Stream.EmitAbbrev(std::move(Abv));
2325 
2326   // Abbreviation for DECL_PARM_VAR
2327   Abv = std::make_shared<BitCodeAbbrev>();
2328   Abv->Add(BitCodeAbbrevOp(serialization::DECL_PARM_VAR));
2329   // Redeclarable
2330   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2331   // Decl
2332   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2333                            8)); // Packed DeclBits: ModuleOwnershipKind, isUsed,
2334                                 // isReferenced, AccessSpecifier,
2335                                 // HasStandaloneLexicalDC, HasAttrs, isImplicit,
2336                                 // TopLevelDeclInObjCContainer,
2337                                 // isInvalidDecl,
2338   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2339   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2340   // NamedDecl
2341   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2342   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2343   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2344   // ValueDecl
2345   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2346   // DeclaratorDecl
2347   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2348   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2349   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2350   // VarDecl
2351   Abv->Add(
2352       BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2353                       12)); // Packed Var Decl bits: SClass, TSCSpec, InitStyle,
2354                             // isARCPseudoStrong, Linkage, ModulesCodegen
2355   Abv->Add(BitCodeAbbrevOp(0));                          // VarKind (local enum)
2356   // ParmVarDecl
2357   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ScopeIndex
2358   Abv->Add(BitCodeAbbrevOp(
2359       BitCodeAbbrevOp::Fixed,
2360       19)); // Packed Parm Var Decl bits: IsObjCMethodParameter, ScopeDepth,
2361             // ObjCDeclQualifier, KNRPromoted,
2362             // HasInheritedDefaultArg, HasUninstantiatedDefaultArg
2363   // Type Source Info
2364   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2365   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2366   DeclParmVarAbbrev = Stream.EmitAbbrev(std::move(Abv));
2367 
2368   // Abbreviation for DECL_TYPEDEF
2369   Abv = std::make_shared<BitCodeAbbrev>();
2370   Abv->Add(BitCodeAbbrevOp(serialization::DECL_TYPEDEF));
2371   // Redeclarable
2372   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2373   // Decl
2374   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2375                            7)); // Packed DeclBits: ModuleOwnershipKind,
2376                                 // isReferenced, isUsed, AccessSpecifier. Other
2377                                 // higher bits should be 0: isImplicit,
2378                                 // HasStandaloneLexicalDC, HasAttrs,
2379                                 // TopLevelDeclInObjCContainer, isInvalidDecl
2380   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2381   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2382   // NamedDecl
2383   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2384   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2385   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2386   // TypeDecl
2387   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2388   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2389   // TypedefDecl
2390   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2391   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2392   DeclTypedefAbbrev = Stream.EmitAbbrev(std::move(Abv));
2393 
2394   // Abbreviation for DECL_VAR
2395   Abv = std::make_shared<BitCodeAbbrev>();
2396   Abv->Add(BitCodeAbbrevOp(serialization::DECL_VAR));
2397   // Redeclarable
2398   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
2399   // Decl
2400   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2401                            12)); // Packed DeclBits: HasStandaloneLexicalDC,
2402                                  // isInvalidDecl, HasAttrs, isImplicit, isUsed,
2403                                  // isReferenced, TopLevelDeclInObjCContainer,
2404                                  // AccessSpecifier, ModuleOwnershipKind
2405   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2406   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2407   // NamedDecl
2408   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2409   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2410   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
2411   // ValueDecl
2412   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2413   // DeclaratorDecl
2414   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
2415   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
2416   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TSIType
2417   // VarDecl
2418   Abv->Add(BitCodeAbbrevOp(
2419       BitCodeAbbrevOp::Fixed,
2420       21)); // Packed Var Decl bits:  Linkage, ModulesCodegen,
2421             // SClass, TSCSpec, InitStyle,
2422             // isARCPseudoStrong, IsThisDeclarationADemotedDefinition,
2423             // isExceptionVariable, isNRVOVariable, isCXXForRangeDecl,
2424             // isInline, isInlineSpecified, isConstexpr,
2425             // isInitCapture, isPrevDeclInSameScope,
2426             // EscapingByref, HasDeducedType, ImplicitParamKind, isObjCForDecl
2427   Abv->Add(BitCodeAbbrevOp(0));                         // VarKind (local enum)
2428   // Type Source Info
2429   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2430   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
2431   DeclVarAbbrev = Stream.EmitAbbrev(std::move(Abv));
2432 
2433   // Abbreviation for DECL_CXX_METHOD
2434   DeclCXXMethodAbbrev =
2435       Stream.EmitAbbrev(getCXXMethodAbbrev<FunctionDecl::TK_NonTemplate>());
2436   DeclTemplateCXXMethodAbbrev = Stream.EmitAbbrev(
2437       getCXXMethodAbbrev<FunctionDecl::TK_FunctionTemplate>());
2438   DeclDependentNonTemplateCXXMethodAbbrev = Stream.EmitAbbrev(
2439       getCXXMethodAbbrev<FunctionDecl::TK_DependentNonTemplate>());
2440   DeclMemberSpecializedCXXMethodAbbrev = Stream.EmitAbbrev(
2441       getCXXMethodAbbrev<FunctionDecl::TK_MemberSpecialization>());
2442   DeclTemplateSpecializedCXXMethodAbbrev = Stream.EmitAbbrev(
2443       getCXXMethodAbbrev<FunctionDecl::TK_FunctionTemplateSpecialization>());
2444   DeclDependentSpecializationCXXMethodAbbrev = Stream.EmitAbbrev(
2445       getCXXMethodAbbrev<
2446           FunctionDecl::TK_DependentFunctionTemplateSpecialization>());
2447 
2448   // Abbreviation for DECL_TEMPLATE_TYPE_PARM
2449   Abv = std::make_shared<BitCodeAbbrev>();
2450   Abv->Add(BitCodeAbbrevOp(serialization::DECL_TEMPLATE_TYPE_PARM));
2451   Abv->Add(BitCodeAbbrevOp(0)); // hasTypeConstraint
2452   // Decl
2453   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2454                            7)); // Packed DeclBits: ModuleOwnershipKind,
2455                                 // isReferenced, isUsed, AccessSpecifier. Other
2456                                 // higher bits should be 0: isImplicit,
2457                                 // HasStandaloneLexicalDC, HasAttrs,
2458                                 // TopLevelDeclInObjCContainer, isInvalidDecl
2459   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2460   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2461   // NamedDecl
2462   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2463   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2464   Abv->Add(BitCodeAbbrevOp(0));
2465   // TypeDecl
2466   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2467   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
2468   // TemplateTypeParmDecl
2469   Abv->Add(
2470       BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // wasDeclaredWithTypename
2471   Abv->Add(BitCodeAbbrevOp(0));                    // OwnsDefaultArg
2472   DeclTemplateTypeParmAbbrev = Stream.EmitAbbrev(std::move(Abv));
2473 
2474   // Abbreviation for DECL_USING_SHADOW
2475   Abv = std::make_shared<BitCodeAbbrev>();
2476   Abv->Add(BitCodeAbbrevOp(serialization::DECL_USING_SHADOW));
2477   // Redeclarable
2478   Abv->Add(BitCodeAbbrevOp(0)); // No redeclaration
2479   // Decl
2480   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2481                            12)); // Packed DeclBits: HasStandaloneLexicalDC,
2482                                  // isInvalidDecl, HasAttrs, isImplicit, isUsed,
2483                                  // isReferenced, TopLevelDeclInObjCContainer,
2484                                  // AccessSpecifier, ModuleOwnershipKind
2485   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
2486   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
2487   // NamedDecl
2488   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
2489   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
2490   Abv->Add(BitCodeAbbrevOp(0));
2491   // UsingShadowDecl
2492   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // TargetDecl
2493   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 11)); // IDNS
2494   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // UsingOrNextShadow
2495   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR,
2496                            6)); // InstantiatedFromUsingShadowDecl
2497   DeclUsingShadowAbbrev = Stream.EmitAbbrev(std::move(Abv));
2498 
2499   // Abbreviation for EXPR_DECL_REF
2500   Abv = std::make_shared<BitCodeAbbrev>();
2501   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_DECL_REF));
2502   // Stmt
2503   //  Expr
2504   //  PackingBits: DependenceKind, ValueKind. ObjectKind should be 0.
2505   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2506   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2507   // DeclRefExpr
2508   // Packing Bits: , HadMultipleCandidates, RefersToEnclosingVariableOrCapture,
2509   // IsImmediateEscalating, NonOdrUseReason.
2510   // GetDeclFound, HasQualifier and ExplicitTemplateArgs should be 0.
2511   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));
2512   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclRef
2513   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2514   DeclRefExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2515 
2516   // Abbreviation for EXPR_INTEGER_LITERAL
2517   Abv = std::make_shared<BitCodeAbbrev>();
2518   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_INTEGER_LITERAL));
2519   //Stmt
2520   // Expr
2521   // DependenceKind, ValueKind, ObjectKind
2522   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2523   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2524   // Integer Literal
2525   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2526   Abv->Add(BitCodeAbbrevOp(32));                      // Bit Width
2527   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Value
2528   IntegerLiteralAbbrev = Stream.EmitAbbrev(std::move(Abv));
2529 
2530   // Abbreviation for EXPR_CHARACTER_LITERAL
2531   Abv = std::make_shared<BitCodeAbbrev>();
2532   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CHARACTER_LITERAL));
2533   //Stmt
2534   // Expr
2535   // DependenceKind, ValueKind, ObjectKind
2536   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2537   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2538   // Character Literal
2539   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getValue
2540   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2541   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // getKind
2542   CharacterLiteralAbbrev = Stream.EmitAbbrev(std::move(Abv));
2543 
2544   // Abbreviation for EXPR_IMPLICIT_CAST
2545   Abv = std::make_shared<BitCodeAbbrev>();
2546   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_IMPLICIT_CAST));
2547   // Stmt
2548   // Expr
2549   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2550   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2551   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2552   // CastExpr
2553   Abv->Add(BitCodeAbbrevOp(0)); // PathSize
2554   // Packing Bits: CastKind, StoredFPFeatures, isPartOfExplicitCast
2555   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 9));
2556   // ImplicitCastExpr
2557   ExprImplicitCastAbbrev = Stream.EmitAbbrev(std::move(Abv));
2558 
2559   // Abbreviation for EXPR_BINARY_OPERATOR
2560   Abv = std::make_shared<BitCodeAbbrev>();
2561   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_BINARY_OPERATOR));
2562   // Stmt
2563   // Expr
2564   // Packing Bits: DependenceKind. ValueKind and ObjectKind should
2565   // be 0 in this case.
2566   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));
2567   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2568   // BinaryOperator
2569   Abv->Add(
2570       BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpCode and HasFPFeatures
2571   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2572   BinaryOperatorAbbrev = Stream.EmitAbbrev(std::move(Abv));
2573 
2574   // Abbreviation for EXPR_COMPOUND_ASSIGN_OPERATOR
2575   Abv = std::make_shared<BitCodeAbbrev>();
2576   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_COMPOUND_ASSIGN_OPERATOR));
2577   // Stmt
2578   // Expr
2579   // Packing Bits: DependenceKind. ValueKind and ObjectKind should
2580   // be 0 in this case.
2581   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));
2582   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2583   // BinaryOperator
2584   // Packing Bits: OpCode. The HasFPFeatures bit should be 0
2585   Abv->Add(
2586       BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpCode and HasFPFeatures
2587   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2588   // CompoundAssignOperator
2589   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHSType
2590   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Result Type
2591   CompoundAssignOperatorAbbrev = Stream.EmitAbbrev(std::move(Abv));
2592 
2593   // Abbreviation for EXPR_CALL
2594   Abv = std::make_shared<BitCodeAbbrev>();
2595   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CALL));
2596   // Stmt
2597   // Expr
2598   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2599   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2600   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2601   // CallExpr
2602   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumArgs
2603   Abv->Add(BitCodeAbbrevOp(0));                       // ADLCallKind
2604   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2605   CallExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2606 
2607   // Abbreviation for EXPR_CXX_OPERATOR_CALL
2608   Abv = std::make_shared<BitCodeAbbrev>();
2609   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CXX_OPERATOR_CALL));
2610   // Stmt
2611   // Expr
2612   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2613   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2614   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2615   // CallExpr
2616   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumArgs
2617   Abv->Add(BitCodeAbbrevOp(0));                       // ADLCallKind
2618   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2619   // CXXOperatorCallExpr
2620   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Operator Kind
2621   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2622   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2623   CXXOperatorCallExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2624 
2625   // Abbreviation for EXPR_CXX_MEMBER_CALL
2626   Abv = std::make_shared<BitCodeAbbrev>();
2627   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CXX_MEMBER_CALL));
2628   // Stmt
2629   // Expr
2630   // Packing Bits: DependenceKind, ValueKind, ObjectKind,
2631   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10));
2632   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2633   // CallExpr
2634   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumArgs
2635   Abv->Add(BitCodeAbbrevOp(0));                       // ADLCallKind
2636   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2637   // CXXMemberCallExpr
2638   CXXMemberCallExprAbbrev = Stream.EmitAbbrev(std::move(Abv));
2639 
2640   // Abbreviation for STMT_COMPOUND
2641   Abv = std::make_shared<BitCodeAbbrev>();
2642   Abv->Add(BitCodeAbbrevOp(serialization::STMT_COMPOUND));
2643   // Stmt
2644   // CompoundStmt
2645   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Num Stmts
2646   Abv->Add(BitCodeAbbrevOp(0));                       // hasStoredFPFeatures
2647   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2648   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
2649   CompoundStmtAbbrev = Stream.EmitAbbrev(std::move(Abv));
2650 
2651   Abv = std::make_shared<BitCodeAbbrev>();
2652   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_LEXICAL));
2653   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2654   DeclContextLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
2655 
2656   Abv = std::make_shared<BitCodeAbbrev>();
2657   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_VISIBLE));
2658   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2659   DeclContextVisibleLookupAbbrev = Stream.EmitAbbrev(std::move(Abv));
2660 }
2661 
2662 /// isRequiredDecl - Check if this is a "required" Decl, which must be seen by
2663 /// consumers of the AST.
2664 ///
2665 /// Such decls will always be deserialized from the AST file, so we would like
2666 /// this to be as restrictive as possible. Currently the predicate is driven by
2667 /// code generation requirements, if other clients have a different notion of
2668 /// what is "required" then we may have to consider an alternate scheme where
2669 /// clients can iterate over the top-level decls and get information on them,
2670 /// without necessary deserializing them. We could explicitly require such
2671 /// clients to use a separate API call to "realize" the decl. This should be
2672 /// relatively painless since they would presumably only do it for top-level
2673 /// decls.
2674 static bool isRequiredDecl(const Decl *D, ASTContext &Context,
2675                            Module *WritingModule) {
2676   // Named modules have different semantics than header modules. Every named
2677   // module units owns a translation unit. So the importer of named modules
2678   // doesn't need to deserilize everything ahead of time.
2679   if (WritingModule && WritingModule->isNamedModule()) {
2680     // The PragmaCommentDecl and PragmaDetectMismatchDecl are MSVC's extension.
2681     // And the behavior of MSVC for such cases will leak this to the module
2682     // users. Given pragma is not a standard thing, the compiler has the space
2683     // to do their own decision. Let's follow MSVC here.
2684     if (isa<PragmaCommentDecl, PragmaDetectMismatchDecl>(D))
2685       return true;
2686     return false;
2687   }
2688 
2689   // An ObjCMethodDecl is never considered as "required" because its
2690   // implementation container always is.
2691 
2692   // File scoped assembly or obj-c or OMP declare target implementation must be
2693   // seen.
2694   if (isa<FileScopeAsmDecl, TopLevelStmtDecl, ObjCImplDecl>(D))
2695     return true;
2696 
2697   if (WritingModule && isPartOfPerModuleInitializer(D)) {
2698     // These declarations are part of the module initializer, and are emitted
2699     // if and when the module is imported, rather than being emitted eagerly.
2700     return false;
2701   }
2702 
2703   return Context.DeclMustBeEmitted(D);
2704 }
2705 
2706 void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) {
2707   PrettyDeclStackTraceEntry CrashInfo(Context, D, SourceLocation(),
2708                                       "serializing");
2709 
2710   // Determine the ID for this declaration.
2711   serialization::DeclID ID;
2712   assert(!D->isFromASTFile() && "should not be emitting imported decl");
2713   serialization::DeclID &IDR = DeclIDs[D];
2714   if (IDR == 0)
2715     IDR = NextDeclID++;
2716 
2717   ID = IDR;
2718 
2719   assert(ID >= FirstDeclID && "invalid decl ID");
2720 
2721   RecordData Record;
2722   ASTDeclWriter W(*this, Context, Record);
2723 
2724   // Build a record for this declaration
2725   W.Visit(D);
2726 
2727   // Emit this declaration to the bitstream.
2728   uint64_t Offset = W.Emit(D);
2729 
2730   // Record the offset for this declaration
2731   SourceLocation Loc = D->getLocation();
2732   unsigned Index = ID - FirstDeclID;
2733   if (DeclOffsets.size() == Index)
2734     DeclOffsets.emplace_back(getAdjustedLocation(Loc), Offset,
2735                              DeclTypesBlockStartOffset);
2736   else if (DeclOffsets.size() < Index) {
2737     // FIXME: Can/should this happen?
2738     DeclOffsets.resize(Index+1);
2739     DeclOffsets[Index].setLocation(getAdjustedLocation(Loc));
2740     DeclOffsets[Index].setBitOffset(Offset, DeclTypesBlockStartOffset);
2741   } else {
2742     llvm_unreachable("declarations should be emitted in ID order");
2743   }
2744 
2745   SourceManager &SM = Context.getSourceManager();
2746   if (Loc.isValid() && SM.isLocalSourceLocation(Loc))
2747     associateDeclWithFile(D, ID);
2748 
2749   // Note declarations that should be deserialized eagerly so that we can add
2750   // them to a record in the AST file later.
2751   if (isRequiredDecl(D, Context, WritingModule))
2752     EagerlyDeserializedDecls.push_back(ID);
2753 }
2754 
2755 void ASTRecordWriter::AddFunctionDefinition(const FunctionDecl *FD) {
2756   // Switch case IDs are per function body.
2757   Writer->ClearSwitchCaseIDs();
2758 
2759   assert(FD->doesThisDeclarationHaveABody());
2760   bool ModulesCodegen = false;
2761   if (!FD->isDependentContext()) {
2762     std::optional<GVALinkage> Linkage;
2763     if (Writer->WritingModule &&
2764         Writer->WritingModule->isInterfaceOrPartition()) {
2765       // When building a C++20 module interface unit or a partition unit, a
2766       // strong definition in the module interface is provided by the
2767       // compilation of that unit, not by its users. (Inline functions are still
2768       // emitted in module users.)
2769       Linkage = Writer->Context->GetGVALinkageForFunction(FD);
2770       ModulesCodegen = *Linkage >= GVA_StrongExternal;
2771     }
2772     if (Writer->Context->getLangOpts().ModulesCodegen ||
2773         (FD->hasAttr<DLLExportAttr>() &&
2774          Writer->Context->getLangOpts().BuildingPCHWithObjectFile)) {
2775 
2776       // Under -fmodules-codegen, codegen is performed for all non-internal,
2777       // non-always_inline functions, unless they are available elsewhere.
2778       if (!FD->hasAttr<AlwaysInlineAttr>()) {
2779         if (!Linkage)
2780           Linkage = Writer->Context->GetGVALinkageForFunction(FD);
2781         ModulesCodegen =
2782             *Linkage != GVA_Internal && *Linkage != GVA_AvailableExternally;
2783       }
2784     }
2785   }
2786   Record->push_back(ModulesCodegen);
2787   if (ModulesCodegen)
2788     Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(FD));
2789   if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
2790     Record->push_back(CD->getNumCtorInitializers());
2791     if (CD->getNumCtorInitializers())
2792       AddCXXCtorInitializers(llvm::ArrayRef(CD->init_begin(), CD->init_end()));
2793   }
2794   AddStmt(FD->getBody());
2795 }
2796