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