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