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