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