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