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