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