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