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