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