1 //===--- ASTWriterDecl.cpp - Declaration Serialization --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements serialization for Declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Serialization/ASTWriter.h"
15 #include "ASTCommon.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclContextInternals.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Serialization/ASTReader.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Bitcode/BitstreamWriter.h"
25 #include "llvm/Support/ErrorHandling.h"
26 using namespace clang;
27 using namespace serialization;
28 
29 //===----------------------------------------------------------------------===//
30 // Declaration serialization
31 //===----------------------------------------------------------------------===//
32 
33 namespace clang {
34   class ASTDeclWriter : public DeclVisitor<ASTDeclWriter, void> {
35     ASTWriter &Writer;
36     ASTContext &Context;
37     ASTRecordWriter Record;
38 
39     serialization::DeclCode Code;
40     unsigned AbbrevToUse;
41 
42   public:
43     ASTDeclWriter(ASTWriter &Writer, ASTContext &Context,
44                   ASTWriter::RecordDataImpl &Record)
45         : Writer(Writer), Context(Context), Record(Writer, Record),
46           Code((serialization::DeclCode)0), AbbrevToUse(0) {}
47 
48     uint64_t Emit(Decl *D) {
49       if (!Code)
50         llvm::report_fatal_error(StringRef("unexpected declaration kind '") +
51             D->getDeclKindName() + "'");
52 
53       auto Offset = Record.Emit(Code, AbbrevToUse);
54 
55       // Flush any base specifiers and ctor initializers that
56       // were written as part of this declaration.
57       Writer.FlushPendingAfterDecl();
58 
59       return Offset;
60     }
61 
62     void Visit(Decl *D);
63 
64     void VisitDecl(Decl *D);
65     void VisitPragmaCommentDecl(PragmaCommentDecl *D);
66     void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
67     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
68     void VisitNamedDecl(NamedDecl *D);
69     void VisitLabelDecl(LabelDecl *LD);
70     void VisitNamespaceDecl(NamespaceDecl *D);
71     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
72     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
73     void VisitTypeDecl(TypeDecl *D);
74     void VisitTypedefNameDecl(TypedefNameDecl *D);
75     void VisitTypedefDecl(TypedefDecl *D);
76     void VisitTypeAliasDecl(TypeAliasDecl *D);
77     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
78     void VisitTagDecl(TagDecl *D);
79     void VisitEnumDecl(EnumDecl *D);
80     void VisitRecordDecl(RecordDecl *D);
81     void VisitCXXRecordDecl(CXXRecordDecl *D);
82     void VisitClassTemplateSpecializationDecl(
83                                             ClassTemplateSpecializationDecl *D);
84     void VisitClassTemplatePartialSpecializationDecl(
85                                      ClassTemplatePartialSpecializationDecl *D);
86     void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
87     void VisitVarTemplatePartialSpecializationDecl(
88         VarTemplatePartialSpecializationDecl *D);
89     void VisitClassScopeFunctionSpecializationDecl(
90                                        ClassScopeFunctionSpecializationDecl *D);
91     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
92     void VisitValueDecl(ValueDecl *D);
93     void VisitEnumConstantDecl(EnumConstantDecl *D);
94     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
95     void VisitDeclaratorDecl(DeclaratorDecl *D);
96     void VisitFunctionDecl(FunctionDecl *D);
97     void VisitCXXMethodDecl(CXXMethodDecl *D);
98     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
99     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
100     void VisitCXXConversionDecl(CXXConversionDecl *D);
101     void VisitFieldDecl(FieldDecl *D);
102     void VisitMSPropertyDecl(MSPropertyDecl *D);
103     void VisitIndirectFieldDecl(IndirectFieldDecl *D);
104     void VisitVarDecl(VarDecl *D);
105     void VisitImplicitParamDecl(ImplicitParamDecl *D);
106     void VisitParmVarDecl(ParmVarDecl *D);
107     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
108     void VisitTemplateDecl(TemplateDecl *D);
109     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
110     void VisitClassTemplateDecl(ClassTemplateDecl *D);
111     void VisitVarTemplateDecl(VarTemplateDecl *D);
112     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
113     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
114     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
115     void VisitUsingDecl(UsingDecl *D);
116     void VisitUsingShadowDecl(UsingShadowDecl *D);
117     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
118     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
119     void VisitImportDecl(ImportDecl *D);
120     void VisitAccessSpecDecl(AccessSpecDecl *D);
121     void VisitFriendDecl(FriendDecl *D);
122     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
123     void VisitStaticAssertDecl(StaticAssertDecl *D);
124     void VisitBlockDecl(BlockDecl *D);
125     void VisitCapturedDecl(CapturedDecl *D);
126     void VisitEmptyDecl(EmptyDecl *D);
127 
128     void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
129                           uint64_t VisibleOffset);
130     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
131 
132 
133     // FIXME: Put in the same order is DeclNodes.td?
134     void VisitObjCMethodDecl(ObjCMethodDecl *D);
135     void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
136     void VisitObjCContainerDecl(ObjCContainerDecl *D);
137     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
138     void VisitObjCIvarDecl(ObjCIvarDecl *D);
139     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
140     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
141     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
142     void VisitObjCImplDecl(ObjCImplDecl *D);
143     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
144     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
145     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
146     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
147     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
148     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
149     void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
150     void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
151 
152     void AddLocalOffset(uint64_t LocalOffset) {
153       uint64_t Offset = Writer.Stream.GetCurrentBitNo();
154       assert(LocalOffset < Offset && "invalid offset");
155       Record.push_back(LocalOffset ? Offset - LocalOffset : 0);
156     }
157 
158     /// Add an Objective-C type parameter list to the given record.
159     void AddObjCTypeParamList(ObjCTypeParamList *typeParams) {
160       // Empty type parameter list.
161       if (!typeParams) {
162         Record.push_back(0);
163         return;
164       }
165 
166       Record.push_back(typeParams->size());
167       for (auto typeParam : *typeParams) {
168         Record.AddDeclRef(typeParam);
169       }
170       Record.AddSourceLocation(typeParams->getLAngleLoc());
171       Record.AddSourceLocation(typeParams->getRAngleLoc());
172     }
173 
174     /// Add to the record the first declaration from each module file that
175     /// provides a declaration of D. The intent is to provide a sufficient
176     /// set such that reloading this set will load all current redeclarations.
177     void AddFirstDeclFromEachModule(const Decl *D, bool IncludeLocal) {
178       llvm::MapVector<ModuleFile*, const Decl*> Firsts;
179       // FIXME: We can skip entries that we know are implied by others.
180       for (const Decl *R = D->getMostRecentDecl(); R; R = R->getPreviousDecl()) {
181         if (R->isFromASTFile())
182           Firsts[Writer.Chain->getOwningModuleFile(R)] = R;
183         else if (IncludeLocal)
184           Firsts[nullptr] = R;
185       }
186       for (const auto &F : Firsts)
187         Record.AddDeclRef(F.second);
188     }
189 
190     /// Get the specialization decl from an entry in the specialization list.
191     template <typename EntryType>
192     typename RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::DeclType *
193     getSpecializationDecl(EntryType &T) {
194       return RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::getDecl(&T);
195     }
196 
197     /// Get the list of partial specializations from a template's common ptr.
198     template<typename T>
199     decltype(T::PartialSpecializations) &getPartialSpecializations(T *Common) {
200       return Common->PartialSpecializations;
201     }
202     ArrayRef<Decl> getPartialSpecializations(FunctionTemplateDecl::Common *) {
203       return None;
204     }
205 
206     template<typename DeclTy>
207     void AddTemplateSpecializations(DeclTy *D) {
208       auto *Common = D->getCommonPtr();
209 
210       // If we have any lazy specializations, and the external AST source is
211       // our chained AST reader, we can just write out the DeclIDs. Otherwise,
212       // we need to resolve them to actual declarations.
213       if (Writer.Chain != Writer.Context->getExternalSource() &&
214           Common->LazySpecializations) {
215         D->LoadLazySpecializations();
216         assert(!Common->LazySpecializations);
217       }
218 
219       ArrayRef<DeclID> LazySpecializations;
220       if (auto *LS = Common->LazySpecializations)
221         LazySpecializations = llvm::makeArrayRef(LS + 1, LS[0]);
222 
223       // Add a slot to the record for the number of specializations.
224       unsigned I = Record.size();
225       Record.push_back(0);
226 
227       // AddFirstDeclFromEachModule might trigger deserialization, invalidating
228       // *Specializations iterators.
229       llvm::SmallVector<const Decl*, 16> Specs;
230       for (auto &Entry : Common->Specializations)
231         Specs.push_back(getSpecializationDecl(Entry));
232       for (auto &Entry : getPartialSpecializations(Common))
233         Specs.push_back(getSpecializationDecl(Entry));
234 
235       for (auto *D : Specs) {
236         assert(D->isCanonicalDecl() && "non-canonical decl in set");
237         AddFirstDeclFromEachModule(D, /*IncludeLocal*/true);
238       }
239       Record.append(LazySpecializations.begin(), LazySpecializations.end());
240 
241       // Update the size entry we added earlier.
242       Record[I] = Record.size() - I - 1;
243     }
244 
245     /// Ensure that this template specialization is associated with the specified
246     /// template on reload.
247     void RegisterTemplateSpecialization(const Decl *Template,
248                                         const Decl *Specialization) {
249       Template = Template->getCanonicalDecl();
250 
251       // If the canonical template is local, we'll write out this specialization
252       // when we emit it.
253       // FIXME: We can do the same thing if there is any local declaration of
254       // the template, to avoid emitting an update record.
255       if (!Template->isFromASTFile())
256         return;
257 
258       // We only need to associate the first local declaration of the
259       // specialization. The other declarations will get pulled in by it.
260       if (Writer.getFirstLocalDecl(Specialization) != Specialization)
261         return;
262 
263       Writer.DeclUpdates[Template].push_back(ASTWriter::DeclUpdate(
264           UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION, Specialization));
265     }
266   };
267 }
268 
269 void ASTDeclWriter::Visit(Decl *D) {
270   DeclVisitor<ASTDeclWriter>::Visit(D);
271 
272   // Source locations require array (variable-length) abbreviations.  The
273   // abbreviation infrastructure requires that arrays are encoded last, so
274   // we handle it here in the case of those classes derived from DeclaratorDecl
275   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
276     Record.AddTypeSourceInfo(DD->getTypeSourceInfo());
277   }
278 
279   // Handle FunctionDecl's body here and write it after all other Stmts/Exprs
280   // have been written. We want it last because we will not read it back when
281   // retrieving it from the AST, we'll just lazily set the offset.
282   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
283     Record.push_back(FD->doesThisDeclarationHaveABody());
284     if (FD->doesThisDeclarationHaveABody())
285       Record.AddFunctionDefinition(FD);
286   }
287 }
288 
289 void ASTDeclWriter::VisitDecl(Decl *D) {
290   Record.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()));
291   if (D->getDeclContext() != D->getLexicalDeclContext())
292     Record.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()));
293   else
294     Record.push_back(0);
295   Record.push_back(D->isInvalidDecl());
296   Record.push_back(D->hasAttrs());
297   if (D->hasAttrs())
298     Record.AddAttributes(D->getAttrs());
299   Record.push_back(D->isImplicit());
300   Record.push_back(D->isUsed(false));
301   Record.push_back(D->isReferenced());
302   Record.push_back(D->isTopLevelDeclInObjCContainer());
303   Record.push_back(D->getAccess());
304   Record.push_back(D->isModulePrivate());
305   Record.push_back(Writer.inferSubmoduleIDFromLocation(D->getLocation()));
306 
307   // If this declaration injected a name into a context different from its
308   // lexical context, and that context is an imported namespace, we need to
309   // update its visible declarations to include this name.
310   //
311   // This happens when we instantiate a class with a friend declaration or a
312   // function with a local extern declaration, for instance.
313   //
314   // FIXME: Can we handle this in AddedVisibleDecl instead?
315   if (D->isOutOfLine()) {
316     auto *DC = D->getDeclContext();
317     while (auto *NS = dyn_cast<NamespaceDecl>(DC->getRedeclContext())) {
318       if (!NS->isFromASTFile())
319         break;
320       Writer.UpdatedDeclContexts.insert(NS->getPrimaryContext());
321       if (!NS->isInlineNamespace())
322         break;
323       DC = NS->getParent();
324     }
325   }
326 }
327 
328 void ASTDeclWriter::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
329   StringRef Arg = D->getArg();
330   Record.push_back(Arg.size());
331   VisitDecl(D);
332   Record.AddSourceLocation(D->getLocStart());
333   Record.push_back(D->getCommentKind());
334   Record.AddString(Arg);
335   Code = serialization::DECL_PRAGMA_COMMENT;
336 }
337 
338 void ASTDeclWriter::VisitPragmaDetectMismatchDecl(
339     PragmaDetectMismatchDecl *D) {
340   StringRef Name = D->getName();
341   StringRef Value = D->getValue();
342   Record.push_back(Name.size() + 1 + Value.size());
343   VisitDecl(D);
344   Record.AddSourceLocation(D->getLocStart());
345   Record.AddString(Name);
346   Record.AddString(Value);
347   Code = serialization::DECL_PRAGMA_DETECT_MISMATCH;
348 }
349 
350 void ASTDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
351   llvm_unreachable("Translation units aren't directly serialized");
352 }
353 
354 void ASTDeclWriter::VisitNamedDecl(NamedDecl *D) {
355   VisitDecl(D);
356   Record.AddDeclarationName(D->getDeclName());
357   Record.push_back(needsAnonymousDeclarationNumber(D)
358                        ? Writer.getAnonymousDeclarationNumber(D)
359                        : 0);
360 }
361 
362 void ASTDeclWriter::VisitTypeDecl(TypeDecl *D) {
363   VisitNamedDecl(D);
364   Record.AddSourceLocation(D->getLocStart());
365   Record.AddTypeRef(QualType(D->getTypeForDecl(), 0));
366 }
367 
368 void ASTDeclWriter::VisitTypedefNameDecl(TypedefNameDecl *D) {
369   VisitRedeclarable(D);
370   VisitTypeDecl(D);
371   Record.AddTypeSourceInfo(D->getTypeSourceInfo());
372   Record.push_back(D->isModed());
373   if (D->isModed())
374     Record.AddTypeRef(D->getUnderlyingType());
375 }
376 
377 void ASTDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
378   VisitTypedefNameDecl(D);
379   if (D->getDeclContext() == D->getLexicalDeclContext() &&
380       !D->hasAttrs() &&
381       !D->isImplicit() &&
382       D->getFirstDecl() == D->getMostRecentDecl() &&
383       !D->isInvalidDecl() &&
384       !D->isTopLevelDeclInObjCContainer() &&
385       !D->isModulePrivate() &&
386       !needsAnonymousDeclarationNumber(D) &&
387       D->getDeclName().getNameKind() == DeclarationName::Identifier)
388     AbbrevToUse = Writer.getDeclTypedefAbbrev();
389 
390   Code = serialization::DECL_TYPEDEF;
391 }
392 
393 void ASTDeclWriter::VisitTypeAliasDecl(TypeAliasDecl *D) {
394   VisitTypedefNameDecl(D);
395   Record.AddDeclRef(D->getDescribedAliasTemplate());
396   Code = serialization::DECL_TYPEALIAS;
397 }
398 
399 void ASTDeclWriter::VisitTagDecl(TagDecl *D) {
400   VisitRedeclarable(D);
401   VisitTypeDecl(D);
402   Record.push_back(D->getIdentifierNamespace());
403   Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
404   if (!isa<CXXRecordDecl>(D))
405     Record.push_back(D->isCompleteDefinition());
406   Record.push_back(D->isEmbeddedInDeclarator());
407   Record.push_back(D->isFreeStanding());
408   Record.push_back(D->isCompleteDefinitionRequired());
409   Record.AddSourceLocation(D->getRBraceLoc());
410 
411   if (D->hasExtInfo()) {
412     Record.push_back(1);
413     Record.AddQualifierInfo(*D->getExtInfo());
414   } else if (auto *TD = D->getTypedefNameForAnonDecl()) {
415     Record.push_back(2);
416     Record.AddDeclRef(TD);
417     Record.AddIdentifierRef(TD->getDeclName().getAsIdentifierInfo());
418   } else {
419     Record.push_back(0);
420   }
421 }
422 
423 void ASTDeclWriter::VisitEnumDecl(EnumDecl *D) {
424   VisitTagDecl(D);
425   Record.AddTypeSourceInfo(D->getIntegerTypeSourceInfo());
426   if (!D->getIntegerTypeSourceInfo())
427     Record.AddTypeRef(D->getIntegerType());
428   Record.AddTypeRef(D->getPromotionType());
429   Record.push_back(D->getNumPositiveBits());
430   Record.push_back(D->getNumNegativeBits());
431   Record.push_back(D->isScoped());
432   Record.push_back(D->isScopedUsingClassTag());
433   Record.push_back(D->isFixed());
434   if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
435     Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
436     Record.push_back(MemberInfo->getTemplateSpecializationKind());
437     Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
438   } else {
439     Record.AddDeclRef(nullptr);
440   }
441 
442   if (D->getDeclContext() == D->getLexicalDeclContext() &&
443       !D->hasAttrs() &&
444       !D->isImplicit() &&
445       !D->isUsed(false) &&
446       !D->hasExtInfo() &&
447       !D->getTypedefNameForAnonDecl() &&
448       D->getFirstDecl() == D->getMostRecentDecl() &&
449       !D->isInvalidDecl() &&
450       !D->isReferenced() &&
451       !D->isTopLevelDeclInObjCContainer() &&
452       D->getAccess() == AS_none &&
453       !D->isModulePrivate() &&
454       !CXXRecordDecl::classofKind(D->getKind()) &&
455       !D->getIntegerTypeSourceInfo() &&
456       !D->getMemberSpecializationInfo() &&
457       !needsAnonymousDeclarationNumber(D) &&
458       D->getDeclName().getNameKind() == DeclarationName::Identifier)
459     AbbrevToUse = Writer.getDeclEnumAbbrev();
460 
461   Code = serialization::DECL_ENUM;
462 }
463 
464 void ASTDeclWriter::VisitRecordDecl(RecordDecl *D) {
465   VisitTagDecl(D);
466   Record.push_back(D->hasFlexibleArrayMember());
467   Record.push_back(D->isAnonymousStructOrUnion());
468   Record.push_back(D->hasObjectMember());
469   Record.push_back(D->hasVolatileMember());
470 
471   if (D->getDeclContext() == D->getLexicalDeclContext() &&
472       !D->hasAttrs() &&
473       !D->isImplicit() &&
474       !D->isUsed(false) &&
475       !D->hasExtInfo() &&
476       !D->getTypedefNameForAnonDecl() &&
477       D->getFirstDecl() == D->getMostRecentDecl() &&
478       !D->isInvalidDecl() &&
479       !D->isReferenced() &&
480       !D->isTopLevelDeclInObjCContainer() &&
481       D->getAccess() == AS_none &&
482       !D->isModulePrivate() &&
483       !CXXRecordDecl::classofKind(D->getKind()) &&
484       !needsAnonymousDeclarationNumber(D) &&
485       D->getDeclName().getNameKind() == DeclarationName::Identifier)
486     AbbrevToUse = Writer.getDeclRecordAbbrev();
487 
488   Code = serialization::DECL_RECORD;
489 }
490 
491 void ASTDeclWriter::VisitValueDecl(ValueDecl *D) {
492   VisitNamedDecl(D);
493   Record.AddTypeRef(D->getType());
494 }
495 
496 void ASTDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
497   VisitValueDecl(D);
498   Record.push_back(D->getInitExpr()? 1 : 0);
499   if (D->getInitExpr())
500     Record.AddStmt(D->getInitExpr());
501   Record.AddAPSInt(D->getInitVal());
502 
503   Code = serialization::DECL_ENUM_CONSTANT;
504 }
505 
506 void ASTDeclWriter::VisitDeclaratorDecl(DeclaratorDecl *D) {
507   VisitValueDecl(D);
508   Record.AddSourceLocation(D->getInnerLocStart());
509   Record.push_back(D->hasExtInfo());
510   if (D->hasExtInfo())
511     Record.AddQualifierInfo(*D->getExtInfo());
512 }
513 
514 void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
515   VisitRedeclarable(D);
516   VisitDeclaratorDecl(D);
517   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
518   Record.push_back(D->getIdentifierNamespace());
519 
520   // FunctionDecl's body is handled last at ASTWriterDecl::Visit,
521   // after everything else is written.
522 
523   Record.push_back((int)D->SClass); // FIXME: stable encoding
524   Record.push_back(D->IsInline);
525   Record.push_back(D->IsInlineSpecified);
526   Record.push_back(D->IsVirtualAsWritten);
527   Record.push_back(D->IsPure);
528   Record.push_back(D->HasInheritedPrototype);
529   Record.push_back(D->HasWrittenPrototype);
530   Record.push_back(D->IsDeleted);
531   Record.push_back(D->IsTrivial);
532   Record.push_back(D->IsDefaulted);
533   Record.push_back(D->IsExplicitlyDefaulted);
534   Record.push_back(D->HasImplicitReturnZero);
535   Record.push_back(D->IsConstexpr);
536   Record.push_back(D->HasSkippedBody);
537   Record.push_back(D->IsLateTemplateParsed);
538   Record.push_back(D->getLinkageInternal());
539   Record.AddSourceLocation(D->getLocEnd());
540 
541   Record.push_back(D->getTemplatedKind());
542   switch (D->getTemplatedKind()) {
543   case FunctionDecl::TK_NonTemplate:
544     break;
545   case FunctionDecl::TK_FunctionTemplate:
546     Record.AddDeclRef(D->getDescribedFunctionTemplate());
547     break;
548   case FunctionDecl::TK_MemberSpecialization: {
549     MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo();
550     Record.AddDeclRef(MemberInfo->getInstantiatedFrom());
551     Record.push_back(MemberInfo->getTemplateSpecializationKind());
552     Record.AddSourceLocation(MemberInfo->getPointOfInstantiation());
553     break;
554   }
555   case FunctionDecl::TK_FunctionTemplateSpecialization: {
556     FunctionTemplateSpecializationInfo *
557       FTSInfo = D->getTemplateSpecializationInfo();
558 
559     RegisterTemplateSpecialization(FTSInfo->getTemplate(), D);
560 
561     Record.AddDeclRef(FTSInfo->getTemplate());
562     Record.push_back(FTSInfo->getTemplateSpecializationKind());
563 
564     // Template arguments.
565     Record.AddTemplateArgumentList(FTSInfo->TemplateArguments);
566 
567     // Template args as written.
568     Record.push_back(FTSInfo->TemplateArgumentsAsWritten != nullptr);
569     if (FTSInfo->TemplateArgumentsAsWritten) {
570       Record.push_back(FTSInfo->TemplateArgumentsAsWritten->NumTemplateArgs);
571       for (int i=0, e = FTSInfo->TemplateArgumentsAsWritten->NumTemplateArgs;
572              i!=e; ++i)
573         Record.AddTemplateArgumentLoc(
574             (*FTSInfo->TemplateArgumentsAsWritten)[i]);
575       Record.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->LAngleLoc);
576       Record.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->RAngleLoc);
577     }
578 
579     Record.AddSourceLocation(FTSInfo->getPointOfInstantiation());
580 
581     if (D->isCanonicalDecl()) {
582       // Write the template that contains the specializations set. We will
583       // add a FunctionTemplateSpecializationInfo to it when reading.
584       Record.AddDeclRef(FTSInfo->getTemplate()->getCanonicalDecl());
585     }
586     break;
587   }
588   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
589     DependentFunctionTemplateSpecializationInfo *
590       DFTSInfo = D->getDependentSpecializationInfo();
591 
592     // Templates.
593     Record.push_back(DFTSInfo->getNumTemplates());
594     for (int i=0, e = DFTSInfo->getNumTemplates(); i != e; ++i)
595       Record.AddDeclRef(DFTSInfo->getTemplate(i));
596 
597     // Templates args.
598     Record.push_back(DFTSInfo->getNumTemplateArgs());
599     for (int i=0, e = DFTSInfo->getNumTemplateArgs(); i != e; ++i)
600       Record.AddTemplateArgumentLoc(DFTSInfo->getTemplateArg(i));
601     Record.AddSourceLocation(DFTSInfo->getLAngleLoc());
602     Record.AddSourceLocation(DFTSInfo->getRAngleLoc());
603     break;
604   }
605   }
606 
607   Record.push_back(D->param_size());
608   for (auto P : D->params())
609     Record.AddDeclRef(P);
610   Code = serialization::DECL_FUNCTION;
611 }
612 
613 void ASTDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
614   VisitNamedDecl(D);
615   // FIXME: convert to LazyStmtPtr?
616   // Unlike C/C++, method bodies will never be in header files.
617   bool HasBodyStuff = D->getBody() != nullptr     ||
618                       D->getSelfDecl() != nullptr || D->getCmdDecl() != nullptr;
619   Record.push_back(HasBodyStuff);
620   if (HasBodyStuff) {
621     Record.AddStmt(D->getBody());
622     Record.AddDeclRef(D->getSelfDecl());
623     Record.AddDeclRef(D->getCmdDecl());
624   }
625   Record.push_back(D->isInstanceMethod());
626   Record.push_back(D->isVariadic());
627   Record.push_back(D->isPropertyAccessor());
628   Record.push_back(D->isDefined());
629   Record.push_back(D->IsOverriding);
630   Record.push_back(D->HasSkippedBody);
631 
632   Record.push_back(D->IsRedeclaration);
633   Record.push_back(D->HasRedeclaration);
634   if (D->HasRedeclaration) {
635     assert(Context.getObjCMethodRedeclaration(D));
636     Record.AddDeclRef(Context.getObjCMethodRedeclaration(D));
637   }
638 
639   // FIXME: stable encoding for @required/@optional
640   Record.push_back(D->getImplementationControl());
641   // FIXME: stable encoding for in/out/inout/bycopy/byref/oneway/nullability
642   Record.push_back(D->getObjCDeclQualifier());
643   Record.push_back(D->hasRelatedResultType());
644   Record.AddTypeRef(D->getReturnType());
645   Record.AddTypeSourceInfo(D->getReturnTypeSourceInfo());
646   Record.AddSourceLocation(D->getLocEnd());
647   Record.push_back(D->param_size());
648   for (const auto *P : D->params())
649     Record.AddDeclRef(P);
650 
651   Record.push_back(D->SelLocsKind);
652   unsigned NumStoredSelLocs = D->getNumStoredSelLocs();
653   SourceLocation *SelLocs = D->getStoredSelLocs();
654   Record.push_back(NumStoredSelLocs);
655   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
656     Record.AddSourceLocation(SelLocs[i]);
657 
658   Code = serialization::DECL_OBJC_METHOD;
659 }
660 
661 void ASTDeclWriter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
662   VisitTypedefNameDecl(D);
663   Record.push_back(D->Variance);
664   Record.push_back(D->Index);
665   Record.AddSourceLocation(D->VarianceLoc);
666   Record.AddSourceLocation(D->ColonLoc);
667 
668   Code = serialization::DECL_OBJC_TYPE_PARAM;
669 }
670 
671 void ASTDeclWriter::VisitObjCContainerDecl(ObjCContainerDecl *D) {
672   VisitNamedDecl(D);
673   Record.AddSourceLocation(D->getAtStartLoc());
674   Record.AddSourceRange(D->getAtEndRange());
675   // Abstract class (no need to define a stable serialization::DECL code).
676 }
677 
678 void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
679   VisitRedeclarable(D);
680   VisitObjCContainerDecl(D);
681   Record.AddTypeRef(QualType(D->getTypeForDecl(), 0));
682   AddObjCTypeParamList(D->TypeParamList);
683 
684   Record.push_back(D->isThisDeclarationADefinition());
685   if (D->isThisDeclarationADefinition()) {
686     // Write the DefinitionData
687     ObjCInterfaceDecl::DefinitionData &Data = D->data();
688 
689     Record.AddTypeSourceInfo(D->getSuperClassTInfo());
690     Record.AddSourceLocation(D->getEndOfDefinitionLoc());
691     Record.push_back(Data.HasDesignatedInitializers);
692 
693     // Write out the protocols that are directly referenced by the @interface.
694     Record.push_back(Data.ReferencedProtocols.size());
695     for (const auto *P : D->protocols())
696       Record.AddDeclRef(P);
697     for (const auto &PL : D->protocol_locs())
698       Record.AddSourceLocation(PL);
699 
700     // Write out the protocols that are transitively referenced.
701     Record.push_back(Data.AllReferencedProtocols.size());
702     for (ObjCList<ObjCProtocolDecl>::iterator
703               P = Data.AllReferencedProtocols.begin(),
704            PEnd = Data.AllReferencedProtocols.end();
705          P != PEnd; ++P)
706       Record.AddDeclRef(*P);
707 
708 
709     if (ObjCCategoryDecl *Cat = D->getCategoryListRaw()) {
710       // Ensure that we write out the set of categories for this class.
711       Writer.ObjCClassesWithCategories.insert(D);
712 
713       // Make sure that the categories get serialized.
714       for (; Cat; Cat = Cat->getNextClassCategoryRaw())
715         (void)Writer.GetDeclRef(Cat);
716     }
717   }
718 
719   Code = serialization::DECL_OBJC_INTERFACE;
720 }
721 
722 void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
723   VisitFieldDecl(D);
724   // FIXME: stable encoding for @public/@private/@protected/@package
725   Record.push_back(D->getAccessControl());
726   Record.push_back(D->getSynthesize());
727 
728   if (D->getDeclContext() == D->getLexicalDeclContext() &&
729       !D->hasAttrs() &&
730       !D->isImplicit() &&
731       !D->isUsed(false) &&
732       !D->isInvalidDecl() &&
733       !D->isReferenced() &&
734       !D->isModulePrivate() &&
735       !D->getBitWidth() &&
736       !D->hasExtInfo() &&
737       D->getDeclName())
738     AbbrevToUse = Writer.getDeclObjCIvarAbbrev();
739 
740   Code = serialization::DECL_OBJC_IVAR;
741 }
742 
743 void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
744   VisitRedeclarable(D);
745   VisitObjCContainerDecl(D);
746 
747   Record.push_back(D->isThisDeclarationADefinition());
748   if (D->isThisDeclarationADefinition()) {
749     Record.push_back(D->protocol_size());
750     for (const auto *I : D->protocols())
751       Record.AddDeclRef(I);
752     for (const auto &PL : D->protocol_locs())
753       Record.AddSourceLocation(PL);
754   }
755 
756   Code = serialization::DECL_OBJC_PROTOCOL;
757 }
758 
759 void ASTDeclWriter::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
760   VisitFieldDecl(D);
761   Code = serialization::DECL_OBJC_AT_DEFS_FIELD;
762 }
763 
764 void ASTDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
765   VisitObjCContainerDecl(D);
766   Record.AddSourceLocation(D->getCategoryNameLoc());
767   Record.AddSourceLocation(D->getIvarLBraceLoc());
768   Record.AddSourceLocation(D->getIvarRBraceLoc());
769   Record.AddDeclRef(D->getClassInterface());
770   AddObjCTypeParamList(D->TypeParamList);
771   Record.push_back(D->protocol_size());
772   for (const auto *I : D->protocols())
773     Record.AddDeclRef(I);
774   for (const auto &PL : D->protocol_locs())
775     Record.AddSourceLocation(PL);
776   Code = serialization::DECL_OBJC_CATEGORY;
777 }
778 
779 void ASTDeclWriter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D) {
780   VisitNamedDecl(D);
781   Record.AddDeclRef(D->getClassInterface());
782   Code = serialization::DECL_OBJC_COMPATIBLE_ALIAS;
783 }
784 
785 void ASTDeclWriter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
786   VisitNamedDecl(D);
787   Record.AddSourceLocation(D->getAtLoc());
788   Record.AddSourceLocation(D->getLParenLoc());
789   Record.AddTypeRef(D->getType());
790   Record.AddTypeSourceInfo(D->getTypeSourceInfo());
791   // FIXME: stable encoding
792   Record.push_back((unsigned)D->getPropertyAttributes());
793   Record.push_back((unsigned)D->getPropertyAttributesAsWritten());
794   // FIXME: stable encoding
795   Record.push_back((unsigned)D->getPropertyImplementation());
796   Record.AddDeclarationName(D->getGetterName());
797   Record.AddDeclarationName(D->getSetterName());
798   Record.AddDeclRef(D->getGetterMethodDecl());
799   Record.AddDeclRef(D->getSetterMethodDecl());
800   Record.AddDeclRef(D->getPropertyIvarDecl());
801   Code = serialization::DECL_OBJC_PROPERTY;
802 }
803 
804 void ASTDeclWriter::VisitObjCImplDecl(ObjCImplDecl *D) {
805   VisitObjCContainerDecl(D);
806   Record.AddDeclRef(D->getClassInterface());
807   // Abstract class (no need to define a stable serialization::DECL code).
808 }
809 
810 void ASTDeclWriter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
811   VisitObjCImplDecl(D);
812   Record.AddIdentifierRef(D->getIdentifier());
813   Record.AddSourceLocation(D->getCategoryNameLoc());
814   Code = serialization::DECL_OBJC_CATEGORY_IMPL;
815 }
816 
817 void ASTDeclWriter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
818   VisitObjCImplDecl(D);
819   Record.AddDeclRef(D->getSuperClass());
820   Record.AddSourceLocation(D->getSuperClassLoc());
821   Record.AddSourceLocation(D->getIvarLBraceLoc());
822   Record.AddSourceLocation(D->getIvarRBraceLoc());
823   Record.push_back(D->hasNonZeroConstructors());
824   Record.push_back(D->hasDestructors());
825   Record.push_back(D->NumIvarInitializers);
826   if (D->NumIvarInitializers)
827     Record.AddCXXCtorInitializersRef(
828         llvm::makeArrayRef(D->init_begin(), D->init_end()));
829   Code = serialization::DECL_OBJC_IMPLEMENTATION;
830 }
831 
832 void ASTDeclWriter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
833   VisitDecl(D);
834   Record.AddSourceLocation(D->getLocStart());
835   Record.AddDeclRef(D->getPropertyDecl());
836   Record.AddDeclRef(D->getPropertyIvarDecl());
837   Record.AddSourceLocation(D->getPropertyIvarDeclLoc());
838   Record.AddStmt(D->getGetterCXXConstructor());
839   Record.AddStmt(D->getSetterCXXAssignment());
840   Code = serialization::DECL_OBJC_PROPERTY_IMPL;
841 }
842 
843 void ASTDeclWriter::VisitFieldDecl(FieldDecl *D) {
844   VisitDeclaratorDecl(D);
845   Record.push_back(D->isMutable());
846   if (D->InitStorage.getInt() == FieldDecl::ISK_BitWidthOrNothing &&
847       D->InitStorage.getPointer() == nullptr) {
848     Record.push_back(0);
849   } else if (D->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) {
850     Record.push_back(D->InitStorage.getInt() + 1);
851     Record.AddTypeRef(
852         QualType(static_cast<Type *>(D->InitStorage.getPointer()), 0));
853   } else {
854     Record.push_back(D->InitStorage.getInt() + 1);
855     Record.AddStmt(static_cast<Expr *>(D->InitStorage.getPointer()));
856   }
857   if (!D->getDeclName())
858     Record.AddDeclRef(Context.getInstantiatedFromUnnamedFieldDecl(D));
859 
860   if (D->getDeclContext() == D->getLexicalDeclContext() &&
861       !D->hasAttrs() &&
862       !D->isImplicit() &&
863       !D->isUsed(false) &&
864       !D->isInvalidDecl() &&
865       !D->isReferenced() &&
866       !D->isTopLevelDeclInObjCContainer() &&
867       !D->isModulePrivate() &&
868       !D->getBitWidth() &&
869       !D->hasInClassInitializer() &&
870       !D->hasExtInfo() &&
871       !ObjCIvarDecl::classofKind(D->getKind()) &&
872       !ObjCAtDefsFieldDecl::classofKind(D->getKind()) &&
873       D->getDeclName())
874     AbbrevToUse = Writer.getDeclFieldAbbrev();
875 
876   Code = serialization::DECL_FIELD;
877 }
878 
879 void ASTDeclWriter::VisitMSPropertyDecl(MSPropertyDecl *D) {
880   VisitDeclaratorDecl(D);
881   Record.AddIdentifierRef(D->getGetterId());
882   Record.AddIdentifierRef(D->getSetterId());
883   Code = serialization::DECL_MS_PROPERTY;
884 }
885 
886 void ASTDeclWriter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
887   VisitValueDecl(D);
888   Record.push_back(D->getChainingSize());
889 
890   for (const auto *P : D->chain())
891     Record.AddDeclRef(P);
892   Code = serialization::DECL_INDIRECTFIELD;
893 }
894 
895 void ASTDeclWriter::VisitVarDecl(VarDecl *D) {
896   VisitRedeclarable(D);
897   VisitDeclaratorDecl(D);
898   Record.push_back(D->getStorageClass());
899   Record.push_back(D->getTSCSpec());
900   Record.push_back(D->getInitStyle());
901   if (!isa<ParmVarDecl>(D)) {
902     Record.push_back(D->isExceptionVariable());
903     Record.push_back(D->isNRVOVariable());
904     Record.push_back(D->isCXXForRangeDecl());
905     Record.push_back(D->isARCPseudoStrong());
906     Record.push_back(D->isConstexpr());
907     Record.push_back(D->isInitCapture());
908     Record.push_back(D->isPreviousDeclInSameBlockScope());
909   }
910   Record.push_back(D->getLinkageInternal());
911 
912   if (D->getInit()) {
913     Record.push_back(!D->isInitKnownICE() ? 1 : (D->isInitICE() ? 3 : 2));
914     Record.AddStmt(D->getInit());
915   } else {
916     Record.push_back(0);
917   }
918 
919   enum {
920     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
921   };
922   if (VarTemplateDecl *TemplD = D->getDescribedVarTemplate()) {
923     Record.push_back(VarTemplate);
924     Record.AddDeclRef(TemplD);
925   } else if (MemberSpecializationInfo *SpecInfo
926                = D->getMemberSpecializationInfo()) {
927     Record.push_back(StaticDataMemberSpecialization);
928     Record.AddDeclRef(SpecInfo->getInstantiatedFrom());
929     Record.push_back(SpecInfo->getTemplateSpecializationKind());
930     Record.AddSourceLocation(SpecInfo->getPointOfInstantiation());
931   } else {
932     Record.push_back(VarNotTemplate);
933   }
934 
935   if (D->getDeclContext() == D->getLexicalDeclContext() &&
936       !D->hasAttrs() &&
937       !D->isImplicit() &&
938       !D->isUsed(false) &&
939       !D->isInvalidDecl() &&
940       !D->isReferenced() &&
941       !D->isTopLevelDeclInObjCContainer() &&
942       D->getAccess() == AS_none &&
943       !D->isModulePrivate() &&
944       !needsAnonymousDeclarationNumber(D) &&
945       D->getDeclName().getNameKind() == DeclarationName::Identifier &&
946       !D->hasExtInfo() &&
947       D->getFirstDecl() == D->getMostRecentDecl() &&
948       D->getInitStyle() == VarDecl::CInit &&
949       D->getInit() == nullptr &&
950       !isa<ParmVarDecl>(D) &&
951       !isa<VarTemplateSpecializationDecl>(D) &&
952       !D->isConstexpr() &&
953       !D->isInitCapture() &&
954       !D->isPreviousDeclInSameBlockScope() &&
955       !D->getMemberSpecializationInfo())
956     AbbrevToUse = Writer.getDeclVarAbbrev();
957 
958   Code = serialization::DECL_VAR;
959 }
960 
961 void ASTDeclWriter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
962   VisitVarDecl(D);
963   Code = serialization::DECL_IMPLICIT_PARAM;
964 }
965 
966 void ASTDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
967   VisitVarDecl(D);
968   Record.push_back(D->isObjCMethodParameter());
969   Record.push_back(D->getFunctionScopeDepth());
970   Record.push_back(D->getFunctionScopeIndex());
971   Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
972   Record.push_back(D->isKNRPromoted());
973   Record.push_back(D->hasInheritedDefaultArg());
974   Record.push_back(D->hasUninstantiatedDefaultArg());
975   if (D->hasUninstantiatedDefaultArg())
976     Record.AddStmt(D->getUninstantiatedDefaultArg());
977   Code = serialization::DECL_PARM_VAR;
978 
979   assert(!D->isARCPseudoStrong()); // can be true of ImplicitParamDecl
980 
981   // If the assumptions about the DECL_PARM_VAR abbrev are true, use it.  Here
982   // we dynamically check for the properties that we optimize for, but don't
983   // know are true of all PARM_VAR_DECLs.
984   if (D->getDeclContext() == D->getLexicalDeclContext() &&
985       !D->hasAttrs() &&
986       !D->hasExtInfo() &&
987       !D->isImplicit() &&
988       !D->isUsed(false) &&
989       !D->isInvalidDecl() &&
990       !D->isReferenced() &&
991       D->getAccess() == AS_none &&
992       !D->isModulePrivate() &&
993       D->getStorageClass() == 0 &&
994       D->getInitStyle() == VarDecl::CInit && // Can params have anything else?
995       D->getFunctionScopeDepth() == 0 &&
996       D->getObjCDeclQualifier() == 0 &&
997       !D->isKNRPromoted() &&
998       !D->hasInheritedDefaultArg() &&
999       D->getInit() == nullptr &&
1000       !D->hasUninstantiatedDefaultArg())  // No default expr.
1001     AbbrevToUse = Writer.getDeclParmVarAbbrev();
1002 
1003   // Check things we know are true of *every* PARM_VAR_DECL, which is more than
1004   // just us assuming it.
1005   assert(!D->getTSCSpec() && "PARM_VAR_DECL can't use TLS");
1006   assert(D->getAccess() == AS_none && "PARM_VAR_DECL can't be public/private");
1007   assert(!D->isExceptionVariable() && "PARM_VAR_DECL can't be exception var");
1008   assert(D->getPreviousDecl() == nullptr && "PARM_VAR_DECL can't be redecl");
1009   assert(!D->isStaticDataMember() &&
1010          "PARM_VAR_DECL can't be static data member");
1011 }
1012 
1013 void ASTDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
1014   VisitDecl(D);
1015   Record.AddStmt(D->getAsmString());
1016   Record.AddSourceLocation(D->getRParenLoc());
1017   Code = serialization::DECL_FILE_SCOPE_ASM;
1018 }
1019 
1020 void ASTDeclWriter::VisitEmptyDecl(EmptyDecl *D) {
1021   VisitDecl(D);
1022   Code = serialization::DECL_EMPTY;
1023 }
1024 
1025 void ASTDeclWriter::VisitBlockDecl(BlockDecl *D) {
1026   VisitDecl(D);
1027   Record.AddStmt(D->getBody());
1028   Record.AddTypeSourceInfo(D->getSignatureAsWritten());
1029   Record.push_back(D->param_size());
1030   for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
1031        P != PEnd; ++P)
1032     Record.AddDeclRef(*P);
1033   Record.push_back(D->isVariadic());
1034   Record.push_back(D->blockMissingReturnType());
1035   Record.push_back(D->isConversionFromLambda());
1036   Record.push_back(D->capturesCXXThis());
1037   Record.push_back(D->getNumCaptures());
1038   for (const auto &capture : D->captures()) {
1039     Record.AddDeclRef(capture.getVariable());
1040 
1041     unsigned flags = 0;
1042     if (capture.isByRef()) flags |= 1;
1043     if (capture.isNested()) flags |= 2;
1044     if (capture.hasCopyExpr()) flags |= 4;
1045     Record.push_back(flags);
1046 
1047     if (capture.hasCopyExpr()) Record.AddStmt(capture.getCopyExpr());
1048   }
1049 
1050   Code = serialization::DECL_BLOCK;
1051 }
1052 
1053 void ASTDeclWriter::VisitCapturedDecl(CapturedDecl *CD) {
1054   Record.push_back(CD->getNumParams());
1055   VisitDecl(CD);
1056   Record.push_back(CD->getContextParamPosition());
1057   Record.push_back(CD->isNothrow() ? 1 : 0);
1058   // Body is stored by VisitCapturedStmt.
1059   for (unsigned I = 0; I < CD->getNumParams(); ++I)
1060     Record.AddDeclRef(CD->getParam(I));
1061   Code = serialization::DECL_CAPTURED;
1062 }
1063 
1064 void ASTDeclWriter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1065   VisitDecl(D);
1066   Record.push_back(D->getLanguage());
1067   Record.AddSourceLocation(D->getExternLoc());
1068   Record.AddSourceLocation(D->getRBraceLoc());
1069   Code = serialization::DECL_LINKAGE_SPEC;
1070 }
1071 
1072 void ASTDeclWriter::VisitLabelDecl(LabelDecl *D) {
1073   VisitNamedDecl(D);
1074   Record.AddSourceLocation(D->getLocStart());
1075   Code = serialization::DECL_LABEL;
1076 }
1077 
1078 
1079 void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) {
1080   VisitRedeclarable(D);
1081   VisitNamedDecl(D);
1082   Record.push_back(D->isInline());
1083   Record.AddSourceLocation(D->getLocStart());
1084   Record.AddSourceLocation(D->getRBraceLoc());
1085 
1086   if (D->isOriginalNamespace())
1087     Record.AddDeclRef(D->getAnonymousNamespace());
1088   Code = serialization::DECL_NAMESPACE;
1089 
1090   if (Writer.hasChain() && D->isAnonymousNamespace() &&
1091       D == D->getMostRecentDecl()) {
1092     // This is a most recent reopening of the anonymous namespace. If its parent
1093     // is in a previous PCH (or is the TU), mark that parent for update, because
1094     // the original namespace always points to the latest re-opening of its
1095     // anonymous namespace.
1096     Decl *Parent = cast<Decl>(
1097         D->getParent()->getRedeclContext()->getPrimaryContext());
1098     if (Parent->isFromASTFile() || isa<TranslationUnitDecl>(Parent)) {
1099       Writer.DeclUpdates[Parent].push_back(
1100           ASTWriter::DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, D));
1101     }
1102   }
1103 }
1104 
1105 void ASTDeclWriter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1106   VisitRedeclarable(D);
1107   VisitNamedDecl(D);
1108   Record.AddSourceLocation(D->getNamespaceLoc());
1109   Record.AddSourceLocation(D->getTargetNameLoc());
1110   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1111   Record.AddDeclRef(D->getNamespace());
1112   Code = serialization::DECL_NAMESPACE_ALIAS;
1113 }
1114 
1115 void ASTDeclWriter::VisitUsingDecl(UsingDecl *D) {
1116   VisitNamedDecl(D);
1117   Record.AddSourceLocation(D->getUsingLoc());
1118   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1119   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
1120   Record.AddDeclRef(D->FirstUsingShadow.getPointer());
1121   Record.push_back(D->hasTypename());
1122   Record.AddDeclRef(Context.getInstantiatedFromUsingDecl(D));
1123   Code = serialization::DECL_USING;
1124 }
1125 
1126 void ASTDeclWriter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1127   VisitRedeclarable(D);
1128   VisitNamedDecl(D);
1129   Record.AddDeclRef(D->getTargetDecl());
1130   Record.AddDeclRef(D->UsingOrNextShadow);
1131   Record.AddDeclRef(Context.getInstantiatedFromUsingShadowDecl(D));
1132   Code = serialization::DECL_USING_SHADOW;
1133 }
1134 
1135 void ASTDeclWriter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1136   VisitNamedDecl(D);
1137   Record.AddSourceLocation(D->getUsingLoc());
1138   Record.AddSourceLocation(D->getNamespaceKeyLocation());
1139   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1140   Record.AddDeclRef(D->getNominatedNamespace());
1141   Record.AddDeclRef(dyn_cast<Decl>(D->getCommonAncestor()));
1142   Code = serialization::DECL_USING_DIRECTIVE;
1143 }
1144 
1145 void ASTDeclWriter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1146   VisitValueDecl(D);
1147   Record.AddSourceLocation(D->getUsingLoc());
1148   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1149   Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName());
1150   Code = serialization::DECL_UNRESOLVED_USING_VALUE;
1151 }
1152 
1153 void ASTDeclWriter::VisitUnresolvedUsingTypenameDecl(
1154                                                UnresolvedUsingTypenameDecl *D) {
1155   VisitTypeDecl(D);
1156   Record.AddSourceLocation(D->getTypenameLoc());
1157   Record.AddNestedNameSpecifierLoc(D->getQualifierLoc());
1158   Code = serialization::DECL_UNRESOLVED_USING_TYPENAME;
1159 }
1160 
1161 void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
1162   VisitRecordDecl(D);
1163 
1164   enum {
1165     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1166   };
1167   if (ClassTemplateDecl *TemplD = D->getDescribedClassTemplate()) {
1168     Record.push_back(CXXRecTemplate);
1169     Record.AddDeclRef(TemplD);
1170   } else if (MemberSpecializationInfo *MSInfo
1171                = D->getMemberSpecializationInfo()) {
1172     Record.push_back(CXXRecMemberSpecialization);
1173     Record.AddDeclRef(MSInfo->getInstantiatedFrom());
1174     Record.push_back(MSInfo->getTemplateSpecializationKind());
1175     Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
1176   } else {
1177     Record.push_back(CXXRecNotTemplate);
1178   }
1179 
1180   Record.push_back(D->isThisDeclarationADefinition());
1181   if (D->isThisDeclarationADefinition())
1182     Record.AddCXXDefinitionData(D);
1183 
1184   // Store (what we currently believe to be) the key function to avoid
1185   // deserializing every method so we can compute it.
1186   if (D->IsCompleteDefinition)
1187     Record.AddDeclRef(Context.getCurrentKeyFunction(D));
1188 
1189   Code = serialization::DECL_CXX_RECORD;
1190 }
1191 
1192 void ASTDeclWriter::VisitCXXMethodDecl(CXXMethodDecl *D) {
1193   VisitFunctionDecl(D);
1194   if (D->isCanonicalDecl()) {
1195     Record.push_back(D->size_overridden_methods());
1196     for (CXXMethodDecl::method_iterator
1197            I = D->begin_overridden_methods(), E = D->end_overridden_methods();
1198            I != E; ++I)
1199       Record.AddDeclRef(*I);
1200   } else {
1201     // We only need to record overridden methods once for the canonical decl.
1202     Record.push_back(0);
1203   }
1204 
1205   if (D->getDeclContext() == D->getLexicalDeclContext() &&
1206       D->getFirstDecl() == D->getMostRecentDecl() &&
1207       !D->isInvalidDecl() &&
1208       !D->hasAttrs() &&
1209       !D->isTopLevelDeclInObjCContainer() &&
1210       D->getDeclName().getNameKind() == DeclarationName::Identifier &&
1211       !D->hasExtInfo() &&
1212       !D->hasInheritedPrototype() &&
1213       D->hasWrittenPrototype())
1214     AbbrevToUse = Writer.getDeclCXXMethodAbbrev();
1215 
1216   Code = serialization::DECL_CXX_METHOD;
1217 }
1218 
1219 void ASTDeclWriter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1220   VisitCXXMethodDecl(D);
1221 
1222   Record.AddDeclRef(D->getInheritedConstructor());
1223   Record.push_back(D->IsExplicitSpecified);
1224 
1225   Code = serialization::DECL_CXX_CONSTRUCTOR;
1226 }
1227 
1228 void ASTDeclWriter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1229   VisitCXXMethodDecl(D);
1230 
1231   Record.AddDeclRef(D->getOperatorDelete());
1232 
1233   Code = serialization::DECL_CXX_DESTRUCTOR;
1234 }
1235 
1236 void ASTDeclWriter::VisitCXXConversionDecl(CXXConversionDecl *D) {
1237   VisitCXXMethodDecl(D);
1238   Record.push_back(D->IsExplicitSpecified);
1239   Code = serialization::DECL_CXX_CONVERSION;
1240 }
1241 
1242 void ASTDeclWriter::VisitImportDecl(ImportDecl *D) {
1243   VisitDecl(D);
1244   Record.push_back(Writer.getSubmoduleID(D->getImportedModule()));
1245   ArrayRef<SourceLocation> IdentifierLocs = D->getIdentifierLocs();
1246   Record.push_back(!IdentifierLocs.empty());
1247   if (IdentifierLocs.empty()) {
1248     Record.AddSourceLocation(D->getLocEnd());
1249     Record.push_back(1);
1250   } else {
1251     for (unsigned I = 0, N = IdentifierLocs.size(); I != N; ++I)
1252       Record.AddSourceLocation(IdentifierLocs[I]);
1253     Record.push_back(IdentifierLocs.size());
1254   }
1255   // Note: the number of source locations must always be the last element in
1256   // the record.
1257   Code = serialization::DECL_IMPORT;
1258 }
1259 
1260 void ASTDeclWriter::VisitAccessSpecDecl(AccessSpecDecl *D) {
1261   VisitDecl(D);
1262   Record.AddSourceLocation(D->getColonLoc());
1263   Code = serialization::DECL_ACCESS_SPEC;
1264 }
1265 
1266 void ASTDeclWriter::VisitFriendDecl(FriendDecl *D) {
1267   // Record the number of friend type template parameter lists here
1268   // so as to simplify memory allocation during deserialization.
1269   Record.push_back(D->NumTPLists);
1270   VisitDecl(D);
1271   bool hasFriendDecl = D->Friend.is<NamedDecl*>();
1272   Record.push_back(hasFriendDecl);
1273   if (hasFriendDecl)
1274     Record.AddDeclRef(D->getFriendDecl());
1275   else
1276     Record.AddTypeSourceInfo(D->getFriendType());
1277   for (unsigned i = 0; i < D->NumTPLists; ++i)
1278     Record.AddTemplateParameterList(D->getFriendTypeTemplateParameterList(i));
1279   Record.AddDeclRef(D->getNextFriend());
1280   Record.push_back(D->UnsupportedFriend);
1281   Record.AddSourceLocation(D->FriendLoc);
1282   Code = serialization::DECL_FRIEND;
1283 }
1284 
1285 void ASTDeclWriter::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1286   VisitDecl(D);
1287   Record.push_back(D->getNumTemplateParameters());
1288   for (unsigned i = 0, e = D->getNumTemplateParameters(); i != e; ++i)
1289     Record.AddTemplateParameterList(D->getTemplateParameterList(i));
1290   Record.push_back(D->getFriendDecl() != nullptr);
1291   if (D->getFriendDecl())
1292     Record.AddDeclRef(D->getFriendDecl());
1293   else
1294     Record.AddTypeSourceInfo(D->getFriendType());
1295   Record.AddSourceLocation(D->getFriendLoc());
1296   Code = serialization::DECL_FRIEND_TEMPLATE;
1297 }
1298 
1299 void ASTDeclWriter::VisitTemplateDecl(TemplateDecl *D) {
1300   VisitNamedDecl(D);
1301 
1302   Record.AddDeclRef(D->getTemplatedDecl());
1303   Record.AddTemplateParameterList(D->getTemplateParameters());
1304 }
1305 
1306 void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1307   VisitRedeclarable(D);
1308 
1309   // Emit data to initialize CommonOrPrev before VisitTemplateDecl so that
1310   // getCommonPtr() can be used while this is still initializing.
1311   if (D->isFirstDecl()) {
1312     // This declaration owns the 'common' pointer, so serialize that data now.
1313     Record.AddDeclRef(D->getInstantiatedFromMemberTemplate());
1314     if (D->getInstantiatedFromMemberTemplate())
1315       Record.push_back(D->isMemberSpecialization());
1316   }
1317 
1318   VisitTemplateDecl(D);
1319   Record.push_back(D->getIdentifierNamespace());
1320 }
1321 
1322 void ASTDeclWriter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1323   VisitRedeclarableTemplateDecl(D);
1324 
1325   if (D->isFirstDecl())
1326     AddTemplateSpecializations(D);
1327   Code = serialization::DECL_CLASS_TEMPLATE;
1328 }
1329 
1330 void ASTDeclWriter::VisitClassTemplateSpecializationDecl(
1331                                            ClassTemplateSpecializationDecl *D) {
1332   RegisterTemplateSpecialization(D->getSpecializedTemplate(), D);
1333 
1334   VisitCXXRecordDecl(D);
1335 
1336   llvm::PointerUnion<ClassTemplateDecl *,
1337                      ClassTemplatePartialSpecializationDecl *> InstFrom
1338     = D->getSpecializedTemplateOrPartial();
1339   if (Decl *InstFromD = InstFrom.dyn_cast<ClassTemplateDecl *>()) {
1340     Record.AddDeclRef(InstFromD);
1341   } else {
1342     Record.AddDeclRef(InstFrom.get<ClassTemplatePartialSpecializationDecl *>());
1343     Record.AddTemplateArgumentList(&D->getTemplateInstantiationArgs());
1344   }
1345 
1346   Record.AddTemplateArgumentList(&D->getTemplateArgs());
1347   Record.AddSourceLocation(D->getPointOfInstantiation());
1348   Record.push_back(D->getSpecializationKind());
1349   Record.push_back(D->isCanonicalDecl());
1350 
1351   if (D->isCanonicalDecl()) {
1352     // When reading, we'll add it to the folding set of the following template.
1353     Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl());
1354   }
1355 
1356   // Explicit info.
1357   Record.AddTypeSourceInfo(D->getTypeAsWritten());
1358   if (D->getTypeAsWritten()) {
1359     Record.AddSourceLocation(D->getExternLoc());
1360     Record.AddSourceLocation(D->getTemplateKeywordLoc());
1361   }
1362 
1363   Code = serialization::DECL_CLASS_TEMPLATE_SPECIALIZATION;
1364 }
1365 
1366 void ASTDeclWriter::VisitClassTemplatePartialSpecializationDecl(
1367                                     ClassTemplatePartialSpecializationDecl *D) {
1368   VisitClassTemplateSpecializationDecl(D);
1369 
1370   Record.AddTemplateParameterList(D->getTemplateParameters());
1371   Record.AddASTTemplateArgumentListInfo(D->getTemplateArgsAsWritten());
1372 
1373   // These are read/set from/to the first declaration.
1374   if (D->getPreviousDecl() == nullptr) {
1375     Record.AddDeclRef(D->getInstantiatedFromMember());
1376     Record.push_back(D->isMemberSpecialization());
1377   }
1378 
1379   Code = serialization::DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION;
1380 }
1381 
1382 void ASTDeclWriter::VisitVarTemplateDecl(VarTemplateDecl *D) {
1383   VisitRedeclarableTemplateDecl(D);
1384 
1385   if (D->isFirstDecl())
1386     AddTemplateSpecializations(D);
1387   Code = serialization::DECL_VAR_TEMPLATE;
1388 }
1389 
1390 void ASTDeclWriter::VisitVarTemplateSpecializationDecl(
1391     VarTemplateSpecializationDecl *D) {
1392   RegisterTemplateSpecialization(D->getSpecializedTemplate(), D);
1393 
1394   VisitVarDecl(D);
1395 
1396   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
1397   InstFrom = D->getSpecializedTemplateOrPartial();
1398   if (Decl *InstFromD = InstFrom.dyn_cast<VarTemplateDecl *>()) {
1399     Record.AddDeclRef(InstFromD);
1400   } else {
1401     Record.AddDeclRef(InstFrom.get<VarTemplatePartialSpecializationDecl *>());
1402     Record.AddTemplateArgumentList(&D->getTemplateInstantiationArgs());
1403   }
1404 
1405   // Explicit info.
1406   Record.AddTypeSourceInfo(D->getTypeAsWritten());
1407   if (D->getTypeAsWritten()) {
1408     Record.AddSourceLocation(D->getExternLoc());
1409     Record.AddSourceLocation(D->getTemplateKeywordLoc());
1410   }
1411 
1412   Record.AddTemplateArgumentList(&D->getTemplateArgs());
1413   Record.AddSourceLocation(D->getPointOfInstantiation());
1414   Record.push_back(D->getSpecializationKind());
1415   Record.push_back(D->isCanonicalDecl());
1416 
1417   if (D->isCanonicalDecl()) {
1418     // When reading, we'll add it to the folding set of the following template.
1419     Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl());
1420   }
1421 
1422   Code = serialization::DECL_VAR_TEMPLATE_SPECIALIZATION;
1423 }
1424 
1425 void ASTDeclWriter::VisitVarTemplatePartialSpecializationDecl(
1426     VarTemplatePartialSpecializationDecl *D) {
1427   VisitVarTemplateSpecializationDecl(D);
1428 
1429   Record.AddTemplateParameterList(D->getTemplateParameters());
1430   Record.AddASTTemplateArgumentListInfo(D->getTemplateArgsAsWritten());
1431 
1432   // These are read/set from/to the first declaration.
1433   if (D->getPreviousDecl() == nullptr) {
1434     Record.AddDeclRef(D->getInstantiatedFromMember());
1435     Record.push_back(D->isMemberSpecialization());
1436   }
1437 
1438   Code = serialization::DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION;
1439 }
1440 
1441 void ASTDeclWriter::VisitClassScopeFunctionSpecializationDecl(
1442                                     ClassScopeFunctionSpecializationDecl *D) {
1443   VisitDecl(D);
1444   Record.AddDeclRef(D->getSpecialization());
1445   Code = serialization::DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION;
1446 }
1447 
1448 
1449 void ASTDeclWriter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1450   VisitRedeclarableTemplateDecl(D);
1451 
1452   if (D->isFirstDecl())
1453     AddTemplateSpecializations(D);
1454   Code = serialization::DECL_FUNCTION_TEMPLATE;
1455 }
1456 
1457 void ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1458   VisitTypeDecl(D);
1459 
1460   Record.push_back(D->wasDeclaredWithTypename());
1461 
1462   bool OwnsDefaultArg = D->hasDefaultArgument() &&
1463                         !D->defaultArgumentWasInherited();
1464   Record.push_back(OwnsDefaultArg);
1465   if (OwnsDefaultArg)
1466     Record.AddTypeSourceInfo(D->getDefaultArgumentInfo());
1467 
1468   Code = serialization::DECL_TEMPLATE_TYPE_PARM;
1469 }
1470 
1471 void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1472   // For an expanded parameter pack, record the number of expansion types here
1473   // so that it's easier for deserialization to allocate the right amount of
1474   // memory.
1475   if (D->isExpandedParameterPack())
1476     Record.push_back(D->getNumExpansionTypes());
1477 
1478   VisitDeclaratorDecl(D);
1479   // TemplateParmPosition.
1480   Record.push_back(D->getDepth());
1481   Record.push_back(D->getPosition());
1482 
1483   if (D->isExpandedParameterPack()) {
1484     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1485       Record.AddTypeRef(D->getExpansionType(I));
1486       Record.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I));
1487     }
1488 
1489     Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK;
1490   } else {
1491     // Rest of NonTypeTemplateParmDecl.
1492     Record.push_back(D->isParameterPack());
1493     bool OwnsDefaultArg = D->hasDefaultArgument() &&
1494                           !D->defaultArgumentWasInherited();
1495     Record.push_back(OwnsDefaultArg);
1496     if (OwnsDefaultArg)
1497       Record.AddStmt(D->getDefaultArgument());
1498     Code = serialization::DECL_NON_TYPE_TEMPLATE_PARM;
1499   }
1500 }
1501 
1502 void ASTDeclWriter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1503   // For an expanded parameter pack, record the number of expansion types here
1504   // so that it's easier for deserialization to allocate the right amount of
1505   // memory.
1506   if (D->isExpandedParameterPack())
1507     Record.push_back(D->getNumExpansionTemplateParameters());
1508 
1509   VisitTemplateDecl(D);
1510   // TemplateParmPosition.
1511   Record.push_back(D->getDepth());
1512   Record.push_back(D->getPosition());
1513 
1514   if (D->isExpandedParameterPack()) {
1515     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1516          I != N; ++I)
1517       Record.AddTemplateParameterList(D->getExpansionTemplateParameters(I));
1518     Code = serialization::DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK;
1519   } else {
1520     // Rest of TemplateTemplateParmDecl.
1521     Record.push_back(D->isParameterPack());
1522     bool OwnsDefaultArg = D->hasDefaultArgument() &&
1523                           !D->defaultArgumentWasInherited();
1524     Record.push_back(OwnsDefaultArg);
1525     if (OwnsDefaultArg)
1526       Record.AddTemplateArgumentLoc(D->getDefaultArgument());
1527     Code = serialization::DECL_TEMPLATE_TEMPLATE_PARM;
1528   }
1529 }
1530 
1531 void ASTDeclWriter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1532   VisitRedeclarableTemplateDecl(D);
1533   Code = serialization::DECL_TYPE_ALIAS_TEMPLATE;
1534 }
1535 
1536 void ASTDeclWriter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1537   VisitDecl(D);
1538   Record.AddStmt(D->getAssertExpr());
1539   Record.push_back(D->isFailed());
1540   Record.AddStmt(D->getMessage());
1541   Record.AddSourceLocation(D->getRParenLoc());
1542   Code = serialization::DECL_STATIC_ASSERT;
1543 }
1544 
1545 /// \brief Emit the DeclContext part of a declaration context decl.
1546 ///
1547 /// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
1548 /// block for this declaration context is stored. May be 0 to indicate
1549 /// that there are no declarations stored within this context.
1550 ///
1551 /// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
1552 /// block for this declaration context is stored. May be 0 to indicate
1553 /// that there are no declarations visible from this context. Note
1554 /// that this value will not be emitted for non-primary declaration
1555 /// contexts.
1556 void ASTDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
1557                                      uint64_t VisibleOffset) {
1558   AddLocalOffset(LexicalOffset);
1559   AddLocalOffset(VisibleOffset);
1560 }
1561 
1562 const Decl *ASTWriter::getFirstLocalDecl(const Decl *D) {
1563   /// \brief Is this a local declaration (that is, one that will be written to
1564   /// our AST file)? This is the case for declarations that are neither imported
1565   /// from another AST file nor predefined.
1566   auto IsLocalDecl = [&](const Decl *D) -> bool {
1567     if (D->isFromASTFile())
1568       return false;
1569     auto I = DeclIDs.find(D);
1570     return (I == DeclIDs.end() || I->second >= NUM_PREDEF_DECL_IDS);
1571   };
1572 
1573   assert(IsLocalDecl(D) && "expected a local declaration");
1574 
1575   const Decl *Canon = D->getCanonicalDecl();
1576   if (IsLocalDecl(Canon))
1577     return Canon;
1578 
1579   const Decl *&CacheEntry = FirstLocalDeclCache[Canon];
1580   if (CacheEntry)
1581     return CacheEntry;
1582 
1583   for (const Decl *Redecl = D; Redecl; Redecl = Redecl->getPreviousDecl())
1584     if (IsLocalDecl(Redecl))
1585       D = Redecl;
1586   return CacheEntry = D;
1587 }
1588 
1589 template <typename T>
1590 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
1591   T *First = D->getFirstDecl();
1592   T *MostRecent = First->getMostRecentDecl();
1593   T *DAsT = static_cast<T *>(D);
1594   if (MostRecent != First) {
1595     assert(isRedeclarableDeclKind(DAsT->getKind()) &&
1596            "Not considered redeclarable?");
1597 
1598     Record.AddDeclRef(First);
1599 
1600     // Write out a list of local redeclarations of this declaration if it's the
1601     // first local declaration in the chain.
1602     const Decl *FirstLocal = Writer.getFirstLocalDecl(DAsT);
1603     if (DAsT == FirstLocal) {
1604       // Emit a list of all imported first declarations so that we can be sure
1605       // that all redeclarations visible to this module are before D in the
1606       // redecl chain.
1607       unsigned I = Record.size();
1608       Record.push_back(0);
1609       if (Writer.Chain)
1610         AddFirstDeclFromEachModule(DAsT, /*IncludeLocal*/false);
1611       // This is the number of imported first declarations + 1.
1612       Record[I] = Record.size() - I;
1613 
1614       // Collect the set of local redeclarations of this declaration, from
1615       // newest to oldest.
1616       ASTWriter::RecordData LocalRedecls;
1617       ASTRecordWriter LocalRedeclWriter(Record, LocalRedecls);
1618       for (const Decl *Prev = FirstLocal->getMostRecentDecl();
1619            Prev != FirstLocal; Prev = Prev->getPreviousDecl())
1620         if (!Prev->isFromASTFile())
1621           LocalRedeclWriter.AddDeclRef(Prev);
1622 
1623       // If we have any redecls, write them now as a separate record preceding
1624       // the declaration itself.
1625       if (LocalRedecls.empty())
1626         Record.push_back(0);
1627       else {
1628         AddLocalOffset(LocalRedeclWriter.Emit(LOCAL_REDECLARATIONS));
1629       }
1630     } else {
1631       Record.push_back(0);
1632       Record.AddDeclRef(FirstLocal);
1633     }
1634 
1635     // Make sure that we serialize both the previous and the most-recent
1636     // declarations, which (transitively) ensures that all declarations in the
1637     // chain get serialized.
1638     //
1639     // FIXME: This is not correct; when we reach an imported declaration we
1640     // won't emit its previous declaration.
1641     (void)Writer.GetDeclRef(D->getPreviousDecl());
1642     (void)Writer.GetDeclRef(MostRecent);
1643   } else {
1644     // We use the sentinel value 0 to indicate an only declaration.
1645     Record.push_back(0);
1646   }
1647 }
1648 
1649 void ASTDeclWriter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1650   Record.push_back(D->varlist_size());
1651   VisitDecl(D);
1652   for (auto *I : D->varlists())
1653     Record.AddStmt(I);
1654   Code = serialization::DECL_OMP_THREADPRIVATE;
1655 }
1656 
1657 void ASTDeclWriter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1658   VisitValueDecl(D);
1659   Record.AddSourceLocation(D->getLocStart());
1660   Record.AddStmt(D->getCombiner());
1661   Record.AddStmt(D->getInitializer());
1662   Record.AddDeclRef(D->getPrevDeclInScope());
1663   Code = serialization::DECL_OMP_DECLARE_REDUCTION;
1664 }
1665 
1666 void ASTDeclWriter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1667   VisitVarDecl(D);
1668   Code = serialization::DECL_OMP_CAPTUREDEXPR;
1669 }
1670 
1671 //===----------------------------------------------------------------------===//
1672 // ASTWriter Implementation
1673 //===----------------------------------------------------------------------===//
1674 
1675 void ASTWriter::WriteDeclAbbrevs() {
1676   using namespace llvm;
1677 
1678   BitCodeAbbrev *Abv;
1679 
1680   // Abbreviation for DECL_FIELD
1681   Abv = new BitCodeAbbrev();
1682   Abv->Add(BitCodeAbbrevOp(serialization::DECL_FIELD));
1683   // Decl
1684   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1685   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1686   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1687   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1688   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1689   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1690   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1691   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1692   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2));  // AccessSpecifier
1693   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1694   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1695   // NamedDecl
1696   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1697   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1698   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1699   // ValueDecl
1700   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
1701   // DeclaratorDecl
1702   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
1703   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
1704   // FieldDecl
1705   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isMutable
1706   Abv->Add(BitCodeAbbrevOp(0));                       //getBitWidth
1707   // Type Source Info
1708   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1709   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1710   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
1711   DeclFieldAbbrev = Stream.EmitAbbrev(Abv);
1712 
1713   // Abbreviation for DECL_OBJC_IVAR
1714   Abv = new BitCodeAbbrev();
1715   Abv->Add(BitCodeAbbrevOp(serialization::DECL_OBJC_IVAR));
1716   // Decl
1717   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1718   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1719   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1720   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1721   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1722   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1723   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1724   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1725   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2));  // AccessSpecifier
1726   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1727   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1728   // NamedDecl
1729   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1730   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1731   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1732   // ValueDecl
1733   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
1734   // DeclaratorDecl
1735   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
1736   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
1737   // FieldDecl
1738   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isMutable
1739   Abv->Add(BitCodeAbbrevOp(0));                       //getBitWidth
1740   // ObjC Ivar
1741   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getAccessControl
1742   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getSynthesize
1743   // Type Source Info
1744   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1745   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1746   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
1747   DeclObjCIvarAbbrev = Stream.EmitAbbrev(Abv);
1748 
1749   // Abbreviation for DECL_ENUM
1750   Abv = new BitCodeAbbrev();
1751   Abv->Add(BitCodeAbbrevOp(serialization::DECL_ENUM));
1752   // Redeclarable
1753   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1754   // Decl
1755   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1756   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1757   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1758   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1759   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1760   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1761   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1762   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1763   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifier
1764   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1765   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1766   // NamedDecl
1767   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1768   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1769   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1770   // TypeDecl
1771   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
1772   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
1773   // TagDecl
1774   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNamespace
1775   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getTagKind
1776   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isCompleteDefinition
1777   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // EmbeddedInDeclarator
1778   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFreeStanding
1779   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsCompleteDefinitionRequired
1780   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
1781   Abv->Add(BitCodeAbbrevOp(0));                         // ExtInfoKind
1782   // EnumDecl
1783   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddTypeRef
1784   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IntegerType
1785   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getPromotionType
1786   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getNumPositiveBits
1787   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getNumNegativeBits
1788   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isScoped
1789   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isScopedUsingClassTag
1790   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isFixed
1791   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // InstantiatedMembEnum
1792   // DC
1793   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LexicalOffset
1794   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // VisibleOffset
1795   DeclEnumAbbrev = Stream.EmitAbbrev(Abv);
1796 
1797   // Abbreviation for DECL_RECORD
1798   Abv = new BitCodeAbbrev();
1799   Abv->Add(BitCodeAbbrevOp(serialization::DECL_RECORD));
1800   // Redeclarable
1801   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1802   // Decl
1803   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1804   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1805   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1806   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1807   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1808   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1809   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1810   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1811   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifier
1812   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1813   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1814   // NamedDecl
1815   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1816   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1817   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1818   // TypeDecl
1819   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
1820   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
1821   // TagDecl
1822   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNamespace
1823   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getTagKind
1824   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isCompleteDefinition
1825   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // EmbeddedInDeclarator
1826   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFreeStanding
1827   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsCompleteDefinitionRequired
1828   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SourceLocation
1829   Abv->Add(BitCodeAbbrevOp(0));                         // ExtInfoKind
1830   // RecordDecl
1831   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // FlexibleArrayMember
1832   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // AnonymousStructUnion
1833   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // hasObjectMember
1834   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // hasVolatileMember
1835   // DC
1836   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LexicalOffset
1837   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // VisibleOffset
1838   DeclRecordAbbrev = Stream.EmitAbbrev(Abv);
1839 
1840   // Abbreviation for DECL_PARM_VAR
1841   Abv = new BitCodeAbbrev();
1842   Abv->Add(BitCodeAbbrevOp(serialization::DECL_PARM_VAR));
1843   // Redeclarable
1844   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1845   // Decl
1846   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1847   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1848   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1849   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1850   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1851   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1852   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1853   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1854   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifier
1855   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1856   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1857   // NamedDecl
1858   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1859   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1860   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1861   // ValueDecl
1862   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
1863   // DeclaratorDecl
1864   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
1865   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
1866   // VarDecl
1867   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClass
1868   Abv->Add(BitCodeAbbrevOp(0));                       // getTSCSpec
1869   Abv->Add(BitCodeAbbrevOp(0));                       // hasCXXDirectInitializer
1870   Abv->Add(BitCodeAbbrevOp(0));                       // Linkage
1871   Abv->Add(BitCodeAbbrevOp(0));                       // HasInit
1872   Abv->Add(BitCodeAbbrevOp(0));                   // HasMemberSpecializationInfo
1873   // ParmVarDecl
1874   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsObjCMethodParameter
1875   Abv->Add(BitCodeAbbrevOp(0));                       // ScopeDepth
1876   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ScopeIndex
1877   Abv->Add(BitCodeAbbrevOp(0));                       // ObjCDeclQualifier
1878   Abv->Add(BitCodeAbbrevOp(0));                       // KNRPromoted
1879   Abv->Add(BitCodeAbbrevOp(0));                       // HasInheritedDefaultArg
1880   Abv->Add(BitCodeAbbrevOp(0));                   // HasUninstantiatedDefaultArg
1881   // Type Source Info
1882   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1883   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1884   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
1885   DeclParmVarAbbrev = Stream.EmitAbbrev(Abv);
1886 
1887   // Abbreviation for DECL_TYPEDEF
1888   Abv = new BitCodeAbbrev();
1889   Abv->Add(BitCodeAbbrevOp(serialization::DECL_TYPEDEF));
1890   // Redeclarable
1891   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1892   // Decl
1893   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1894   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1895   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1896   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1897   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1898   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isUsed
1899   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isReferenced
1900   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1901   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // C++ AccessSpecifier
1902   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1903   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1904   // NamedDecl
1905   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1906   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1907   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1908   // TypeDecl
1909   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
1910   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
1911   // TypedefDecl
1912   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1913   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
1914   DeclTypedefAbbrev = Stream.EmitAbbrev(Abv);
1915 
1916   // Abbreviation for DECL_VAR
1917   Abv = new BitCodeAbbrev();
1918   Abv->Add(BitCodeAbbrevOp(serialization::DECL_VAR));
1919   // Redeclarable
1920   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1921   // Decl
1922   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1923   Abv->Add(BitCodeAbbrevOp(0));                       // LexicalDeclContext
1924   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
1925   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1926   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1927   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1928   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1929   Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCContainer
1930   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifier
1931   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
1932   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
1933   // NamedDecl
1934   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1935   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1936   Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
1937   // ValueDecl
1938   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
1939   // DeclaratorDecl
1940   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
1941   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
1942   // VarDecl
1943   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // StorageClass
1944   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // getTSCSpec
1945   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // CXXDirectInitializer
1946   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isExceptionVariable
1947   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isNRVOVariable
1948   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isCXXForRangeDecl
1949   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isARCPseudoStrong
1950   Abv->Add(BitCodeAbbrevOp(0));                         // isConstexpr
1951   Abv->Add(BitCodeAbbrevOp(0));                         // isInitCapture
1952   Abv->Add(BitCodeAbbrevOp(0));                         // isPrevDeclInSameScope
1953   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage
1954   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // HasInit
1955   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // HasMemberSpecInfo
1956   // Type Source Info
1957   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1958   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1959   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // TypeLoc
1960   DeclVarAbbrev = Stream.EmitAbbrev(Abv);
1961 
1962   // Abbreviation for DECL_CXX_METHOD
1963   Abv = new BitCodeAbbrev();
1964   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CXX_METHOD));
1965   // RedeclarableDecl
1966   Abv->Add(BitCodeAbbrevOp(0));                         // CanonicalDecl
1967   // Decl
1968   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // DeclContext
1969   Abv->Add(BitCodeAbbrevOp(0));                         // LexicalDeclContext
1970   Abv->Add(BitCodeAbbrevOp(0));                         // Invalid
1971   Abv->Add(BitCodeAbbrevOp(0));                         // HasAttrs
1972   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Implicit
1973   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Used
1974   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Referenced
1975   Abv->Add(BitCodeAbbrevOp(0));                         // InObjCContainer
1976   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Access
1977   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModulePrivate
1978   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // SubmoduleID
1979   // NamedDecl
1980   Abv->Add(BitCodeAbbrevOp(DeclarationName::Identifier)); // NameKind
1981   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Identifier
1982   Abv->Add(BitCodeAbbrevOp(0));                         // AnonDeclNumber
1983   // ValueDecl
1984   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
1985   // DeclaratorDecl
1986   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // InnerLocStart
1987   Abv->Add(BitCodeAbbrevOp(0));                         // HasExtInfo
1988   // FunctionDecl
1989   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 11)); // IDNS
1990   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // StorageClass
1991   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Inline
1992   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InlineSpecified
1993   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // VirtualAsWritten
1994   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Pure
1995   Abv->Add(BitCodeAbbrevOp(0));                         // HasInheritedProto
1996   Abv->Add(BitCodeAbbrevOp(1));                         // HasWrittenProto
1997   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Deleted
1998   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Trivial
1999   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Defaulted
2000   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ExplicitlyDefaulted
2001   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ImplicitReturnZero
2002   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constexpr
2003   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // SkippedBody
2004   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // LateParsed
2005   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage
2006   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LocEnd
2007   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // TemplateKind
2008   // This Array slurps the rest of the record. Fortunately we want to encode
2009   // (nearly) all the remaining (variable number of) fields in the same way.
2010   //
2011   // This is the function template information if any, then
2012   //         NumParams and Params[] from FunctionDecl, and
2013   //         NumOverriddenMethods, OverriddenMethods[] from CXXMethodDecl.
2014   //
2015   //  Add an AbbrevOp for 'size then elements' and use it here.
2016   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2017   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2018   DeclCXXMethodAbbrev = Stream.EmitAbbrev(Abv);
2019 
2020   // Abbreviation for EXPR_DECL_REF
2021   Abv = new BitCodeAbbrev();
2022   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_DECL_REF));
2023   //Stmt
2024   //Expr
2025   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2026   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
2027   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
2028   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
2029   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
2030   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
2031   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
2032   //DeclRefExpr
2033   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //HasQualifier
2034   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //GetDeclFound
2035   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ExplicitTemplateArgs
2036   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //HadMultipleCandidates
2037   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2038                            1)); // RefersToEnclosingVariableOrCapture
2039   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclRef
2040   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2041   DeclRefExprAbbrev = Stream.EmitAbbrev(Abv);
2042 
2043   // Abbreviation for EXPR_INTEGER_LITERAL
2044   Abv = new BitCodeAbbrev();
2045   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_INTEGER_LITERAL));
2046   //Stmt
2047   //Expr
2048   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2049   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
2050   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
2051   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
2052   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
2053   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
2054   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
2055   //Integer Literal
2056   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2057   Abv->Add(BitCodeAbbrevOp(32));                      // Bit Width
2058   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Value
2059   IntegerLiteralAbbrev = Stream.EmitAbbrev(Abv);
2060 
2061   // Abbreviation for EXPR_CHARACTER_LITERAL
2062   Abv = new BitCodeAbbrev();
2063   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_CHARACTER_LITERAL));
2064   //Stmt
2065   //Expr
2066   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2067   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
2068   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
2069   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
2070   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
2071   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
2072   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
2073   //Character Literal
2074   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // getValue
2075   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
2076   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // getKind
2077   CharacterLiteralAbbrev = Stream.EmitAbbrev(Abv);
2078 
2079   // Abbreviation for EXPR_IMPLICIT_CAST
2080   Abv = new BitCodeAbbrev();
2081   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_IMPLICIT_CAST));
2082   // Stmt
2083   // Expr
2084   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
2085   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
2086   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
2087   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
2088   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
2089   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
2090   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
2091   // CastExpr
2092   Abv->Add(BitCodeAbbrevOp(0)); // PathSize
2093   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // CastKind
2094   // ImplicitCastExpr
2095   ExprImplicitCastAbbrev = Stream.EmitAbbrev(Abv);
2096 
2097   Abv = new BitCodeAbbrev();
2098   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_LEXICAL));
2099   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2100   DeclContextLexicalAbbrev = Stream.EmitAbbrev(Abv);
2101 
2102   Abv = new BitCodeAbbrev();
2103   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_VISIBLE));
2104   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2105   DeclContextVisibleLookupAbbrev = Stream.EmitAbbrev(Abv);
2106 }
2107 
2108 /// isRequiredDecl - Check if this is a "required" Decl, which must be seen by
2109 /// consumers of the AST.
2110 ///
2111 /// Such decls will always be deserialized from the AST file, so we would like
2112 /// this to be as restrictive as possible. Currently the predicate is driven by
2113 /// code generation requirements, if other clients have a different notion of
2114 /// what is "required" then we may have to consider an alternate scheme where
2115 /// clients can iterate over the top-level decls and get information on them,
2116 /// without necessary deserializing them. We could explicitly require such
2117 /// clients to use a separate API call to "realize" the decl. This should be
2118 /// relatively painless since they would presumably only do it for top-level
2119 /// decls.
2120 static bool isRequiredDecl(const Decl *D, ASTContext &Context,
2121                            bool WritingModule) {
2122   // An ObjCMethodDecl is never considered as "required" because its
2123   // implementation container always is.
2124 
2125   // File scoped assembly or obj-c or OMP declare target implementation must be
2126   // seen.
2127   if (isa<FileScopeAsmDecl>(D) || isa<ObjCImplDecl>(D) ||
2128       D->hasAttr<OMPDeclareTargetDeclAttr>())
2129     return true;
2130 
2131   // ImportDecl is used by codegen to determine the set of imported modules to
2132   // search for inputs for automatic linking; include it if it has a semantic
2133   // effect.
2134   if (isa<ImportDecl>(D) && !WritingModule)
2135     return true;
2136 
2137   return Context.DeclMustBeEmitted(D);
2138 }
2139 
2140 void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) {
2141   // Determine the ID for this declaration.
2142   serialization::DeclID ID;
2143   assert(!D->isFromASTFile() && "should not be emitting imported decl");
2144   serialization::DeclID &IDR = DeclIDs[D];
2145   if (IDR == 0)
2146     IDR = NextDeclID++;
2147 
2148   ID = IDR;
2149 
2150   assert(ID >= FirstDeclID && "invalid decl ID");
2151 
2152   // If this declaration is also a DeclContext, write blocks for the
2153   // declarations that lexically stored inside its context and those
2154   // declarations that are visible from its context. These blocks
2155   // are written before the declaration itself so that we can put
2156   // their offsets into the record for the declaration.
2157   uint64_t LexicalOffset = 0;
2158   uint64_t VisibleOffset = 0;
2159   DeclContext *DC = dyn_cast<DeclContext>(D);
2160   if (DC) {
2161     LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
2162     VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
2163   }
2164 
2165   RecordData Record;
2166   ASTDeclWriter W(*this, Context, Record);
2167 
2168   // Build a record for this declaration
2169   W.Visit(D);
2170   if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
2171 
2172   // Emit this declaration to the bitstream.
2173   uint64_t Offset = W.Emit(D);
2174 
2175   // Record the offset for this declaration
2176   SourceLocation Loc = D->getLocation();
2177   unsigned Index = ID - FirstDeclID;
2178   if (DeclOffsets.size() == Index)
2179     DeclOffsets.push_back(DeclOffset(Loc, Offset));
2180   else if (DeclOffsets.size() < Index) {
2181     // FIXME: Can/should this happen?
2182     DeclOffsets.resize(Index+1);
2183     DeclOffsets[Index].setLocation(Loc);
2184     DeclOffsets[Index].BitOffset = Offset;
2185   } else {
2186     llvm_unreachable("declarations should be emitted in ID order");
2187   }
2188 
2189   SourceManager &SM = Context.getSourceManager();
2190   if (Loc.isValid() && SM.isLocalSourceLocation(Loc))
2191     associateDeclWithFile(D, ID);
2192 
2193   // Note declarations that should be deserialized eagerly so that we can add
2194   // them to a record in the AST file later.
2195   if (isRequiredDecl(D, Context, WritingModule))
2196     EagerlyDeserializedDecls.push_back(ID);
2197 }
2198 
2199 void ASTRecordWriter::AddFunctionDefinition(const FunctionDecl *FD) {
2200   // Switch case IDs are per function body.
2201   Writer->ClearSwitchCaseIDs();
2202 
2203   assert(FD->doesThisDeclarationHaveABody());
2204   if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
2205     Record->push_back(CD->getNumCtorInitializers());
2206     if (CD->getNumCtorInitializers())
2207       AddCXXCtorInitializersRef(
2208           llvm::makeArrayRef(CD->init_begin(), CD->init_end()));
2209   }
2210   AddStmt(FD->getBody());
2211 }
2212