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