ASTReaderDecl.cpp revision 76a40219ee5624d78aba167dce02bdbaa930955f
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->EndRangeLoc = ReadSourceLocation(Record, Idx);
399
400  // Read in the parameters.
401  unsigned NumParams = Record[Idx++];
402  llvm::SmallVector<ParmVarDecl *, 16> Params;
403  Params.reserve(NumParams);
404  for (unsigned I = 0; I != NumParams; ++I)
405    Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
406  FD->setParams(*Reader.getContext(), Params.data(), NumParams);
407}
408
409void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
410  VisitNamedDecl(MD);
411  if (Record[Idx++]) {
412    // In practice, this won't be executed (since method definitions
413    // don't occur in header files).
414    MD->setBody(Reader.ReadStmt(F));
415    MD->setSelfDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
416    MD->setCmdDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
417  }
418  MD->setInstanceMethod(Record[Idx++]);
419  MD->setVariadic(Record[Idx++]);
420  MD->setSynthesized(Record[Idx++]);
421  MD->setDefined(Record[Idx++]);
422  MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
423  MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
424  MD->setNumSelectorArgs(unsigned(Record[Idx++]));
425  MD->setResultType(Reader.GetType(Record[Idx++]));
426  MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
427  MD->setEndLoc(ReadSourceLocation(Record, Idx));
428  unsigned NumParams = Record[Idx++];
429  llvm::SmallVector<ParmVarDecl *, 16> Params;
430  Params.reserve(NumParams);
431  for (unsigned I = 0; I != NumParams; ++I)
432    Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
433  MD->setMethodParams(*Reader.getContext(), Params.data(), NumParams,
434                      NumParams);
435}
436
437void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
438  VisitNamedDecl(CD);
439  SourceLocation A = ReadSourceLocation(Record, Idx);
440  SourceLocation B = ReadSourceLocation(Record, Idx);
441  CD->setAtEndRange(SourceRange(A, B));
442}
443
444void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
445  VisitObjCContainerDecl(ID);
446  ID->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtrOrNull());
447  ID->setSuperClass(cast_or_null<ObjCInterfaceDecl>
448                       (Reader.GetDecl(Record[Idx++])));
449
450  // Read the directly referenced protocols and their SourceLocations.
451  unsigned NumProtocols = Record[Idx++];
452  llvm::SmallVector<ObjCProtocolDecl *, 16> Protocols;
453  Protocols.reserve(NumProtocols);
454  for (unsigned I = 0; I != NumProtocols; ++I)
455    Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
456  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
457  ProtoLocs.reserve(NumProtocols);
458  for (unsigned I = 0; I != NumProtocols; ++I)
459    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
460  ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
461                      *Reader.getContext());
462
463  // Read the transitive closure of protocols referenced by this class.
464  NumProtocols = Record[Idx++];
465  Protocols.clear();
466  Protocols.reserve(NumProtocols);
467  for (unsigned I = 0; I != NumProtocols; ++I)
468    Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
469  ID->AllReferencedProtocols.set(Protocols.data(), NumProtocols,
470                                 *Reader.getContext());
471
472  // Read the ivars.
473  unsigned NumIvars = Record[Idx++];
474  llvm::SmallVector<ObjCIvarDecl *, 16> IVars;
475  IVars.reserve(NumIvars);
476  for (unsigned I = 0; I != NumIvars; ++I)
477    IVars.push_back(cast<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
478  ID->setCategoryList(
479               cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
480  // We will rebuild this list lazily.
481  ID->setIvarList(0);
482  ID->setForwardDecl(Record[Idx++]);
483  ID->setImplicitInterfaceDecl(Record[Idx++]);
484  ID->setClassLoc(ReadSourceLocation(Record, Idx));
485  ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
486  ID->setLocEnd(ReadSourceLocation(Record, Idx));
487}
488
489void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
490  VisitFieldDecl(IVD);
491  IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
492  // This field will be built lazily.
493  IVD->setNextIvar(0);
494  bool synth = Record[Idx++];
495  IVD->setSynthesize(synth);
496}
497
498void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
499  VisitObjCContainerDecl(PD);
500  PD->setForwardDecl(Record[Idx++]);
501  PD->setLocEnd(ReadSourceLocation(Record, Idx));
502  unsigned NumProtoRefs = Record[Idx++];
503  llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
504  ProtoRefs.reserve(NumProtoRefs);
505  for (unsigned I = 0; I != NumProtoRefs; ++I)
506    ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
507  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
508  ProtoLocs.reserve(NumProtoRefs);
509  for (unsigned I = 0; I != NumProtoRefs; ++I)
510    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
511  PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
512                      *Reader.getContext());
513}
514
515void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
516  VisitFieldDecl(FD);
517}
518
519void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
520  VisitDecl(CD);
521  unsigned NumClassRefs = Record[Idx++];
522  llvm::SmallVector<ObjCInterfaceDecl *, 16> ClassRefs;
523  ClassRefs.reserve(NumClassRefs);
524  for (unsigned I = 0; I != NumClassRefs; ++I)
525    ClassRefs.push_back(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
526  llvm::SmallVector<SourceLocation, 16> SLocs;
527  SLocs.reserve(NumClassRefs);
528  for (unsigned I = 0; I != NumClassRefs; ++I)
529    SLocs.push_back(ReadSourceLocation(Record, Idx));
530  CD->setClassList(*Reader.getContext(), ClassRefs.data(), SLocs.data(),
531                   NumClassRefs);
532}
533
534void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
535  VisitDecl(FPD);
536  unsigned NumProtoRefs = Record[Idx++];
537  llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
538  ProtoRefs.reserve(NumProtoRefs);
539  for (unsigned I = 0; I != NumProtoRefs; ++I)
540    ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
541  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
542  ProtoLocs.reserve(NumProtoRefs);
543  for (unsigned I = 0; I != NumProtoRefs; ++I)
544    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
545  FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
546                       *Reader.getContext());
547}
548
549void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
550  VisitObjCContainerDecl(CD);
551  CD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
552  unsigned NumProtoRefs = Record[Idx++];
553  llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
554  ProtoRefs.reserve(NumProtoRefs);
555  for (unsigned I = 0; I != NumProtoRefs; ++I)
556    ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
557  llvm::SmallVector<SourceLocation, 16> ProtoLocs;
558  ProtoLocs.reserve(NumProtoRefs);
559  for (unsigned I = 0; I != NumProtoRefs; ++I)
560    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
561  CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
562                      *Reader.getContext());
563  CD->setNextClassCategory(cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
564  CD->setHasSynthBitfield(Record[Idx++]);
565  CD->setAtLoc(ReadSourceLocation(Record, Idx));
566  CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
567}
568
569void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
570  VisitNamedDecl(CAD);
571  CAD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
572}
573
574void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
575  VisitNamedDecl(D);
576  D->setAtLoc(ReadSourceLocation(Record, Idx));
577  D->setType(GetTypeSourceInfo(Record, Idx));
578  // FIXME: stable encoding
579  D->setPropertyAttributes(
580                      (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
581  D->setPropertyAttributesAsWritten(
582                      (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
583  // FIXME: stable encoding
584  D->setPropertyImplementation(
585                            (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
586  D->setGetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
587  D->setSetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
588  D->setGetterMethodDecl(
589                 cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
590  D->setSetterMethodDecl(
591                 cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
592  D->setPropertyIvarDecl(
593                   cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
594}
595
596void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
597  VisitObjCContainerDecl(D);
598  D->setClassInterface(
599              cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
600}
601
602void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
603  VisitObjCImplDecl(D);
604  D->setIdentifier(Reader.GetIdentifierInfo(Record, Idx));
605}
606
607void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
608  VisitObjCImplDecl(D);
609  D->setSuperClass(
610              cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
611  llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
612      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
613  D->setHasSynthBitfield(Record[Idx++]);
614}
615
616
617void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
618  VisitDecl(D);
619  D->setAtLoc(ReadSourceLocation(Record, Idx));
620  D->setPropertyDecl(
621               cast_or_null<ObjCPropertyDecl>(Reader.GetDecl(Record[Idx++])));
622  D->PropertyIvarDecl =
623                   cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++]));
624  D->IvarLoc = ReadSourceLocation(Record, Idx);
625  D->setGetterCXXConstructor(Reader.ReadExpr(F));
626  D->setSetterCXXAssignment(Reader.ReadExpr(F));
627}
628
629void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
630  VisitDeclaratorDecl(FD);
631  FD->setMutable(Record[Idx++]);
632  if (Record[Idx++])
633    FD->setBitWidth(Reader.ReadExpr(F));
634  if (!FD->getDeclName()) {
635    FieldDecl *Tmpl = cast_or_null<FieldDecl>(Reader.GetDecl(Record[Idx++]));
636    if (Tmpl)
637      Reader.getContext()->setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
638  }
639}
640
641void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
642  VisitValueDecl(FD);
643
644  FD->ChainingSize = Record[Idx++];
645  assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
646  FD->Chaining = new (*Reader.getContext())NamedDecl*[FD->ChainingSize];
647
648  for (unsigned I = 0; I != FD->ChainingSize; ++I)
649    FD->Chaining[I] = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
650}
651
652void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
653  VisitDeclaratorDecl(VD);
654  VisitRedeclarable(VD);
655  VD->SClass = (StorageClass)Record[Idx++];
656  VD->setStorageClassAsWritten((StorageClass)Record[Idx++]);
657  VD->setThreadSpecified(Record[Idx++]);
658  VD->setCXXDirectInitializer(Record[Idx++]);
659  VD->setExceptionVariable(Record[Idx++]);
660  VD->setNRVOVariable(Record[Idx++]);
661  if (Record[Idx++])
662    VD->setInit(Reader.ReadExpr(F));
663
664  if (Record[Idx++]) { // HasMemberSpecializationInfo.
665    VarDecl *Tmpl = cast<VarDecl>(Reader.GetDecl(Record[Idx++]));
666    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
667    SourceLocation POI = ReadSourceLocation(Record, Idx);
668    Reader.getContext()->setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
669  }
670}
671
672void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
673  VisitVarDecl(PD);
674}
675
676void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
677  VisitVarDecl(PD);
678  PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
679  PD->setHasInheritedDefaultArg(Record[Idx++]);
680  if (Record[Idx++]) // hasUninstantiatedDefaultArg.
681    PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
682}
683
684void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
685  VisitDecl(AD);
686  AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
687}
688
689void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
690  VisitDecl(BD);
691  BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
692  BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
693  unsigned NumParams = Record[Idx++];
694  llvm::SmallVector<ParmVarDecl *, 16> Params;
695  Params.reserve(NumParams);
696  for (unsigned I = 0; I != NumParams; ++I)
697    Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
698  BD->setParams(Params.data(), NumParams);
699
700  bool capturesCXXThis = Record[Idx++];
701  unsigned numCaptures = Record[Idx++];
702  llvm::SmallVector<BlockDecl::Capture, 16> captures;
703  captures.reserve(numCaptures);
704  for (unsigned i = 0; i != numCaptures; ++i) {
705    VarDecl *decl = cast<VarDecl>(Reader.GetDecl(Record[Idx++]));
706    unsigned flags = Record[Idx++];
707    bool byRef = (flags & 1);
708    bool nested = (flags & 2);
709    Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
710
711    captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
712  }
713  BD->setCaptures(*Reader.getContext(), captures.begin(),
714                  captures.end(), capturesCXXThis);
715}
716
717void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
718  VisitDecl(D);
719  D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
720  D->setHasBraces(Record[Idx++]);
721}
722
723void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
724  VisitNamedDecl(D);
725  D->IsInline = Record[Idx++];
726  D->LBracLoc = ReadSourceLocation(Record, Idx);
727  D->RBracLoc = ReadSourceLocation(Record, Idx);
728  D->NextNamespace = Record[Idx++];
729
730  bool IsOriginal = Record[Idx++];
731  D->OrigOrAnonNamespace.setInt(IsOriginal);
732  D->OrigOrAnonNamespace.setPointer(
733                    cast_or_null<NamespaceDecl>(Reader.GetDecl(Record[Idx++])));
734}
735
736void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
737  VisitNamedDecl(D);
738  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
739  D->setQualifierRange(ReadSourceRange(Record, Idx));
740  D->setQualifier(Reader.ReadNestedNameSpecifier(Record, Idx));
741  D->IdentLoc = ReadSourceLocation(Record, Idx);
742  D->Namespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
743}
744
745void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
746  VisitNamedDecl(D);
747  D->setUsingLocation(ReadSourceLocation(Record, Idx));
748  D->setNestedNameRange(ReadSourceRange(Record, Idx));
749  D->setTargetNestedNameDecl(Reader.ReadNestedNameSpecifier(Record, Idx));
750  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
751  D->FirstUsingShadow = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
752  D->setTypeName(Record[Idx++]);
753  NamedDecl *Pattern = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
754  if (Pattern)
755    Reader.getContext()->setInstantiatedFromUsingDecl(D, Pattern);
756}
757
758void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
759  VisitNamedDecl(D);
760  D->setTargetDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
761  D->UsingOrNextShadow = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
762  UsingShadowDecl *Pattern
763      = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
764  if (Pattern)
765    Reader.getContext()->setInstantiatedFromUsingShadowDecl(D, Pattern);
766}
767
768void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
769  VisitNamedDecl(D);
770  D->UsingLoc = ReadSourceLocation(Record, Idx);
771  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
772  D->QualifierRange = ReadSourceRange(Record, Idx);
773  D->Qualifier = Reader.ReadNestedNameSpecifier(Record, Idx);
774  D->NominatedNamespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
775  D->CommonAncestor = cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++]));
776}
777
778void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
779  VisitValueDecl(D);
780  D->setTargetNestedNameRange(ReadSourceRange(Record, Idx));
781  D->setUsingLoc(ReadSourceLocation(Record, Idx));
782  D->setTargetNestedNameSpecifier(Reader.ReadNestedNameSpecifier(Record, Idx));
783  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
784}
785
786void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
787                                               UnresolvedUsingTypenameDecl *D) {
788  VisitTypeDecl(D);
789  D->TargetNestedNameRange = ReadSourceRange(Record, Idx);
790  D->UsingLocation = ReadSourceLocation(Record, Idx);
791  D->TypenameLocation = ReadSourceLocation(Record, Idx);
792  D->TargetNestedNameSpecifier = Reader.ReadNestedNameSpecifier(Record, Idx);
793}
794
795void ASTDeclReader::ReadCXXDefinitionData(
796                                   struct CXXRecordDecl::DefinitionData &Data,
797                                   const RecordData &Record, unsigned &Idx) {
798  Data.UserDeclaredConstructor = Record[Idx++];
799  Data.UserDeclaredCopyConstructor = Record[Idx++];
800  Data.UserDeclaredCopyAssignment = Record[Idx++];
801  Data.UserDeclaredDestructor = Record[Idx++];
802  Data.Aggregate = Record[Idx++];
803  Data.PlainOldData = Record[Idx++];
804  Data.Empty = Record[Idx++];
805  Data.Polymorphic = Record[Idx++];
806  Data.Abstract = Record[Idx++];
807  Data.HasTrivialConstructor = Record[Idx++];
808  Data.HasTrivialCopyConstructor = Record[Idx++];
809  Data.HasTrivialCopyAssignment = Record[Idx++];
810  Data.HasTrivialDestructor = Record[Idx++];
811  Data.ComputedVisibleConversions = Record[Idx++];
812  Data.DeclaredDefaultConstructor = Record[Idx++];
813  Data.DeclaredCopyConstructor = Record[Idx++];
814  Data.DeclaredCopyAssignment = Record[Idx++];
815  Data.DeclaredDestructor = Record[Idx++];
816
817  Data.NumBases = Record[Idx++];
818  if (Data.NumBases)
819    Data.Bases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
820  Data.NumVBases = Record[Idx++];
821  if (Data.NumVBases)
822    Data.VBases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
823
824  Reader.ReadUnresolvedSet(Data.Conversions, Record, Idx);
825  Reader.ReadUnresolvedSet(Data.VisibleConversions, Record, Idx);
826  assert(Data.Definition && "Data.Definition should be already set!");
827  Data.FirstFriend
828      = cast_or_null<FriendDecl>(Reader.GetDecl(Record[Idx++]));
829}
830
831void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
832                                                CXXRecordDecl *DefinitionDecl,
833                                                const RecordData &Record,
834                                                unsigned &Idx) {
835  ASTContext &C = *Reader.getContext();
836
837  if (D == DefinitionDecl) {
838    D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
839    ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
840    // We read the definition info. Check if there are pending forward
841    // references that need to point to this DefinitionData pointer.
842    ASTReader::PendingForwardRefsMap::iterator
843        FindI = Reader.PendingForwardRefs.find(D);
844    if (FindI != Reader.PendingForwardRefs.end()) {
845      ASTReader::ForwardRefs &Refs = FindI->second;
846      for (ASTReader::ForwardRefs::iterator
847             I = Refs.begin(), E = Refs.end(); I != E; ++I)
848        (*I)->DefinitionData = D->DefinitionData;
849#ifndef NDEBUG
850      // We later check whether PendingForwardRefs is empty to make sure all
851      // pending references were linked.
852      Reader.PendingForwardRefs.erase(D);
853#endif
854    }
855  } else if (DefinitionDecl) {
856    if (DefinitionDecl->DefinitionData) {
857      D->DefinitionData = DefinitionDecl->DefinitionData;
858    } else {
859      // The definition is still initializing.
860      Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
861    }
862  }
863}
864
865void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
866  VisitRecordDecl(D);
867
868  CXXRecordDecl *DefinitionDecl
869      = cast_or_null<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
870  InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
871
872  ASTContext &C = *Reader.getContext();
873
874  enum CXXRecKind {
875    CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
876  };
877  switch ((CXXRecKind)Record[Idx++]) {
878  default:
879    assert(false && "Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
880  case CXXRecNotTemplate:
881    break;
882  case CXXRecTemplate:
883    D->TemplateOrInstantiation
884        = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
885    break;
886  case CXXRecMemberSpecialization: {
887    CXXRecordDecl *RD = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
888    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
889    SourceLocation POI = ReadSourceLocation(Record, Idx);
890    MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
891    MSI->setPointOfInstantiation(POI);
892    D->TemplateOrInstantiation = MSI;
893    break;
894  }
895  }
896
897  // Load the key function to avoid deserializing every method so we can
898  // compute it.
899  if (D->IsDefinition) {
900    CXXMethodDecl *Key
901        = cast_or_null<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
902    if (Key)
903      C.KeyFunctions[D] = Key;
904  }
905}
906
907void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
908  VisitFunctionDecl(D);
909  unsigned NumOverridenMethods = Record[Idx++];
910  while (NumOverridenMethods--) {
911    CXXMethodDecl *MD = cast<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
912    // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
913    // MD may be initializing.
914    Reader.getContext()->addOverriddenMethod(D, MD);
915  }
916}
917
918void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
919  VisitCXXMethodDecl(D);
920
921  D->IsExplicitSpecified = Record[Idx++];
922  D->ImplicitlyDefined = Record[Idx++];
923  llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
924      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
925}
926
927void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
928  VisitCXXMethodDecl(D);
929
930  D->ImplicitlyDefined = Record[Idx++];
931  D->OperatorDelete = cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++]));
932}
933
934void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
935  VisitCXXMethodDecl(D);
936  D->IsExplicitSpecified = Record[Idx++];
937}
938
939void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
940  VisitDecl(D);
941  D->setColonLoc(ReadSourceLocation(Record, Idx));
942}
943
944void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
945  VisitDecl(D);
946  if (Record[Idx++])
947    D->Friend = GetTypeSourceInfo(Record, Idx);
948  else
949    D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
950  D->NextFriend = Record[Idx++];
951  D->UnsupportedFriend = (Record[Idx++] != 0);
952  D->FriendLoc = ReadSourceLocation(Record, Idx);
953}
954
955void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
956  VisitDecl(D);
957  unsigned NumParams = Record[Idx++];
958  D->NumParams = NumParams;
959  D->Params = new TemplateParameterList*[NumParams];
960  for (unsigned i = 0; i != NumParams; ++i)
961    D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
962  if (Record[Idx++]) // HasFriendDecl
963    D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
964  else
965    D->Friend = GetTypeSourceInfo(Record, Idx);
966  D->FriendLoc = ReadSourceLocation(Record, Idx);
967}
968
969void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
970  VisitNamedDecl(D);
971
972  NamedDecl *TemplatedDecl
973    = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
974  TemplateParameterList* TemplateParams
975      = Reader.ReadTemplateParameterList(F, Record, Idx);
976  D->init(TemplatedDecl, TemplateParams);
977}
978
979void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
980  // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
981  // can be used while this is still initializing.
982
983  assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
984  RedeclarableTemplateDecl *PrevDecl =
985      cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
986  assert((PrevDecl == 0 || PrevDecl->getKind() == D->getKind()) &&
987         "PrevDecl kind mismatch");
988  if (PrevDecl)
989    D->CommonOrPrev = PrevDecl;
990  if (PrevDecl == 0) {
991    D->CommonOrPrev = D->newCommon(*Reader.getContext());
992    if (RedeclarableTemplateDecl *RTD
993          = cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]))) {
994      assert(RTD->getKind() == D->getKind() &&
995             "InstantiatedFromMemberTemplate kind mismatch");
996      D->setInstantiatedFromMemberTemplateImpl(RTD);
997      if (Record[Idx++])
998        D->setMemberSpecialization();
999    }
1000
1001    RedeclarableTemplateDecl *LatestDecl =
1002        cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
1003
1004    // This decl is a first one and the latest declaration that it points to is
1005    // in the same AST file. However, if this actually needs to point to a
1006    // redeclaration in another AST file, we need to update it by checking
1007    // the FirstLatestDeclIDs map which tracks this kind of decls.
1008    assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
1009    ASTReader::FirstLatestDeclIDMap::iterator I
1010        = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1011    if (I != Reader.FirstLatestDeclIDs.end()) {
1012      Decl *NewLatest = Reader.GetDecl(I->second);
1013      assert((LatestDecl->getLocation().isInvalid() ||
1014              NewLatest->getLocation().isInvalid()  ||
1015              !Reader.SourceMgr.isBeforeInTranslationUnit(
1016                                                  NewLatest->getLocation(),
1017                                                  LatestDecl->getLocation())) &&
1018             "The new latest is supposed to come after the previous latest");
1019      LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
1020    }
1021
1022    assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
1023    D->getCommonPtr()->Latest = LatestDecl;
1024  }
1025
1026  VisitTemplateDecl(D);
1027  D->IdentifierNamespace = Record[Idx++];
1028}
1029
1030void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1031  VisitRedeclarableTemplateDecl(D);
1032
1033  if (D->getPreviousDeclaration() == 0) {
1034    // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1035    // the specializations.
1036    llvm::SmallVector<serialization::DeclID, 2> SpecIDs;
1037    SpecIDs.push_back(0);
1038
1039    // Specializations.
1040    unsigned Size = Record[Idx++];
1041    SpecIDs[0] += Size;
1042    SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1043    Idx += Size;
1044
1045    // Partial specializations.
1046    Size = Record[Idx++];
1047    SpecIDs[0] += Size;
1048    SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1049    Idx += Size;
1050
1051    if (SpecIDs[0]) {
1052      typedef serialization::DeclID DeclID;
1053
1054      ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1055      CommonPtr->LazySpecializations
1056        = new (*Reader.getContext()) DeclID [SpecIDs.size()];
1057      memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1058             SpecIDs.size() * sizeof(DeclID));
1059    }
1060
1061    // InjectedClassNameType is computed.
1062  }
1063}
1064
1065void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1066                                           ClassTemplateSpecializationDecl *D) {
1067  VisitCXXRecordDecl(D);
1068
1069  ASTContext &C = *Reader.getContext();
1070  if (Decl *InstD = Reader.GetDecl(Record[Idx++])) {
1071    if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1072      D->SpecializedTemplate = CTD;
1073    } else {
1074      llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1075      Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1076      TemplateArgumentList *ArgList
1077        = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1078                                           TemplArgs.size());
1079      ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1080          = new (C) ClassTemplateSpecializationDecl::
1081                                             SpecializedPartialSpecialization();
1082      PS->PartialSpecialization
1083          = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1084      PS->TemplateArgs = ArgList;
1085      D->SpecializedTemplate = PS;
1086    }
1087  }
1088
1089  // Explicit info.
1090  if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1091    ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1092        = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1093    ExplicitInfo->TypeAsWritten = TyInfo;
1094    ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1095    ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1096    D->ExplicitInfo = ExplicitInfo;
1097  }
1098
1099  llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1100  Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1101  D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1102                                                     TemplArgs.size());
1103  D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1104  D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1105
1106  if (D->isCanonicalDecl()) { // It's kept in the folding set.
1107    ClassTemplateDecl *CanonPattern
1108                       = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
1109    if (ClassTemplatePartialSpecializationDecl *Partial
1110                       = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1111      CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1112    } else {
1113      CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1114    }
1115  }
1116}
1117
1118void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1119                                    ClassTemplatePartialSpecializationDecl *D) {
1120  VisitClassTemplateSpecializationDecl(D);
1121
1122  ASTContext &C = *Reader.getContext();
1123  D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1124
1125  unsigned NumArgs = Record[Idx++];
1126  if (NumArgs) {
1127    D->NumArgsAsWritten = NumArgs;
1128    D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1129    for (unsigned i=0; i != NumArgs; ++i)
1130      D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1131  }
1132
1133  D->SequenceNumber = Record[Idx++];
1134
1135  // These are read/set from/to the first declaration.
1136  if (D->getPreviousDeclaration() == 0) {
1137    D->InstantiatedFromMember.setPointer(
1138        cast_or_null<ClassTemplatePartialSpecializationDecl>(
1139                                                Reader.GetDecl(Record[Idx++])));
1140    D->InstantiatedFromMember.setInt(Record[Idx++]);
1141  }
1142}
1143
1144void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1145  VisitRedeclarableTemplateDecl(D);
1146
1147  if (D->getPreviousDeclaration() == 0) {
1148    // This FunctionTemplateDecl owns a CommonPtr; read it.
1149
1150    // Read the function specialization declarations.
1151    // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1152    // when reading the specialized FunctionDecl.
1153    unsigned NumSpecs = Record[Idx++];
1154    while (NumSpecs--)
1155      Reader.GetDecl(Record[Idx++]);
1156  }
1157}
1158
1159void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1160  VisitTypeDecl(D);
1161
1162  D->setDeclaredWithTypename(Record[Idx++]);
1163  D->setParameterPack(Record[Idx++]);
1164
1165  bool Inherited = Record[Idx++];
1166  TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1167  D->setDefaultArgument(DefArg, Inherited);
1168}
1169
1170void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1171  VisitDeclaratorDecl(D);
1172  // TemplateParmPosition.
1173  D->setDepth(Record[Idx++]);
1174  D->setPosition(Record[Idx++]);
1175  if (D->isExpandedParameterPack()) {
1176    void **Data = reinterpret_cast<void **>(D + 1);
1177    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1178      Data[2*I] = Reader.GetType(Record[Idx++]).getAsOpaquePtr();
1179      Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1180    }
1181  } else {
1182    // Rest of NonTypeTemplateParmDecl.
1183    D->ParameterPack = Record[Idx++];
1184    if (Record[Idx++]) {
1185      Expr *DefArg = Reader.ReadExpr(F);
1186      bool Inherited = Record[Idx++];
1187      D->setDefaultArgument(DefArg, Inherited);
1188   }
1189  }
1190}
1191
1192void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1193  VisitTemplateDecl(D);
1194  // TemplateParmPosition.
1195  D->setDepth(Record[Idx++]);
1196  D->setPosition(Record[Idx++]);
1197  // Rest of TemplateTemplateParmDecl.
1198  TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1199  bool IsInherited = Record[Idx++];
1200  D->setDefaultArgument(Arg, IsInherited);
1201  D->ParameterPack = Record[Idx++];
1202}
1203
1204void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1205  VisitDecl(D);
1206  D->AssertExpr = Reader.ReadExpr(F);
1207  D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1208}
1209
1210std::pair<uint64_t, uint64_t>
1211ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1212  uint64_t LexicalOffset = Record[Idx++];
1213  uint64_t VisibleOffset = Record[Idx++];
1214  return std::make_pair(LexicalOffset, VisibleOffset);
1215}
1216
1217template <typename T>
1218void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1219  enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1220  RedeclKind Kind = (RedeclKind)Record[Idx++];
1221  switch (Kind) {
1222  default:
1223    assert(0 && "Out of sync with ASTDeclWriter::VisitRedeclarable or messed up"
1224                " reading");
1225  case NoRedeclaration:
1226    break;
1227  case PointsToPrevious:
1228    D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(
1229                                cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1230    break;
1231  case PointsToLatest:
1232    D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(
1233                                cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1234    break;
1235  }
1236
1237  assert(!(Kind == PointsToPrevious &&
1238           Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
1239               Reader.FirstLatestDeclIDs.end()) &&
1240         "This decl is not first, it should not be in the map");
1241  if (Kind == PointsToPrevious)
1242    return;
1243
1244  // This decl is a first one and the latest declaration that it points to is in
1245  // the same AST file. However, if this actually needs to point to a
1246  // redeclaration in another AST file, we need to update it by checking the
1247  // FirstLatestDeclIDs map which tracks this kind of decls.
1248  assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
1249         "Invalid ThisDeclID ?");
1250  ASTReader::FirstLatestDeclIDMap::iterator I
1251      = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1252  if (I != Reader.FirstLatestDeclIDs.end()) {
1253    Decl *NewLatest = Reader.GetDecl(I->second);
1254    D->RedeclLink
1255        = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
1256  }
1257}
1258
1259//===----------------------------------------------------------------------===//
1260// Attribute Reading
1261//===----------------------------------------------------------------------===//
1262
1263/// \brief Reads attributes from the current stream position.
1264void ASTReader::ReadAttributes(PerFileData &F, AttrVec &Attrs,
1265                               const RecordData &Record, unsigned &Idx) {
1266  for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1267    Attr *New = 0;
1268    attr::Kind Kind = (attr::Kind)Record[Idx++];
1269    SourceLocation Loc = ReadSourceLocation(F, Record, Idx);
1270
1271#include "clang/Serialization/AttrPCHRead.inc"
1272
1273    assert(New && "Unable to decode attribute?");
1274    Attrs.push_back(New);
1275  }
1276}
1277
1278//===----------------------------------------------------------------------===//
1279// ASTReader Implementation
1280//===----------------------------------------------------------------------===//
1281
1282/// \brief Note that we have loaded the declaration with the given
1283/// Index.
1284///
1285/// This routine notes that this declaration has already been loaded,
1286/// so that future GetDecl calls will return this declaration rather
1287/// than trying to load a new declaration.
1288inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1289  assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1290  DeclsLoaded[Index] = D;
1291}
1292
1293
1294/// \brief Determine whether the consumer will be interested in seeing
1295/// this declaration (via HandleTopLevelDecl).
1296///
1297/// This routine should return true for anything that might affect
1298/// code generation, e.g., inline function definitions, Objective-C
1299/// declarations with metadata, etc.
1300static bool isConsumerInterestedIn(Decl *D) {
1301  if (isa<FileScopeAsmDecl>(D))
1302    return true;
1303  if (VarDecl *Var = dyn_cast<VarDecl>(D))
1304    return Var->isFileVarDecl() &&
1305           Var->isThisDeclarationADefinition() == VarDecl::Definition;
1306  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1307    return Func->isThisDeclarationADefinition();
1308  return isa<ObjCProtocolDecl>(D) || isa<ObjCImplementationDecl>(D);
1309}
1310
1311/// \brief Get the correct cursor and offset for loading a type.
1312ASTReader::RecordLocation
1313ASTReader::DeclCursorForIndex(unsigned Index, DeclID ID) {
1314  // See if there's an override.
1315  DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1316  if (It != ReplacedDecls.end())
1317    return RecordLocation(It->second.first, It->second.second);
1318
1319  PerFileData *F = 0;
1320  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1321    F = Chain[N - I - 1];
1322    if (Index < F->LocalNumDecls)
1323      break;
1324    Index -= F->LocalNumDecls;
1325  }
1326  assert(F && F->LocalNumDecls > Index && "Broken chain");
1327  return RecordLocation(F, F->DeclOffsets[Index]);
1328}
1329
1330/// \brief Read the declaration at the given offset from the AST file.
1331Decl *ASTReader::ReadDeclRecord(unsigned Index, DeclID ID) {
1332  RecordLocation Loc = DeclCursorForIndex(Index, ID);
1333  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1334  // Keep track of where we are in the stream, then jump back there
1335  // after reading this declaration.
1336  SavedStreamPosition SavedPosition(DeclsCursor);
1337
1338  ReadingKindTracker ReadingKind(Read_Decl, *this);
1339
1340  // Note that we are loading a declaration record.
1341  Deserializing ADecl(this);
1342
1343  DeclsCursor.JumpToBit(Loc.Offset);
1344  RecordData Record;
1345  unsigned Code = DeclsCursor.ReadCode();
1346  unsigned Idx = 0;
1347  ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, Record, Idx);
1348
1349  Decl *D = 0;
1350  switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1351  case DECL_CONTEXT_LEXICAL:
1352  case DECL_CONTEXT_VISIBLE:
1353    assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1354    break;
1355  case DECL_TRANSLATION_UNIT:
1356    assert(Index == 0 && "Translation unit must be at index 0");
1357    D = Context->getTranslationUnitDecl();
1358    break;
1359  case DECL_TYPEDEF:
1360    D = TypedefDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1361    break;
1362  case DECL_ENUM:
1363    D = EnumDecl::Create(*Context, Decl::EmptyShell());
1364    break;
1365  case DECL_RECORD:
1366    D = RecordDecl::Create(*Context, Decl::EmptyShell());
1367    break;
1368  case DECL_ENUM_CONSTANT:
1369    D = EnumConstantDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1370                                 0, llvm::APSInt());
1371    break;
1372  case DECL_FUNCTION:
1373    D = FunctionDecl::Create(*Context, 0, SourceLocation(), DeclarationName(),
1374                             QualType(), 0);
1375    break;
1376  case DECL_LINKAGE_SPEC:
1377    D = LinkageSpecDecl::Create(*Context, 0, SourceLocation(),
1378                                (LinkageSpecDecl::LanguageIDs)0,
1379                                false);
1380    break;
1381  case DECL_NAMESPACE:
1382    D = NamespaceDecl::Create(*Context, 0, SourceLocation(), 0);
1383    break;
1384  case DECL_NAMESPACE_ALIAS:
1385    D = NamespaceAliasDecl::Create(*Context, 0, SourceLocation(),
1386                                   SourceLocation(), 0, SourceRange(), 0,
1387                                   SourceLocation(), 0);
1388    break;
1389  case DECL_USING:
1390    D = UsingDecl::Create(*Context, 0, SourceRange(), SourceLocation(),
1391                          0, DeclarationNameInfo(), false);
1392    break;
1393  case DECL_USING_SHADOW:
1394    D = UsingShadowDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1395    break;
1396  case DECL_USING_DIRECTIVE:
1397    D = UsingDirectiveDecl::Create(*Context, 0, SourceLocation(),
1398                                   SourceLocation(), SourceRange(), 0,
1399                                   SourceLocation(), 0, 0);
1400    break;
1401  case DECL_UNRESOLVED_USING_VALUE:
1402    D = UnresolvedUsingValueDecl::Create(*Context, 0, SourceLocation(),
1403                                         SourceRange(), 0,
1404                                         DeclarationNameInfo());
1405    break;
1406  case DECL_UNRESOLVED_USING_TYPENAME:
1407    D = UnresolvedUsingTypenameDecl::Create(*Context, 0, SourceLocation(),
1408                                            SourceLocation(), SourceRange(),
1409                                            0, SourceLocation(),
1410                                            DeclarationName());
1411    break;
1412  case DECL_CXX_RECORD:
1413    D = CXXRecordDecl::Create(*Context, Decl::EmptyShell());
1414    break;
1415  case DECL_CXX_METHOD:
1416    D = CXXMethodDecl::Create(*Context, 0, DeclarationNameInfo(),
1417                              QualType(), 0);
1418    break;
1419  case DECL_CXX_CONSTRUCTOR:
1420    D = CXXConstructorDecl::Create(*Context, Decl::EmptyShell());
1421    break;
1422  case DECL_CXX_DESTRUCTOR:
1423    D = CXXDestructorDecl::Create(*Context, Decl::EmptyShell());
1424    break;
1425  case DECL_CXX_CONVERSION:
1426    D = CXXConversionDecl::Create(*Context, Decl::EmptyShell());
1427    break;
1428  case DECL_ACCESS_SPEC:
1429    D = AccessSpecDecl::Create(*Context, Decl::EmptyShell());
1430    break;
1431  case DECL_FRIEND:
1432    D = FriendDecl::Create(*Context, Decl::EmptyShell());
1433    break;
1434  case DECL_FRIEND_TEMPLATE:
1435    D = FriendTemplateDecl::Create(*Context, Decl::EmptyShell());
1436    break;
1437  case DECL_CLASS_TEMPLATE:
1438    D = ClassTemplateDecl::Create(*Context, 0, SourceLocation(),
1439                                  DeclarationName(), 0, 0, 0);
1440    break;
1441  case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1442    D = ClassTemplateSpecializationDecl::Create(*Context, Decl::EmptyShell());
1443    break;
1444  case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1445    D = ClassTemplatePartialSpecializationDecl::Create(*Context,
1446                                                            Decl::EmptyShell());
1447    break;
1448  case DECL_FUNCTION_TEMPLATE:
1449    D = FunctionTemplateDecl::Create(*Context, 0, SourceLocation(),
1450                                     DeclarationName(), 0, 0);
1451    break;
1452  case DECL_TEMPLATE_TYPE_PARM:
1453    D = TemplateTypeParmDecl::Create(*Context, Decl::EmptyShell());
1454    break;
1455  case DECL_NON_TYPE_TEMPLATE_PARM:
1456    D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0,0,0,
1457                                        QualType(), false, 0);
1458    break;
1459  case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1460    D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1461                                        0, QualType(), 0, 0, Record[Idx++],
1462                                        0);
1463    break;
1464  case DECL_TEMPLATE_TEMPLATE_PARM:
1465    D = TemplateTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1466                                         false, 0, 0);
1467    break;
1468  case DECL_STATIC_ASSERT:
1469    D = StaticAssertDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1470    break;
1471
1472  case DECL_OBJC_METHOD:
1473    D = ObjCMethodDecl::Create(*Context, SourceLocation(), SourceLocation(),
1474                               Selector(), QualType(), 0, 0);
1475    break;
1476  case DECL_OBJC_INTERFACE:
1477    D = ObjCInterfaceDecl::Create(*Context, 0, SourceLocation(), 0);
1478    break;
1479  case DECL_OBJC_IVAR:
1480    D = ObjCIvarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1481                             ObjCIvarDecl::None);
1482    break;
1483  case DECL_OBJC_PROTOCOL:
1484    D = ObjCProtocolDecl::Create(*Context, 0, SourceLocation(), 0);
1485    break;
1486  case DECL_OBJC_AT_DEFS_FIELD:
1487    D = ObjCAtDefsFieldDecl::Create(*Context, 0, SourceLocation(), 0,
1488                                    QualType(), 0);
1489    break;
1490  case DECL_OBJC_CLASS:
1491    D = ObjCClassDecl::Create(*Context, 0, SourceLocation());
1492    break;
1493  case DECL_OBJC_FORWARD_PROTOCOL:
1494    D = ObjCForwardProtocolDecl::Create(*Context, 0, SourceLocation());
1495    break;
1496  case DECL_OBJC_CATEGORY:
1497    D = ObjCCategoryDecl::Create(*Context, 0, SourceLocation(),
1498                                 SourceLocation(), SourceLocation(), 0);
1499    break;
1500  case DECL_OBJC_CATEGORY_IMPL:
1501    D = ObjCCategoryImplDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1502    break;
1503  case DECL_OBJC_IMPLEMENTATION:
1504    D = ObjCImplementationDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1505    break;
1506  case DECL_OBJC_COMPATIBLE_ALIAS:
1507    D = ObjCCompatibleAliasDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1508    break;
1509  case DECL_OBJC_PROPERTY:
1510    D = ObjCPropertyDecl::Create(*Context, 0, SourceLocation(), 0, SourceLocation(),
1511                                 0);
1512    break;
1513  case DECL_OBJC_PROPERTY_IMPL:
1514    D = ObjCPropertyImplDecl::Create(*Context, 0, SourceLocation(),
1515                                     SourceLocation(), 0,
1516                                     ObjCPropertyImplDecl::Dynamic, 0,
1517                                     SourceLocation());
1518    break;
1519  case DECL_FIELD:
1520    D = FieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, 0,
1521                          false);
1522    break;
1523  case DECL_INDIRECTFIELD:
1524    D = IndirectFieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1525                                  0, 0);
1526    break;
1527  case DECL_VAR:
1528    D = VarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1529                        SC_None, SC_None);
1530    break;
1531
1532  case DECL_IMPLICIT_PARAM:
1533    D = ImplicitParamDecl::Create(*Context, 0, SourceLocation(), 0, QualType());
1534    break;
1535
1536  case DECL_PARM_VAR:
1537    D = ParmVarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1538                            SC_None, SC_None, 0);
1539    break;
1540  case DECL_FILE_SCOPE_ASM:
1541    D = FileScopeAsmDecl::Create(*Context, 0, SourceLocation(), 0);
1542    break;
1543  case DECL_BLOCK:
1544    D = BlockDecl::Create(*Context, 0, SourceLocation());
1545    break;
1546  case DECL_CXX_BASE_SPECIFIERS:
1547    Error("attempt to read a C++ base-specifier record as a declaration");
1548    return 0;
1549  }
1550
1551  assert(D && "Unknown declaration reading AST file");
1552  LoadedDecl(Index, D);
1553  Reader.Visit(D);
1554
1555  // If this declaration is also a declaration context, get the
1556  // offsets for its tables of lexical and visible declarations.
1557  if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1558    std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1559    if (Offsets.first || Offsets.second) {
1560      DC->setHasExternalLexicalStorage(Offsets.first != 0);
1561      DC->setHasExternalVisibleStorage(Offsets.second != 0);
1562      DeclContextInfo Info;
1563      if (ReadDeclContextStorage(DeclsCursor, Offsets, Info))
1564        return 0;
1565      DeclContextInfos &Infos = DeclContextOffsets[DC];
1566      // Reading the TU will happen after reading its lexical update blocks,
1567      // so we need to make sure we insert in front. For all other contexts,
1568      // the vector is empty here anyway, so there's no loss in efficiency.
1569      Infos.insert(Infos.begin(), Info);
1570
1571      // Now add the pending visible updates for this decl context, if it has
1572      // any.
1573      DeclContextVisibleUpdatesPending::iterator I =
1574          PendingVisibleUpdates.find(ID);
1575      if (I != PendingVisibleUpdates.end()) {
1576        DeclContextVisibleUpdates &U = I->second;
1577        Info.LexicalDecls = 0;
1578        Info.NumLexicalDecls = 0;
1579        for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
1580             UI != UE; ++UI) {
1581          Info.NameLookupTableData = *UI;
1582          Infos.push_back(Info);
1583        }
1584        PendingVisibleUpdates.erase(I);
1585      }
1586    }
1587  }
1588  assert(Idx == Record.size());
1589
1590  // The declaration may have been modified by files later in the chain.
1591  // If this is the case, read the record containing the updates from each file
1592  // and pass it to ASTDeclReader to make the modifications.
1593  DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
1594  if (UpdI != DeclUpdateOffsets.end()) {
1595    FileOffsetsTy &UpdateOffsets = UpdI->second;
1596    for (FileOffsetsTy::iterator
1597           I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
1598      PerFileData *F = I->first;
1599      uint64_t Offset = I->second;
1600      llvm::BitstreamCursor &Cursor = F->DeclsCursor;
1601      SavedStreamPosition SavedPosition(Cursor);
1602      Cursor.JumpToBit(Offset);
1603      RecordData Record;
1604      unsigned Code = Cursor.ReadCode();
1605      unsigned RecCode = Cursor.ReadRecord(Code, Record);
1606      (void)RecCode;
1607      assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
1608      Reader.UpdateDecl(D, Record);
1609    }
1610  }
1611
1612  // If we have deserialized a declaration that has a definition the
1613  // AST consumer might need to know about, queue it.
1614  // We don't pass it to the consumer immediately because we may be in recursive
1615  // loading, and some declarations may still be initializing.
1616  if (isConsumerInterestedIn(D))
1617    InterestingDecls.push_back(D);
1618
1619  return D;
1620}
1621
1622void ASTDeclReader::UpdateDecl(Decl *D, const RecordData &Record) {
1623  unsigned Idx = 0;
1624  while (Idx < Record.size()) {
1625    switch ((DeclUpdateKind)Record[Idx++]) {
1626    case UPD_CXX_SET_DEFINITIONDATA: {
1627      CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1628      CXXRecordDecl *
1629          DefinitionDecl = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
1630      assert(!RD->DefinitionData && "DefinitionData is already set!");
1631      InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
1632      break;
1633    }
1634
1635    case UPD_CXX_ADDED_IMPLICIT_MEMBER:
1636      cast<CXXRecordDecl>(D)->addedMember(Reader.GetDecl(Record[Idx++]));
1637      break;
1638
1639    case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
1640      // It will be added to the template's specializations set when loaded.
1641      Reader.GetDecl(Record[Idx++]);
1642    }
1643  }
1644}
1645