ASTReaderDecl.cpp revision c0534b6cdc414aa86ef7e9ab37f7a81a79140f02
1//===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
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 the ASTReader::ReadDeclRecord method, which is the
11// entrypoint for loading a decl.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ASTCommon.h"
16#include "clang/Serialization/ASTReader.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclVisitor.h"
20#include "clang/AST/DeclGroup.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/Expr.h"
24using namespace clang;
25using namespace clang::serialization;
26
27//===----------------------------------------------------------------------===//
28// Declaration deserialization
29//===----------------------------------------------------------------------===//
30
31namespace clang {
32  class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
33    ASTReader &Reader;
34    ASTReader::PerFileData &F;
35    llvm::BitstreamCursor &Cursor;
36    const DeclID ThisDeclID;
37    typedef ASTReader::RecordData RecordData;
38    const RecordData &Record;
39    unsigned &Idx;
40    TypeID TypeIDForTypeDecl;
41
42    uint64_t GetCurrentCursorOffset();
43    SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
44      return Reader.ReadSourceLocation(F, R, I);
45    }
46    SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
47      return Reader.ReadSourceRange(F, R, I);
48    }
49    TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
50      return Reader.GetTypeSourceInfo(F, R, I);
51    }
52    void ReadQualifierInfo(QualifierInfo &Info,
53                           const RecordData &R, unsigned &I) {
54      Reader.ReadQualifierInfo(F, Info, R, I);
55    }
56    void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
57                                const RecordData &R, unsigned &I) {
58      Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
59    }
60    void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
61                                const RecordData &R, unsigned &I) {
62      Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
63    }
64
65    void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
66                               const RecordData &R, unsigned &I);
67
68    void InitializeCXXDefinitionData(CXXRecordDecl *D,
69                                     CXXRecordDecl *DefinitionDecl,
70                                     const RecordData &Record, unsigned &Idx);
71  public:
72    ASTDeclReader(ASTReader &Reader, ASTReader::PerFileData &F,
73                  llvm::BitstreamCursor &Cursor, DeclID thisDeclID,
74                  const RecordData &Record, unsigned &Idx)
75      : Reader(Reader), F(F), Cursor(Cursor), ThisDeclID(thisDeclID),
76        Record(Record), Idx(Idx), TypeIDForTypeDecl(0) { }
77
78    void Visit(Decl *D);
79
80    void UpdateDecl(Decl *D, const RecordData &Record);
81
82    void VisitDecl(Decl *D);
83    void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
84    void VisitNamedDecl(NamedDecl *ND);
85    void VisitNamespaceDecl(NamespaceDecl *D);
86    void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
87    void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
88    void VisitTypeDecl(TypeDecl *TD);
89    void VisitTypedefDecl(TypedefDecl *TD);
90    void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
91    void VisitTagDecl(TagDecl *TD);
92    void VisitEnumDecl(EnumDecl *ED);
93    void VisitRecordDecl(RecordDecl *RD);
94    void VisitCXXRecordDecl(CXXRecordDecl *D);
95    void VisitClassTemplateSpecializationDecl(
96                                            ClassTemplateSpecializationDecl *D);
97    void VisitClassTemplatePartialSpecializationDecl(
98                                     ClassTemplatePartialSpecializationDecl *D);
99    void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
100    void VisitValueDecl(ValueDecl *VD);
101    void VisitEnumConstantDecl(EnumConstantDecl *ECD);
102    void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
103    void VisitDeclaratorDecl(DeclaratorDecl *DD);
104    void VisitFunctionDecl(FunctionDecl *FD);
105    void VisitCXXMethodDecl(CXXMethodDecl *D);
106    void VisitCXXConstructorDecl(CXXConstructorDecl *D);
107    void VisitCXXDestructorDecl(CXXDestructorDecl *D);
108    void VisitCXXConversionDecl(CXXConversionDecl *D);
109    void VisitFieldDecl(FieldDecl *FD);
110    void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
111    void VisitVarDecl(VarDecl *VD);
112    void VisitImplicitParamDecl(ImplicitParamDecl *PD);
113    void VisitParmVarDecl(ParmVarDecl *PD);
114    void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
115    void VisitTemplateDecl(TemplateDecl *D);
116    void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
117    void VisitClassTemplateDecl(ClassTemplateDecl *D);
118    void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
119    void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
120    void VisitUsingDecl(UsingDecl *D);
121    void VisitUsingShadowDecl(UsingShadowDecl *D);
122    void VisitLinkageSpecDecl(LinkageSpecDecl *D);
123    void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
124    void VisitAccessSpecDecl(AccessSpecDecl *D);
125    void VisitFriendDecl(FriendDecl *D);
126    void VisitFriendTemplateDecl(FriendTemplateDecl *D);
127    void VisitStaticAssertDecl(StaticAssertDecl *D);
128    void VisitBlockDecl(BlockDecl *BD);
129
130    std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
131    template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
132
133    // FIXME: Reorder according to DeclNodes.td?
134    void VisitObjCMethodDecl(ObjCMethodDecl *D);
135    void VisitObjCContainerDecl(ObjCContainerDecl *D);
136    void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
137    void VisitObjCIvarDecl(ObjCIvarDecl *D);
138    void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
139    void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
140    void VisitObjCClassDecl(ObjCClassDecl *D);
141    void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
142    void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
143    void VisitObjCImplDecl(ObjCImplDecl *D);
144    void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
145    void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
146    void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
147    void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
148    void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
149  };
150}
151
152uint64_t ASTDeclReader::GetCurrentCursorOffset() {
153  uint64_t Off = 0;
154  for (unsigned I = 0, N = Reader.Chain.size(); I != N; ++I) {
155    ASTReader::PerFileData &F = *Reader.Chain[N - I - 1];
156    if (&Cursor == &F.DeclsCursor) {
157      Off += F.DeclsCursor.GetCurrentBitNo();
158      break;
159    }
160    Off += F.SizeInBits;
161  }
162  return Off;
163}
164
165void ASTDeclReader::Visit(Decl *D) {
166  DeclVisitor<ASTDeclReader, void>::Visit(D);
167
168  if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
169    // if we have a fully initialized TypeDecl, we can safely read its type now.
170    TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
171  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
172    // FunctionDecl's body was written last after all other Stmts/Exprs.
173    if (Record[Idx++])
174      FD->setLazyBody(GetCurrentCursorOffset());
175  }
176}
177
178void ASTDeclReader::VisitDecl(Decl *D) {
179  D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
180  D->setLexicalDeclContext(
181                     cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
182  D->setLocation(ReadSourceLocation(Record, Idx));
183  D->setInvalidDecl(Record[Idx++]);
184  if (Record[Idx++]) { // hasAttrs
185    AttrVec Attrs;
186    Reader.ReadAttributes(F, Attrs, Record, Idx);
187    D->setAttrs(Attrs);
188  }
189  D->setImplicit(Record[Idx++]);
190  D->setUsed(Record[Idx++]);
191  D->setAccess((AccessSpecifier)Record[Idx++]);
192  D->setPCHLevel(Record[Idx++] + (F.Type <= ASTReader::PCH));
193}
194
195void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
196  VisitDecl(TU);
197  TU->setAnonymousNamespace(
198                    cast_or_null<NamespaceDecl>(Reader.GetDecl(Record[Idx++])));
199}
200
201void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
202  VisitDecl(ND);
203  ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
204}
205
206void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
207  VisitNamedDecl(TD);
208  // Delay type reading until after we have fully initialized the decl.
209  TypeIDForTypeDecl = Record[Idx++];
210}
211
212void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
213  VisitTypeDecl(TD);
214  TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
215}
216
217void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
218  VisitTypeDecl(TD);
219  VisitRedeclarable(TD);
220  TD->IdentifierNamespace = Record[Idx++];
221  TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
222  TD->setDefinition(Record[Idx++]);
223  TD->setEmbeddedInDeclarator(Record[Idx++]);
224  TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
225  TD->setTagKeywordLoc(ReadSourceLocation(Record, Idx));
226  if (Record[Idx++]) { // hasExtInfo
227    TagDecl::ExtInfo *Info = new (*Reader.getContext()) TagDecl::ExtInfo();
228    ReadQualifierInfo(*Info, Record, Idx);
229    TD->TypedefDeclOrQualifier = Info;
230  } else
231    TD->setTypedefForAnonDecl(
232                      cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
233}
234
235void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
236  VisitTagDecl(ED);
237  if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
238    ED->setIntegerTypeSourceInfo(TI);
239  else
240    ED->setIntegerType(Reader.GetType(Record[Idx++]));
241  ED->setPromotionType(Reader.GetType(Record[Idx++]));
242  ED->setNumPositiveBits(Record[Idx++]);
243  ED->setNumNegativeBits(Record[Idx++]);
244  ED->IsScoped = Record[Idx++];
245  ED->IsScopedUsingClassTag = Record[Idx++];
246  ED->IsFixed = Record[Idx++];
247  ED->setInstantiationOfMemberEnum(
248                         cast_or_null<EnumDecl>(Reader.GetDecl(Record[Idx++])));
249}
250
251void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
252  VisitTagDecl(RD);
253  RD->setHasFlexibleArrayMember(Record[Idx++]);
254  RD->setAnonymousStructOrUnion(Record[Idx++]);
255  RD->setHasObjectMember(Record[Idx++]);
256}
257
258void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
259  VisitNamedDecl(VD);
260  VD->setType(Reader.GetType(Record[Idx++]));
261}
262
263void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
264  VisitValueDecl(ECD);
265  if (Record[Idx++])
266    ECD->setInitExpr(Reader.ReadExpr(F));
267  ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
268}
269
270void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
271  VisitValueDecl(DD);
272  if (Record[Idx++]) { // hasExtInfo
273    DeclaratorDecl::ExtInfo *Info
274        = new (*Reader.getContext()) DeclaratorDecl::ExtInfo();
275    ReadQualifierInfo(*Info, Record, Idx);
276    Info->TInfo = GetTypeSourceInfo(Record, Idx);
277    DD->DeclInfo = Info;
278  } else
279    DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
280}
281
282void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
283  VisitDeclaratorDecl(FD);
284  VisitRedeclarable(FD);
285
286  ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
287  FD->IdentifierNamespace = Record[Idx++];
288  switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
289  default: assert(false && "Unhandled TemplatedKind!");
290    break;
291  case FunctionDecl::TK_NonTemplate:
292    break;
293  case FunctionDecl::TK_FunctionTemplate:
294    FD->setDescribedFunctionTemplate(
295                     cast<FunctionTemplateDecl>(Reader.GetDecl(Record[Idx++])));
296    break;
297  case FunctionDecl::TK_MemberSpecialization: {
298    FunctionDecl *InstFD = cast<FunctionDecl>(Reader.GetDecl(Record[Idx++]));
299    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
300    SourceLocation POI = ReadSourceLocation(Record, Idx);
301    FD->setInstantiationOfMemberFunction(*Reader.getContext(), InstFD, TSK);
302    FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
303    break;
304  }
305  case FunctionDecl::TK_FunctionTemplateSpecialization: {
306    FunctionTemplateDecl *Template
307      = cast<FunctionTemplateDecl>(Reader.GetDecl(Record[Idx++]));
308    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
309
310    // Template arguments.
311    llvm::SmallVector<TemplateArgument, 8> TemplArgs;
312    Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
313
314    // Template args as written.
315    llvm::SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
316    SourceLocation LAngleLoc, RAngleLoc;
317    if (Record[Idx++]) {  // TemplateArgumentsAsWritten != 0
318      unsigned NumTemplateArgLocs = Record[Idx++];
319      TemplArgLocs.reserve(NumTemplateArgLocs);
320      for (unsigned i=0; i != NumTemplateArgLocs; ++i)
321        TemplArgLocs.push_back(
322            Reader.ReadTemplateArgumentLoc(F, Record, Idx));
323
324      LAngleLoc = ReadSourceLocation(Record, Idx);
325      RAngleLoc = ReadSourceLocation(Record, Idx);
326    }
327
328    SourceLocation POI = ReadSourceLocation(Record, Idx);
329
330    ASTContext &C = *Reader.getContext();
331    TemplateArgumentList *TemplArgList
332      = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
333    TemplateArgumentListInfo *TemplArgsInfo
334      = new (C) TemplateArgumentListInfo(LAngleLoc, RAngleLoc);
335    for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
336      TemplArgsInfo->addArgument(TemplArgLocs[i]);
337    FunctionTemplateSpecializationInfo *FTInfo
338        = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
339                                                     TemplArgList,
340                                                     TemplArgsInfo, POI);
341    FD->TemplateOrSpecialization = FTInfo;
342
343    if (FD->isCanonicalDecl()) { // if canonical add to template's set.
344      // The template that contains the specializations set. It's not safe to
345      // use getCanonicalDecl on Template since it may still be initializing.
346      FunctionTemplateDecl *CanonTemplate
347        = cast<FunctionTemplateDecl>(Reader.GetDecl(Record[Idx++]));
348      // Get the InsertPos by FindNodeOrInsertPos() instead of calling
349      // InsertNode(FTInfo) directly to avoid the getASTContext() call in
350      // FunctionTemplateSpecializationInfo's Profile().
351      // We avoid getASTContext because a decl in the parent hierarchy may
352      // be initializing.
353      llvm::FoldingSetNodeID ID;
354      FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
355                                                  TemplArgs.size(), C);
356      void *InsertPos = 0;
357      CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
358      assert(InsertPos && "Another specialization already inserted!");
359      CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
360    }
361    break;
362  }
363  case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
364    // Templates.
365    UnresolvedSet<8> TemplDecls;
366    unsigned NumTemplates = Record[Idx++];
367    while (NumTemplates--)
368      TemplDecls.addDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
369
370    // Templates args.
371    TemplateArgumentListInfo TemplArgs;
372    unsigned NumArgs = Record[Idx++];
373    while (NumArgs--)
374      TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
375    TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
376    TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
377
378    FD->setDependentTemplateSpecialization(*Reader.getContext(),
379                                           TemplDecls, TemplArgs);
380    break;
381  }
382  }
383
384  // FunctionDecl's body is handled last at ASTDeclReader::Visit,
385  // after everything else is read.
386
387  FD->SClass = (StorageClass)Record[Idx++];
388  FD->SClassAsWritten = (StorageClass)Record[Idx++];
389  FD->IsInline = Record[Idx++];
390  FD->IsInlineSpecified = Record[Idx++];
391  FD->IsVirtualAsWritten = Record[Idx++];
392  FD->IsPure = Record[Idx++];
393  FD->HasInheritedPrototype = Record[Idx++];
394  FD->HasWrittenPrototype = Record[Idx++];
395  FD->IsDeleted = Record[Idx++];
396  FD->IsTrivial = Record[Idx++];
397  FD->HasImplicitReturnZero = Record[Idx++];
398  FD->IsMarkedOverride = Record[Idx++];
399  FD->IsMarkedFinal = Record[Idx++];
400
401  FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
402
403  // Read in the parameters.
404  unsigned NumParams = Record[Idx++];
405  llvm::SmallVector<ParmVarDecl *, 16> Params;
406  Params.reserve(NumParams);
407  for (unsigned I = 0; I != NumParams; ++I)
408    Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
409  FD->setParams(*Reader.getContext(), Params.data(), NumParams);
410}
411
412void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
413  VisitNamedDecl(MD);
414  if (Record[Idx++]) {
415    // In practice, this won't be executed (since method definitions
416    // don't occur in header files).
417    MD->setBody(Reader.ReadStmt(F));
418    MD->setSelfDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
419    MD->setCmdDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
420  }
421  MD->setInstanceMethod(Record[Idx++]);
422  MD->setVariadic(Record[Idx++]);
423  MD->setSynthesized(Record[Idx++]);
424  MD->setDefined(Record[Idx++]);
425  MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
426  MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
427  MD->setNumSelectorArgs(unsigned(Record[Idx++]));
428  MD->setResultType(Reader.GetType(Record[Idx++]));
429  MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
430  MD->setEndLoc(ReadSourceLocation(Record, Idx));
431  unsigned NumParams = Record[Idx++];
432  llvm::SmallVector<ParmVarDecl *, 16> Params;
433  Params.reserve(NumParams);
434  for (unsigned I = 0; I != NumParams; ++I)
435    Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
436  MD->setMethodParams(*Reader.getContext(), Params.data(), NumParams,
437                      NumParams);
438}
439
440void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
441  VisitNamedDecl(CD);
442  SourceLocation A = ReadSourceLocation(Record, Idx);
443  SourceLocation B = ReadSourceLocation(Record, Idx);
444  CD->setAtEndRange(SourceRange(A, B));
445}
446
447void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
448  VisitObjCContainerDecl(ID);
449  ID->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtrOrNull());
450  ID->setSuperClass(cast_or_null<ObjCInterfaceDecl>
451                       (Reader.GetDecl(Record[Idx++])));
452
453  // Read the directly referenced protocols and their SourceLocations.
454  unsigned NumProtocols = Record[Idx++];
455  llvm::SmallVector<ObjCProtocolDecl *, 16> Protocols;
456  Protocols.reserve(NumProtocols);
457  for (unsigned I = 0; I != NumProtocols; ++I)
458    Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
459  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
460  ProtoLocs.reserve(NumProtocols);
461  for (unsigned I = 0; I != NumProtocols; ++I)
462    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
463  ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
464                      *Reader.getContext());
465
466  // Read the transitive closure of protocols referenced by this class.
467  NumProtocols = Record[Idx++];
468  Protocols.clear();
469  Protocols.reserve(NumProtocols);
470  for (unsigned I = 0; I != NumProtocols; ++I)
471    Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
472  ID->AllReferencedProtocols.set(Protocols.data(), NumProtocols,
473                                 *Reader.getContext());
474
475  // Read the ivars.
476  unsigned NumIvars = Record[Idx++];
477  llvm::SmallVector<ObjCIvarDecl *, 16> IVars;
478  IVars.reserve(NumIvars);
479  for (unsigned I = 0; I != NumIvars; ++I)
480    IVars.push_back(cast<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
481  ID->setCategoryList(
482               cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
483  // We will rebuild this list lazily.
484  ID->setIvarList(0);
485  ID->setForwardDecl(Record[Idx++]);
486  ID->setImplicitInterfaceDecl(Record[Idx++]);
487  ID->setClassLoc(ReadSourceLocation(Record, Idx));
488  ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
489  ID->setLocEnd(ReadSourceLocation(Record, Idx));
490}
491
492void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
493  VisitFieldDecl(IVD);
494  IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
495  // This field will be built lazily.
496  IVD->setNextIvar(0);
497  bool synth = Record[Idx++];
498  IVD->setSynthesize(synth);
499}
500
501void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
502  VisitObjCContainerDecl(PD);
503  PD->setForwardDecl(Record[Idx++]);
504  PD->setLocEnd(ReadSourceLocation(Record, Idx));
505  unsigned NumProtoRefs = Record[Idx++];
506  llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
507  ProtoRefs.reserve(NumProtoRefs);
508  for (unsigned I = 0; I != NumProtoRefs; ++I)
509    ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
510  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
511  ProtoLocs.reserve(NumProtoRefs);
512  for (unsigned I = 0; I != NumProtoRefs; ++I)
513    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
514  PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
515                      *Reader.getContext());
516}
517
518void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
519  VisitFieldDecl(FD);
520}
521
522void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
523  VisitDecl(CD);
524  unsigned NumClassRefs = Record[Idx++];
525  llvm::SmallVector<ObjCInterfaceDecl *, 16> ClassRefs;
526  ClassRefs.reserve(NumClassRefs);
527  for (unsigned I = 0; I != NumClassRefs; ++I)
528    ClassRefs.push_back(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
529  llvm::SmallVector<SourceLocation, 16> SLocs;
530  SLocs.reserve(NumClassRefs);
531  for (unsigned I = 0; I != NumClassRefs; ++I)
532    SLocs.push_back(ReadSourceLocation(Record, Idx));
533  CD->setClassList(*Reader.getContext(), ClassRefs.data(), SLocs.data(),
534                   NumClassRefs);
535}
536
537void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
538  VisitDecl(FPD);
539  unsigned NumProtoRefs = Record[Idx++];
540  llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
541  ProtoRefs.reserve(NumProtoRefs);
542  for (unsigned I = 0; I != NumProtoRefs; ++I)
543    ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
544  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
545  ProtoLocs.reserve(NumProtoRefs);
546  for (unsigned I = 0; I != NumProtoRefs; ++I)
547    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
548  FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
549                       *Reader.getContext());
550}
551
552void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
553  VisitObjCContainerDecl(CD);
554  CD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
555  unsigned NumProtoRefs = Record[Idx++];
556  llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
557  ProtoRefs.reserve(NumProtoRefs);
558  for (unsigned I = 0; I != NumProtoRefs; ++I)
559    ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
560  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
561  ProtoLocs.reserve(NumProtoRefs);
562  for (unsigned I = 0; I != NumProtoRefs; ++I)
563    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
564  CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
565                      *Reader.getContext());
566  CD->setNextClassCategory(cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
567  CD->setHasSynthBitfield(Record[Idx++]);
568  CD->setAtLoc(ReadSourceLocation(Record, Idx));
569  CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
570}
571
572void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
573  VisitNamedDecl(CAD);
574  CAD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
575}
576
577void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
578  VisitNamedDecl(D);
579  D->setAtLoc(ReadSourceLocation(Record, Idx));
580  D->setType(GetTypeSourceInfo(Record, Idx));
581  // FIXME: stable encoding
582  D->setPropertyAttributes(
583                      (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
584  D->setPropertyAttributesAsWritten(
585                      (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
586  // FIXME: stable encoding
587  D->setPropertyImplementation(
588                            (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
589  D->setGetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
590  D->setSetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
591  D->setGetterMethodDecl(
592                 cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
593  D->setSetterMethodDecl(
594                 cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
595  D->setPropertyIvarDecl(
596                   cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
597}
598
599void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
600  VisitObjCContainerDecl(D);
601  D->setClassInterface(
602              cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
603}
604
605void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
606  VisitObjCImplDecl(D);
607  D->setIdentifier(Reader.GetIdentifierInfo(Record, Idx));
608}
609
610void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
611  VisitObjCImplDecl(D);
612  D->setSuperClass(
613              cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
614  llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
615      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
616  D->setHasSynthBitfield(Record[Idx++]);
617}
618
619
620void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
621  VisitDecl(D);
622  D->setAtLoc(ReadSourceLocation(Record, Idx));
623  D->setPropertyDecl(
624               cast_or_null<ObjCPropertyDecl>(Reader.GetDecl(Record[Idx++])));
625  D->PropertyIvarDecl =
626                   cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++]));
627  D->IvarLoc = ReadSourceLocation(Record, Idx);
628  D->setGetterCXXConstructor(Reader.ReadExpr(F));
629  D->setSetterCXXAssignment(Reader.ReadExpr(F));
630}
631
632void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
633  VisitDeclaratorDecl(FD);
634  FD->setMutable(Record[Idx++]);
635  if (Record[Idx++])
636    FD->setBitWidth(Reader.ReadExpr(F));
637  if (!FD->getDeclName()) {
638    FieldDecl *Tmpl = cast_or_null<FieldDecl>(Reader.GetDecl(Record[Idx++]));
639    if (Tmpl)
640      Reader.getContext()->setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
641  }
642}
643
644void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
645  VisitValueDecl(FD);
646
647  FD->ChainingSize = Record[Idx++];
648  assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
649  FD->Chaining = new (*Reader.getContext())NamedDecl*[FD->ChainingSize];
650
651  for (unsigned I = 0; I != FD->ChainingSize; ++I)
652    FD->Chaining[I] = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
653}
654
655void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
656  VisitDeclaratorDecl(VD);
657  VisitRedeclarable(VD);
658  VD->SClass = (StorageClass)Record[Idx++];
659  VD->setStorageClassAsWritten((StorageClass)Record[Idx++]);
660  VD->setThreadSpecified(Record[Idx++]);
661  VD->setCXXDirectInitializer(Record[Idx++]);
662  VD->setExceptionVariable(Record[Idx++]);
663  VD->setNRVOVariable(Record[Idx++]);
664  if (Record[Idx++])
665    VD->setInit(Reader.ReadExpr(F));
666
667  if (Record[Idx++]) { // HasMemberSpecializationInfo.
668    VarDecl *Tmpl = cast<VarDecl>(Reader.GetDecl(Record[Idx++]));
669    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
670    SourceLocation POI = ReadSourceLocation(Record, Idx);
671    Reader.getContext()->setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
672  }
673}
674
675void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
676  VisitVarDecl(PD);
677}
678
679void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
680  VisitVarDecl(PD);
681  PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
682  PD->setHasInheritedDefaultArg(Record[Idx++]);
683  if (Record[Idx++]) // hasUninstantiatedDefaultArg.
684    PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
685}
686
687void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
688  VisitDecl(AD);
689  AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
690}
691
692void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
693  VisitDecl(BD);
694  BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
695  BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
696  unsigned NumParams = Record[Idx++];
697  llvm::SmallVector<ParmVarDecl *, 16> Params;
698  Params.reserve(NumParams);
699  for (unsigned I = 0; I != NumParams; ++I)
700    Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
701  BD->setParams(Params.data(), NumParams);
702}
703
704void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
705  VisitDecl(D);
706  D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
707  D->setHasBraces(Record[Idx++]);
708}
709
710void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
711  VisitNamedDecl(D);
712  D->IsInline = Record[Idx++];
713  D->LBracLoc = ReadSourceLocation(Record, Idx);
714  D->RBracLoc = ReadSourceLocation(Record, Idx);
715  D->NextNamespace = Record[Idx++];
716
717  bool IsOriginal = Record[Idx++];
718  D->OrigOrAnonNamespace.setInt(IsOriginal);
719  D->OrigOrAnonNamespace.setPointer(
720                    cast_or_null<NamespaceDecl>(Reader.GetDecl(Record[Idx++])));
721}
722
723void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
724  VisitNamedDecl(D);
725  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
726  D->setQualifierRange(ReadSourceRange(Record, Idx));
727  D->setQualifier(Reader.ReadNestedNameSpecifier(Record, Idx));
728  D->IdentLoc = ReadSourceLocation(Record, Idx);
729  D->Namespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
730}
731
732void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
733  VisitNamedDecl(D);
734  D->setUsingLocation(ReadSourceLocation(Record, Idx));
735  D->setNestedNameRange(ReadSourceRange(Record, Idx));
736  D->setTargetNestedNameDecl(Reader.ReadNestedNameSpecifier(Record, Idx));
737  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
738  D->FirstUsingShadow = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
739  D->setTypeName(Record[Idx++]);
740  NamedDecl *Pattern = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
741  if (Pattern)
742    Reader.getContext()->setInstantiatedFromUsingDecl(D, Pattern);
743}
744
745void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
746  VisitNamedDecl(D);
747  D->setTargetDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
748  D->UsingOrNextShadow = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
749  UsingShadowDecl *Pattern
750      = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
751  if (Pattern)
752    Reader.getContext()->setInstantiatedFromUsingShadowDecl(D, Pattern);
753}
754
755void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
756  VisitNamedDecl(D);
757  D->UsingLoc = ReadSourceLocation(Record, Idx);
758  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
759  D->QualifierRange = ReadSourceRange(Record, Idx);
760  D->Qualifier = Reader.ReadNestedNameSpecifier(Record, Idx);
761  D->NominatedNamespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
762  D->CommonAncestor = cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++]));
763}
764
765void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
766  VisitValueDecl(D);
767  D->setTargetNestedNameRange(ReadSourceRange(Record, Idx));
768  D->setUsingLoc(ReadSourceLocation(Record, Idx));
769  D->setTargetNestedNameSpecifier(Reader.ReadNestedNameSpecifier(Record, Idx));
770  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
771}
772
773void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
774                                               UnresolvedUsingTypenameDecl *D) {
775  VisitTypeDecl(D);
776  D->TargetNestedNameRange = ReadSourceRange(Record, Idx);
777  D->UsingLocation = ReadSourceLocation(Record, Idx);
778  D->TypenameLocation = ReadSourceLocation(Record, Idx);
779  D->TargetNestedNameSpecifier = Reader.ReadNestedNameSpecifier(Record, Idx);
780}
781
782void ASTDeclReader::ReadCXXDefinitionData(
783                                   struct CXXRecordDecl::DefinitionData &Data,
784                                   const RecordData &Record, unsigned &Idx) {
785  Data.UserDeclaredConstructor = Record[Idx++];
786  Data.UserDeclaredCopyConstructor = Record[Idx++];
787  Data.UserDeclaredCopyAssignment = Record[Idx++];
788  Data.UserDeclaredDestructor = Record[Idx++];
789  Data.Aggregate = Record[Idx++];
790  Data.PlainOldData = Record[Idx++];
791  Data.Empty = Record[Idx++];
792  Data.Polymorphic = Record[Idx++];
793  Data.Abstract = Record[Idx++];
794  Data.HasTrivialConstructor = Record[Idx++];
795  Data.HasTrivialCopyConstructor = Record[Idx++];
796  Data.HasTrivialCopyAssignment = Record[Idx++];
797  Data.HasTrivialDestructor = Record[Idx++];
798  Data.ComputedVisibleConversions = Record[Idx++];
799  Data.DeclaredDefaultConstructor = Record[Idx++];
800  Data.DeclaredCopyConstructor = Record[Idx++];
801  Data.DeclaredCopyAssignment = Record[Idx++];
802  Data.DeclaredDestructor = Record[Idx++];
803  Data.NumBases = Record[Idx++];
804  if (Data.NumBases)
805    Data.Bases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
806  Data.NumVBases = Record[Idx++];
807  if (Data.NumVBases)
808    Data.VBases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
809
810  Reader.ReadUnresolvedSet(Data.Conversions, Record, Idx);
811  Reader.ReadUnresolvedSet(Data.VisibleConversions, Record, Idx);
812  assert(Data.Definition && "Data.Definition should be already set!");
813  Data.FirstFriend
814      = cast_or_null<FriendDecl>(Reader.GetDecl(Record[Idx++]));
815}
816
817void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
818                                                CXXRecordDecl *DefinitionDecl,
819                                                const RecordData &Record,
820                                                unsigned &Idx) {
821  ASTContext &C = *Reader.getContext();
822
823  if (D == DefinitionDecl) {
824    D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
825    ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
826    // We read the definition info. Check if there are pending forward
827    // references that need to point to this DefinitionData pointer.
828    ASTReader::PendingForwardRefsMap::iterator
829        FindI = Reader.PendingForwardRefs.find(D);
830    if (FindI != Reader.PendingForwardRefs.end()) {
831      ASTReader::ForwardRefs &Refs = FindI->second;
832      for (ASTReader::ForwardRefs::iterator
833             I = Refs.begin(), E = Refs.end(); I != E; ++I)
834        (*I)->DefinitionData = D->DefinitionData;
835#ifndef NDEBUG
836      // We later check whether PendingForwardRefs is empty to make sure all
837      // pending references were linked.
838      Reader.PendingForwardRefs.erase(D);
839#endif
840    }
841  } else if (DefinitionDecl) {
842    if (DefinitionDecl->DefinitionData) {
843      D->DefinitionData = DefinitionDecl->DefinitionData;
844    } else {
845      // The definition is still initializing.
846      Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
847    }
848  }
849}
850
851void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
852  VisitRecordDecl(D);
853
854  CXXRecordDecl *DefinitionDecl
855      = cast_or_null<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
856  InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
857
858  ASTContext &C = *Reader.getContext();
859
860  enum CXXRecKind {
861    CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
862  };
863  switch ((CXXRecKind)Record[Idx++]) {
864  default:
865    assert(false && "Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
866  case CXXRecNotTemplate:
867    break;
868  case CXXRecTemplate:
869    D->TemplateOrInstantiation
870        = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
871    break;
872  case CXXRecMemberSpecialization: {
873    CXXRecordDecl *RD = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
874    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
875    SourceLocation POI = ReadSourceLocation(Record, Idx);
876    MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
877    MSI->setPointOfInstantiation(POI);
878    D->TemplateOrInstantiation = MSI;
879    break;
880  }
881  }
882
883  // Load the key function to avoid deserializing every method so we can
884  // compute it.
885  if (D->IsDefinition) {
886    CXXMethodDecl *Key
887        = cast_or_null<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
888    if (Key)
889      C.KeyFunctions[D] = Key;
890  }
891}
892
893void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
894  VisitFunctionDecl(D);
895  unsigned NumOverridenMethods = Record[Idx++];
896  while (NumOverridenMethods--) {
897    CXXMethodDecl *MD = cast<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
898    // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
899    // MD may be initializing.
900    Reader.getContext()->addOverriddenMethod(D, MD);
901  }
902}
903
904void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
905  VisitCXXMethodDecl(D);
906
907  D->IsExplicitSpecified = Record[Idx++];
908  D->ImplicitlyDefined = Record[Idx++];
909  llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
910      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
911}
912
913void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
914  VisitCXXMethodDecl(D);
915
916  D->ImplicitlyDefined = Record[Idx++];
917  D->OperatorDelete = cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++]));
918}
919
920void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
921  VisitCXXMethodDecl(D);
922  D->IsExplicitSpecified = Record[Idx++];
923}
924
925void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
926  VisitDecl(D);
927  D->setColonLoc(ReadSourceLocation(Record, Idx));
928}
929
930void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
931  VisitDecl(D);
932  if (Record[Idx++])
933    D->Friend = GetTypeSourceInfo(Record, Idx);
934  else
935    D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
936  D->NextFriend = Record[Idx++];
937  D->UnsupportedFriend = (Record[Idx++] != 0);
938  D->FriendLoc = ReadSourceLocation(Record, Idx);
939}
940
941void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
942  VisitDecl(D);
943  unsigned NumParams = Record[Idx++];
944  D->NumParams = NumParams;
945  D->Params = new TemplateParameterList*[NumParams];
946  for (unsigned i = 0; i != NumParams; ++i)
947    D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
948  if (Record[Idx++]) // HasFriendDecl
949    D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
950  else
951    D->Friend = GetTypeSourceInfo(Record, Idx);
952  D->FriendLoc = ReadSourceLocation(Record, Idx);
953}
954
955void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
956  VisitNamedDecl(D);
957
958  NamedDecl *TemplatedDecl
959    = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
960  TemplateParameterList* TemplateParams
961      = Reader.ReadTemplateParameterList(F, Record, Idx);
962  D->init(TemplatedDecl, TemplateParams);
963}
964
965void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
966  // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
967  // can be used while this is still initializing.
968
969  assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
970  RedeclarableTemplateDecl *PrevDecl =
971      cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
972  assert((PrevDecl == 0 || PrevDecl->getKind() == D->getKind()) &&
973         "PrevDecl kind mismatch");
974  if (PrevDecl)
975    D->CommonOrPrev = PrevDecl;
976  if (PrevDecl == 0) {
977    D->CommonOrPrev = D->newCommon(*Reader.getContext());
978    if (RedeclarableTemplateDecl *RTD
979          = cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]))) {
980      assert(RTD->getKind() == D->getKind() &&
981             "InstantiatedFromMemberTemplate kind mismatch");
982      D->setInstantiatedFromMemberTemplateImpl(RTD);
983      if (Record[Idx++])
984        D->setMemberSpecialization();
985    }
986
987    RedeclarableTemplateDecl *LatestDecl =
988        cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
989
990    // This decl is a first one and the latest declaration that it points to is
991    // in the same AST file. However, if this actually needs to point to a
992    // redeclaration in another AST file, we need to update it by checking
993    // the FirstLatestDeclIDs map which tracks this kind of decls.
994    assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
995    ASTReader::FirstLatestDeclIDMap::iterator I
996        = Reader.FirstLatestDeclIDs.find(ThisDeclID);
997    if (I != Reader.FirstLatestDeclIDs.end()) {
998      Decl *NewLatest = Reader.GetDecl(I->second);
999      assert((LatestDecl->getLocation().isInvalid() ||
1000              NewLatest->getLocation().isInvalid()  ||
1001              !Reader.SourceMgr.isBeforeInTranslationUnit(
1002                                                  NewLatest->getLocation(),
1003                                                  LatestDecl->getLocation())) &&
1004             "The new latest is supposed to come after the previous latest");
1005      LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
1006    }
1007
1008    assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
1009    D->getCommonPtr()->Latest = LatestDecl;
1010  }
1011
1012  VisitTemplateDecl(D);
1013  D->IdentifierNamespace = Record[Idx++];
1014}
1015
1016void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1017  VisitRedeclarableTemplateDecl(D);
1018
1019  if (D->getPreviousDeclaration() == 0) {
1020    // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1021    // the specializations.
1022    llvm::SmallVector<serialization::DeclID, 2> SpecIDs;
1023    SpecIDs.push_back(0);
1024
1025    // Specializations.
1026    unsigned Size = Record[Idx++];
1027    SpecIDs[0] += Size;
1028    SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1029    Idx += Size;
1030
1031    // Partial specializations.
1032    Size = Record[Idx++];
1033    SpecIDs[0] += Size;
1034    SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1035    Idx += Size;
1036
1037    if (SpecIDs[0]) {
1038      typedef serialization::DeclID DeclID;
1039
1040      ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1041      CommonPtr->LazySpecializations
1042        = new (*Reader.getContext()) DeclID [SpecIDs.size()];
1043      memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1044             SpecIDs.size() * sizeof(DeclID));
1045    }
1046
1047    // InjectedClassNameType is computed.
1048  }
1049}
1050
1051void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1052                                           ClassTemplateSpecializationDecl *D) {
1053  VisitCXXRecordDecl(D);
1054
1055  ASTContext &C = *Reader.getContext();
1056  if (Decl *InstD = Reader.GetDecl(Record[Idx++])) {
1057    if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1058      D->SpecializedTemplate = CTD;
1059    } else {
1060      llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1061      Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1062      TemplateArgumentList *ArgList
1063        = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1064                                           TemplArgs.size());
1065      ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1066          = new (C) ClassTemplateSpecializationDecl::
1067                                             SpecializedPartialSpecialization();
1068      PS->PartialSpecialization
1069          = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1070      PS->TemplateArgs = ArgList;
1071      D->SpecializedTemplate = PS;
1072    }
1073  }
1074
1075  // Explicit info.
1076  if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1077    ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1078        = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1079    ExplicitInfo->TypeAsWritten = TyInfo;
1080    ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1081    ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1082    D->ExplicitInfo = ExplicitInfo;
1083  }
1084
1085  llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1086  Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1087  D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1088                                                     TemplArgs.size());
1089  D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1090  D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1091
1092  if (D->isCanonicalDecl()) { // It's kept in the folding set.
1093    ClassTemplateDecl *CanonPattern
1094                       = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
1095    if (ClassTemplatePartialSpecializationDecl *Partial
1096                       = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1097      CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1098    } else {
1099      CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1100    }
1101  }
1102}
1103
1104void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1105                                    ClassTemplatePartialSpecializationDecl *D) {
1106  VisitClassTemplateSpecializationDecl(D);
1107
1108  ASTContext &C = *Reader.getContext();
1109  D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1110
1111  unsigned NumArgs = Record[Idx++];
1112  if (NumArgs) {
1113    D->NumArgsAsWritten = NumArgs;
1114    D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1115    for (unsigned i=0; i != NumArgs; ++i)
1116      D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1117  }
1118
1119  D->SequenceNumber = Record[Idx++];
1120
1121  // These are read/set from/to the first declaration.
1122  if (D->getPreviousDeclaration() == 0) {
1123    D->InstantiatedFromMember.setPointer(
1124        cast_or_null<ClassTemplatePartialSpecializationDecl>(
1125                                                Reader.GetDecl(Record[Idx++])));
1126    D->InstantiatedFromMember.setInt(Record[Idx++]);
1127  }
1128}
1129
1130void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1131  VisitRedeclarableTemplateDecl(D);
1132
1133  if (D->getPreviousDeclaration() == 0) {
1134    // This FunctionTemplateDecl owns a CommonPtr; read it.
1135
1136    // Read the function specialization declarations.
1137    // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1138    // when reading the specialized FunctionDecl.
1139    unsigned NumSpecs = Record[Idx++];
1140    while (NumSpecs--)
1141      Reader.GetDecl(Record[Idx++]);
1142  }
1143}
1144
1145void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1146  VisitTypeDecl(D);
1147
1148  D->setDeclaredWithTypename(Record[Idx++]);
1149  D->setParameterPack(Record[Idx++]);
1150
1151  bool Inherited = Record[Idx++];
1152  TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1153  D->setDefaultArgument(DefArg, Inherited);
1154}
1155
1156void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1157  VisitVarDecl(D);
1158  // TemplateParmPosition.
1159  D->setDepth(Record[Idx++]);
1160  D->setPosition(Record[Idx++]);
1161  if (D->isExpandedParameterPack()) {
1162    void **Data = reinterpret_cast<void **>(D + 1);
1163    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1164      Data[2*I] = Reader.GetType(Record[Idx++]).getAsOpaquePtr();
1165      Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1166    }
1167  } else {
1168    // Rest of NonTypeTemplateParmDecl.
1169    D->ParameterPack = Record[Idx++];
1170    if (Record[Idx++]) {
1171      Expr *DefArg = Reader.ReadExpr(F);
1172      bool Inherited = Record[Idx++];
1173      D->setDefaultArgument(DefArg, Inherited);
1174   }
1175  }
1176}
1177
1178void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1179  VisitTemplateDecl(D);
1180  // TemplateParmPosition.
1181  D->setDepth(Record[Idx++]);
1182  D->setPosition(Record[Idx++]);
1183  // Rest of TemplateTemplateParmDecl.
1184  TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1185  bool IsInherited = Record[Idx++];
1186  D->setDefaultArgument(Arg, IsInherited);
1187  D->ParameterPack = Record[Idx++];
1188}
1189
1190void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1191  VisitDecl(D);
1192  D->AssertExpr = Reader.ReadExpr(F);
1193  D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1194}
1195
1196std::pair<uint64_t, uint64_t>
1197ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1198  uint64_t LexicalOffset = Record[Idx++];
1199  uint64_t VisibleOffset = Record[Idx++];
1200  return std::make_pair(LexicalOffset, VisibleOffset);
1201}
1202
1203template <typename T>
1204void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1205  enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1206  RedeclKind Kind = (RedeclKind)Record[Idx++];
1207  switch (Kind) {
1208  default:
1209    assert(0 && "Out of sync with ASTDeclWriter::VisitRedeclarable or messed up"
1210                " reading");
1211  case NoRedeclaration:
1212    break;
1213  case PointsToPrevious:
1214    D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(
1215                                cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1216    break;
1217  case PointsToLatest:
1218    D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(
1219                                cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1220    break;
1221  }
1222
1223  assert(!(Kind == PointsToPrevious &&
1224           Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
1225               Reader.FirstLatestDeclIDs.end()) &&
1226         "This decl is not first, it should not be in the map");
1227  if (Kind == PointsToPrevious)
1228    return;
1229
1230  // This decl is a first one and the latest declaration that it points to is in
1231  // the same AST file. However, if this actually needs to point to a
1232  // redeclaration in another AST file, we need to update it by checking the
1233  // FirstLatestDeclIDs map which tracks this kind of decls.
1234  assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
1235         "Invalid ThisDeclID ?");
1236  ASTReader::FirstLatestDeclIDMap::iterator I
1237      = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1238  if (I != Reader.FirstLatestDeclIDs.end()) {
1239    Decl *NewLatest = Reader.GetDecl(I->second);
1240    D->RedeclLink
1241        = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
1242  }
1243}
1244
1245//===----------------------------------------------------------------------===//
1246// Attribute Reading
1247//===----------------------------------------------------------------------===//
1248
1249/// \brief Reads attributes from the current stream position.
1250void ASTReader::ReadAttributes(PerFileData &F, AttrVec &Attrs,
1251                               const RecordData &Record, unsigned &Idx) {
1252  for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1253    Attr *New = 0;
1254    attr::Kind Kind = (attr::Kind)Record[Idx++];
1255    SourceLocation Loc = ReadSourceLocation(F, Record, Idx);
1256    bool isInherited = Record[Idx++];
1257
1258#include "clang/Serialization/AttrPCHRead.inc"
1259
1260    assert(New && "Unable to decode attribute?");
1261    New->setInherited(isInherited);
1262    Attrs.push_back(New);
1263  }
1264}
1265
1266//===----------------------------------------------------------------------===//
1267// ASTReader Implementation
1268//===----------------------------------------------------------------------===//
1269
1270/// \brief Note that we have loaded the declaration with the given
1271/// Index.
1272///
1273/// This routine notes that this declaration has already been loaded,
1274/// so that future GetDecl calls will return this declaration rather
1275/// than trying to load a new declaration.
1276inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1277  assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1278  DeclsLoaded[Index] = D;
1279}
1280
1281
1282/// \brief Determine whether the consumer will be interested in seeing
1283/// this declaration (via HandleTopLevelDecl).
1284///
1285/// This routine should return true for anything that might affect
1286/// code generation, e.g., inline function definitions, Objective-C
1287/// declarations with metadata, etc.
1288static bool isConsumerInterestedIn(Decl *D) {
1289  if (isa<FileScopeAsmDecl>(D))
1290    return true;
1291  if (VarDecl *Var = dyn_cast<VarDecl>(D))
1292    return Var->isFileVarDecl() &&
1293           Var->isThisDeclarationADefinition() == VarDecl::Definition;
1294  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1295    return Func->isThisDeclarationADefinition();
1296  return isa<ObjCProtocolDecl>(D) || isa<ObjCImplementationDecl>(D);
1297}
1298
1299/// \brief Get the correct cursor and offset for loading a type.
1300ASTReader::RecordLocation
1301ASTReader::DeclCursorForIndex(unsigned Index, DeclID ID) {
1302  // See if there's an override.
1303  DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1304  if (It != ReplacedDecls.end())
1305    return RecordLocation(It->second.first, It->second.second);
1306
1307  PerFileData *F = 0;
1308  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1309    F = Chain[N - I - 1];
1310    if (Index < F->LocalNumDecls)
1311      break;
1312    Index -= F->LocalNumDecls;
1313  }
1314  assert(F && F->LocalNumDecls > Index && "Broken chain");
1315  return RecordLocation(F, F->DeclOffsets[Index]);
1316}
1317
1318/// \brief Read the declaration at the given offset from the AST file.
1319Decl *ASTReader::ReadDeclRecord(unsigned Index, DeclID ID) {
1320  RecordLocation Loc = DeclCursorForIndex(Index, ID);
1321  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1322  // Keep track of where we are in the stream, then jump back there
1323  // after reading this declaration.
1324  SavedStreamPosition SavedPosition(DeclsCursor);
1325
1326  ReadingKindTracker ReadingKind(Read_Decl, *this);
1327
1328  // Note that we are loading a declaration record.
1329  Deserializing ADecl(this);
1330
1331  DeclsCursor.JumpToBit(Loc.Offset);
1332  RecordData Record;
1333  unsigned Code = DeclsCursor.ReadCode();
1334  unsigned Idx = 0;
1335  ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, Record, Idx);
1336
1337  Decl *D = 0;
1338  switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1339  case DECL_CONTEXT_LEXICAL:
1340  case DECL_CONTEXT_VISIBLE:
1341    assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1342    break;
1343  case DECL_TRANSLATION_UNIT:
1344    assert(Index == 0 && "Translation unit must be at index 0");
1345    D = Context->getTranslationUnitDecl();
1346    break;
1347  case DECL_TYPEDEF:
1348    D = TypedefDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1349    break;
1350  case DECL_ENUM:
1351    D = EnumDecl::Create(*Context, Decl::EmptyShell());
1352    break;
1353  case DECL_RECORD:
1354    D = RecordDecl::Create(*Context, Decl::EmptyShell());
1355    break;
1356  case DECL_ENUM_CONSTANT:
1357    D = EnumConstantDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1358                                 0, llvm::APSInt());
1359    break;
1360  case DECL_FUNCTION:
1361    D = FunctionDecl::Create(*Context, 0, SourceLocation(), DeclarationName(),
1362                             QualType(), 0);
1363    break;
1364  case DECL_LINKAGE_SPEC:
1365    D = LinkageSpecDecl::Create(*Context, 0, SourceLocation(),
1366                                (LinkageSpecDecl::LanguageIDs)0,
1367                                false);
1368    break;
1369  case DECL_NAMESPACE:
1370    D = NamespaceDecl::Create(*Context, 0, SourceLocation(), 0);
1371    break;
1372  case DECL_NAMESPACE_ALIAS:
1373    D = NamespaceAliasDecl::Create(*Context, 0, SourceLocation(),
1374                                   SourceLocation(), 0, SourceRange(), 0,
1375                                   SourceLocation(), 0);
1376    break;
1377  case DECL_USING:
1378    D = UsingDecl::Create(*Context, 0, SourceRange(), SourceLocation(),
1379                          0, DeclarationNameInfo(), false);
1380    break;
1381  case DECL_USING_SHADOW:
1382    D = UsingShadowDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1383    break;
1384  case DECL_USING_DIRECTIVE:
1385    D = UsingDirectiveDecl::Create(*Context, 0, SourceLocation(),
1386                                   SourceLocation(), SourceRange(), 0,
1387                                   SourceLocation(), 0, 0);
1388    break;
1389  case DECL_UNRESOLVED_USING_VALUE:
1390    D = UnresolvedUsingValueDecl::Create(*Context, 0, SourceLocation(),
1391                                         SourceRange(), 0,
1392                                         DeclarationNameInfo());
1393    break;
1394  case DECL_UNRESOLVED_USING_TYPENAME:
1395    D = UnresolvedUsingTypenameDecl::Create(*Context, 0, SourceLocation(),
1396                                            SourceLocation(), SourceRange(),
1397                                            0, SourceLocation(),
1398                                            DeclarationName());
1399    break;
1400  case DECL_CXX_RECORD:
1401    D = CXXRecordDecl::Create(*Context, Decl::EmptyShell());
1402    break;
1403  case DECL_CXX_METHOD:
1404    D = CXXMethodDecl::Create(*Context, 0, DeclarationNameInfo(),
1405                              QualType(), 0);
1406    break;
1407  case DECL_CXX_CONSTRUCTOR:
1408    D = CXXConstructorDecl::Create(*Context, Decl::EmptyShell());
1409    break;
1410  case DECL_CXX_DESTRUCTOR:
1411    D = CXXDestructorDecl::Create(*Context, Decl::EmptyShell());
1412    break;
1413  case DECL_CXX_CONVERSION:
1414    D = CXXConversionDecl::Create(*Context, Decl::EmptyShell());
1415    break;
1416  case DECL_ACCESS_SPEC:
1417    D = AccessSpecDecl::Create(*Context, Decl::EmptyShell());
1418    break;
1419  case DECL_FRIEND:
1420    D = FriendDecl::Create(*Context, Decl::EmptyShell());
1421    break;
1422  case DECL_FRIEND_TEMPLATE:
1423    D = FriendTemplateDecl::Create(*Context, Decl::EmptyShell());
1424    break;
1425  case DECL_CLASS_TEMPLATE:
1426    D = ClassTemplateDecl::Create(*Context, 0, SourceLocation(),
1427                                  DeclarationName(), 0, 0, 0);
1428    break;
1429  case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1430    D = ClassTemplateSpecializationDecl::Create(*Context, Decl::EmptyShell());
1431    break;
1432  case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1433    D = ClassTemplatePartialSpecializationDecl::Create(*Context,
1434                                                            Decl::EmptyShell());
1435    break;
1436  case DECL_FUNCTION_TEMPLATE:
1437    D = FunctionTemplateDecl::Create(*Context, 0, SourceLocation(),
1438                                     DeclarationName(), 0, 0);
1439    break;
1440  case DECL_TEMPLATE_TYPE_PARM:
1441    D = TemplateTypeParmDecl::Create(*Context, Decl::EmptyShell());
1442    break;
1443  case DECL_NON_TYPE_TEMPLATE_PARM:
1444    D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0,0,0,
1445                                        QualType(), false, 0);
1446    break;
1447  case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1448    D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1449                                        0, QualType(), 0, 0, Record[Idx++],
1450                                        0);
1451    break;
1452  case DECL_TEMPLATE_TEMPLATE_PARM:
1453    D = TemplateTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1454                                         false, 0, 0);
1455    break;
1456  case DECL_STATIC_ASSERT:
1457    D = StaticAssertDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1458    break;
1459
1460  case DECL_OBJC_METHOD:
1461    D = ObjCMethodDecl::Create(*Context, SourceLocation(), SourceLocation(),
1462                               Selector(), QualType(), 0, 0);
1463    break;
1464  case DECL_OBJC_INTERFACE:
1465    D = ObjCInterfaceDecl::Create(*Context, 0, SourceLocation(), 0);
1466    break;
1467  case DECL_OBJC_IVAR:
1468    D = ObjCIvarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1469                             ObjCIvarDecl::None);
1470    break;
1471  case DECL_OBJC_PROTOCOL:
1472    D = ObjCProtocolDecl::Create(*Context, 0, SourceLocation(), 0);
1473    break;
1474  case DECL_OBJC_AT_DEFS_FIELD:
1475    D = ObjCAtDefsFieldDecl::Create(*Context, 0, SourceLocation(), 0,
1476                                    QualType(), 0);
1477    break;
1478  case DECL_OBJC_CLASS:
1479    D = ObjCClassDecl::Create(*Context, 0, SourceLocation());
1480    break;
1481  case DECL_OBJC_FORWARD_PROTOCOL:
1482    D = ObjCForwardProtocolDecl::Create(*Context, 0, SourceLocation());
1483    break;
1484  case DECL_OBJC_CATEGORY:
1485    D = ObjCCategoryDecl::Create(*Context, 0, SourceLocation(),
1486                                 SourceLocation(), SourceLocation(), 0);
1487    break;
1488  case DECL_OBJC_CATEGORY_IMPL:
1489    D = ObjCCategoryImplDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1490    break;
1491  case DECL_OBJC_IMPLEMENTATION:
1492    D = ObjCImplementationDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1493    break;
1494  case DECL_OBJC_COMPATIBLE_ALIAS:
1495    D = ObjCCompatibleAliasDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1496    break;
1497  case DECL_OBJC_PROPERTY:
1498    D = ObjCPropertyDecl::Create(*Context, 0, SourceLocation(), 0, SourceLocation(),
1499                                 0);
1500    break;
1501  case DECL_OBJC_PROPERTY_IMPL:
1502    D = ObjCPropertyImplDecl::Create(*Context, 0, SourceLocation(),
1503                                     SourceLocation(), 0,
1504                                     ObjCPropertyImplDecl::Dynamic, 0,
1505                                     SourceLocation());
1506    break;
1507  case DECL_FIELD:
1508    D = FieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, 0,
1509                          false);
1510    break;
1511  case DECL_INDIRECTFIELD:
1512    D = IndirectFieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1513                                  0, 0);
1514    break;
1515  case DECL_VAR:
1516    D = VarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1517                        SC_None, SC_None);
1518    break;
1519
1520  case DECL_IMPLICIT_PARAM:
1521    D = ImplicitParamDecl::Create(*Context, 0, SourceLocation(), 0, QualType());
1522    break;
1523
1524  case DECL_PARM_VAR:
1525    D = ParmVarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1526                            SC_None, SC_None, 0);
1527    break;
1528  case DECL_FILE_SCOPE_ASM:
1529    D = FileScopeAsmDecl::Create(*Context, 0, SourceLocation(), 0);
1530    break;
1531  case DECL_BLOCK:
1532    D = BlockDecl::Create(*Context, 0, SourceLocation());
1533    break;
1534  case DECL_CXX_BASE_SPECIFIERS:
1535    Error("attempt to read a C++ base-specifier record as a declaration");
1536    return 0;
1537  }
1538
1539  assert(D && "Unknown declaration reading AST file");
1540  LoadedDecl(Index, D);
1541  Reader.Visit(D);
1542
1543  // If this declaration is also a declaration context, get the
1544  // offsets for its tables of lexical and visible declarations.
1545  if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1546    std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1547    if (Offsets.first || Offsets.second) {
1548      DC->setHasExternalLexicalStorage(Offsets.first != 0);
1549      DC->setHasExternalVisibleStorage(Offsets.second != 0);
1550      DeclContextInfo Info;
1551      if (ReadDeclContextStorage(DeclsCursor, Offsets, Info))
1552        return 0;
1553      DeclContextInfos &Infos = DeclContextOffsets[DC];
1554      // Reading the TU will happen after reading its lexical update blocks,
1555      // so we need to make sure we insert in front. For all other contexts,
1556      // the vector is empty here anyway, so there's no loss in efficiency.
1557      Infos.insert(Infos.begin(), Info);
1558
1559      // Now add the pending visible updates for this decl context, if it has
1560      // any.
1561      DeclContextVisibleUpdatesPending::iterator I =
1562          PendingVisibleUpdates.find(ID);
1563      if (I != PendingVisibleUpdates.end()) {
1564        DeclContextVisibleUpdates &U = I->second;
1565        Info.LexicalDecls = 0;
1566        Info.NumLexicalDecls = 0;
1567        for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
1568             UI != UE; ++UI) {
1569          Info.NameLookupTableData = *UI;
1570          Infos.push_back(Info);
1571        }
1572        PendingVisibleUpdates.erase(I);
1573      }
1574    }
1575  }
1576  assert(Idx == Record.size());
1577
1578  // The declaration may have been modified by files later in the chain.
1579  // If this is the case, read the record containing the updates from each file
1580  // and pass it to ASTDeclReader to make the modifications.
1581  DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
1582  if (UpdI != DeclUpdateOffsets.end()) {
1583    FileOffsetsTy &UpdateOffsets = UpdI->second;
1584    for (FileOffsetsTy::iterator
1585           I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
1586      PerFileData *F = I->first;
1587      uint64_t Offset = I->second;
1588      llvm::BitstreamCursor &Cursor = F->DeclsCursor;
1589      SavedStreamPosition SavedPosition(Cursor);
1590      Cursor.JumpToBit(Offset);
1591      RecordData Record;
1592      unsigned Code = Cursor.ReadCode();
1593      unsigned RecCode = Cursor.ReadRecord(Code, Record);
1594      (void)RecCode;
1595      assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
1596      Reader.UpdateDecl(D, Record);
1597    }
1598  }
1599
1600  // If we have deserialized a declaration that has a definition the
1601  // AST consumer might need to know about, queue it.
1602  // We don't pass it to the consumer immediately because we may be in recursive
1603  // loading, and some declarations may still be initializing.
1604  if (isConsumerInterestedIn(D))
1605    InterestingDecls.push_back(D);
1606
1607  return D;
1608}
1609
1610void ASTDeclReader::UpdateDecl(Decl *D, const RecordData &Record) {
1611  unsigned Idx = 0;
1612  while (Idx < Record.size()) {
1613    switch ((DeclUpdateKind)Record[Idx++]) {
1614    case UPD_CXX_SET_DEFINITIONDATA: {
1615      CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1616      CXXRecordDecl *
1617          DefinitionDecl = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
1618      assert(!RD->DefinitionData && "DefinitionData is already set!");
1619      InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
1620      break;
1621    }
1622
1623    case UPD_CXX_ADDED_IMPLICIT_MEMBER:
1624      cast<CXXRecordDecl>(D)->addedMember(Reader.GetDecl(Record[Idx++]));
1625      break;
1626
1627    case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
1628      // It will be added to the template's specializations set when loaded.
1629      Reader.GetDecl(Record[Idx++]);
1630    }
1631  }
1632}
1633