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/DeclVisitor.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Bitcode/BitstreamWriter.h"
23 #include "llvm/Support/ErrorHandling.h"
24 using namespace clang;
25 using namespace serialization;
26 
27 //===----------------------------------------------------------------------===//
28 // Declaration serialization
29 //===----------------------------------------------------------------------===//
30 
31 namespace clang {
32   class ASTDeclWriter : public DeclVisitor<ASTDeclWriter, void> {
33 
34     ASTWriter &Writer;
35     ASTContext &Context;
36     typedef ASTWriter::RecordData RecordData;
37     RecordData &Record;
38 
39   public:
40     serialization::DeclCode Code;
41     unsigned AbbrevToUse;
42 
43     ASTDeclWriter(ASTWriter &Writer, ASTContext &Context, RecordData &Record)
44       : Writer(Writer), Context(Context), Record(Record) {
45     }
46 
47     void Visit(Decl *D);
48 
49     void VisitDecl(Decl *D);
50     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
51     void VisitNamedDecl(NamedDecl *D);
52     void VisitLabelDecl(LabelDecl *LD);
53     void VisitNamespaceDecl(NamespaceDecl *D);
54     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
55     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
56     void VisitTypeDecl(TypeDecl *D);
57     void VisitTypedefDecl(TypedefDecl *D);
58     void VisitTypeAliasDecl(TypeAliasDecl *D);
59     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
60     void VisitTagDecl(TagDecl *D);
61     void VisitEnumDecl(EnumDecl *D);
62     void VisitRecordDecl(RecordDecl *D);
63     void VisitCXXRecordDecl(CXXRecordDecl *D);
64     void VisitClassTemplateSpecializationDecl(
65                                             ClassTemplateSpecializationDecl *D);
66     void VisitClassTemplatePartialSpecializationDecl(
67                                      ClassTemplatePartialSpecializationDecl *D);
68     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
69     void VisitValueDecl(ValueDecl *D);
70     void VisitEnumConstantDecl(EnumConstantDecl *D);
71     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
72     void VisitDeclaratorDecl(DeclaratorDecl *D);
73     void VisitFunctionDecl(FunctionDecl *D);
74     void VisitCXXMethodDecl(CXXMethodDecl *D);
75     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
76     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
77     void VisitCXXConversionDecl(CXXConversionDecl *D);
78     void VisitFieldDecl(FieldDecl *D);
79     void VisitIndirectFieldDecl(IndirectFieldDecl *D);
80     void VisitVarDecl(VarDecl *D);
81     void VisitImplicitParamDecl(ImplicitParamDecl *D);
82     void VisitParmVarDecl(ParmVarDecl *D);
83     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
84     void VisitTemplateDecl(TemplateDecl *D);
85     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
86     void VisitClassTemplateDecl(ClassTemplateDecl *D);
87     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
88     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
89     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
90     void VisitUsingDecl(UsingDecl *D);
91     void VisitUsingShadowDecl(UsingShadowDecl *D);
92     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
93     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
94     void VisitAccessSpecDecl(AccessSpecDecl *D);
95     void VisitFriendDecl(FriendDecl *D);
96     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
97     void VisitStaticAssertDecl(StaticAssertDecl *D);
98     void VisitBlockDecl(BlockDecl *D);
99 
100     void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
101                           uint64_t VisibleOffset);
102     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
103 
104 
105     // FIXME: Put in the same order is DeclNodes.td?
106     void VisitObjCMethodDecl(ObjCMethodDecl *D);
107     void VisitObjCContainerDecl(ObjCContainerDecl *D);
108     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
109     void VisitObjCIvarDecl(ObjCIvarDecl *D);
110     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
111     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
112     void VisitObjCClassDecl(ObjCClassDecl *D);
113     void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
114     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
115     void VisitObjCImplDecl(ObjCImplDecl *D);
116     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
117     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
118     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
119     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
120     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
121   };
122 }
123 
124 void ASTDeclWriter::Visit(Decl *D) {
125   DeclVisitor<ASTDeclWriter>::Visit(D);
126 
127   // Handle FunctionDecl's body here and write it after all other Stmts/Exprs
128   // have been written. We want it last because we will not read it back when
129   // retrieving it from the AST, we'll just lazily set the offset.
130   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
131     Record.push_back(FD->doesThisDeclarationHaveABody());
132     if (FD->doesThisDeclarationHaveABody())
133       Writer.AddStmt(FD->getBody());
134   }
135 }
136 
137 void ASTDeclWriter::VisitDecl(Decl *D) {
138   Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
139   Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
140   Writer.AddSourceLocation(D->getLocation(), Record);
141   Record.push_back(D->isInvalidDecl());
142   Record.push_back(D->hasAttrs());
143   if (D->hasAttrs())
144     Writer.WriteAttributes(D->getAttrs(), Record);
145   Record.push_back(D->isImplicit());
146   Record.push_back(D->isUsed(false));
147   Record.push_back(D->isReferenced());
148   Record.push_back(D->getAccess());
149   Record.push_back(D->getPCHLevel());
150 }
151 
152 void ASTDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
153   VisitDecl(D);
154   Writer.AddDeclRef(D->getAnonymousNamespace(), Record);
155   Code = serialization::DECL_TRANSLATION_UNIT;
156 }
157 
158 void ASTDeclWriter::VisitNamedDecl(NamedDecl *D) {
159   VisitDecl(D);
160   Writer.AddDeclarationName(D->getDeclName(), Record);
161 }
162 
163 void ASTDeclWriter::VisitTypeDecl(TypeDecl *D) {
164   VisitNamedDecl(D);
165   Writer.AddSourceLocation(D->getLocStart(), Record);
166   Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
167 }
168 
169 void ASTDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
170   VisitTypeDecl(D);
171   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
172   Code = serialization::DECL_TYPEDEF;
173 }
174 
175 void ASTDeclWriter::VisitTypeAliasDecl(TypeAliasDecl *D) {
176   VisitTypeDecl(D);
177   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
178   Code = serialization::DECL_TYPEALIAS;
179 }
180 
181 void ASTDeclWriter::VisitTagDecl(TagDecl *D) {
182   VisitTypeDecl(D);
183   VisitRedeclarable(D);
184   Record.push_back(D->getIdentifierNamespace());
185   Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
186   Record.push_back(D->isDefinition());
187   Record.push_back(D->isEmbeddedInDeclarator());
188   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
189   Record.push_back(D->hasExtInfo());
190   if (D->hasExtInfo())
191     Writer.AddQualifierInfo(*D->getExtInfo(), Record);
192   else
193     Writer.AddDeclRef(D->getTypedefNameForAnonDecl(), Record);
194 }
195 
196 void ASTDeclWriter::VisitEnumDecl(EnumDecl *D) {
197   VisitTagDecl(D);
198   Writer.AddTypeSourceInfo(D->getIntegerTypeSourceInfo(), Record);
199   if (!D->getIntegerTypeSourceInfo())
200     Writer.AddTypeRef(D->getIntegerType(), Record);
201   Writer.AddTypeRef(D->getPromotionType(), Record);
202   Record.push_back(D->getNumPositiveBits());
203   Record.push_back(D->getNumNegativeBits());
204   Record.push_back(D->isScoped());
205   Record.push_back(D->isScopedUsingClassTag());
206   Record.push_back(D->isFixed());
207   Writer.AddDeclRef(D->getInstantiatedFromMemberEnum(), Record);
208   Code = serialization::DECL_ENUM;
209 }
210 
211 void ASTDeclWriter::VisitRecordDecl(RecordDecl *D) {
212   VisitTagDecl(D);
213   Record.push_back(D->hasFlexibleArrayMember());
214   Record.push_back(D->isAnonymousStructOrUnion());
215   Record.push_back(D->hasObjectMember());
216   Code = serialization::DECL_RECORD;
217 }
218 
219 void ASTDeclWriter::VisitValueDecl(ValueDecl *D) {
220   VisitNamedDecl(D);
221   Writer.AddTypeRef(D->getType(), Record);
222 }
223 
224 void ASTDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
225   VisitValueDecl(D);
226   Record.push_back(D->getInitExpr()? 1 : 0);
227   if (D->getInitExpr())
228     Writer.AddStmt(D->getInitExpr());
229   Writer.AddAPSInt(D->getInitVal(), Record);
230   Code = serialization::DECL_ENUM_CONSTANT;
231 }
232 
233 void ASTDeclWriter::VisitDeclaratorDecl(DeclaratorDecl *D) {
234   VisitValueDecl(D);
235   Writer.AddSourceLocation(D->getInnerLocStart(), Record);
236   Record.push_back(D->hasExtInfo());
237   if (D->hasExtInfo())
238     Writer.AddQualifierInfo(*D->getExtInfo(), Record);
239   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
240 }
241 
242 void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
243   VisitDeclaratorDecl(D);
244   VisitRedeclarable(D);
245 
246   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
247   Record.push_back(D->getIdentifierNamespace());
248   Record.push_back(D->getTemplatedKind());
249   switch (D->getTemplatedKind()) {
250   default: assert(false && "Unhandled TemplatedKind!");
251     break;
252   case FunctionDecl::TK_NonTemplate:
253     break;
254   case FunctionDecl::TK_FunctionTemplate:
255     Writer.AddDeclRef(D->getDescribedFunctionTemplate(), Record);
256     break;
257   case FunctionDecl::TK_MemberSpecialization: {
258     MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo();
259     Writer.AddDeclRef(MemberInfo->getInstantiatedFrom(), Record);
260     Record.push_back(MemberInfo->getTemplateSpecializationKind());
261     Writer.AddSourceLocation(MemberInfo->getPointOfInstantiation(), Record);
262     break;
263   }
264   case FunctionDecl::TK_FunctionTemplateSpecialization: {
265     FunctionTemplateSpecializationInfo *
266       FTSInfo = D->getTemplateSpecializationInfo();
267     Writer.AddDeclRef(FTSInfo->getTemplate(), Record);
268     Record.push_back(FTSInfo->getTemplateSpecializationKind());
269 
270     // Template arguments.
271     Writer.AddTemplateArgumentList(FTSInfo->TemplateArguments, Record);
272 
273     // Template args as written.
274     Record.push_back(FTSInfo->TemplateArgumentsAsWritten != 0);
275     if (FTSInfo->TemplateArgumentsAsWritten) {
276       Record.push_back(FTSInfo->TemplateArgumentsAsWritten->size());
277       for (int i=0, e = FTSInfo->TemplateArgumentsAsWritten->size(); i!=e; ++i)
278         Writer.AddTemplateArgumentLoc((*FTSInfo->TemplateArgumentsAsWritten)[i],
279                                       Record);
280       Writer.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->getLAngleLoc(),
281                                Record);
282       Writer.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->getRAngleLoc(),
283                                Record);
284     }
285 
286     Writer.AddSourceLocation(FTSInfo->getPointOfInstantiation(), Record);
287 
288     if (D->isCanonicalDecl()) {
289       // Write the template that contains the specializations set. We will
290       // add a FunctionTemplateSpecializationInfo to it when reading.
291       Writer.AddDeclRef(FTSInfo->getTemplate()->getCanonicalDecl(), Record);
292     }
293     break;
294   }
295   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
296     DependentFunctionTemplateSpecializationInfo *
297       DFTSInfo = D->getDependentSpecializationInfo();
298 
299     // Templates.
300     Record.push_back(DFTSInfo->getNumTemplates());
301     for (int i=0, e = DFTSInfo->getNumTemplates(); i != e; ++i)
302       Writer.AddDeclRef(DFTSInfo->getTemplate(i), Record);
303 
304     // Templates args.
305     Record.push_back(DFTSInfo->getNumTemplateArgs());
306     for (int i=0, e = DFTSInfo->getNumTemplateArgs(); i != e; ++i)
307       Writer.AddTemplateArgumentLoc(DFTSInfo->getTemplateArg(i), Record);
308     Writer.AddSourceLocation(DFTSInfo->getLAngleLoc(), Record);
309     Writer.AddSourceLocation(DFTSInfo->getRAngleLoc(), Record);
310     break;
311   }
312   }
313 
314   // FunctionDecl's body is handled last at ASTWriterDecl::Visit,
315   // after everything else is written.
316 
317   Record.push_back(D->getStorageClass()); // FIXME: stable encoding
318   Record.push_back(D->getStorageClassAsWritten());
319   Record.push_back(D->IsInline);
320   Record.push_back(D->isInlineSpecified());
321   Record.push_back(D->isVirtualAsWritten());
322   Record.push_back(D->isPure());
323   Record.push_back(D->hasInheritedPrototype());
324   Record.push_back(D->hasWrittenPrototype());
325   Record.push_back(D->isDeletedAsWritten());
326   Record.push_back(D->isTrivial());
327   Record.push_back(D->isDefaulted());
328   Record.push_back(D->isExplicitlyDefaulted());
329   Record.push_back(D->hasImplicitReturnZero());
330   Writer.AddSourceLocation(D->getLocEnd(), Record);
331 
332   Record.push_back(D->param_size());
333   for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
334        P != PEnd; ++P)
335     Writer.AddDeclRef(*P, Record);
336   Code = serialization::DECL_FUNCTION;
337 }
338 
339 void ASTDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
340   VisitNamedDecl(D);
341   // FIXME: convert to LazyStmtPtr?
342   // Unlike C/C++, method bodies will never be in header files.
343   bool HasBodyStuff = D->getBody() != 0     ||
344                       D->getSelfDecl() != 0 || D->getCmdDecl() != 0;
345   Record.push_back(HasBodyStuff);
346   if (HasBodyStuff) {
347     Writer.AddStmt(D->getBody());
348     Writer.AddDeclRef(D->getSelfDecl(), Record);
349     Writer.AddDeclRef(D->getCmdDecl(), Record);
350   }
351   Record.push_back(D->isInstanceMethod());
352   Record.push_back(D->isVariadic());
353   Record.push_back(D->isSynthesized());
354   Record.push_back(D->isDefined());
355   // FIXME: stable encoding for @required/@optional
356   Record.push_back(D->getImplementationControl());
357   // FIXME: stable encoding for in/out/inout/bycopy/byref/oneway
358   Record.push_back(D->getObjCDeclQualifier());
359   Record.push_back(D->getNumSelectorArgs());
360   Writer.AddTypeRef(D->getResultType(), Record);
361   Writer.AddTypeSourceInfo(D->getResultTypeSourceInfo(), Record);
362   Writer.AddSourceLocation(D->getLocEnd(), Record);
363   Record.push_back(D->param_size());
364   for (ObjCMethodDecl::param_iterator P = D->param_begin(),
365                                    PEnd = D->param_end(); P != PEnd; ++P)
366     Writer.AddDeclRef(*P, Record);
367   Code = serialization::DECL_OBJC_METHOD;
368 }
369 
370 void ASTDeclWriter::VisitObjCContainerDecl(ObjCContainerDecl *D) {
371   VisitNamedDecl(D);
372   Writer.AddSourceRange(D->getAtEndRange(), Record);
373   // Abstract class (no need to define a stable serialization::DECL code).
374 }
375 
376 void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
377   VisitObjCContainerDecl(D);
378   Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
379   Writer.AddDeclRef(D->getSuperClass(), Record);
380 
381   // Write out the protocols that are directly referenced by the @interface.
382   Record.push_back(D->ReferencedProtocols.size());
383   for (ObjCInterfaceDecl::protocol_iterator P = D->protocol_begin(),
384          PEnd = D->protocol_end();
385        P != PEnd; ++P)
386     Writer.AddDeclRef(*P, Record);
387   for (ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(),
388          PLEnd = D->protocol_loc_end();
389        PL != PLEnd; ++PL)
390     Writer.AddSourceLocation(*PL, Record);
391 
392   // Write out the protocols that are transitively referenced.
393   Record.push_back(D->AllReferencedProtocols.size());
394   for (ObjCList<ObjCProtocolDecl>::iterator
395         P = D->AllReferencedProtocols.begin(),
396         PEnd = D->AllReferencedProtocols.end();
397        P != PEnd; ++P)
398     Writer.AddDeclRef(*P, Record);
399 
400   // Write out the ivars.
401   Record.push_back(D->ivar_size());
402   for (ObjCInterfaceDecl::ivar_iterator I = D->ivar_begin(),
403                                      IEnd = D->ivar_end(); I != IEnd; ++I)
404     Writer.AddDeclRef(*I, Record);
405   Writer.AddDeclRef(D->getCategoryList(), Record);
406   Record.push_back(D->isForwardDecl());
407   Record.push_back(D->isImplicitInterfaceDecl());
408   Writer.AddSourceLocation(D->getClassLoc(), Record);
409   Writer.AddSourceLocation(D->getSuperClassLoc(), Record);
410   Writer.AddSourceLocation(D->getLocEnd(), Record);
411   Code = serialization::DECL_OBJC_INTERFACE;
412 }
413 
414 void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
415   VisitFieldDecl(D);
416   // FIXME: stable encoding for @public/@private/@protected/@package
417   Record.push_back(D->getAccessControl());
418   Record.push_back(D->getSynthesize());
419   Code = serialization::DECL_OBJC_IVAR;
420 }
421 
422 void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
423   VisitObjCContainerDecl(D);
424   Record.push_back(D->isForwardDecl());
425   Writer.AddSourceLocation(D->getLocEnd(), Record);
426   Record.push_back(D->protocol_size());
427   for (ObjCProtocolDecl::protocol_iterator
428        I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I)
429     Writer.AddDeclRef(*I, Record);
430   for (ObjCProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin(),
431          PLEnd = D->protocol_loc_end();
432        PL != PLEnd; ++PL)
433     Writer.AddSourceLocation(*PL, Record);
434   Code = serialization::DECL_OBJC_PROTOCOL;
435 }
436 
437 void ASTDeclWriter::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
438   VisitFieldDecl(D);
439   Code = serialization::DECL_OBJC_AT_DEFS_FIELD;
440 }
441 
442 void ASTDeclWriter::VisitObjCClassDecl(ObjCClassDecl *D) {
443   VisitDecl(D);
444   Record.push_back(D->size());
445   for (ObjCClassDecl::iterator I = D->begin(), IEnd = D->end(); I != IEnd; ++I)
446     Writer.AddDeclRef(I->getInterface(), Record);
447   for (ObjCClassDecl::iterator I = D->begin(), IEnd = D->end(); I != IEnd; ++I)
448     Writer.AddSourceLocation(I->getLocation(), Record);
449   Code = serialization::DECL_OBJC_CLASS;
450 }
451 
452 void ASTDeclWriter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
453   VisitDecl(D);
454   Record.push_back(D->protocol_size());
455   for (ObjCForwardProtocolDecl::protocol_iterator
456        I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I)
457     Writer.AddDeclRef(*I, Record);
458   for (ObjCForwardProtocolDecl::protocol_loc_iterator
459          PL = D->protocol_loc_begin(), PLEnd = D->protocol_loc_end();
460        PL != PLEnd; ++PL)
461     Writer.AddSourceLocation(*PL, Record);
462   Code = serialization::DECL_OBJC_FORWARD_PROTOCOL;
463 }
464 
465 void ASTDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
466   VisitObjCContainerDecl(D);
467   Writer.AddDeclRef(D->getClassInterface(), Record);
468   Record.push_back(D->protocol_size());
469   for (ObjCCategoryDecl::protocol_iterator
470        I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I)
471     Writer.AddDeclRef(*I, Record);
472   for (ObjCCategoryDecl::protocol_loc_iterator
473          PL = D->protocol_loc_begin(), PLEnd = D->protocol_loc_end();
474        PL != PLEnd; ++PL)
475     Writer.AddSourceLocation(*PL, Record);
476   Writer.AddDeclRef(D->getNextClassCategory(), Record);
477   Record.push_back(D->hasSynthBitfield());
478   Writer.AddSourceLocation(D->getAtLoc(), Record);
479   Writer.AddSourceLocation(D->getCategoryNameLoc(), Record);
480   Code = serialization::DECL_OBJC_CATEGORY;
481 }
482 
483 void ASTDeclWriter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D) {
484   VisitNamedDecl(D);
485   Writer.AddDeclRef(D->getClassInterface(), Record);
486   Code = serialization::DECL_OBJC_COMPATIBLE_ALIAS;
487 }
488 
489 void ASTDeclWriter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
490   VisitNamedDecl(D);
491   Writer.AddSourceLocation(D->getAtLoc(), Record);
492   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
493   // FIXME: stable encoding
494   Record.push_back((unsigned)D->getPropertyAttributes());
495   Record.push_back((unsigned)D->getPropertyAttributesAsWritten());
496   // FIXME: stable encoding
497   Record.push_back((unsigned)D->getPropertyImplementation());
498   Writer.AddDeclarationName(D->getGetterName(), Record);
499   Writer.AddDeclarationName(D->getSetterName(), Record);
500   Writer.AddDeclRef(D->getGetterMethodDecl(), Record);
501   Writer.AddDeclRef(D->getSetterMethodDecl(), Record);
502   Writer.AddDeclRef(D->getPropertyIvarDecl(), Record);
503   Code = serialization::DECL_OBJC_PROPERTY;
504 }
505 
506 void ASTDeclWriter::VisitObjCImplDecl(ObjCImplDecl *D) {
507   VisitObjCContainerDecl(D);
508   Writer.AddDeclRef(D->getClassInterface(), Record);
509   // Abstract class (no need to define a stable serialization::DECL code).
510 }
511 
512 void ASTDeclWriter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
513   VisitObjCImplDecl(D);
514   Writer.AddIdentifierRef(D->getIdentifier(), Record);
515   Code = serialization::DECL_OBJC_CATEGORY_IMPL;
516 }
517 
518 void ASTDeclWriter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
519   VisitObjCImplDecl(D);
520   Writer.AddDeclRef(D->getSuperClass(), Record);
521   Writer.AddCXXCtorInitializers(D->IvarInitializers, D->NumIvarInitializers,
522                                 Record);
523   Record.push_back(D->hasSynthBitfield());
524   Code = serialization::DECL_OBJC_IMPLEMENTATION;
525 }
526 
527 void ASTDeclWriter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
528   VisitDecl(D);
529   Writer.AddSourceLocation(D->getLocStart(), Record);
530   Writer.AddDeclRef(D->getPropertyDecl(), Record);
531   Writer.AddDeclRef(D->getPropertyIvarDecl(), Record);
532   Writer.AddSourceLocation(D->getPropertyIvarDeclLoc(), Record);
533   Writer.AddStmt(D->getGetterCXXConstructor());
534   Writer.AddStmt(D->getSetterCXXAssignment());
535   Code = serialization::DECL_OBJC_PROPERTY_IMPL;
536 }
537 
538 void ASTDeclWriter::VisitFieldDecl(FieldDecl *D) {
539   VisitDeclaratorDecl(D);
540   Record.push_back(D->isMutable());
541   Record.push_back(D->getBitWidth()? 1 : 0);
542   if (D->getBitWidth())
543     Writer.AddStmt(D->getBitWidth());
544   if (!D->getDeclName())
545     Writer.AddDeclRef(Context.getInstantiatedFromUnnamedFieldDecl(D), Record);
546   Code = serialization::DECL_FIELD;
547 }
548 
549 void ASTDeclWriter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
550   VisitValueDecl(D);
551   Record.push_back(D->getChainingSize());
552 
553   for (IndirectFieldDecl::chain_iterator
554        P = D->chain_begin(),
555        PEnd = D->chain_end(); P != PEnd; ++P)
556     Writer.AddDeclRef(*P, Record);
557   Code = serialization::DECL_INDIRECTFIELD;
558 }
559 
560 void ASTDeclWriter::VisitVarDecl(VarDecl *D) {
561   VisitDeclaratorDecl(D);
562   VisitRedeclarable(D);
563   Record.push_back(D->getStorageClass()); // FIXME: stable encoding
564   Record.push_back(D->getStorageClassAsWritten());
565   Record.push_back(D->isThreadSpecified());
566   Record.push_back(D->hasCXXDirectInitializer());
567   Record.push_back(D->isExceptionVariable());
568   Record.push_back(D->isNRVOVariable());
569   Record.push_back(D->isCXXForRangeDecl());
570   Record.push_back(D->getInit() ? 1 : 0);
571   if (D->getInit())
572     Writer.AddStmt(D->getInit());
573 
574   MemberSpecializationInfo *SpecInfo
575     = D->isStaticDataMember() ? D->getMemberSpecializationInfo() : 0;
576   Record.push_back(SpecInfo != 0);
577   if (SpecInfo) {
578     Writer.AddDeclRef(SpecInfo->getInstantiatedFrom(), Record);
579     Record.push_back(SpecInfo->getTemplateSpecializationKind());
580     Writer.AddSourceLocation(SpecInfo->getPointOfInstantiation(), Record);
581   }
582 
583   Code = serialization::DECL_VAR;
584 }
585 
586 void ASTDeclWriter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
587   VisitVarDecl(D);
588   Code = serialization::DECL_IMPLICIT_PARAM;
589 }
590 
591 void ASTDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
592   VisitVarDecl(D);
593   Record.push_back(D->isObjCMethodParameter());
594   Record.push_back(D->getFunctionScopeDepth());
595   Record.push_back(D->getFunctionScopeIndex());
596   Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
597   Record.push_back(D->isKNRPromoted());
598   Record.push_back(D->hasInheritedDefaultArg());
599   Record.push_back(D->hasUninstantiatedDefaultArg());
600   if (D->hasUninstantiatedDefaultArg())
601     Writer.AddStmt(D->getUninstantiatedDefaultArg());
602   Code = serialization::DECL_PARM_VAR;
603 
604   // If the assumptions about the DECL_PARM_VAR abbrev are true, use it.  Here
605   // we dynamically check for the properties that we optimize for, but don't
606   // know are true of all PARM_VAR_DECLs.
607   if (!D->getTypeSourceInfo() &&
608       !D->hasAttrs() &&
609       !D->isImplicit() &&
610       !D->isUsed(false) &&
611       D->getAccess() == AS_none &&
612       D->getPCHLevel() == 0 &&
613       D->getStorageClass() == 0 &&
614       !D->hasCXXDirectInitializer() && // Can params have this ever?
615       D->getFunctionScopeDepth() == 0 &&
616       D->getObjCDeclQualifier() == 0 &&
617       !D->isKNRPromoted() &&
618       !D->hasInheritedDefaultArg() &&
619       D->getInit() == 0 &&
620       !D->hasUninstantiatedDefaultArg())  // No default expr.
621     AbbrevToUse = Writer.getParmVarDeclAbbrev();
622 
623   // Check things we know are true of *every* PARM_VAR_DECL, which is more than
624   // just us assuming it.
625   assert(!D->isInvalidDecl() && "Shouldn't emit invalid decls");
626   assert(!D->isThreadSpecified() && "PARM_VAR_DECL can't be __thread");
627   assert(D->getAccess() == AS_none && "PARM_VAR_DECL can't be public/private");
628   assert(!D->isExceptionVariable() && "PARM_VAR_DECL can't be exception var");
629   assert(D->getPreviousDeclaration() == 0 && "PARM_VAR_DECL can't be redecl");
630   assert(!D->isStaticDataMember() &&
631          "PARM_VAR_DECL can't be static data member");
632 }
633 
634 void ASTDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
635   VisitDecl(D);
636   Writer.AddStmt(D->getAsmString());
637   Writer.AddSourceLocation(D->getRParenLoc(), Record);
638   Code = serialization::DECL_FILE_SCOPE_ASM;
639 }
640 
641 void ASTDeclWriter::VisitBlockDecl(BlockDecl *D) {
642   VisitDecl(D);
643   Writer.AddStmt(D->getBody());
644   Writer.AddTypeSourceInfo(D->getSignatureAsWritten(), Record);
645   Record.push_back(D->param_size());
646   for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
647        P != PEnd; ++P)
648     Writer.AddDeclRef(*P, Record);
649   Record.push_back(D->capturesCXXThis());
650   Record.push_back(D->getNumCaptures());
651   for (BlockDecl::capture_iterator
652          i = D->capture_begin(), e = D->capture_end(); i != e; ++i) {
653     const BlockDecl::Capture &capture = *i;
654     Writer.AddDeclRef(capture.getVariable(), Record);
655 
656     unsigned flags = 0;
657     if (capture.isByRef()) flags |= 1;
658     if (capture.isNested()) flags |= 2;
659     if (capture.hasCopyExpr()) flags |= 4;
660     Record.push_back(flags);
661 
662     if (capture.hasCopyExpr()) Writer.AddStmt(capture.getCopyExpr());
663   }
664 
665   Code = serialization::DECL_BLOCK;
666 }
667 
668 void ASTDeclWriter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
669   VisitDecl(D);
670   Record.push_back(D->getLanguage());
671   Writer.AddSourceLocation(D->getExternLoc(), Record);
672   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
673   Code = serialization::DECL_LINKAGE_SPEC;
674 }
675 
676 void ASTDeclWriter::VisitLabelDecl(LabelDecl *D) {
677   VisitNamedDecl(D);
678   Writer.AddSourceLocation(D->getLocStart(), Record);
679   Code = serialization::DECL_LABEL;
680 }
681 
682 
683 void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) {
684   VisitNamedDecl(D);
685   Record.push_back(D->isInline());
686   Writer.AddSourceLocation(D->getLocStart(), Record);
687   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
688   Writer.AddDeclRef(D->getNextNamespace(), Record);
689 
690   // Only write one reference--original or anonymous
691   Record.push_back(D->isOriginalNamespace());
692   if (D->isOriginalNamespace())
693     Writer.AddDeclRef(D->getAnonymousNamespace(), Record);
694   else
695     Writer.AddDeclRef(D->getOriginalNamespace(), Record);
696   Code = serialization::DECL_NAMESPACE;
697 
698   if (Writer.hasChain() && !D->isOriginalNamespace() &&
699       D->getOriginalNamespace()->getPCHLevel() > 0) {
700     NamespaceDecl *NS = D->getOriginalNamespace();
701     Writer.AddUpdatedDeclContext(NS);
702 
703     // Make sure all visible decls are written. They will be recorded later.
704     NS->lookup(DeclarationName());
705     StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(NS->getLookupPtr());
706     if (Map) {
707       for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
708            D != DEnd; ++D) {
709         DeclContext::lookup_result Result = D->second.getLookupResult();
710         while (Result.first != Result.second) {
711           Writer.GetDeclRef(*Result.first);
712           ++Result.first;
713         }
714       }
715     }
716   }
717 
718   if (Writer.hasChain() && D->isAnonymousNamespace() && !D->getNextNamespace()){
719     // This is a most recent reopening of the anonymous namespace. If its parent
720     // is in a previous PCH (or is the TU), mark that parent for update, because
721     // the original namespace always points to the latest re-opening of its
722     // anonymous namespace.
723     Decl *Parent = cast<Decl>(
724         D->getParent()->getRedeclContext()->getPrimaryContext());
725     if (Parent->getPCHLevel() > 0) {
726       ASTWriter::UpdateRecord &Record = Writer.DeclUpdates[Parent];
727       Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
728       Writer.AddDeclRef(D, Record);
729     }
730   }
731 }
732 
733 void ASTDeclWriter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
734   VisitNamedDecl(D);
735   Writer.AddSourceLocation(D->getNamespaceLoc(), Record);
736   Writer.AddSourceLocation(D->getTargetNameLoc(), Record);
737   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
738   Writer.AddDeclRef(D->getNamespace(), Record);
739   Code = serialization::DECL_NAMESPACE_ALIAS;
740 }
741 
742 void ASTDeclWriter::VisitUsingDecl(UsingDecl *D) {
743   VisitNamedDecl(D);
744   Writer.AddSourceLocation(D->getUsingLocation(), Record);
745   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
746   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
747   Writer.AddDeclRef(D->FirstUsingShadow, Record);
748   Record.push_back(D->isTypeName());
749   Writer.AddDeclRef(Context.getInstantiatedFromUsingDecl(D), Record);
750   Code = serialization::DECL_USING;
751 }
752 
753 void ASTDeclWriter::VisitUsingShadowDecl(UsingShadowDecl *D) {
754   VisitNamedDecl(D);
755   Writer.AddDeclRef(D->getTargetDecl(), Record);
756   Writer.AddDeclRef(D->UsingOrNextShadow, Record);
757   Writer.AddDeclRef(Context.getInstantiatedFromUsingShadowDecl(D), Record);
758   Code = serialization::DECL_USING_SHADOW;
759 }
760 
761 void ASTDeclWriter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
762   VisitNamedDecl(D);
763   Writer.AddSourceLocation(D->getUsingLoc(), Record);
764   Writer.AddSourceLocation(D->getNamespaceKeyLocation(), Record);
765   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
766   Writer.AddDeclRef(D->getNominatedNamespace(), Record);
767   Writer.AddDeclRef(dyn_cast<Decl>(D->getCommonAncestor()), Record);
768   Code = serialization::DECL_USING_DIRECTIVE;
769 }
770 
771 void ASTDeclWriter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
772   VisitValueDecl(D);
773   Writer.AddSourceLocation(D->getUsingLoc(), Record);
774   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
775   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
776   Code = serialization::DECL_UNRESOLVED_USING_VALUE;
777 }
778 
779 void ASTDeclWriter::VisitUnresolvedUsingTypenameDecl(
780                                                UnresolvedUsingTypenameDecl *D) {
781   VisitTypeDecl(D);
782   Writer.AddSourceLocation(D->getTypenameLoc(), Record);
783   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
784   Code = serialization::DECL_UNRESOLVED_USING_TYPENAME;
785 }
786 
787 void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
788   VisitRecordDecl(D);
789 
790   CXXRecordDecl *DefinitionDecl = 0;
791   if (D->DefinitionData)
792     DefinitionDecl = D->DefinitionData->Definition;
793   Writer.AddDeclRef(DefinitionDecl, Record);
794   if (D == DefinitionDecl)
795     Writer.AddCXXDefinitionData(D, Record);
796 
797   enum {
798     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
799   };
800   if (ClassTemplateDecl *TemplD = D->getDescribedClassTemplate()) {
801     Record.push_back(CXXRecTemplate);
802     Writer.AddDeclRef(TemplD, Record);
803   } else if (MemberSpecializationInfo *MSInfo
804                = D->getMemberSpecializationInfo()) {
805     Record.push_back(CXXRecMemberSpecialization);
806     Writer.AddDeclRef(MSInfo->getInstantiatedFrom(), Record);
807     Record.push_back(MSInfo->getTemplateSpecializationKind());
808     Writer.AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
809   } else {
810     Record.push_back(CXXRecNotTemplate);
811   }
812 
813   // Store the key function to avoid deserializing every method so we can
814   // compute it.
815   if (D->IsDefinition)
816     Writer.AddDeclRef(Context.getKeyFunction(D), Record);
817 
818   Code = serialization::DECL_CXX_RECORD;
819 }
820 
821 void ASTDeclWriter::VisitCXXMethodDecl(CXXMethodDecl *D) {
822   VisitFunctionDecl(D);
823   Record.push_back(D->size_overridden_methods());
824   for (CXXMethodDecl::method_iterator
825          I = D->begin_overridden_methods(), E = D->end_overridden_methods();
826          I != E; ++I)
827     Writer.AddDeclRef(*I, Record);
828   Code = serialization::DECL_CXX_METHOD;
829 }
830 
831 void ASTDeclWriter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
832   VisitCXXMethodDecl(D);
833 
834   Record.push_back(D->IsExplicitSpecified);
835   Record.push_back(D->ImplicitlyDefined);
836   Writer.AddCXXCtorInitializers(D->CtorInitializers, D->NumCtorInitializers,
837                                 Record);
838 
839   Code = serialization::DECL_CXX_CONSTRUCTOR;
840 }
841 
842 void ASTDeclWriter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
843   VisitCXXMethodDecl(D);
844 
845   Record.push_back(D->ImplicitlyDefined);
846   Writer.AddDeclRef(D->OperatorDelete, Record);
847 
848   Code = serialization::DECL_CXX_DESTRUCTOR;
849 }
850 
851 void ASTDeclWriter::VisitCXXConversionDecl(CXXConversionDecl *D) {
852   VisitCXXMethodDecl(D);
853   Record.push_back(D->IsExplicitSpecified);
854   Code = serialization::DECL_CXX_CONVERSION;
855 }
856 
857 void ASTDeclWriter::VisitAccessSpecDecl(AccessSpecDecl *D) {
858   VisitDecl(D);
859   Writer.AddSourceLocation(D->getColonLoc(), Record);
860   Code = serialization::DECL_ACCESS_SPEC;
861 }
862 
863 void ASTDeclWriter::VisitFriendDecl(FriendDecl *D) {
864   VisitDecl(D);
865   Record.push_back(D->Friend.is<TypeSourceInfo*>());
866   if (D->Friend.is<TypeSourceInfo*>())
867     Writer.AddTypeSourceInfo(D->Friend.get<TypeSourceInfo*>(), Record);
868   else
869     Writer.AddDeclRef(D->Friend.get<NamedDecl*>(), Record);
870   Writer.AddDeclRef(D->getNextFriend(), Record);
871   Record.push_back(D->UnsupportedFriend);
872   Writer.AddSourceLocation(D->FriendLoc, Record);
873   Code = serialization::DECL_FRIEND;
874 }
875 
876 void ASTDeclWriter::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
877   VisitDecl(D);
878   Record.push_back(D->getNumTemplateParameters());
879   for (unsigned i = 0, e = D->getNumTemplateParameters(); i != e; ++i)
880     Writer.AddTemplateParameterList(D->getTemplateParameterList(i), Record);
881   Record.push_back(D->getFriendDecl() != 0);
882   if (D->getFriendDecl())
883     Writer.AddDeclRef(D->getFriendDecl(), Record);
884   else
885     Writer.AddTypeSourceInfo(D->getFriendType(), Record);
886   Writer.AddSourceLocation(D->getFriendLoc(), Record);
887   Code = serialization::DECL_FRIEND_TEMPLATE;
888 }
889 
890 void ASTDeclWriter::VisitTemplateDecl(TemplateDecl *D) {
891   VisitNamedDecl(D);
892 
893   Writer.AddDeclRef(D->getTemplatedDecl(), Record);
894   Writer.AddTemplateParameterList(D->getTemplateParameters(), Record);
895 }
896 
897 void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
898   // Emit data to initialize CommonOrPrev before VisitTemplateDecl so that
899   // getCommonPtr() can be used while this is still initializing.
900 
901   Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
902   if (D->getPreviousDeclaration())
903     Writer.AddDeclRef(D->getFirstDeclaration(), Record);
904 
905   if (D->getPreviousDeclaration() == 0) {
906     // This TemplateDecl owns the CommonPtr; write it.
907     assert(D->isCanonicalDecl());
908 
909     Writer.AddDeclRef(D->getInstantiatedFromMemberTemplate(), Record);
910     if (D->getInstantiatedFromMemberTemplate())
911       Record.push_back(D->isMemberSpecialization());
912 
913     Writer.AddDeclRef(D->getCommonPtr()->Latest, Record);
914   } else {
915     RedeclarableTemplateDecl *First = D->getFirstDeclaration();
916     assert(First != D);
917     // If this is a most recent redeclaration that is pointed to by a first decl
918     // in a chained PCH, keep track of the association with the map so we can
919     // update the first decl during AST reading.
920     if (First->getMostRecentDeclaration() == D &&
921         First->getPCHLevel() > D->getPCHLevel()) {
922       assert(Writer.FirstLatestDecls.find(First)==Writer.FirstLatestDecls.end()
923              && "The latest is already set");
924       Writer.FirstLatestDecls[First] = D;
925     }
926   }
927 
928   VisitTemplateDecl(D);
929   Record.push_back(D->getIdentifierNamespace());
930 }
931 
932 void ASTDeclWriter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
933   VisitRedeclarableTemplateDecl(D);
934 
935   if (D->getPreviousDeclaration() == 0) {
936     typedef llvm::FoldingSet<ClassTemplateSpecializationDecl> CTSDSetTy;
937     CTSDSetTy &CTSDSet = D->getSpecializations();
938     Record.push_back(CTSDSet.size());
939     for (CTSDSetTy::iterator I=CTSDSet.begin(), E = CTSDSet.end(); I!=E; ++I) {
940       assert(I->isCanonicalDecl() && "Expected only canonical decls in set");
941       Writer.AddDeclRef(&*I, Record);
942     }
943 
944     typedef llvm::FoldingSet<ClassTemplatePartialSpecializationDecl> CTPSDSetTy;
945     CTPSDSetTy &CTPSDSet = D->getPartialSpecializations();
946     Record.push_back(CTPSDSet.size());
947     for (CTPSDSetTy::iterator I=CTPSDSet.begin(), E=CTPSDSet.end(); I!=E; ++I) {
948       assert(I->isCanonicalDecl() && "Expected only canonical decls in set");
949       Writer.AddDeclRef(&*I, Record);
950     }
951 
952     // InjectedClassNameType is computed, no need to write it.
953   }
954   Code = serialization::DECL_CLASS_TEMPLATE;
955 }
956 
957 void ASTDeclWriter::VisitClassTemplateSpecializationDecl(
958                                            ClassTemplateSpecializationDecl *D) {
959   VisitCXXRecordDecl(D);
960 
961   llvm::PointerUnion<ClassTemplateDecl *,
962                      ClassTemplatePartialSpecializationDecl *> InstFrom
963     = D->getSpecializedTemplateOrPartial();
964   Decl *InstFromD;
965   if (InstFrom.is<ClassTemplateDecl *>()) {
966     InstFromD = InstFrom.get<ClassTemplateDecl *>();
967     Writer.AddDeclRef(InstFromD, Record);
968   } else {
969     InstFromD = InstFrom.get<ClassTemplatePartialSpecializationDecl *>();
970     Writer.AddDeclRef(InstFromD, Record);
971     Writer.AddTemplateArgumentList(&D->getTemplateInstantiationArgs(), Record);
972     InstFromD = cast<ClassTemplatePartialSpecializationDecl>(InstFromD)->
973                     getSpecializedTemplate();
974   }
975 
976   // Explicit info.
977   Writer.AddTypeSourceInfo(D->getTypeAsWritten(), Record);
978   if (D->getTypeAsWritten()) {
979     Writer.AddSourceLocation(D->getExternLoc(), Record);
980     Writer.AddSourceLocation(D->getTemplateKeywordLoc(), Record);
981   }
982 
983   Writer.AddTemplateArgumentList(&D->getTemplateArgs(), Record);
984   Writer.AddSourceLocation(D->getPointOfInstantiation(), Record);
985   Record.push_back(D->getSpecializationKind());
986 
987   if (D->isCanonicalDecl()) {
988     // When reading, we'll add it to the folding set of the following template.
989     Writer.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl(), Record);
990   }
991 
992   Code = serialization::DECL_CLASS_TEMPLATE_SPECIALIZATION;
993 }
994 
995 void ASTDeclWriter::VisitClassTemplatePartialSpecializationDecl(
996                                     ClassTemplatePartialSpecializationDecl *D) {
997   VisitClassTemplateSpecializationDecl(D);
998 
999   Writer.AddTemplateParameterList(D->getTemplateParameters(), Record);
1000 
1001   Record.push_back(D->getNumTemplateArgsAsWritten());
1002   for (int i = 0, e = D->getNumTemplateArgsAsWritten(); i != e; ++i)
1003     Writer.AddTemplateArgumentLoc(D->getTemplateArgsAsWritten()[i], Record);
1004 
1005   Record.push_back(D->getSequenceNumber());
1006 
1007   // These are read/set from/to the first declaration.
1008   if (D->getPreviousDeclaration() == 0) {
1009     Writer.AddDeclRef(D->getInstantiatedFromMember(), Record);
1010     Record.push_back(D->isMemberSpecialization());
1011   }
1012 
1013   Code = serialization::DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION;
1014 }
1015 
1016 void ASTDeclWriter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1017   VisitRedeclarableTemplateDecl(D);
1018 
1019   if (D->getPreviousDeclaration() == 0) {
1020     // This FunctionTemplateDecl owns the CommonPtr; write it.
1021 
1022     // Write the function specialization declarations.
1023     Record.push_back(D->getSpecializations().size());
1024     for (llvm::FoldingSet<FunctionTemplateSpecializationInfo>::iterator
1025            I = D->getSpecializations().begin(),
1026            E = D->getSpecializations().end()   ; I != E; ++I) {
1027       assert(I->Function->isCanonicalDecl() &&
1028              "Expected only canonical decls in set");
1029       Writer.AddDeclRef(I->Function, Record);
1030     }
1031   }
1032   Code = serialization::DECL_FUNCTION_TEMPLATE;
1033 }
1034 
1035 void ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1036   VisitTypeDecl(D);
1037 
1038   Record.push_back(D->wasDeclaredWithTypename());
1039   Record.push_back(D->defaultArgumentWasInherited());
1040   Writer.AddTypeSourceInfo(D->getDefaultArgumentInfo(), Record);
1041 
1042   Code = serialization::DECL_TEMPLATE_TYPE_PARM;
1043 }
1044 
1045 void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1046   // For an expanded parameter pack, record the number of expansion types here
1047   // so that it's easier for
1048   if (D->isExpandedParameterPack())
1049     Record.push_back(D->getNumExpansionTypes());
1050 
1051   VisitDeclaratorDecl(D);
1052   // TemplateParmPosition.
1053   Record.push_back(D->getDepth());
1054   Record.push_back(D->getPosition());
1055 
1056   if (D->isExpandedParameterPack()) {
1057     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1058       Writer.AddTypeRef(D->getExpansionType(I), Record);
1059       Writer.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I), Record);
1060     }
1061 
1062     Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK;
1063   } else {
1064     // Rest of NonTypeTemplateParmDecl.
1065     Record.push_back(D->isParameterPack());
1066     Record.push_back(D->getDefaultArgument() != 0);
1067     if (D->getDefaultArgument()) {
1068       Writer.AddStmt(D->getDefaultArgument());
1069       Record.push_back(D->defaultArgumentWasInherited());
1070     }
1071     Code = serialization::DECL_NON_TYPE_TEMPLATE_PARM;
1072   }
1073 }
1074 
1075 void ASTDeclWriter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1076   VisitTemplateDecl(D);
1077   // TemplateParmPosition.
1078   Record.push_back(D->getDepth());
1079   Record.push_back(D->getPosition());
1080   // Rest of TemplateTemplateParmDecl.
1081   Writer.AddTemplateArgumentLoc(D->getDefaultArgument(), Record);
1082   Record.push_back(D->defaultArgumentWasInherited());
1083   Record.push_back(D->isParameterPack());
1084   Code = serialization::DECL_TEMPLATE_TEMPLATE_PARM;
1085 }
1086 
1087 void ASTDeclWriter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1088   VisitRedeclarableTemplateDecl(D);
1089   Code = serialization::DECL_TYPE_ALIAS_TEMPLATE;
1090 }
1091 
1092 void ASTDeclWriter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1093   VisitDecl(D);
1094   Writer.AddStmt(D->getAssertExpr());
1095   Writer.AddStmt(D->getMessage());
1096   Writer.AddSourceLocation(D->getRParenLoc(), Record);
1097   Code = serialization::DECL_STATIC_ASSERT;
1098 }
1099 
1100 /// \brief Emit the DeclContext part of a declaration context decl.
1101 ///
1102 /// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
1103 /// block for this declaration context is stored. May be 0 to indicate
1104 /// that there are no declarations stored within this context.
1105 ///
1106 /// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
1107 /// block for this declaration context is stored. May be 0 to indicate
1108 /// that there are no declarations visible from this context. Note
1109 /// that this value will not be emitted for non-primary declaration
1110 /// contexts.
1111 void ASTDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
1112                                      uint64_t VisibleOffset) {
1113   Record.push_back(LexicalOffset);
1114   Record.push_back(VisibleOffset);
1115 }
1116 
1117 template <typename T>
1118 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
1119   enum { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1120   if (D->RedeclLink.getNext() == D) {
1121     Record.push_back(NoRedeclaration);
1122   } else {
1123     if (D->RedeclLink.NextIsPrevious()) {
1124       Record.push_back(PointsToPrevious);
1125       Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
1126       Writer.AddDeclRef(D->getFirstDeclaration(), Record);
1127     } else {
1128       Record.push_back(PointsToLatest);
1129       Writer.AddDeclRef(D->RedeclLink.getPointer(), Record);
1130     }
1131   }
1132 
1133   T *First = D->getFirstDeclaration();
1134   T *ThisDecl = static_cast<T*>(D);
1135   // If this is a most recent redeclaration that is pointed to by a first decl
1136   // in a chained PCH, keep track of the association with the map so we can
1137   // update the first decl during AST reading.
1138   if (ThisDecl != First && First->getMostRecentDeclaration() == ThisDecl &&
1139       First->getPCHLevel() > ThisDecl->getPCHLevel()) {
1140     assert(Writer.FirstLatestDecls.find(First) == Writer.FirstLatestDecls.end()
1141            && "The latest is already set");
1142     Writer.FirstLatestDecls[First] = ThisDecl;
1143   }
1144 }
1145 
1146 //===----------------------------------------------------------------------===//
1147 // ASTWriter Implementation
1148 //===----------------------------------------------------------------------===//
1149 
1150 void ASTWriter::WriteDeclsBlockAbbrevs() {
1151   using namespace llvm;
1152   // Abbreviation for DECL_PARM_VAR.
1153   BitCodeAbbrev *Abv = new BitCodeAbbrev();
1154   Abv->Add(BitCodeAbbrevOp(serialization::DECL_PARM_VAR));
1155 
1156   // Decl
1157   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1158   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
1159   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
1160   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
1161   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1162   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1163   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1164   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1165   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifier
1166   Abv->Add(BitCodeAbbrevOp(0));                       // PCH level
1167 
1168   // NamedDecl
1169   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1170   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1171   // ValueDecl
1172   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
1173   // DeclaratorDecl
1174   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
1175   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
1176   Abv->Add(BitCodeAbbrevOp(serialization::PREDEF_TYPE_NULL_ID)); // InfoType
1177   // VarDecl
1178   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1179   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClass
1180   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClassAsWritten
1181   Abv->Add(BitCodeAbbrevOp(0));                       // isThreadSpecified
1182   Abv->Add(BitCodeAbbrevOp(0));                       // hasCXXDirectInitializer
1183   Abv->Add(BitCodeAbbrevOp(0));                       // isExceptionVariable
1184   Abv->Add(BitCodeAbbrevOp(0));                       // isNRVOVariable
1185   Abv->Add(BitCodeAbbrevOp(0));                       // isCXXForRangeDecl
1186   Abv->Add(BitCodeAbbrevOp(0));                       // HasInit
1187   Abv->Add(BitCodeAbbrevOp(0));                   // HasMemberSpecializationInfo
1188   // ParmVarDecl
1189   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsObjCMethodParameter
1190   Abv->Add(BitCodeAbbrevOp(0));                       // ScopeDepth
1191   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ScopeIndex
1192   Abv->Add(BitCodeAbbrevOp(0));                       // ObjCDeclQualifier
1193   Abv->Add(BitCodeAbbrevOp(0));                       // KNRPromoted
1194   Abv->Add(BitCodeAbbrevOp(0));                       // HasInheritedDefaultArg
1195   Abv->Add(BitCodeAbbrevOp(0));                   // HasUninstantiatedDefaultArg
1196 
1197   ParmVarDeclAbbrev = Stream.EmitAbbrev(Abv);
1198 
1199   Abv = new BitCodeAbbrev();
1200   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_LEXICAL));
1201   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1202   DeclContextLexicalAbbrev = Stream.EmitAbbrev(Abv);
1203 
1204   Abv = new BitCodeAbbrev();
1205   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_VISIBLE));
1206   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1207   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1208   DeclContextVisibleLookupAbbrev = Stream.EmitAbbrev(Abv);
1209 }
1210 
1211 /// isRequiredDecl - Check if this is a "required" Decl, which must be seen by
1212 /// consumers of the AST.
1213 ///
1214 /// Such decls will always be deserialized from the AST file, so we would like
1215 /// this to be as restrictive as possible. Currently the predicate is driven by
1216 /// code generation requirements, if other clients have a different notion of
1217 /// what is "required" then we may have to consider an alternate scheme where
1218 /// clients can iterate over the top-level decls and get information on them,
1219 /// without necessary deserializing them. We could explicitly require such
1220 /// clients to use a separate API call to "realize" the decl. This should be
1221 /// relatively painless since they would presumably only do it for top-level
1222 /// decls.
1223 static bool isRequiredDecl(const Decl *D, ASTContext &Context) {
1224   // File scoped assembly or obj-c implementation must be seen.
1225   if (isa<FileScopeAsmDecl>(D) || isa<ObjCImplementationDecl>(D))
1226     return true;
1227 
1228   return Context.DeclMustBeEmitted(D);
1229 }
1230 
1231 void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) {
1232   // Switch case IDs are per Decl.
1233   ClearSwitchCaseIDs();
1234 
1235   RecordData Record;
1236   ASTDeclWriter W(*this, Context, Record);
1237 
1238   // If this declaration is also a DeclContext, write blocks for the
1239   // declarations that lexically stored inside its context and those
1240   // declarations that are visible from its context. These blocks
1241   // are written before the declaration itself so that we can put
1242   // their offsets into the record for the declaration.
1243   uint64_t LexicalOffset = 0;
1244   uint64_t VisibleOffset = 0;
1245   DeclContext *DC = dyn_cast<DeclContext>(D);
1246   if (DC) {
1247     LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
1248     VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
1249   }
1250 
1251   // Determine the ID for this declaration
1252   serialization::DeclID &IDR = DeclIDs[D];
1253   if (IDR == 0)
1254     IDR = NextDeclID++;
1255   serialization::DeclID ID = IDR;
1256 
1257   if (ID < FirstDeclID) {
1258     // We're replacing a decl in a previous file.
1259     ReplacedDecls.push_back(std::make_pair(ID, Stream.GetCurrentBitNo()));
1260   } else {
1261     unsigned Index = ID - FirstDeclID;
1262 
1263     // Record the offset for this declaration
1264     if (DeclOffsets.size() == Index)
1265       DeclOffsets.push_back(Stream.GetCurrentBitNo());
1266     else if (DeclOffsets.size() < Index) {
1267       DeclOffsets.resize(Index+1);
1268       DeclOffsets[Index] = Stream.GetCurrentBitNo();
1269     }
1270   }
1271 
1272   // Build and emit a record for this declaration
1273   Record.clear();
1274   W.Code = (serialization::DeclCode)0;
1275   W.AbbrevToUse = 0;
1276   W.Visit(D);
1277   if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
1278 
1279   if (!W.Code)
1280     llvm::report_fatal_error(llvm::StringRef("unexpected declaration kind '") +
1281                             D->getDeclKindName() + "'");
1282   Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
1283 
1284   // Flush any expressions that were written as part of this declaration.
1285   FlushStmts();
1286 
1287   // Flush C++ base specifiers, if there are any.
1288   FlushCXXBaseSpecifiers();
1289 
1290   // Note "external" declarations so that we can add them to a record in the
1291   // AST file later.
1292   //
1293   // FIXME: This should be renamed, the predicate is much more complicated.
1294   if (isRequiredDecl(D, Context))
1295     ExternalDefinitions.push_back(ID);
1296 }
1297