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