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