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