1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Serialization/ASTReader.h"
16 #include "ASTCommon.h"
17 #include "ASTReaderInternals.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Sema/IdentifierResolver.h"
26 #include "clang/Sema/Sema.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 using namespace clang;
30 using namespace clang::serialization;
31 
32 //===----------------------------------------------------------------------===//
33 // Declaration deserialization
34 //===----------------------------------------------------------------------===//
35 
36 namespace clang {
37   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
38     ASTReader &Reader;
39     ModuleFile &F;
40     const DeclID ThisDeclID;
41     const unsigned RawLocation;
42     typedef ASTReader::RecordData RecordData;
43     const RecordData &Record;
44     unsigned &Idx;
45     TypeID TypeIDForTypeDecl;
46     unsigned AnonymousDeclNumber;
47     GlobalDeclID NamedDeclForTagDecl;
48     IdentifierInfo *TypedefNameForLinkage;
49 
50     bool HasPendingBody;
51 
52     uint64_t GetCurrentCursorOffset();
53 
54     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
55       return Reader.ReadSourceLocation(F, R, I);
56     }
57 
58     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
59       return Reader.ReadSourceRange(F, R, I);
60     }
61 
62     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
63       return Reader.GetTypeSourceInfo(F, R, I);
64     }
65 
66     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
67       return Reader.ReadDeclID(F, R, I);
68     }
69 
70     Decl *ReadDecl(const RecordData &R, unsigned &I) {
71       return Reader.ReadDecl(F, R, I);
72     }
73 
74     template<typename T>
75     T *ReadDeclAs(const RecordData &R, unsigned &I) {
76       return Reader.ReadDeclAs<T>(F, R, I);
77     }
78 
79     void ReadQualifierInfo(QualifierInfo &Info,
80                            const RecordData &R, unsigned &I) {
81       Reader.ReadQualifierInfo(F, Info, R, I);
82     }
83 
84     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
85                                 const RecordData &R, unsigned &I) {
86       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
87     }
88 
89     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
90                                 const RecordData &R, unsigned &I) {
91       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
92     }
93 
94     serialization::SubmoduleID readSubmoduleID(const RecordData &R,
95                                                unsigned &I) {
96       if (I >= R.size())
97         return 0;
98 
99       return Reader.getGlobalSubmoduleID(F, R[I++]);
100     }
101 
102     Module *readModule(const RecordData &R, unsigned &I) {
103       return Reader.getSubmodule(readSubmoduleID(R, I));
104     }
105 
106     void ReadCXXRecordDefinition(CXXRecordDecl *D);
107     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
108                                const RecordData &R, unsigned &I);
109     void MergeDefinitionData(CXXRecordDecl *D,
110                              struct CXXRecordDecl::DefinitionData &&NewDD);
111 
112     static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
113                                                  DeclContext *DC,
114                                                  unsigned Index);
115     static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
116                                            unsigned Index, NamedDecl *D);
117 
118     /// \brief RAII class used to capture the first ID within a redeclaration
119     /// chain and to introduce it into the list of pending redeclaration chains
120     /// on destruction.
121     ///
122     /// The caller can choose not to introduce this ID into the list of pending
123     /// redeclaration chains by calling \c suppress().
124     class RedeclarableResult {
125       ASTReader &Reader;
126       GlobalDeclID FirstID;
127       mutable bool Owning;
128       Decl::Kind DeclKind;
129 
130       void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
131 
132     public:
133       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
134                          Decl::Kind DeclKind)
135         : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
136 
137       RedeclarableResult(const RedeclarableResult &Other)
138         : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
139           DeclKind(Other.DeclKind)
140       {
141         Other.Owning = false;
142       }
143 
144       ~RedeclarableResult() {
145         if (FirstID && Owning && isRedeclarableDeclKind(DeclKind) &&
146             Reader.PendingDeclChainsKnown.insert(FirstID).second)
147           Reader.PendingDeclChains.push_back(FirstID);
148       }
149 
150       /// \brief Retrieve the first ID.
151       GlobalDeclID getFirstID() const { return FirstID; }
152 
153       /// \brief Do not introduce this declaration ID into the set of pending
154       /// declaration chains.
155       void suppress() {
156         Owning = false;
157       }
158     };
159 
160     /// \brief Class used to capture the result of searching for an existing
161     /// declaration of a specific kind and name, along with the ability
162     /// to update the place where this result was found (the declaration
163     /// chain hanging off an identifier or the DeclContext we searched in)
164     /// if requested.
165     class FindExistingResult {
166       ASTReader &Reader;
167       NamedDecl *New;
168       NamedDecl *Existing;
169       mutable bool AddResult;
170 
171       unsigned AnonymousDeclNumber;
172       IdentifierInfo *TypedefNameForLinkage;
173 
174       void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
175 
176     public:
177       FindExistingResult(ASTReader &Reader)
178           : Reader(Reader), New(nullptr), Existing(nullptr), AddResult(false),
179             AnonymousDeclNumber(0), TypedefNameForLinkage(0) {}
180 
181       FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
182                          unsigned AnonymousDeclNumber,
183                          IdentifierInfo *TypedefNameForLinkage)
184           : Reader(Reader), New(New), Existing(Existing), AddResult(true),
185             AnonymousDeclNumber(AnonymousDeclNumber),
186             TypedefNameForLinkage(TypedefNameForLinkage) {}
187 
188       FindExistingResult(const FindExistingResult &Other)
189           : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
190             AddResult(Other.AddResult),
191             AnonymousDeclNumber(Other.AnonymousDeclNumber),
192             TypedefNameForLinkage(Other.TypedefNameForLinkage) {
193         Other.AddResult = false;
194       }
195 
196       ~FindExistingResult();
197 
198       /// \brief Suppress the addition of this result into the known set of
199       /// names.
200       void suppress() { AddResult = false; }
201 
202       operator NamedDecl*() const { return Existing; }
203 
204       template<typename T>
205       operator T*() const { return dyn_cast_or_null<T>(Existing); }
206     };
207 
208     static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
209                                                     DeclContext *DC);
210     FindExistingResult findExisting(NamedDecl *D);
211 
212   public:
213     ASTDeclReader(ASTReader &Reader, ModuleFile &F, DeclID thisDeclID,
214                   unsigned RawLocation, const RecordData &Record, unsigned &Idx)
215         : Reader(Reader), F(F), ThisDeclID(thisDeclID),
216           RawLocation(RawLocation), Record(Record), Idx(Idx),
217           TypeIDForTypeDecl(0), NamedDeclForTagDecl(0),
218           TypedefNameForLinkage(nullptr), HasPendingBody(false) {}
219 
220     template <typename DeclT>
221     static void attachPreviousDeclImpl(ASTReader &Reader,
222                                        Redeclarable<DeclT> *D, Decl *Previous);
223     static void attachPreviousDeclImpl(ASTReader &Reader, ...);
224     static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous);
225 
226     template <typename DeclT>
227     static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
228     static void attachLatestDeclImpl(...);
229     static void attachLatestDecl(Decl *D, Decl *latest);
230 
231     template <typename DeclT>
232     static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
233     static void markIncompleteDeclChainImpl(...);
234 
235     /// \brief Determine whether this declaration has a pending body.
236     bool hasPendingBody() const { return HasPendingBody; }
237 
238     void Visit(Decl *D);
239 
240     void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
241                     const RecordData &Record);
242 
243     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
244                                     ObjCCategoryDecl *Next) {
245       Cat->NextClassCategory = Next;
246     }
247 
248     void VisitDecl(Decl *D);
249     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
250     void VisitNamedDecl(NamedDecl *ND);
251     void VisitLabelDecl(LabelDecl *LD);
252     void VisitNamespaceDecl(NamespaceDecl *D);
253     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
254     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
255     void VisitTypeDecl(TypeDecl *TD);
256     RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
257     void VisitTypedefDecl(TypedefDecl *TD);
258     void VisitTypeAliasDecl(TypeAliasDecl *TD);
259     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
260     RedeclarableResult VisitTagDecl(TagDecl *TD);
261     void VisitEnumDecl(EnumDecl *ED);
262     RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
263     void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
264     RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
265     void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
266     RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
267                                             ClassTemplateSpecializationDecl *D);
268     void VisitClassTemplateSpecializationDecl(
269         ClassTemplateSpecializationDecl *D) {
270       VisitClassTemplateSpecializationDeclImpl(D);
271     }
272     void VisitClassTemplatePartialSpecializationDecl(
273                                      ClassTemplatePartialSpecializationDecl *D);
274     void VisitClassScopeFunctionSpecializationDecl(
275                                        ClassScopeFunctionSpecializationDecl *D);
276     RedeclarableResult
277     VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
278     void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
279       VisitVarTemplateSpecializationDeclImpl(D);
280     }
281     void VisitVarTemplatePartialSpecializationDecl(
282         VarTemplatePartialSpecializationDecl *D);
283     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
284     void VisitValueDecl(ValueDecl *VD);
285     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
286     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
287     void VisitDeclaratorDecl(DeclaratorDecl *DD);
288     void VisitFunctionDecl(FunctionDecl *FD);
289     void VisitCXXMethodDecl(CXXMethodDecl *D);
290     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
291     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
292     void VisitCXXConversionDecl(CXXConversionDecl *D);
293     void VisitFieldDecl(FieldDecl *FD);
294     void VisitMSPropertyDecl(MSPropertyDecl *FD);
295     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
296     RedeclarableResult VisitVarDeclImpl(VarDecl *D);
297     void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
298     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
299     void VisitParmVarDecl(ParmVarDecl *PD);
300     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
301     DeclID VisitTemplateDecl(TemplateDecl *D);
302     RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
303     void VisitClassTemplateDecl(ClassTemplateDecl *D);
304     void VisitVarTemplateDecl(VarTemplateDecl *D);
305     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
306     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
307     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
308     void VisitUsingDecl(UsingDecl *D);
309     void VisitUsingShadowDecl(UsingShadowDecl *D);
310     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
311     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
312     void VisitImportDecl(ImportDecl *D);
313     void VisitAccessSpecDecl(AccessSpecDecl *D);
314     void VisitFriendDecl(FriendDecl *D);
315     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
316     void VisitStaticAssertDecl(StaticAssertDecl *D);
317     void VisitBlockDecl(BlockDecl *BD);
318     void VisitCapturedDecl(CapturedDecl *CD);
319     void VisitEmptyDecl(EmptyDecl *D);
320 
321     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
322 
323     template<typename T>
324     RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
325 
326     template<typename T>
327     void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
328                            DeclID TemplatePatternID = 0);
329 
330     template<typename T>
331     void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
332                            RedeclarableResult &Redecl,
333                            DeclID TemplatePatternID = 0);
334 
335     template<typename T>
336     void mergeMergeable(Mergeable<T> *D);
337 
338     void mergeTemplatePattern(RedeclarableTemplateDecl *D,
339                               RedeclarableTemplateDecl *Existing,
340                               DeclID DsID);
341 
342     // FIXME: Reorder according to DeclNodes.td?
343     void VisitObjCMethodDecl(ObjCMethodDecl *D);
344     void VisitObjCContainerDecl(ObjCContainerDecl *D);
345     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
346     void VisitObjCIvarDecl(ObjCIvarDecl *D);
347     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
348     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
349     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
350     void VisitObjCImplDecl(ObjCImplDecl *D);
351     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
352     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
353     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
354     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
355     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
356     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
357   };
358 }
359 
360 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
361   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
362 }
363 
364 void ASTDeclReader::Visit(Decl *D) {
365   DeclVisitor<ASTDeclReader, void>::Visit(D);
366 
367   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
368     if (DD->DeclInfo) {
369       DeclaratorDecl::ExtInfo *Info =
370           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
371       Info->TInfo =
372           GetTypeSourceInfo(Record, Idx);
373     }
374     else {
375       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
376     }
377   }
378 
379   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
380     // We have a fully initialized TypeDecl. Read its type now.
381     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
382 
383     // If this is a tag declaration with a typedef name for linkage, it's safe
384     // to load that typedef now.
385     if (NamedDeclForTagDecl)
386       cast<TagDecl>(D)->NamedDeclOrQualifier =
387           cast<NamedDecl>(Reader.GetDecl(NamedDeclForTagDecl));
388   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
389     // if we have a fully initialized TypeDecl, we can safely read its type now.
390     ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
391   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
392     // FunctionDecl's body was written last after all other Stmts/Exprs.
393     // We only read it if FD doesn't already have a body (e.g., from another
394     // module).
395     // FIXME: Also consider = default and = delete.
396     // FIXME: Can we diagnose ODR violations somehow?
397     if (Record[Idx++]) {
398       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
399       HasPendingBody = true;
400     }
401   }
402 }
403 
404 void ASTDeclReader::VisitDecl(Decl *D) {
405   if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
406       isa<ParmVarDecl>(D)) {
407     // We don't want to deserialize the DeclContext of a template
408     // parameter or of a parameter of a function template immediately.   These
409     // entities might be used in the formulation of its DeclContext (for
410     // example, a function parameter can be used in decltype() in trailing
411     // return type of the function).  Use the translation unit DeclContext as a
412     // placeholder.
413     GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
414     GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
415     Reader.addPendingDeclContextInfo(D,
416                                      SemaDCIDForTemplateParmDecl,
417                                      LexicalDCIDForTemplateParmDecl);
418     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
419   } else {
420     DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
421     DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
422     DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
423     // Avoid calling setLexicalDeclContext() directly because it uses
424     // Decl::getASTContext() internally which is unsafe during derialization.
425     D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
426                            Reader.getContext());
427   }
428   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
429   D->setInvalidDecl(Record[Idx++]);
430   if (Record[Idx++]) { // hasAttrs
431     AttrVec Attrs;
432     Reader.ReadAttributes(F, Attrs, Record, Idx);
433     // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
434     // internally which is unsafe during derialization.
435     D->setAttrsImpl(Attrs, Reader.getContext());
436   }
437   D->setImplicit(Record[Idx++]);
438   D->Used = Record[Idx++];
439   D->setReferenced(Record[Idx++]);
440   D->setTopLevelDeclInObjCContainer(Record[Idx++]);
441   D->setAccess((AccessSpecifier)Record[Idx++]);
442   D->FromASTFile = true;
443   D->setModulePrivate(Record[Idx++]);
444   D->Hidden = D->isModulePrivate();
445 
446   // Determine whether this declaration is part of a (sub)module. If so, it
447   // may not yet be visible.
448   if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
449     // Store the owning submodule ID in the declaration.
450     D->setOwningModuleID(SubmoduleID);
451 
452     // Module-private declarations are never visible, so there is no work to do.
453     if (!D->isModulePrivate()) {
454       if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
455         if (Owner->NameVisibility != Module::AllVisible) {
456           // The owning module is not visible. Mark this declaration as hidden.
457           D->Hidden = true;
458 
459           // Note that this declaration was hidden because its owning module is
460           // not yet visible.
461           Reader.HiddenNamesMap[Owner].HiddenDecls.push_back(D);
462         }
463       }
464     }
465   }
466 }
467 
468 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
469   llvm_unreachable("Translation units are not serialized");
470 }
471 
472 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
473   VisitDecl(ND);
474   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
475   if (needsAnonymousDeclarationNumber(ND))
476     AnonymousDeclNumber = Record[Idx++];
477 }
478 
479 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
480   VisitNamedDecl(TD);
481   TD->setLocStart(ReadSourceLocation(Record, Idx));
482   // Delay type reading until after we have fully initialized the decl.
483   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
484 }
485 
486 ASTDeclReader::RedeclarableResult
487 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
488   RedeclarableResult Redecl = VisitRedeclarable(TD);
489   VisitTypeDecl(TD);
490   TypeSourceInfo *TInfo = GetTypeSourceInfo(Record, Idx);
491   if (Record[Idx++]) { // isModed
492     QualType modedT = Reader.readType(F, Record, Idx);
493     TD->setModedTypeSourceInfo(TInfo, modedT);
494   } else
495     TD->setTypeSourceInfo(TInfo);
496   return Redecl;
497 }
498 
499 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
500   RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
501   mergeRedeclarable(TD, Redecl);
502 }
503 
504 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
505   RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
506   if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>(Record, Idx))
507     // Merged when we merge the template.
508     TD->setDescribedAliasTemplate(Template);
509   else
510     mergeRedeclarable(TD, Redecl);
511 }
512 
513 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
514   RedeclarableResult Redecl = VisitRedeclarable(TD);
515   VisitTypeDecl(TD);
516 
517   TD->IdentifierNamespace = Record[Idx++];
518   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
519   if (!isa<CXXRecordDecl>(TD))
520     TD->setCompleteDefinition(Record[Idx++]);
521   TD->setEmbeddedInDeclarator(Record[Idx++]);
522   TD->setFreeStanding(Record[Idx++]);
523   TD->setCompleteDefinitionRequired(Record[Idx++]);
524   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
525 
526   switch (Record[Idx++]) {
527   case 0:
528     break;
529   case 1: { // ExtInfo
530     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
531     ReadQualifierInfo(*Info, Record, Idx);
532     TD->NamedDeclOrQualifier = Info;
533     break;
534   }
535   case 2: // TypedefNameForAnonDecl
536     NamedDeclForTagDecl = ReadDeclID(Record, Idx);
537     TypedefNameForLinkage = Reader.GetIdentifierInfo(F, Record, Idx);
538     break;
539   case 3: // DeclaratorForAnonDecl
540     NamedDeclForTagDecl = ReadDeclID(Record, Idx);
541     break;
542   default:
543     llvm_unreachable("unexpected tag info kind");
544   }
545 
546   if (!isa<CXXRecordDecl>(TD))
547     mergeRedeclarable(TD, Redecl);
548   return Redecl;
549 }
550 
551 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
552   VisitTagDecl(ED);
553   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
554     ED->setIntegerTypeSourceInfo(TI);
555   else
556     ED->setIntegerType(Reader.readType(F, Record, Idx));
557   ED->setPromotionType(Reader.readType(F, Record, Idx));
558   ED->setNumPositiveBits(Record[Idx++]);
559   ED->setNumNegativeBits(Record[Idx++]);
560   ED->IsScoped = Record[Idx++];
561   ED->IsScopedUsingClassTag = Record[Idx++];
562   ED->IsFixed = Record[Idx++];
563 
564   // If this is a definition subject to the ODR, and we already have a
565   // definition, merge this one into it.
566   if (ED->IsCompleteDefinition &&
567       Reader.getContext().getLangOpts().Modules &&
568       Reader.getContext().getLangOpts().CPlusPlus) {
569     if (EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()]) {
570       Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
571       ED->IsCompleteDefinition = false;
572     } else {
573       OldDef = ED;
574     }
575   }
576 
577   if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
578     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
579     SourceLocation POI = ReadSourceLocation(Record, Idx);
580     ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
581     ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
582   }
583 }
584 
585 ASTDeclReader::RedeclarableResult
586 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
587   RedeclarableResult Redecl = VisitTagDecl(RD);
588   RD->setHasFlexibleArrayMember(Record[Idx++]);
589   RD->setAnonymousStructOrUnion(Record[Idx++]);
590   RD->setHasObjectMember(Record[Idx++]);
591   RD->setHasVolatileMember(Record[Idx++]);
592   return Redecl;
593 }
594 
595 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
596   VisitNamedDecl(VD);
597   VD->setType(Reader.readType(F, Record, Idx));
598 }
599 
600 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
601   VisitValueDecl(ECD);
602   if (Record[Idx++])
603     ECD->setInitExpr(Reader.ReadExpr(F));
604   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
605   mergeMergeable(ECD);
606 }
607 
608 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
609   VisitValueDecl(DD);
610   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
611   if (Record[Idx++]) { // hasExtInfo
612     DeclaratorDecl::ExtInfo *Info
613         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
614     ReadQualifierInfo(*Info, Record, Idx);
615     DD->DeclInfo = Info;
616   }
617 }
618 
619 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
620   RedeclarableResult Redecl = VisitRedeclarable(FD);
621   VisitDeclaratorDecl(FD);
622 
623   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
624   FD->IdentifierNamespace = Record[Idx++];
625 
626   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
627   // after everything else is read.
628 
629   FD->SClass = (StorageClass)Record[Idx++];
630   FD->IsInline = Record[Idx++];
631   FD->IsInlineSpecified = Record[Idx++];
632   FD->IsVirtualAsWritten = Record[Idx++];
633   FD->IsPure = Record[Idx++];
634   FD->HasInheritedPrototype = Record[Idx++];
635   FD->HasWrittenPrototype = Record[Idx++];
636   FD->IsDeleted = Record[Idx++];
637   FD->IsTrivial = Record[Idx++];
638   FD->IsDefaulted = Record[Idx++];
639   FD->IsExplicitlyDefaulted = Record[Idx++];
640   FD->HasImplicitReturnZero = Record[Idx++];
641   FD->IsConstexpr = Record[Idx++];
642   FD->HasSkippedBody = Record[Idx++];
643   FD->IsLateTemplateParsed = Record[Idx++];
644   FD->setCachedLinkage(Linkage(Record[Idx++]));
645   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
646 
647   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
648   case FunctionDecl::TK_NonTemplate:
649     mergeRedeclarable(FD, Redecl);
650     break;
651   case FunctionDecl::TK_FunctionTemplate:
652     // Merged when we merge the template.
653     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
654                                                                       Idx));
655     break;
656   case FunctionDecl::TK_MemberSpecialization: {
657     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
658     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
659     SourceLocation POI = ReadSourceLocation(Record, Idx);
660     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
661     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
662     mergeRedeclarable(FD, Redecl);
663     break;
664   }
665   case FunctionDecl::TK_FunctionTemplateSpecialization: {
666     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
667                                                                       Idx);
668     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
669 
670     // Template arguments.
671     SmallVector<TemplateArgument, 8> TemplArgs;
672     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
673 
674     // Template args as written.
675     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
676     SourceLocation LAngleLoc, RAngleLoc;
677     bool HasTemplateArgumentsAsWritten = Record[Idx++];
678     if (HasTemplateArgumentsAsWritten) {
679       unsigned NumTemplateArgLocs = Record[Idx++];
680       TemplArgLocs.reserve(NumTemplateArgLocs);
681       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
682         TemplArgLocs.push_back(
683             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
684 
685       LAngleLoc = ReadSourceLocation(Record, Idx);
686       RAngleLoc = ReadSourceLocation(Record, Idx);
687     }
688 
689     SourceLocation POI = ReadSourceLocation(Record, Idx);
690 
691     ASTContext &C = Reader.getContext();
692     TemplateArgumentList *TemplArgList
693       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
694     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
695     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
696       TemplArgsInfo.addArgument(TemplArgLocs[i]);
697     FunctionTemplateSpecializationInfo *FTInfo
698         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
699                                                      TemplArgList,
700                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo
701                                                            : nullptr,
702                                                      POI);
703     FD->TemplateOrSpecialization = FTInfo;
704 
705     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
706       // The template that contains the specializations set. It's not safe to
707       // use getCanonicalDecl on Template since it may still be initializing.
708       FunctionTemplateDecl *CanonTemplate
709         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
710       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
711       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
712       // FunctionTemplateSpecializationInfo's Profile().
713       // We avoid getASTContext because a decl in the parent hierarchy may
714       // be initializing.
715       llvm::FoldingSetNodeID ID;
716       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
717       void *InsertPos = nullptr;
718       FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
719       CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
720       if (InsertPos)
721         CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
722       else {
723         assert(Reader.getContext().getLangOpts().Modules &&
724                "already deserialized this template specialization");
725         // FIXME: This specialization is a redeclaration of one from another
726         // module. Merge it.
727       }
728     }
729     break;
730   }
731   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
732     // Templates.
733     UnresolvedSet<8> TemplDecls;
734     unsigned NumTemplates = Record[Idx++];
735     while (NumTemplates--)
736       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
737 
738     // Templates args.
739     TemplateArgumentListInfo TemplArgs;
740     unsigned NumArgs = Record[Idx++];
741     while (NumArgs--)
742       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
743     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
744     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
745 
746     FD->setDependentTemplateSpecialization(Reader.getContext(),
747                                            TemplDecls, TemplArgs);
748 
749     // FIXME: Merging.
750     break;
751   }
752   }
753 
754   // Read in the parameters.
755   unsigned NumParams = Record[Idx++];
756   SmallVector<ParmVarDecl *, 16> Params;
757   Params.reserve(NumParams);
758   for (unsigned I = 0; I != NumParams; ++I)
759     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
760   FD->setParams(Reader.getContext(), Params);
761 }
762 
763 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
764   VisitNamedDecl(MD);
765   if (Record[Idx++]) {
766     // Load the body on-demand. Most clients won't care, because method
767     // definitions rarely show up in headers.
768     Reader.PendingBodies[MD] = GetCurrentCursorOffset();
769     HasPendingBody = true;
770     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
771     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
772   }
773   MD->setInstanceMethod(Record[Idx++]);
774   MD->setVariadic(Record[Idx++]);
775   MD->setPropertyAccessor(Record[Idx++]);
776   MD->setDefined(Record[Idx++]);
777   MD->IsOverriding = Record[Idx++];
778   MD->HasSkippedBody = Record[Idx++];
779 
780   MD->IsRedeclaration = Record[Idx++];
781   MD->HasRedeclaration = Record[Idx++];
782   if (MD->HasRedeclaration)
783     Reader.getContext().setObjCMethodRedeclaration(MD,
784                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
785 
786   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
787   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
788   MD->SetRelatedResultType(Record[Idx++]);
789   MD->setReturnType(Reader.readType(F, Record, Idx));
790   MD->setReturnTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
791   MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
792   unsigned NumParams = Record[Idx++];
793   SmallVector<ParmVarDecl *, 16> Params;
794   Params.reserve(NumParams);
795   for (unsigned I = 0; I != NumParams; ++I)
796     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
797 
798   MD->SelLocsKind = Record[Idx++];
799   unsigned NumStoredSelLocs = Record[Idx++];
800   SmallVector<SourceLocation, 16> SelLocs;
801   SelLocs.reserve(NumStoredSelLocs);
802   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
803     SelLocs.push_back(ReadSourceLocation(Record, Idx));
804 
805   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
806 }
807 
808 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
809   VisitNamedDecl(CD);
810   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
811   CD->setAtEndRange(ReadSourceRange(Record, Idx));
812 }
813 
814 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
815   RedeclarableResult Redecl = VisitRedeclarable(ID);
816   VisitObjCContainerDecl(ID);
817   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
818   mergeRedeclarable(ID, Redecl);
819 
820   if (Record[Idx++]) {
821     // Read the definition.
822     ID->allocateDefinitionData();
823 
824     // Set the definition data of the canonical declaration, so other
825     // redeclarations will see it.
826     ID->getCanonicalDecl()->Data = ID->Data;
827 
828     ObjCInterfaceDecl::DefinitionData &Data = ID->data();
829 
830     // Read the superclass.
831     Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
832     Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
833 
834     Data.EndLoc = ReadSourceLocation(Record, Idx);
835     Data.HasDesignatedInitializers = Record[Idx++];
836 
837     // Read the directly referenced protocols and their SourceLocations.
838     unsigned NumProtocols = Record[Idx++];
839     SmallVector<ObjCProtocolDecl *, 16> Protocols;
840     Protocols.reserve(NumProtocols);
841     for (unsigned I = 0; I != NumProtocols; ++I)
842       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
843     SmallVector<SourceLocation, 16> ProtoLocs;
844     ProtoLocs.reserve(NumProtocols);
845     for (unsigned I = 0; I != NumProtocols; ++I)
846       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
847     ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
848                         Reader.getContext());
849 
850     // Read the transitive closure of protocols referenced by this class.
851     NumProtocols = Record[Idx++];
852     Protocols.clear();
853     Protocols.reserve(NumProtocols);
854     for (unsigned I = 0; I != NumProtocols; ++I)
855       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
856     ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
857                                           Reader.getContext());
858 
859     // We will rebuild this list lazily.
860     ID->setIvarList(nullptr);
861 
862     // Note that we have deserialized a definition.
863     Reader.PendingDefinitions.insert(ID);
864 
865     // Note that we've loaded this Objective-C class.
866     Reader.ObjCClassesLoaded.push_back(ID);
867   } else {
868     ID->Data = ID->getCanonicalDecl()->Data;
869   }
870 }
871 
872 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
873   VisitFieldDecl(IVD);
874   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
875   // This field will be built lazily.
876   IVD->setNextIvar(nullptr);
877   bool synth = Record[Idx++];
878   IVD->setSynthesize(synth);
879 }
880 
881 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
882   RedeclarableResult Redecl = VisitRedeclarable(PD);
883   VisitObjCContainerDecl(PD);
884   mergeRedeclarable(PD, Redecl);
885 
886   if (Record[Idx++]) {
887     // Read the definition.
888     PD->allocateDefinitionData();
889 
890     // Set the definition data of the canonical declaration, so other
891     // redeclarations will see it.
892     PD->getCanonicalDecl()->Data = PD->Data;
893 
894     unsigned NumProtoRefs = Record[Idx++];
895     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
896     ProtoRefs.reserve(NumProtoRefs);
897     for (unsigned I = 0; I != NumProtoRefs; ++I)
898       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
899     SmallVector<SourceLocation, 16> ProtoLocs;
900     ProtoLocs.reserve(NumProtoRefs);
901     for (unsigned I = 0; I != NumProtoRefs; ++I)
902       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
903     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
904                         Reader.getContext());
905 
906     // Note that we have deserialized a definition.
907     Reader.PendingDefinitions.insert(PD);
908   } else {
909     PD->Data = PD->getCanonicalDecl()->Data;
910   }
911 }
912 
913 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
914   VisitFieldDecl(FD);
915 }
916 
917 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
918   VisitObjCContainerDecl(CD);
919   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
920   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
921   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
922 
923   // Note that this category has been deserialized. We do this before
924   // deserializing the interface declaration, so that it will consider this
925   /// category.
926   Reader.CategoriesDeserialized.insert(CD);
927 
928   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
929   unsigned NumProtoRefs = Record[Idx++];
930   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
931   ProtoRefs.reserve(NumProtoRefs);
932   for (unsigned I = 0; I != NumProtoRefs; ++I)
933     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
934   SmallVector<SourceLocation, 16> ProtoLocs;
935   ProtoLocs.reserve(NumProtoRefs);
936   for (unsigned I = 0; I != NumProtoRefs; ++I)
937     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
938   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
939                       Reader.getContext());
940 }
941 
942 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
943   VisitNamedDecl(CAD);
944   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
945 }
946 
947 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
948   VisitNamedDecl(D);
949   D->setAtLoc(ReadSourceLocation(Record, Idx));
950   D->setLParenLoc(ReadSourceLocation(Record, Idx));
951   D->setType(GetTypeSourceInfo(Record, Idx));
952   // FIXME: stable encoding
953   D->setPropertyAttributes(
954                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
955   D->setPropertyAttributesAsWritten(
956                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
957   // FIXME: stable encoding
958   D->setPropertyImplementation(
959                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
960   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
961   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
962   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
963   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
964   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
965 }
966 
967 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
968   VisitObjCContainerDecl(D);
969   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
970 }
971 
972 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
973   VisitObjCImplDecl(D);
974   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
975   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
976 }
977 
978 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
979   VisitObjCImplDecl(D);
980   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
981   D->SuperLoc = ReadSourceLocation(Record, Idx);
982   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
983   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
984   D->setHasNonZeroConstructors(Record[Idx++]);
985   D->setHasDestructors(Record[Idx++]);
986   std::tie(D->IvarInitializers, D->NumIvarInitializers) =
987       Reader.ReadCXXCtorInitializers(F, Record, Idx);
988 }
989 
990 
991 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
992   VisitDecl(D);
993   D->setAtLoc(ReadSourceLocation(Record, Idx));
994   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
995   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
996   D->IvarLoc = ReadSourceLocation(Record, Idx);
997   D->setGetterCXXConstructor(Reader.ReadExpr(F));
998   D->setSetterCXXAssignment(Reader.ReadExpr(F));
999 }
1000 
1001 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1002   VisitDeclaratorDecl(FD);
1003   FD->Mutable = Record[Idx++];
1004   if (int BitWidthOrInitializer = Record[Idx++]) {
1005     FD->InitStorage.setInt(
1006           static_cast<FieldDecl::InitStorageKind>(BitWidthOrInitializer - 1));
1007     if (FD->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) {
1008       // Read captured variable length array.
1009       FD->InitStorage.setPointer(
1010           Reader.readType(F, Record, Idx).getAsOpaquePtr());
1011     } else {
1012       FD->InitStorage.setPointer(Reader.ReadExpr(F));
1013     }
1014   }
1015   if (!FD->getDeclName()) {
1016     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
1017       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1018   }
1019   mergeMergeable(FD);
1020 }
1021 
1022 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1023   VisitDeclaratorDecl(PD);
1024   PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
1025   PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
1026 }
1027 
1028 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1029   VisitValueDecl(FD);
1030 
1031   FD->ChainingSize = Record[Idx++];
1032   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1033   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1034 
1035   for (unsigned I = 0; I != FD->ChainingSize; ++I)
1036     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
1037 }
1038 
1039 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1040   RedeclarableResult Redecl = VisitRedeclarable(VD);
1041   VisitDeclaratorDecl(VD);
1042 
1043   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
1044   VD->VarDeclBits.TSCSpec = Record[Idx++];
1045   VD->VarDeclBits.InitStyle = Record[Idx++];
1046   VD->VarDeclBits.ExceptionVar = Record[Idx++];
1047   VD->VarDeclBits.NRVOVariable = Record[Idx++];
1048   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
1049   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
1050   VD->VarDeclBits.IsConstexpr = Record[Idx++];
1051   VD->VarDeclBits.IsInitCapture = Record[Idx++];
1052   VD->VarDeclBits.PreviousDeclInSameBlockScope = Record[Idx++];
1053   Linkage VarLinkage = Linkage(Record[Idx++]);
1054   VD->setCachedLinkage(VarLinkage);
1055 
1056   // Reconstruct the one piece of the IdentifierNamespace that we need.
1057   if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1058       VD->getLexicalDeclContext()->isFunctionOrMethod())
1059     VD->setLocalExternDecl();
1060 
1061   if (uint64_t Val = Record[Idx++]) {
1062     VD->setInit(Reader.ReadExpr(F));
1063     if (Val > 1) {
1064       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1065       Eval->CheckedICE = true;
1066       Eval->IsICE = Val == 3;
1067     }
1068   }
1069 
1070   enum VarKind {
1071     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1072   };
1073   switch ((VarKind)Record[Idx++]) {
1074   case VarNotTemplate:
1075     // Only true variables (not parameters or implicit parameters) can be merged
1076     if (VD->getKind() != Decl::ParmVar && VD->getKind() != Decl::ImplicitParam &&
1077         !isa<VarTemplateSpecializationDecl>(VD))
1078       mergeRedeclarable(VD, Redecl);
1079     break;
1080   case VarTemplate:
1081     // Merged when we merge the template.
1082     VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>(Record, Idx));
1083     break;
1084   case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1085     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
1086     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1087     SourceLocation POI = ReadSourceLocation(Record, Idx);
1088     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1089     mergeRedeclarable(VD, Redecl);
1090     break;
1091   }
1092   }
1093 
1094   return Redecl;
1095 }
1096 
1097 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1098   VisitVarDecl(PD);
1099 }
1100 
1101 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1102   VisitVarDecl(PD);
1103   unsigned isObjCMethodParam = Record[Idx++];
1104   unsigned scopeDepth = Record[Idx++];
1105   unsigned scopeIndex = Record[Idx++];
1106   unsigned declQualifier = Record[Idx++];
1107   if (isObjCMethodParam) {
1108     assert(scopeDepth == 0);
1109     PD->setObjCMethodScopeInfo(scopeIndex);
1110     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1111   } else {
1112     PD->setScopeInfo(scopeDepth, scopeIndex);
1113   }
1114   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
1115   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
1116   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
1117     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
1118 
1119   // FIXME: If this is a redeclaration of a function from another module, handle
1120   // inheritance of default arguments.
1121 }
1122 
1123 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1124   VisitDecl(AD);
1125   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
1126   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
1127 }
1128 
1129 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1130   VisitDecl(BD);
1131   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
1132   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
1133   unsigned NumParams = Record[Idx++];
1134   SmallVector<ParmVarDecl *, 16> Params;
1135   Params.reserve(NumParams);
1136   for (unsigned I = 0; I != NumParams; ++I)
1137     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
1138   BD->setParams(Params);
1139 
1140   BD->setIsVariadic(Record[Idx++]);
1141   BD->setBlockMissingReturnType(Record[Idx++]);
1142   BD->setIsConversionFromLambda(Record[Idx++]);
1143 
1144   bool capturesCXXThis = Record[Idx++];
1145   unsigned numCaptures = Record[Idx++];
1146   SmallVector<BlockDecl::Capture, 16> captures;
1147   captures.reserve(numCaptures);
1148   for (unsigned i = 0; i != numCaptures; ++i) {
1149     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
1150     unsigned flags = Record[Idx++];
1151     bool byRef = (flags & 1);
1152     bool nested = (flags & 2);
1153     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : nullptr);
1154 
1155     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1156   }
1157   BD->setCaptures(Reader.getContext(), captures.begin(),
1158                   captures.end(), capturesCXXThis);
1159 }
1160 
1161 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1162   VisitDecl(CD);
1163   unsigned ContextParamPos = Record[Idx++];
1164   CD->setNothrow(Record[Idx++] != 0);
1165   // Body is set by VisitCapturedStmt.
1166   for (unsigned I = 0; I < CD->NumParams; ++I) {
1167     if (I != ContextParamPos)
1168       CD->setParam(I, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1169     else
1170       CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1171   }
1172 }
1173 
1174 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1175   VisitDecl(D);
1176   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1177   D->setExternLoc(ReadSourceLocation(Record, Idx));
1178   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1179 }
1180 
1181 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1182   VisitNamedDecl(D);
1183   D->setLocStart(ReadSourceLocation(Record, Idx));
1184 }
1185 
1186 
1187 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1188   RedeclarableResult Redecl = VisitRedeclarable(D);
1189   VisitNamedDecl(D);
1190   D->setInline(Record[Idx++]);
1191   D->LocStart = ReadSourceLocation(Record, Idx);
1192   D->RBraceLoc = ReadSourceLocation(Record, Idx);
1193 
1194   if (Redecl.getFirstID() == ThisDeclID) {
1195     // Each module has its own anonymous namespace, which is disjoint from
1196     // any other module's anonymous namespaces, so don't attach the anonymous
1197     // namespace at all.
1198     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
1199     if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule)
1200       D->setAnonymousNamespace(Anon);
1201   } else {
1202     // Link this namespace back to the first declaration, which has already
1203     // been deserialized.
1204     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1205   }
1206 
1207   mergeRedeclarable(D, Redecl);
1208 }
1209 
1210 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1211   RedeclarableResult Redecl = VisitRedeclarable(D);
1212   VisitNamedDecl(D);
1213   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1214   D->IdentLoc = ReadSourceLocation(Record, Idx);
1215   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1216   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1217   mergeRedeclarable(D, Redecl);
1218 }
1219 
1220 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1221   VisitNamedDecl(D);
1222   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1223   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1224   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1225   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1226   D->setTypename(Record[Idx++]);
1227   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1228     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1229   mergeMergeable(D);
1230 }
1231 
1232 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1233   RedeclarableResult Redecl = VisitRedeclarable(D);
1234   VisitNamedDecl(D);
1235   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1236   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1237   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1238   if (Pattern)
1239     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1240   mergeRedeclarable(D, Redecl);
1241 }
1242 
1243 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1244   VisitNamedDecl(D);
1245   D->UsingLoc = ReadSourceLocation(Record, Idx);
1246   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1247   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1248   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1249   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1250 }
1251 
1252 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1253   VisitValueDecl(D);
1254   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1255   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1256   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1257   mergeMergeable(D);
1258 }
1259 
1260 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1261                                                UnresolvedUsingTypenameDecl *D) {
1262   VisitTypeDecl(D);
1263   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1264   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1265   mergeMergeable(D);
1266 }
1267 
1268 void ASTDeclReader::ReadCXXDefinitionData(
1269                                    struct CXXRecordDecl::DefinitionData &Data,
1270                                    const RecordData &Record, unsigned &Idx) {
1271   // Note: the caller has deserialized the IsLambda bit already.
1272   Data.UserDeclaredConstructor = Record[Idx++];
1273   Data.UserDeclaredSpecialMembers = Record[Idx++];
1274   Data.Aggregate = Record[Idx++];
1275   Data.PlainOldData = Record[Idx++];
1276   Data.Empty = Record[Idx++];
1277   Data.Polymorphic = Record[Idx++];
1278   Data.Abstract = Record[Idx++];
1279   Data.IsStandardLayout = Record[Idx++];
1280   Data.HasNoNonEmptyBases = Record[Idx++];
1281   Data.HasPrivateFields = Record[Idx++];
1282   Data.HasProtectedFields = Record[Idx++];
1283   Data.HasPublicFields = Record[Idx++];
1284   Data.HasMutableFields = Record[Idx++];
1285   Data.HasVariantMembers = Record[Idx++];
1286   Data.HasOnlyCMembers = Record[Idx++];
1287   Data.HasInClassInitializer = Record[Idx++];
1288   Data.HasUninitializedReferenceMember = Record[Idx++];
1289   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1290   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1291   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1292   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1293   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1294   Data.DefaultedDestructorIsDeleted = Record[Idx++];
1295   Data.HasTrivialSpecialMembers = Record[Idx++];
1296   Data.DeclaredNonTrivialSpecialMembers = Record[Idx++];
1297   Data.HasIrrelevantDestructor = Record[Idx++];
1298   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1299   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1300   Data.HasConstexprDefaultConstructor = Record[Idx++];
1301   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1302   Data.ComputedVisibleConversions = Record[Idx++];
1303   Data.UserProvidedDefaultConstructor = Record[Idx++];
1304   Data.DeclaredSpecialMembers = Record[Idx++];
1305   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1306   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1307   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1308   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1309 
1310   Data.NumBases = Record[Idx++];
1311   if (Data.NumBases)
1312     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1313   Data.NumVBases = Record[Idx++];
1314   if (Data.NumVBases)
1315     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1316 
1317   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1318   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1319   assert(Data.Definition && "Data.Definition should be already set!");
1320   Data.FirstFriend = ReadDeclID(Record, Idx);
1321 
1322   if (Data.IsLambda) {
1323     typedef LambdaCapture Capture;
1324     CXXRecordDecl::LambdaDefinitionData &Lambda
1325       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1326     Lambda.Dependent = Record[Idx++];
1327     Lambda.IsGenericLambda = Record[Idx++];
1328     Lambda.CaptureDefault = Record[Idx++];
1329     Lambda.NumCaptures = Record[Idx++];
1330     Lambda.NumExplicitCaptures = Record[Idx++];
1331     Lambda.ManglingNumber = Record[Idx++];
1332     Lambda.ContextDecl = ReadDecl(Record, Idx);
1333     Lambda.Captures
1334       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1335     Capture *ToCapture = Lambda.Captures;
1336     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1337     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1338       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1339       bool IsImplicit = Record[Idx++];
1340       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1341       switch (Kind) {
1342       case LCK_This:
1343       case LCK_VLAType:
1344         *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1345         break;
1346       case LCK_ByCopy:
1347       case LCK_ByRef:
1348         VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1349         SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1350         *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1351         break;
1352       }
1353     }
1354   }
1355 }
1356 
1357 void ASTDeclReader::MergeDefinitionData(
1358     CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1359   assert(D->DefinitionData.getNotUpdated() &&
1360          "merging class definition into non-definition");
1361   auto &DD = *D->DefinitionData.getNotUpdated();
1362 
1363   if (Reader.PendingFakeDefinitionData.count(&DD)) {
1364     // We faked up this definition data because we found a class for which we'd
1365     // not yet loaded the definition. Replace it with the real thing now.
1366     Reader.PendingFakeDefinitionData.erase(&DD);
1367     assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1368 
1369     // Don't change which declaration is the definition; that is required
1370     // to be invariant once we select it.
1371     auto *Def = DD.Definition;
1372     DD = std::move(MergeDD);
1373     DD.Definition = Def;
1374     return;
1375   }
1376 
1377   // If the new definition has new special members, let the name lookup
1378   // code know that it needs to look in the new definition too.
1379   //
1380   // FIXME: We only need to do this if the merged definition declares members
1381   // that this definition did not declare, or if it defines members that this
1382   // definition did not define.
1383   if (MergeDD.DeclaredSpecialMembers && DD.Definition != MergeDD.Definition) {
1384     Reader.MergedLookups[DD.Definition].push_back(MergeDD.Definition);
1385     DD.Definition->setHasExternalVisibleStorage();
1386   }
1387 
1388   // FIXME: Move this out into a .def file?
1389   // FIXME: Issue a diagnostic on a mismatched MATCH_FIELD, rather than
1390   // asserting; this can happen in the case of an ODR violation.
1391   bool DetectedOdrViolation = false;
1392 #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
1393 #define MATCH_FIELD(Field) \
1394     DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1395     OR_FIELD(Field)
1396   MATCH_FIELD(UserDeclaredConstructor)
1397   MATCH_FIELD(UserDeclaredSpecialMembers)
1398   MATCH_FIELD(Aggregate)
1399   MATCH_FIELD(PlainOldData)
1400   MATCH_FIELD(Empty)
1401   MATCH_FIELD(Polymorphic)
1402   MATCH_FIELD(Abstract)
1403   MATCH_FIELD(IsStandardLayout)
1404   MATCH_FIELD(HasNoNonEmptyBases)
1405   MATCH_FIELD(HasPrivateFields)
1406   MATCH_FIELD(HasProtectedFields)
1407   MATCH_FIELD(HasPublicFields)
1408   MATCH_FIELD(HasMutableFields)
1409   MATCH_FIELD(HasVariantMembers)
1410   MATCH_FIELD(HasOnlyCMembers)
1411   MATCH_FIELD(HasInClassInitializer)
1412   MATCH_FIELD(HasUninitializedReferenceMember)
1413   MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
1414   MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
1415   MATCH_FIELD(NeedOverloadResolutionForDestructor)
1416   MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
1417   MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
1418   MATCH_FIELD(DefaultedDestructorIsDeleted)
1419   OR_FIELD(HasTrivialSpecialMembers)
1420   OR_FIELD(DeclaredNonTrivialSpecialMembers)
1421   MATCH_FIELD(HasIrrelevantDestructor)
1422   OR_FIELD(HasConstexprNonCopyMoveConstructor)
1423   MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
1424   OR_FIELD(HasConstexprDefaultConstructor)
1425   MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
1426   // ComputedVisibleConversions is handled below.
1427   MATCH_FIELD(UserProvidedDefaultConstructor)
1428   OR_FIELD(DeclaredSpecialMembers)
1429   MATCH_FIELD(ImplicitCopyConstructorHasConstParam)
1430   MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
1431   OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
1432   OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
1433   MATCH_FIELD(IsLambda)
1434 #undef OR_FIELD
1435 #undef MATCH_FIELD
1436 
1437   if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1438     DetectedOdrViolation = true;
1439   // FIXME: Issue a diagnostic if the base classes don't match when we come
1440   // to lazily load them.
1441 
1442   // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1443   // match when we come to lazily load them.
1444   if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1445     DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1446     DD.ComputedVisibleConversions = true;
1447   }
1448 
1449   // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1450   // lazily load it.
1451 
1452   if (DD.IsLambda) {
1453     // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1454     // when they occur within the body of a function template specialization).
1455   }
1456 
1457   if (DetectedOdrViolation)
1458     Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition);
1459 }
1460 
1461 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D) {
1462   struct CXXRecordDecl::DefinitionData *DD;
1463   ASTContext &C = Reader.getContext();
1464 
1465   // Determine whether this is a lambda closure type, so that we can
1466   // allocate the appropriate DefinitionData structure.
1467   bool IsLambda = Record[Idx++];
1468   if (IsLambda)
1469     DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1470                                                      LCD_None);
1471   else
1472     DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1473 
1474   ReadCXXDefinitionData(*DD, Record, Idx);
1475 
1476   // We might already have a definition for this record. This can happen either
1477   // because we're reading an update record, or because we've already done some
1478   // merging. Either way, just merge into it.
1479   CXXRecordDecl *Canon = D->getCanonicalDecl();
1480   if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
1481     if (CanonDD->Definition != DD->Definition)
1482       Reader.MergedDeclContexts.insert(
1483           std::make_pair(DD->Definition, CanonDD->Definition));
1484     MergeDefinitionData(Canon, std::move(*DD));
1485     D->DefinitionData = Canon->DefinitionData;
1486     return;
1487   }
1488 
1489   // Propagate the DefinitionData pointer to the canonical declaration, so
1490   // that all other deserialized declarations will see it.
1491   if (Canon == D) {
1492     D->DefinitionData = DD;
1493     D->IsCompleteDefinition = true;
1494   } else if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
1495     // We have already deserialized a definition of this record. This
1496     // definition is no longer really a definition. Note that the pre-existing
1497     // definition is the *real* definition.
1498     Reader.MergedDeclContexts.insert(
1499         std::make_pair(D, CanonDD->Definition));
1500     D->DefinitionData = Canon->DefinitionData;
1501     D->IsCompleteDefinition = false;
1502     MergeDefinitionData(D, std::move(*DD));
1503   } else {
1504     Canon->DefinitionData = DD;
1505     D->DefinitionData = Canon->DefinitionData;
1506     D->IsCompleteDefinition = true;
1507 
1508     // Note that we have deserialized a definition. Any declarations
1509     // deserialized before this one will be be given the DefinitionData
1510     // pointer at the end.
1511     Reader.PendingDefinitions.insert(D);
1512   }
1513 }
1514 
1515 ASTDeclReader::RedeclarableResult
1516 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1517   RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1518 
1519   ASTContext &C = Reader.getContext();
1520 
1521   enum CXXRecKind {
1522     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1523   };
1524   switch ((CXXRecKind)Record[Idx++]) {
1525   case CXXRecNotTemplate:
1526     // Merged when we merge the folding set entry in the primary template.
1527     if (!isa<ClassTemplateSpecializationDecl>(D))
1528       mergeRedeclarable(D, Redecl);
1529     break;
1530   case CXXRecTemplate: {
1531     // Merged when we merge the template.
1532     ClassTemplateDecl *Template = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1533     D->TemplateOrInstantiation = Template;
1534     if (!Template->getTemplatedDecl()) {
1535       // We've not actually loaded the ClassTemplateDecl yet, because we're
1536       // currently being loaded as its pattern. Rely on it to set up our
1537       // TypeForDecl (see VisitClassTemplateDecl).
1538       //
1539       // Beware: we do not yet know our canonical declaration, and may still
1540       // get merged once the surrounding class template has got off the ground.
1541       TypeIDForTypeDecl = 0;
1542     }
1543     break;
1544   }
1545   case CXXRecMemberSpecialization: {
1546     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1547     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1548     SourceLocation POI = ReadSourceLocation(Record, Idx);
1549     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1550     MSI->setPointOfInstantiation(POI);
1551     D->TemplateOrInstantiation = MSI;
1552     mergeRedeclarable(D, Redecl);
1553     break;
1554   }
1555   }
1556 
1557   bool WasDefinition = Record[Idx++];
1558   if (WasDefinition)
1559     ReadCXXRecordDefinition(D);
1560   else
1561     // Propagate DefinitionData pointer from the canonical declaration.
1562     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1563 
1564   // Lazily load the key function to avoid deserializing every method so we can
1565   // compute it.
1566   if (WasDefinition) {
1567     DeclID KeyFn = ReadDeclID(Record, Idx);
1568     if (KeyFn && D->IsCompleteDefinition)
1569       // FIXME: This is wrong for the ARM ABI, where some other module may have
1570       // made this function no longer be a key function. We need an update
1571       // record or similar for that case.
1572       C.KeyFunctions[D] = KeyFn;
1573   }
1574 
1575   return Redecl;
1576 }
1577 
1578 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1579   VisitFunctionDecl(D);
1580 
1581   unsigned NumOverridenMethods = Record[Idx++];
1582   if (D->isCanonicalDecl()) {
1583     while (NumOverridenMethods--) {
1584       // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1585       // MD may be initializing.
1586       if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1587         Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1588     }
1589   } else {
1590     // We don't care about which declarations this used to override; we get
1591     // the relevant information from the canonical declaration.
1592     Idx += NumOverridenMethods;
1593   }
1594 }
1595 
1596 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1597   VisitCXXMethodDecl(D);
1598 
1599   if (auto *CD = ReadDeclAs<CXXConstructorDecl>(Record, Idx))
1600     D->setInheritedConstructor(CD);
1601   D->IsExplicitSpecified = Record[Idx++];
1602   // FIXME: We should defer loading this until we need the constructor's body.
1603   std::tie(D->CtorInitializers, D->NumCtorInitializers) =
1604       Reader.ReadCXXCtorInitializers(F, Record, Idx);
1605 }
1606 
1607 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1608   VisitCXXMethodDecl(D);
1609 
1610   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1611 }
1612 
1613 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1614   VisitCXXMethodDecl(D);
1615   D->IsExplicitSpecified = Record[Idx++];
1616 }
1617 
1618 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1619   VisitDecl(D);
1620   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1621   D->ImportedAndComplete.setInt(Record[Idx++]);
1622   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1623   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1624     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1625   ++Idx; // The number of stored source locations.
1626 }
1627 
1628 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1629   VisitDecl(D);
1630   D->setColonLoc(ReadSourceLocation(Record, Idx));
1631 }
1632 
1633 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1634   VisitDecl(D);
1635   if (Record[Idx++]) // hasFriendDecl
1636     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1637   else
1638     D->Friend = GetTypeSourceInfo(Record, Idx);
1639   for (unsigned i = 0; i != D->NumTPLists; ++i)
1640     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1641   D->NextFriend = ReadDeclID(Record, Idx);
1642   D->UnsupportedFriend = (Record[Idx++] != 0);
1643   D->FriendLoc = ReadSourceLocation(Record, Idx);
1644 }
1645 
1646 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1647   VisitDecl(D);
1648   unsigned NumParams = Record[Idx++];
1649   D->NumParams = NumParams;
1650   D->Params = new TemplateParameterList*[NumParams];
1651   for (unsigned i = 0; i != NumParams; ++i)
1652     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1653   if (Record[Idx++]) // HasFriendDecl
1654     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1655   else
1656     D->Friend = GetTypeSourceInfo(Record, Idx);
1657   D->FriendLoc = ReadSourceLocation(Record, Idx);
1658 }
1659 
1660 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1661   VisitNamedDecl(D);
1662 
1663   DeclID PatternID = ReadDeclID(Record, Idx);
1664   NamedDecl *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
1665   TemplateParameterList* TemplateParams
1666       = Reader.ReadTemplateParameterList(F, Record, Idx);
1667   D->init(TemplatedDecl, TemplateParams);
1668 
1669   // FIXME: If this is a redeclaration of a template from another module, handle
1670   // inheritance of default template arguments.
1671 
1672   return PatternID;
1673 }
1674 
1675 ASTDeclReader::RedeclarableResult
1676 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1677   RedeclarableResult Redecl = VisitRedeclarable(D);
1678 
1679   // Make sure we've allocated the Common pointer first. We do this before
1680   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1681   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1682   if (!CanonD->Common) {
1683     CanonD->Common = CanonD->newCommon(Reader.getContext());
1684     Reader.PendingDefinitions.insert(CanonD);
1685   }
1686   D->Common = CanonD->Common;
1687 
1688   // If this is the first declaration of the template, fill in the information
1689   // for the 'common' pointer.
1690   if (ThisDeclID == Redecl.getFirstID()) {
1691     if (RedeclarableTemplateDecl *RTD
1692           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1693       assert(RTD->getKind() == D->getKind() &&
1694              "InstantiatedFromMemberTemplate kind mismatch");
1695       D->setInstantiatedFromMemberTemplate(RTD);
1696       if (Record[Idx++])
1697         D->setMemberSpecialization();
1698     }
1699   }
1700 
1701   DeclID PatternID = VisitTemplateDecl(D);
1702   D->IdentifierNamespace = Record[Idx++];
1703 
1704   mergeRedeclarable(D, Redecl, PatternID);
1705 
1706   // If we merged the template with a prior declaration chain, merge the common
1707   // pointer.
1708   // FIXME: Actually merge here, don't just overwrite.
1709   D->Common = D->getCanonicalDecl()->Common;
1710 
1711   return Redecl;
1712 }
1713 
1714 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1715   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1716 
1717   if (ThisDeclID == Redecl.getFirstID()) {
1718     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1719     // the specializations.
1720     SmallVector<serialization::DeclID, 2> SpecIDs;
1721     SpecIDs.push_back(0);
1722 
1723     // Specializations.
1724     unsigned Size = Record[Idx++];
1725     SpecIDs[0] += Size;
1726     for (unsigned I = 0; I != Size; ++I)
1727       SpecIDs.push_back(ReadDeclID(Record, Idx));
1728 
1729     // Partial specializations.
1730     Size = Record[Idx++];
1731     SpecIDs[0] += Size;
1732     for (unsigned I = 0; I != Size; ++I)
1733       SpecIDs.push_back(ReadDeclID(Record, Idx));
1734 
1735     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1736     if (SpecIDs[0]) {
1737       typedef serialization::DeclID DeclID;
1738 
1739       // FIXME: Append specializations!
1740       CommonPtr->LazySpecializations
1741         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1742       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1743              SpecIDs.size() * sizeof(DeclID));
1744     }
1745   }
1746 
1747   if (D->getTemplatedDecl()->TemplateOrInstantiation) {
1748     // We were loaded before our templated declaration was. We've not set up
1749     // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
1750     // it now.
1751     Reader.Context.getInjectedClassNameType(
1752         D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
1753   }
1754 }
1755 
1756 /// TODO: Unify with ClassTemplateDecl version?
1757 ///       May require unifying ClassTemplateDecl and
1758 ///        VarTemplateDecl beyond TemplateDecl...
1759 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1760   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1761 
1762   if (ThisDeclID == Redecl.getFirstID()) {
1763     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1764     // the specializations.
1765     SmallVector<serialization::DeclID, 2> SpecIDs;
1766     SpecIDs.push_back(0);
1767 
1768     // Specializations.
1769     unsigned Size = Record[Idx++];
1770     SpecIDs[0] += Size;
1771     for (unsigned I = 0; I != Size; ++I)
1772       SpecIDs.push_back(ReadDeclID(Record, Idx));
1773 
1774     // Partial specializations.
1775     Size = Record[Idx++];
1776     SpecIDs[0] += Size;
1777     for (unsigned I = 0; I != Size; ++I)
1778       SpecIDs.push_back(ReadDeclID(Record, Idx));
1779 
1780     VarTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1781     if (SpecIDs[0]) {
1782       typedef serialization::DeclID DeclID;
1783 
1784       // FIXME: Append specializations!
1785       CommonPtr->LazySpecializations =
1786           new (Reader.getContext()) DeclID[SpecIDs.size()];
1787       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1788              SpecIDs.size() * sizeof(DeclID));
1789     }
1790   }
1791 }
1792 
1793 ASTDeclReader::RedeclarableResult
1794 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
1795     ClassTemplateSpecializationDecl *D) {
1796   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
1797 
1798   ASTContext &C = Reader.getContext();
1799   if (Decl *InstD = ReadDecl(Record, Idx)) {
1800     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1801       D->SpecializedTemplate = CTD;
1802     } else {
1803       SmallVector<TemplateArgument, 8> TemplArgs;
1804       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1805       TemplateArgumentList *ArgList
1806         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1807                                            TemplArgs.size());
1808       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1809           = new (C) ClassTemplateSpecializationDecl::
1810                                              SpecializedPartialSpecialization();
1811       PS->PartialSpecialization
1812           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1813       PS->TemplateArgs = ArgList;
1814       D->SpecializedTemplate = PS;
1815     }
1816   }
1817 
1818   SmallVector<TemplateArgument, 8> TemplArgs;
1819   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1820   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1821                                                      TemplArgs.size());
1822   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1823   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1824 
1825   bool writtenAsCanonicalDecl = Record[Idx++];
1826   if (writtenAsCanonicalDecl) {
1827     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1828     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1829       // Set this as, or find, the canonical declaration for this specialization
1830       ClassTemplateSpecializationDecl *CanonSpec;
1831       if (ClassTemplatePartialSpecializationDecl *Partial =
1832               dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1833         CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
1834             .GetOrInsertNode(Partial);
1835       } else {
1836         CanonSpec =
1837             CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1838       }
1839       // If there was already a canonical specialization, merge into it.
1840       if (CanonSpec != D) {
1841         mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
1842 
1843         // This declaration might be a definition. Merge with any existing
1844         // definition.
1845         if (auto *DDD = D->DefinitionData.getNotUpdated()) {
1846           if (auto *CanonDD = CanonSpec->DefinitionData.getNotUpdated()) {
1847             MergeDefinitionData(CanonSpec, std::move(*DDD));
1848             Reader.PendingDefinitions.erase(D);
1849             Reader.MergedDeclContexts.insert(
1850                 std::make_pair(D, CanonDD->Definition));
1851             D->IsCompleteDefinition = false;
1852           } else {
1853             CanonSpec->DefinitionData = D->DefinitionData;
1854           }
1855         }
1856         D->DefinitionData = CanonSpec->DefinitionData;
1857       }
1858     }
1859   }
1860 
1861   // Explicit info.
1862   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1863     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1864         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1865     ExplicitInfo->TypeAsWritten = TyInfo;
1866     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1867     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1868     D->ExplicitInfo = ExplicitInfo;
1869   }
1870 
1871   return Redecl;
1872 }
1873 
1874 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1875                                     ClassTemplatePartialSpecializationDecl *D) {
1876   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
1877 
1878   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1879   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1880 
1881   // These are read/set from/to the first declaration.
1882   if (ThisDeclID == Redecl.getFirstID()) {
1883     D->InstantiatedFromMember.setPointer(
1884       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1885     D->InstantiatedFromMember.setInt(Record[Idx++]);
1886   }
1887 }
1888 
1889 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1890                                     ClassScopeFunctionSpecializationDecl *D) {
1891   VisitDecl(D);
1892   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1893 }
1894 
1895 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1896   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1897 
1898   if (ThisDeclID == Redecl.getFirstID()) {
1899     // This FunctionTemplateDecl owns a CommonPtr; read it.
1900 
1901     // Read the function specialization declaration IDs. The specializations
1902     // themselves will be loaded if they're needed.
1903     if (unsigned NumSpecs = Record[Idx++]) {
1904       // FIXME: Append specializations!
1905       FunctionTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1906       CommonPtr->LazySpecializations = new (Reader.getContext())
1907           serialization::DeclID[NumSpecs + 1];
1908       CommonPtr->LazySpecializations[0] = NumSpecs;
1909       for (unsigned I = 0; I != NumSpecs; ++I)
1910         CommonPtr->LazySpecializations[I + 1] = ReadDeclID(Record, Idx);
1911     }
1912   }
1913 }
1914 
1915 /// TODO: Unify with ClassTemplateSpecializationDecl version?
1916 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1917 ///        VarTemplate(Partial)SpecializationDecl with a new data
1918 ///        structure Template(Partial)SpecializationDecl, and
1919 ///        using Template(Partial)SpecializationDecl as input type.
1920 ASTDeclReader::RedeclarableResult
1921 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
1922     VarTemplateSpecializationDecl *D) {
1923   RedeclarableResult Redecl = VisitVarDeclImpl(D);
1924 
1925   ASTContext &C = Reader.getContext();
1926   if (Decl *InstD = ReadDecl(Record, Idx)) {
1927     if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
1928       D->SpecializedTemplate = VTD;
1929     } else {
1930       SmallVector<TemplateArgument, 8> TemplArgs;
1931       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1932       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
1933           C, TemplArgs.data(), TemplArgs.size());
1934       VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
1935           new (C)
1936           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
1937       PS->PartialSpecialization =
1938           cast<VarTemplatePartialSpecializationDecl>(InstD);
1939       PS->TemplateArgs = ArgList;
1940       D->SpecializedTemplate = PS;
1941     }
1942   }
1943 
1944   // Explicit info.
1945   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1946     VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
1947         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
1948     ExplicitInfo->TypeAsWritten = TyInfo;
1949     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1950     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1951     D->ExplicitInfo = ExplicitInfo;
1952   }
1953 
1954   SmallVector<TemplateArgument, 8> TemplArgs;
1955   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1956   D->TemplateArgs =
1957       TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
1958   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1959   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1960 
1961   bool writtenAsCanonicalDecl = Record[Idx++];
1962   if (writtenAsCanonicalDecl) {
1963     VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
1964     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1965       if (VarTemplatePartialSpecializationDecl *Partial =
1966               dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
1967         CanonPattern->getCommonPtr()->PartialSpecializations
1968             .GetOrInsertNode(Partial);
1969       } else {
1970         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1971       }
1972     }
1973   }
1974 
1975   return Redecl;
1976 }
1977 
1978 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
1979 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1980 ///        VarTemplate(Partial)SpecializationDecl with a new data
1981 ///        structure Template(Partial)SpecializationDecl, and
1982 ///        using Template(Partial)SpecializationDecl as input type.
1983 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
1984     VarTemplatePartialSpecializationDecl *D) {
1985   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
1986 
1987   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1988   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1989 
1990   // These are read/set from/to the first declaration.
1991   if (ThisDeclID == Redecl.getFirstID()) {
1992     D->InstantiatedFromMember.setPointer(
1993         ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
1994     D->InstantiatedFromMember.setInt(Record[Idx++]);
1995   }
1996 }
1997 
1998 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1999   VisitTypeDecl(D);
2000 
2001   D->setDeclaredWithTypename(Record[Idx++]);
2002 
2003   bool Inherited = Record[Idx++];
2004   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
2005   D->setDefaultArgument(DefArg, Inherited);
2006 }
2007 
2008 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2009   VisitDeclaratorDecl(D);
2010   // TemplateParmPosition.
2011   D->setDepth(Record[Idx++]);
2012   D->setPosition(Record[Idx++]);
2013   if (D->isExpandedParameterPack()) {
2014     void **Data = reinterpret_cast<void **>(D + 1);
2015     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2016       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
2017       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
2018     }
2019   } else {
2020     // Rest of NonTypeTemplateParmDecl.
2021     D->ParameterPack = Record[Idx++];
2022     if (Record[Idx++]) {
2023       Expr *DefArg = Reader.ReadExpr(F);
2024       bool Inherited = Record[Idx++];
2025       D->setDefaultArgument(DefArg, Inherited);
2026    }
2027   }
2028 }
2029 
2030 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2031   VisitTemplateDecl(D);
2032   // TemplateParmPosition.
2033   D->setDepth(Record[Idx++]);
2034   D->setPosition(Record[Idx++]);
2035   if (D->isExpandedParameterPack()) {
2036     void **Data = reinterpret_cast<void **>(D + 1);
2037     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2038          I != N; ++I)
2039       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
2040   } else {
2041     // Rest of TemplateTemplateParmDecl.
2042     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
2043     bool IsInherited = Record[Idx++];
2044     D->setDefaultArgument(Arg, IsInherited);
2045     D->ParameterPack = Record[Idx++];
2046   }
2047 }
2048 
2049 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2050   VisitRedeclarableTemplateDecl(D);
2051 }
2052 
2053 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2054   VisitDecl(D);
2055   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
2056   D->AssertExprAndFailed.setInt(Record[Idx++]);
2057   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
2058   D->RParenLoc = ReadSourceLocation(Record, Idx);
2059 }
2060 
2061 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2062   VisitDecl(D);
2063 }
2064 
2065 std::pair<uint64_t, uint64_t>
2066 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2067   uint64_t LexicalOffset = Record[Idx++];
2068   uint64_t VisibleOffset = Record[Idx++];
2069   return std::make_pair(LexicalOffset, VisibleOffset);
2070 }
2071 
2072 template <typename T>
2073 ASTDeclReader::RedeclarableResult
2074 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2075   DeclID FirstDeclID = ReadDeclID(Record, Idx);
2076 
2077   // 0 indicates that this declaration was the only declaration of its entity,
2078   // and is used for space optimization.
2079   if (FirstDeclID == 0)
2080     FirstDeclID = ThisDeclID;
2081 
2082   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2083   if (FirstDecl != D) {
2084     // We delay loading of the redeclaration chain to avoid deeply nested calls.
2085     // We temporarily set the first (canonical) declaration as the previous one
2086     // which is the one that matters and mark the real previous DeclID to be
2087     // loaded & attached later on.
2088     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2089   }
2090 
2091   // Note that this declaration has been deserialized.
2092   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
2093 
2094   // The result structure takes care to note that we need to load the
2095   // other declaration chains for this ID.
2096   return RedeclarableResult(Reader, FirstDeclID,
2097                             static_cast<T *>(D)->getKind());
2098 }
2099 
2100 /// \brief Attempts to merge the given declaration (D) with another declaration
2101 /// of the same entity.
2102 template<typename T>
2103 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2104                                       RedeclarableResult &Redecl,
2105                                       DeclID TemplatePatternID) {
2106   T *D = static_cast<T*>(DBase);
2107   T *DCanon = D->getCanonicalDecl();
2108   if (D != DCanon &&
2109       // IDs < NUM_PREDEF_DECL_IDS are not loaded from an AST file.
2110       Redecl.getFirstID() >= NUM_PREDEF_DECL_IDS &&
2111       (!Reader.getContext().getLangOpts().Modules ||
2112        Reader.getOwningModuleFile(DCanon) == Reader.getOwningModuleFile(D))) {
2113     // All redeclarations between this declaration and its originally-canonical
2114     // declaration get pulled in when we load DCanon; we don't need to
2115     // perform any more merging now.
2116     Redecl.suppress();
2117   }
2118 
2119   // If modules are not available, there is no reason to perform this merge.
2120   if (!Reader.getContext().getLangOpts().Modules)
2121     return;
2122 
2123   if (FindExistingResult ExistingRes = findExisting(D))
2124     if (T *Existing = ExistingRes)
2125       mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2126 }
2127 
2128 /// \brief "Cast" to type T, asserting if we don't have an implicit conversion.
2129 /// We use this to put code in a template that will only be valid for certain
2130 /// instantiations.
2131 template<typename T> static T assert_cast(T t) { return t; }
2132 template<typename T> static T assert_cast(...) {
2133   llvm_unreachable("bad assert_cast");
2134 }
2135 
2136 /// \brief Merge together the pattern declarations from two template
2137 /// declarations.
2138 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2139                                          RedeclarableTemplateDecl *Existing,
2140                                          DeclID DsID) {
2141   auto *DPattern = D->getTemplatedDecl();
2142   auto *ExistingPattern = Existing->getTemplatedDecl();
2143   RedeclarableResult Result(Reader, DPattern->getCanonicalDecl()->getGlobalID(),
2144                             DPattern->getKind());
2145 
2146   if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2147     // Merge with any existing definition.
2148     // FIXME: This is duplicated in several places. Refactor.
2149     auto *ExistingClass =
2150         cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2151     if (auto *DDD = DClass->DefinitionData.getNotUpdated()) {
2152       if (auto *ExistingDD = ExistingClass->DefinitionData.getNotUpdated()) {
2153         MergeDefinitionData(ExistingClass, std::move(*DDD));
2154         Reader.PendingDefinitions.erase(DClass);
2155         Reader.MergedDeclContexts.insert(
2156             std::make_pair(DClass, ExistingDD->Definition));
2157         DClass->IsCompleteDefinition = false;
2158       } else {
2159         ExistingClass->DefinitionData = DClass->DefinitionData;
2160       }
2161     }
2162     DClass->DefinitionData = ExistingClass->DefinitionData;
2163 
2164     return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2165                              Result);
2166   }
2167   if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2168     return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2169                              Result);
2170   if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2171     return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2172   if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2173     return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2174                              Result);
2175   llvm_unreachable("merged an unknown kind of redeclarable template");
2176 }
2177 
2178 /// \brief Attempts to merge the given declaration (D) with another declaration
2179 /// of the same entity.
2180 template<typename T>
2181 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2182                                       RedeclarableResult &Redecl,
2183                                       DeclID TemplatePatternID) {
2184   T *D = static_cast<T*>(DBase);
2185   T *ExistingCanon = Existing->getCanonicalDecl();
2186   T *DCanon = D->getCanonicalDecl();
2187   if (ExistingCanon != DCanon) {
2188     assert(DCanon->getGlobalID() == Redecl.getFirstID());
2189 
2190     // Have our redeclaration link point back at the canonical declaration
2191     // of the existing declaration, so that this declaration has the
2192     // appropriate canonical declaration.
2193     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2194 
2195     // When we merge a namespace, update its pointer to the first namespace.
2196     if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2197       Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2198           assert_cast<NamespaceDecl*>(ExistingCanon));
2199 
2200     // When we merge a template, merge its pattern.
2201     if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2202       mergeTemplatePattern(
2203           DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2204           TemplatePatternID);
2205 
2206     // If this declaration was the canonical declaration, make a note of
2207     // that. We accept the linear algorithm here because the number of
2208     // unique canonical declarations of an entity should always be tiny.
2209     if (DCanon == D) {
2210       SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
2211       if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
2212             == Merged.end())
2213         Merged.push_back(Redecl.getFirstID());
2214     }
2215   }
2216 }
2217 
2218 /// \brief Attempts to merge the given declaration (D) with another declaration
2219 /// of the same entity, for the case where the entity is not actually
2220 /// redeclarable. This happens, for instance, when merging the fields of
2221 /// identical class definitions from two different modules.
2222 template<typename T>
2223 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2224   // If modules are not available, there is no reason to perform this merge.
2225   if (!Reader.getContext().getLangOpts().Modules)
2226     return;
2227 
2228   // ODR-based merging is only performed in C++. In C, identically-named things
2229   // in different translation units are not redeclarations (but may still have
2230   // compatible types).
2231   if (!Reader.getContext().getLangOpts().CPlusPlus)
2232     return;
2233 
2234   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2235     if (T *Existing = ExistingRes)
2236       Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
2237                                           Existing->getCanonicalDecl());
2238 }
2239 
2240 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2241   VisitDecl(D);
2242   unsigned NumVars = D->varlist_size();
2243   SmallVector<Expr *, 16> Vars;
2244   Vars.reserve(NumVars);
2245   for (unsigned i = 0; i != NumVars; ++i) {
2246     Vars.push_back(Reader.ReadExpr(F));
2247   }
2248   D->setVars(Vars);
2249 }
2250 
2251 //===----------------------------------------------------------------------===//
2252 // Attribute Reading
2253 //===----------------------------------------------------------------------===//
2254 
2255 /// \brief Reads attributes from the current stream position.
2256 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
2257                                const RecordData &Record, unsigned &Idx) {
2258   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
2259     Attr *New = nullptr;
2260     attr::Kind Kind = (attr::Kind)Record[Idx++];
2261     SourceRange Range = ReadSourceRange(F, Record, Idx);
2262 
2263 #include "clang/Serialization/AttrPCHRead.inc"
2264 
2265     assert(New && "Unable to decode attribute?");
2266     Attrs.push_back(New);
2267   }
2268 }
2269 
2270 //===----------------------------------------------------------------------===//
2271 // ASTReader Implementation
2272 //===----------------------------------------------------------------------===//
2273 
2274 /// \brief Note that we have loaded the declaration with the given
2275 /// Index.
2276 ///
2277 /// This routine notes that this declaration has already been loaded,
2278 /// so that future GetDecl calls will return this declaration rather
2279 /// than trying to load a new declaration.
2280 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2281   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2282   DeclsLoaded[Index] = D;
2283 }
2284 
2285 
2286 /// \brief Determine whether the consumer will be interested in seeing
2287 /// this declaration (via HandleTopLevelDecl).
2288 ///
2289 /// This routine should return true for anything that might affect
2290 /// code generation, e.g., inline function definitions, Objective-C
2291 /// declarations with metadata, etc.
2292 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
2293   // An ObjCMethodDecl is never considered as "interesting" because its
2294   // implementation container always is.
2295 
2296   if (isa<FileScopeAsmDecl>(D) ||
2297       isa<ObjCProtocolDecl>(D) ||
2298       isa<ObjCImplDecl>(D) ||
2299       isa<ImportDecl>(D) ||
2300       isa<OMPThreadPrivateDecl>(D))
2301     return true;
2302   if (VarDecl *Var = dyn_cast<VarDecl>(D))
2303     return Var->isFileVarDecl() &&
2304            Var->isThisDeclarationADefinition() == VarDecl::Definition;
2305   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
2306     return Func->doesThisDeclarationHaveABody() || HasBody;
2307 
2308   return false;
2309 }
2310 
2311 /// \brief Get the correct cursor and offset for loading a declaration.
2312 ASTReader::RecordLocation
2313 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
2314   // See if there's an override.
2315   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
2316   if (It != ReplacedDecls.end()) {
2317     RawLocation = It->second.RawLoc;
2318     return RecordLocation(It->second.Mod, It->second.Offset);
2319   }
2320 
2321   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2322   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2323   ModuleFile *M = I->second;
2324   const DeclOffset &
2325     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2326   RawLocation = DOffs.Loc;
2327   return RecordLocation(M, DOffs.BitOffset);
2328 }
2329 
2330 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2331   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2332     = GlobalBitOffsetsMap.find(GlobalOffset);
2333 
2334   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2335   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2336 }
2337 
2338 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2339   return LocalOffset + M.GlobalBitOffset;
2340 }
2341 
2342 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2343                                         const TemplateParameterList *Y);
2344 
2345 /// \brief Determine whether two template parameters are similar enough
2346 /// that they may be used in declarations of the same template.
2347 static bool isSameTemplateParameter(const NamedDecl *X,
2348                                     const NamedDecl *Y) {
2349   if (X->getKind() != Y->getKind())
2350     return false;
2351 
2352   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2353     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2354     return TX->isParameterPack() == TY->isParameterPack();
2355   }
2356 
2357   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2358     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2359     return TX->isParameterPack() == TY->isParameterPack() &&
2360            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2361   }
2362 
2363   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2364   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2365   return TX->isParameterPack() == TY->isParameterPack() &&
2366          isSameTemplateParameterList(TX->getTemplateParameters(),
2367                                      TY->getTemplateParameters());
2368 }
2369 
2370 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2371   if (auto *NS = X->getAsNamespace())
2372     return NS;
2373   if (auto *NAS = X->getAsNamespaceAlias())
2374     return NAS->getNamespace();
2375   return nullptr;
2376 }
2377 
2378 static bool isSameQualifier(const NestedNameSpecifier *X,
2379                             const NestedNameSpecifier *Y) {
2380   if (auto *NSX = getNamespace(X)) {
2381     auto *NSY = getNamespace(Y);
2382     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2383       return false;
2384   } else if (X->getKind() != Y->getKind())
2385     return false;
2386 
2387   // FIXME: For namespaces and types, we're permitted to check that the entity
2388   // is named via the same tokens. We should probably do so.
2389   switch (X->getKind()) {
2390   case NestedNameSpecifier::Identifier:
2391     if (X->getAsIdentifier() != Y->getAsIdentifier())
2392       return false;
2393     break;
2394   case NestedNameSpecifier::Namespace:
2395   case NestedNameSpecifier::NamespaceAlias:
2396     // We've already checked that we named the same namespace.
2397     break;
2398   case NestedNameSpecifier::TypeSpec:
2399   case NestedNameSpecifier::TypeSpecWithTemplate:
2400     if (X->getAsType()->getCanonicalTypeInternal() !=
2401         Y->getAsType()->getCanonicalTypeInternal())
2402       return false;
2403     break;
2404   case NestedNameSpecifier::Global:
2405   case NestedNameSpecifier::Super:
2406     return true;
2407   }
2408 
2409   // Recurse into earlier portion of NNS, if any.
2410   auto *PX = X->getPrefix();
2411   auto *PY = Y->getPrefix();
2412   if (PX && PY)
2413     return isSameQualifier(PX, PY);
2414   return !PX && !PY;
2415 }
2416 
2417 /// \brief Determine whether two template parameter lists are similar enough
2418 /// that they may be used in declarations of the same template.
2419 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2420                                         const TemplateParameterList *Y) {
2421   if (X->size() != Y->size())
2422     return false;
2423 
2424   for (unsigned I = 0, N = X->size(); I != N; ++I)
2425     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2426       return false;
2427 
2428   return true;
2429 }
2430 
2431 /// \brief Determine whether the two declarations refer to the same entity.
2432 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2433   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2434 
2435   if (X == Y)
2436     return true;
2437 
2438   // Must be in the same context.
2439   if (!X->getDeclContext()->getRedeclContext()->Equals(
2440          Y->getDeclContext()->getRedeclContext()))
2441     return false;
2442 
2443   // Two typedefs refer to the same entity if they have the same underlying
2444   // type.
2445   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2446     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2447       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2448                                             TypedefY->getUnderlyingType());
2449 
2450   // Must have the same kind.
2451   if (X->getKind() != Y->getKind())
2452     return false;
2453 
2454   // Objective-C classes and protocols with the same name always match.
2455   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2456     return true;
2457 
2458   if (isa<ClassTemplateSpecializationDecl>(X)) {
2459     // No need to handle these here: we merge them when adding them to the
2460     // template.
2461     return false;
2462   }
2463 
2464   // Compatible tags match.
2465   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2466     TagDecl *TagY = cast<TagDecl>(Y);
2467     return (TagX->getTagKind() == TagY->getTagKind()) ||
2468       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2469         TagX->getTagKind() == TTK_Interface) &&
2470        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2471         TagY->getTagKind() == TTK_Interface));
2472   }
2473 
2474   // Functions with the same type and linkage match.
2475   // FIXME: This needs to cope with merging of prototyped/non-prototyped
2476   // functions, etc.
2477   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2478     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2479     return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
2480       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
2481   }
2482 
2483   // Variables with the same type and linkage match.
2484   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2485     VarDecl *VarY = cast<VarDecl>(Y);
2486     return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
2487       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
2488   }
2489 
2490   // Namespaces with the same name and inlinedness match.
2491   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2492     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2493     return NamespaceX->isInline() == NamespaceY->isInline();
2494   }
2495 
2496   // Identical template names and kinds match if their template parameter lists
2497   // and patterns match.
2498   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2499     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2500     return isSameEntity(TemplateX->getTemplatedDecl(),
2501                         TemplateY->getTemplatedDecl()) &&
2502            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2503                                        TemplateY->getTemplateParameters());
2504   }
2505 
2506   // Fields with the same name and the same type match.
2507   if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2508     FieldDecl *FDY = cast<FieldDecl>(Y);
2509     // FIXME: Also check the bitwidth is odr-equivalent, if any.
2510     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2511   }
2512 
2513   // Enumerators with the same name match.
2514   if (isa<EnumConstantDecl>(X))
2515     // FIXME: Also check the value is odr-equivalent.
2516     return true;
2517 
2518   // Using shadow declarations with the same target match.
2519   if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2520     UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2521     return USX->getTargetDecl() == USY->getTargetDecl();
2522   }
2523 
2524   // Using declarations with the same qualifier match. (We already know that
2525   // the name matches.)
2526   if (auto *UX = dyn_cast<UsingDecl>(X)) {
2527     auto *UY = cast<UsingDecl>(Y);
2528     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2529            UX->hasTypename() == UY->hasTypename() &&
2530            UX->isAccessDeclaration() == UY->isAccessDeclaration();
2531   }
2532   if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
2533     auto *UY = cast<UnresolvedUsingValueDecl>(Y);
2534     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2535            UX->isAccessDeclaration() == UY->isAccessDeclaration();
2536   }
2537   if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
2538     return isSameQualifier(
2539         UX->getQualifier(),
2540         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
2541 
2542   // Namespace alias definitions with the same target match.
2543   if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
2544     auto *NAY = cast<NamespaceAliasDecl>(Y);
2545     return NAX->getNamespace()->Equals(NAY->getNamespace());
2546   }
2547 
2548   // FIXME: Many other cases to implement.
2549   return false;
2550 }
2551 
2552 /// Find the context in which we should search for previous declarations when
2553 /// looking for declarations to merge.
2554 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
2555                                                         DeclContext *DC) {
2556   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2557     return ND->getOriginalNamespace();
2558 
2559   if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2560     // Try to dig out the definition.
2561     auto *DD = RD->DefinitionData.getNotUpdated();
2562     if (!DD)
2563       DD = RD->getCanonicalDecl()->DefinitionData.getNotUpdated();
2564 
2565     // If there's no definition yet, then DC's definition is added by an update
2566     // record, but we've not yet loaded that update record. In this case, we
2567     // commit to DC being the canonical definition now, and will fix this when
2568     // we load the update record.
2569     if (!DD) {
2570       DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD);
2571       RD->IsCompleteDefinition = true;
2572       RD->DefinitionData = DD;
2573       RD->getCanonicalDecl()->DefinitionData = DD;
2574 
2575       // Track that we did this horrible thing so that we can fix it later.
2576       Reader.PendingFakeDefinitionData.insert(DD);
2577     }
2578 
2579     return DD->Definition;
2580   }
2581 
2582   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2583     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
2584                                                       : nullptr;
2585 
2586   return nullptr;
2587 }
2588 
2589 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2590   // Record that we had a typedef name for linkage whether or not we merge
2591   // with that declaration.
2592   if (TypedefNameForLinkage) {
2593     DeclContext *DC = New->getDeclContext()->getRedeclContext();
2594     Reader.ImportedTypedefNamesForLinkage.insert(
2595         std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
2596     return;
2597   }
2598 
2599   if (!AddResult || Existing)
2600     return;
2601 
2602   DeclarationName Name = New->getDeclName();
2603   DeclContext *DC = New->getDeclContext()->getRedeclContext();
2604   if (!Name) {
2605     assert(needsAnonymousDeclarationNumber(New));
2606     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
2607                                AnonymousDeclNumber, New);
2608   } else if (DC->isTranslationUnit() && Reader.SemaObj) {
2609     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, Name);
2610   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2611     // Add the declaration to its redeclaration context so later merging
2612     // lookups will find it.
2613     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2614   }
2615 }
2616 
2617 /// Find the declaration that should be merged into, given the declaration found
2618 /// by name lookup. If we're merging an anonymous declaration within a typedef,
2619 /// we need a matching typedef, and we merge with the type inside it.
2620 static NamedDecl *getDeclForMerging(NamedDecl *Found,
2621                                     bool IsTypedefNameForLinkage) {
2622   if (!IsTypedefNameForLinkage)
2623     return Found;
2624 
2625   // If we found a typedef declaration that gives a name to some other
2626   // declaration, then we want that inner declaration. Declarations from
2627   // AST files are handled via ImportedTypedefNamesForLinkage.
2628   if (Found->isFromASTFile()) return 0;
2629   if (auto *TND = dyn_cast<TypedefNameDecl>(Found)) {
2630     if (auto *TT = TND->getTypeSourceInfo()->getType()->getAs<TagType>())
2631       if (TT->getDecl()->getTypedefNameForAnonDecl() == TND)
2632         return TT->getDecl();
2633   }
2634 
2635   return 0;
2636 }
2637 
2638 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
2639                                                      DeclContext *DC,
2640                                                      unsigned Index) {
2641   // If the lexical context has been merged, look into the now-canonical
2642   // definition.
2643   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2644     DC = Merged;
2645 
2646   // If we've seen this before, return the canonical declaration.
2647   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2648   if (Index < Previous.size() && Previous[Index])
2649     return Previous[Index];
2650 
2651   // If this is the first time, but we have parsed a declaration of the context,
2652   // build the anonymous declaration list from the parsed declaration.
2653   if (!cast<Decl>(DC)->isFromASTFile()) {
2654     unsigned Index = 0;
2655     for (Decl *LexicalD : DC->decls()) {
2656       auto *ND = dyn_cast<NamedDecl>(LexicalD);
2657       if (!ND || !needsAnonymousDeclarationNumber(ND))
2658         continue;
2659       if (Previous.size() == Index)
2660         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
2661       else
2662         Previous[Index] = cast<NamedDecl>(ND->getCanonicalDecl());
2663       ++Index;
2664     }
2665   }
2666 
2667   return Index < Previous.size() ? Previous[Index] : nullptr;
2668 }
2669 
2670 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
2671                                                DeclContext *DC, unsigned Index,
2672                                                NamedDecl *D) {
2673   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2674     DC = Merged;
2675 
2676   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2677   if (Index >= Previous.size())
2678     Previous.resize(Index + 1);
2679   if (!Previous[Index])
2680     Previous[Index] = D;
2681 }
2682 
2683 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2684   DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
2685                                                : D->getDeclName();
2686 
2687   if (!Name && !needsAnonymousDeclarationNumber(D)) {
2688     // Don't bother trying to find unnamed declarations that are in
2689     // unmergeable contexts.
2690     FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
2691                               AnonymousDeclNumber, TypedefNameForLinkage);
2692     // FIXME: We may still need to pull in the redeclaration chain; there can
2693     // be redeclarations via 'decltype'.
2694     Result.suppress();
2695     return Result;
2696   }
2697 
2698   // FIXME: Bail out for non-canonical declarations. We will have performed any
2699   // necessary merging already.
2700 
2701   DeclContext *DC = D->getDeclContext()->getRedeclContext();
2702   if (TypedefNameForLinkage) {
2703     auto It = Reader.ImportedTypedefNamesForLinkage.find(
2704         std::make_pair(DC, TypedefNameForLinkage));
2705     if (It != Reader.ImportedTypedefNamesForLinkage.end())
2706       if (isSameEntity(It->second, D))
2707         return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
2708                                   TypedefNameForLinkage);
2709     // Go on to check in other places in case an existing typedef name
2710     // was not imported.
2711   }
2712 
2713   if (!Name) {
2714     // This is an anonymous declaration that we may need to merge. Look it up
2715     // in its context by number.
2716     assert(needsAnonymousDeclarationNumber(D));
2717     if (auto *Existing = getAnonymousDeclForMerging(
2718             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
2719       if (isSameEntity(Existing, D))
2720         return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
2721                                   TypedefNameForLinkage);
2722   } else if (DC->isTranslationUnit() && Reader.SemaObj) {
2723     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
2724 
2725     // Temporarily consider the identifier to be up-to-date. We don't want to
2726     // cause additional lookups here.
2727     class UpToDateIdentifierRAII {
2728       IdentifierInfo *II;
2729       bool WasOutToDate;
2730 
2731     public:
2732       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
2733         : II(II), WasOutToDate(false)
2734       {
2735         if (II) {
2736           WasOutToDate = II->isOutOfDate();
2737           if (WasOutToDate)
2738             II->setOutOfDate(false);
2739         }
2740       }
2741 
2742       ~UpToDateIdentifierRAII() {
2743         if (WasOutToDate)
2744           II->setOutOfDate(true);
2745       }
2746     } UpToDate(Name.getAsIdentifierInfo());
2747 
2748     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2749                                    IEnd = IdResolver.end();
2750          I != IEnd; ++I) {
2751       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
2752         if (isSameEntity(Existing, D))
2753           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
2754                                     TypedefNameForLinkage);
2755     }
2756   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2757     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
2758     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2759       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
2760         if (isSameEntity(Existing, D))
2761           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
2762                                     TypedefNameForLinkage);
2763     }
2764   } else {
2765     // Not in a mergeable context.
2766     return FindExistingResult(Reader);
2767   }
2768 
2769   // If this declaration is from a merged context, make a note that we need to
2770   // check that the canonical definition of that context contains the decl.
2771   //
2772   // FIXME: We should do something similar if we merge two definitions of the
2773   // same template specialization into the same CXXRecordDecl.
2774   auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
2775   if (MergedDCIt != Reader.MergedDeclContexts.end() &&
2776       MergedDCIt->second == D->getDeclContext())
2777     Reader.PendingOdrMergeChecks.push_back(D);
2778 
2779   return FindExistingResult(Reader, D, /*Existing=*/nullptr,
2780                             AnonymousDeclNumber, TypedefNameForLinkage);
2781 }
2782 
2783 template<typename DeclT>
2784 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
2785                                            Redeclarable<DeclT> *D,
2786                                            Decl *Previous) {
2787   D->RedeclLink.setPrevious(cast<DeclT>(Previous));
2788 }
2789 namespace clang {
2790 template<>
2791 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
2792                                            Redeclarable<FunctionDecl> *D,
2793                                            Decl *Previous) {
2794   FunctionDecl *FD = static_cast<FunctionDecl*>(D);
2795   FunctionDecl *PrevFD = cast<FunctionDecl>(Previous);
2796 
2797   FD->RedeclLink.setPrevious(PrevFD);
2798 
2799   // If the previous declaration is an inline function declaration, then this
2800   // declaration is too.
2801   if (PrevFD->IsInline != FD->IsInline) {
2802     // FIXME: [dcl.fct.spec]p4:
2803     //   If a function with external linkage is declared inline in one
2804     //   translation unit, it shall be declared inline in all translation
2805     //   units in which it appears.
2806     //
2807     // Be careful of this case:
2808     //
2809     // module A:
2810     //   template<typename T> struct X { void f(); };
2811     //   template<typename T> inline void X<T>::f() {}
2812     //
2813     // module B instantiates the declaration of X<int>::f
2814     // module C instantiates the definition of X<int>::f
2815     //
2816     // If module B and C are merged, we do not have a violation of this rule.
2817     FD->IsInline = true;
2818   }
2819 
2820   // If this declaration has an unresolved exception specification but the
2821   // previous declaration had a resolved one, resolve the exception
2822   // specification now.
2823   auto *FPT = FD->getType()->getAs<FunctionProtoType>();
2824   auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
2825   if (FPT && PrevFPT &&
2826       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
2827       !isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType())) {
2828     Reader.Context.adjustExceptionSpec(
2829         FD, PrevFPT->getExtProtoInfo().ExceptionSpec);
2830   }
2831 }
2832 }
2833 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
2834   llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
2835 }
2836 
2837 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
2838                                        Decl *Previous) {
2839   assert(D && Previous);
2840 
2841   switch (D->getKind()) {
2842 #define ABSTRACT_DECL(TYPE)
2843 #define DECL(TYPE, BASE)                                           \
2844   case Decl::TYPE:                                                 \
2845     attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous); \
2846     break;
2847 #include "clang/AST/DeclNodes.inc"
2848   }
2849 
2850   // If the declaration was visible in one module, a redeclaration of it in
2851   // another module remains visible even if it wouldn't be visible by itself.
2852   //
2853   // FIXME: In this case, the declaration should only be visible if a module
2854   //        that makes it visible has been imported.
2855   D->IdentifierNamespace |=
2856       Previous->IdentifierNamespace &
2857       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
2858 
2859   // If the previous declaration is marked as used, then this declaration should
2860   // be too.
2861   if (Previous->Used)
2862     D->Used = true;
2863 }
2864 
2865 template<typename DeclT>
2866 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
2867   D->RedeclLink.setLatest(cast<DeclT>(Latest));
2868 }
2869 void ASTDeclReader::attachLatestDeclImpl(...) {
2870   llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
2871 }
2872 
2873 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
2874   assert(D && Latest);
2875 
2876   switch (D->getKind()) {
2877 #define ABSTRACT_DECL(TYPE)
2878 #define DECL(TYPE, BASE)                                  \
2879   case Decl::TYPE:                                        \
2880     attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
2881     break;
2882 #include "clang/AST/DeclNodes.inc"
2883   }
2884 }
2885 
2886 template<typename DeclT>
2887 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
2888   D->RedeclLink.markIncomplete();
2889 }
2890 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
2891   llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
2892 }
2893 
2894 void ASTReader::markIncompleteDeclChain(Decl *D) {
2895   switch (D->getKind()) {
2896 #define ABSTRACT_DECL(TYPE)
2897 #define DECL(TYPE, BASE)                                             \
2898   case Decl::TYPE:                                                   \
2899     ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
2900     break;
2901 #include "clang/AST/DeclNodes.inc"
2902   }
2903 }
2904 
2905 ASTReader::MergedDeclsMap::iterator
2906 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
2907   // If we don't have any stored merged declarations, just look in the
2908   // merged declarations set.
2909   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
2910   if (StoredPos == StoredMergedDecls.end())
2911     return MergedDecls.find(Canon);
2912 
2913   // Append the stored merged declarations to the merged declarations set.
2914   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
2915   if (Pos == MergedDecls.end())
2916     Pos = MergedDecls.insert(std::make_pair(Canon,
2917                                             SmallVector<DeclID, 2>())).first;
2918   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
2919   StoredMergedDecls.erase(StoredPos);
2920 
2921   // Sort and uniquify the set of merged declarations.
2922   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
2923   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
2924                     Pos->second.end());
2925   return Pos;
2926 }
2927 
2928 /// \brief Read the declaration at the given offset from the AST file.
2929 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
2930   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
2931   unsigned RawLocation = 0;
2932   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
2933   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2934   // Keep track of where we are in the stream, then jump back there
2935   // after reading this declaration.
2936   SavedStreamPosition SavedPosition(DeclsCursor);
2937 
2938   ReadingKindTracker ReadingKind(Read_Decl, *this);
2939 
2940   // Note that we are loading a declaration record.
2941   Deserializing ADecl(this);
2942 
2943   DeclsCursor.JumpToBit(Loc.Offset);
2944   RecordData Record;
2945   unsigned Code = DeclsCursor.ReadCode();
2946   unsigned Idx = 0;
2947   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
2948 
2949   Decl *D = nullptr;
2950   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
2951   case DECL_CONTEXT_LEXICAL:
2952   case DECL_CONTEXT_VISIBLE:
2953     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
2954   case DECL_TYPEDEF:
2955     D = TypedefDecl::CreateDeserialized(Context, ID);
2956     break;
2957   case DECL_TYPEALIAS:
2958     D = TypeAliasDecl::CreateDeserialized(Context, ID);
2959     break;
2960   case DECL_ENUM:
2961     D = EnumDecl::CreateDeserialized(Context, ID);
2962     break;
2963   case DECL_RECORD:
2964     D = RecordDecl::CreateDeserialized(Context, ID);
2965     break;
2966   case DECL_ENUM_CONSTANT:
2967     D = EnumConstantDecl::CreateDeserialized(Context, ID);
2968     break;
2969   case DECL_FUNCTION:
2970     D = FunctionDecl::CreateDeserialized(Context, ID);
2971     break;
2972   case DECL_LINKAGE_SPEC:
2973     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2974     break;
2975   case DECL_LABEL:
2976     D = LabelDecl::CreateDeserialized(Context, ID);
2977     break;
2978   case DECL_NAMESPACE:
2979     D = NamespaceDecl::CreateDeserialized(Context, ID);
2980     break;
2981   case DECL_NAMESPACE_ALIAS:
2982     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2983     break;
2984   case DECL_USING:
2985     D = UsingDecl::CreateDeserialized(Context, ID);
2986     break;
2987   case DECL_USING_SHADOW:
2988     D = UsingShadowDecl::CreateDeserialized(Context, ID);
2989     break;
2990   case DECL_USING_DIRECTIVE:
2991     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2992     break;
2993   case DECL_UNRESOLVED_USING_VALUE:
2994     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2995     break;
2996   case DECL_UNRESOLVED_USING_TYPENAME:
2997     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2998     break;
2999   case DECL_CXX_RECORD:
3000     D = CXXRecordDecl::CreateDeserialized(Context, ID);
3001     break;
3002   case DECL_CXX_METHOD:
3003     D = CXXMethodDecl::CreateDeserialized(Context, ID);
3004     break;
3005   case DECL_CXX_CONSTRUCTOR:
3006     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
3007     break;
3008   case DECL_CXX_DESTRUCTOR:
3009     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3010     break;
3011   case DECL_CXX_CONVERSION:
3012     D = CXXConversionDecl::CreateDeserialized(Context, ID);
3013     break;
3014   case DECL_ACCESS_SPEC:
3015     D = AccessSpecDecl::CreateDeserialized(Context, ID);
3016     break;
3017   case DECL_FRIEND:
3018     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3019     break;
3020   case DECL_FRIEND_TEMPLATE:
3021     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3022     break;
3023   case DECL_CLASS_TEMPLATE:
3024     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3025     break;
3026   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3027     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3028     break;
3029   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3030     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3031     break;
3032   case DECL_VAR_TEMPLATE:
3033     D = VarTemplateDecl::CreateDeserialized(Context, ID);
3034     break;
3035   case DECL_VAR_TEMPLATE_SPECIALIZATION:
3036     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3037     break;
3038   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3039     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3040     break;
3041   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3042     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3043     break;
3044   case DECL_FUNCTION_TEMPLATE:
3045     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3046     break;
3047   case DECL_TEMPLATE_TYPE_PARM:
3048     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3049     break;
3050   case DECL_NON_TYPE_TEMPLATE_PARM:
3051     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3052     break;
3053   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3054     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3055     break;
3056   case DECL_TEMPLATE_TEMPLATE_PARM:
3057     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3058     break;
3059   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3060     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3061                                                      Record[Idx++]);
3062     break;
3063   case DECL_TYPE_ALIAS_TEMPLATE:
3064     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3065     break;
3066   case DECL_STATIC_ASSERT:
3067     D = StaticAssertDecl::CreateDeserialized(Context, ID);
3068     break;
3069   case DECL_OBJC_METHOD:
3070     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3071     break;
3072   case DECL_OBJC_INTERFACE:
3073     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3074     break;
3075   case DECL_OBJC_IVAR:
3076     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3077     break;
3078   case DECL_OBJC_PROTOCOL:
3079     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3080     break;
3081   case DECL_OBJC_AT_DEFS_FIELD:
3082     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3083     break;
3084   case DECL_OBJC_CATEGORY:
3085     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3086     break;
3087   case DECL_OBJC_CATEGORY_IMPL:
3088     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3089     break;
3090   case DECL_OBJC_IMPLEMENTATION:
3091     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3092     break;
3093   case DECL_OBJC_COMPATIBLE_ALIAS:
3094     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3095     break;
3096   case DECL_OBJC_PROPERTY:
3097     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3098     break;
3099   case DECL_OBJC_PROPERTY_IMPL:
3100     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3101     break;
3102   case DECL_FIELD:
3103     D = FieldDecl::CreateDeserialized(Context, ID);
3104     break;
3105   case DECL_INDIRECTFIELD:
3106     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3107     break;
3108   case DECL_VAR:
3109     D = VarDecl::CreateDeserialized(Context, ID);
3110     break;
3111   case DECL_IMPLICIT_PARAM:
3112     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3113     break;
3114   case DECL_PARM_VAR:
3115     D = ParmVarDecl::CreateDeserialized(Context, ID);
3116     break;
3117   case DECL_FILE_SCOPE_ASM:
3118     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3119     break;
3120   case DECL_BLOCK:
3121     D = BlockDecl::CreateDeserialized(Context, ID);
3122     break;
3123   case DECL_MS_PROPERTY:
3124     D = MSPropertyDecl::CreateDeserialized(Context, ID);
3125     break;
3126   case DECL_CAPTURED:
3127     D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3128     break;
3129   case DECL_CXX_BASE_SPECIFIERS:
3130     Error("attempt to read a C++ base-specifier record as a declaration");
3131     return nullptr;
3132   case DECL_IMPORT:
3133     // Note: last entry of the ImportDecl record is the number of stored source
3134     // locations.
3135     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3136     break;
3137   case DECL_OMP_THREADPRIVATE:
3138     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3139     break;
3140   case DECL_EMPTY:
3141     D = EmptyDecl::CreateDeserialized(Context, ID);
3142     break;
3143   }
3144 
3145   assert(D && "Unknown declaration reading AST file");
3146   LoadedDecl(Index, D);
3147   // Set the DeclContext before doing any deserialization, to make sure internal
3148   // calls to Decl::getASTContext() by Decl's methods will find the
3149   // TranslationUnitDecl without crashing.
3150   D->setDeclContext(Context.getTranslationUnitDecl());
3151   Reader.Visit(D);
3152 
3153   // If this declaration is also a declaration context, get the
3154   // offsets for its tables of lexical and visible declarations.
3155   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
3156     // FIXME: This should really be
3157     //     DeclContext *LookupDC = DC->getPrimaryContext();
3158     // but that can walk the redeclaration chain, which might not work yet.
3159     DeclContext *LookupDC = DC;
3160     if (isa<NamespaceDecl>(DC))
3161       LookupDC = DC->getPrimaryContext();
3162     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3163     if (Offsets.first || Offsets.second) {
3164       if (Offsets.first != 0)
3165         DC->setHasExternalLexicalStorage(true);
3166       if (Offsets.second != 0)
3167         LookupDC->setHasExternalVisibleStorage(true);
3168       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
3169                                  Loc.F->DeclContextInfos[DC]))
3170         return nullptr;
3171     }
3172 
3173     // Now add the pending visible updates for this decl context, if it has any.
3174     DeclContextVisibleUpdatesPending::iterator I =
3175         PendingVisibleUpdates.find(ID);
3176     if (I != PendingVisibleUpdates.end()) {
3177       // There are updates. This means the context has external visible
3178       // storage, even if the original stored version didn't.
3179       LookupDC->setHasExternalVisibleStorage(true);
3180       for (const auto &Update : I->second) {
3181         DeclContextInfo &Info = Update.second->DeclContextInfos[DC];
3182         delete Info.NameLookupTableData;
3183         Info.NameLookupTableData = Update.first;
3184       }
3185       PendingVisibleUpdates.erase(I);
3186     }
3187   }
3188   assert(Idx == Record.size());
3189 
3190   // Load any relevant update records.
3191   PendingUpdateRecords.push_back(std::make_pair(ID, D));
3192 
3193   // Load the categories after recursive loading is finished.
3194   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3195     if (Class->isThisDeclarationADefinition())
3196       loadObjCCategories(ID, Class);
3197 
3198   // If we have deserialized a declaration that has a definition the
3199   // AST consumer might need to know about, queue it.
3200   // We don't pass it to the consumer immediately because we may be in recursive
3201   // loading, and some declarations may still be initializing.
3202   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
3203     InterestingDecls.push_back(D);
3204 
3205   return D;
3206 }
3207 
3208 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
3209   // The declaration may have been modified by files later in the chain.
3210   // If this is the case, read the record containing the updates from each file
3211   // and pass it to ASTDeclReader to make the modifications.
3212   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3213   if (UpdI != DeclUpdateOffsets.end()) {
3214     FileOffsetsTy &UpdateOffsets = UpdI->second;
3215     bool WasInteresting = isConsumerInterestedIn(D, false);
3216     for (FileOffsetsTy::iterator
3217          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
3218       ModuleFile *F = I->first;
3219       uint64_t Offset = I->second;
3220       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3221       SavedStreamPosition SavedPosition(Cursor);
3222       Cursor.JumpToBit(Offset);
3223       RecordData Record;
3224       unsigned Code = Cursor.ReadCode();
3225       unsigned RecCode = Cursor.readRecord(Code, Record);
3226       (void)RecCode;
3227       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3228 
3229       unsigned Idx = 0;
3230       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
3231       Reader.UpdateDecl(D, *F, Record);
3232 
3233       // We might have made this declaration interesting. If so, remember that
3234       // we need to hand it off to the consumer.
3235       if (!WasInteresting &&
3236           isConsumerInterestedIn(D, Reader.hasPendingBody())) {
3237         InterestingDecls.push_back(D);
3238         WasInteresting = true;
3239       }
3240     }
3241   }
3242 }
3243 
3244 namespace {
3245   /// \brief Module visitor class that finds all of the redeclarations of a
3246   ///
3247   class RedeclChainVisitor {
3248     ASTReader &Reader;
3249     SmallVectorImpl<DeclID> &SearchDecls;
3250     llvm::SmallPtrSetImpl<Decl *> &Deserialized;
3251     GlobalDeclID CanonID;
3252     SmallVector<Decl *, 4> Chain;
3253 
3254   public:
3255     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
3256                        llvm::SmallPtrSetImpl<Decl *> &Deserialized,
3257                        GlobalDeclID CanonID)
3258       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
3259         CanonID(CanonID) {
3260       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
3261         addToChain(Reader.GetDecl(SearchDecls[I]));
3262     }
3263 
3264     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
3265       if (Preorder)
3266         return false;
3267 
3268       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
3269     }
3270 
3271     void addToChain(Decl *D) {
3272       if (!D)
3273         return;
3274 
3275       if (Deserialized.erase(D))
3276         Chain.push_back(D);
3277     }
3278 
3279     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
3280       // Map global ID of the first declaration down to the local ID
3281       // used in this module file.
3282       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
3283       if (!ID)
3284         return;
3285 
3286       // Perform a binary search to find the local redeclarations for this
3287       // declaration (if any).
3288       const LocalRedeclarationsInfo Compare = { ID, 0 };
3289       const LocalRedeclarationsInfo *Result
3290         = std::lower_bound(M.RedeclarationsMap,
3291                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
3292                            Compare);
3293       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
3294           Result->FirstID != ID) {
3295         // If we have a previously-canonical singleton declaration that was
3296         // merged into another redeclaration chain, create a trivial chain
3297         // for this single declaration so that it will get wired into the
3298         // complete redeclaration chain.
3299         if (GlobalID != CanonID &&
3300             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
3301             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
3302           addToChain(Reader.GetDecl(GlobalID));
3303         }
3304 
3305         return;
3306       }
3307 
3308       // Dig out all of the redeclarations.
3309       unsigned Offset = Result->Offset;
3310       unsigned N = M.RedeclarationChains[Offset];
3311       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
3312       for (unsigned I = 0; I != N; ++I)
3313         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
3314     }
3315 
3316     bool visit(ModuleFile &M) {
3317       // Visit each of the declarations.
3318       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
3319         searchForID(M, SearchDecls[I]);
3320       // FIXME: If none of the SearchDecls had local IDs in this module, can
3321       // we avoid searching any ancestor module files?
3322       return false;
3323     }
3324 
3325     ArrayRef<Decl *> getChain() const {
3326       return Chain;
3327     }
3328   };
3329 }
3330 
3331 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
3332   Decl *D = GetDecl(ID);
3333   Decl *CanonDecl = D->getCanonicalDecl();
3334 
3335   // Determine the set of declaration IDs we'll be searching for.
3336   SmallVector<DeclID, 1> SearchDecls;
3337   GlobalDeclID CanonID = 0;
3338   if (D == CanonDecl) {
3339     SearchDecls.push_back(ID); // Always first.
3340     CanonID = ID;
3341   }
3342   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
3343   if (MergedPos != MergedDecls.end())
3344     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
3345 
3346   // Build up the list of redeclarations.
3347   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
3348   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
3349 
3350   // Retrieve the chains.
3351   ArrayRef<Decl *> Chain = Visitor.getChain();
3352   if (Chain.empty())
3353     return;
3354 
3355   // Hook up the chains.
3356   Decl *MostRecent = CanonDecl->getMostRecentDecl();
3357   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3358     if (Chain[I] == CanonDecl)
3359       continue;
3360 
3361     ASTDeclReader::attachPreviousDecl(*this, Chain[I], MostRecent);
3362     MostRecent = Chain[I];
3363   }
3364 
3365   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
3366 }
3367 
3368 namespace {
3369   /// \brief Given an ObjC interface, goes through the modules and links to the
3370   /// interface all the categories for it.
3371   class ObjCCategoriesVisitor {
3372     ASTReader &Reader;
3373     serialization::GlobalDeclID InterfaceID;
3374     ObjCInterfaceDecl *Interface;
3375     llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
3376     unsigned PreviousGeneration;
3377     ObjCCategoryDecl *Tail;
3378     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
3379 
3380     void add(ObjCCategoryDecl *Cat) {
3381       // Only process each category once.
3382       if (!Deserialized.erase(Cat))
3383         return;
3384 
3385       // Check for duplicate categories.
3386       if (Cat->getDeclName()) {
3387         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
3388         if (Existing &&
3389             Reader.getOwningModuleFile(Existing)
3390                                           != Reader.getOwningModuleFile(Cat)) {
3391           // FIXME: We should not warn for duplicates in diamond:
3392           //
3393           //   MT     //
3394           //  /  \    //
3395           // ML  MR   //
3396           //  \  /    //
3397           //   MB     //
3398           //
3399           // If there are duplicates in ML/MR, there will be warning when
3400           // creating MB *and* when importing MB. We should not warn when
3401           // importing.
3402           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
3403             << Interface->getDeclName() << Cat->getDeclName();
3404           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
3405         } else if (!Existing) {
3406           // Record this category.
3407           Existing = Cat;
3408         }
3409       }
3410 
3411       // Add this category to the end of the chain.
3412       if (Tail)
3413         ASTDeclReader::setNextObjCCategory(Tail, Cat);
3414       else
3415         Interface->setCategoryListRaw(Cat);
3416       Tail = Cat;
3417     }
3418 
3419   public:
3420     ObjCCategoriesVisitor(ASTReader &Reader,
3421                           serialization::GlobalDeclID InterfaceID,
3422                           ObjCInterfaceDecl *Interface,
3423                         llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
3424                           unsigned PreviousGeneration)
3425       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
3426         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
3427         Tail(nullptr)
3428     {
3429       // Populate the name -> category map with the set of known categories.
3430       for (auto *Cat : Interface->known_categories()) {
3431         if (Cat->getDeclName())
3432           NameCategoryMap[Cat->getDeclName()] = Cat;
3433 
3434         // Keep track of the tail of the category list.
3435         Tail = Cat;
3436       }
3437     }
3438 
3439     static bool visit(ModuleFile &M, void *UserData) {
3440       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
3441     }
3442 
3443     bool visit(ModuleFile &M) {
3444       // If we've loaded all of the category information we care about from
3445       // this module file, we're done.
3446       if (M.Generation <= PreviousGeneration)
3447         return true;
3448 
3449       // Map global ID of the definition down to the local ID used in this
3450       // module file. If there is no such mapping, we'll find nothing here
3451       // (or in any module it imports).
3452       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
3453       if (!LocalID)
3454         return true;
3455 
3456       // Perform a binary search to find the local redeclarations for this
3457       // declaration (if any).
3458       const ObjCCategoriesInfo Compare = { LocalID, 0 };
3459       const ObjCCategoriesInfo *Result
3460         = std::lower_bound(M.ObjCCategoriesMap,
3461                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
3462                            Compare);
3463       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
3464           Result->DefinitionID != LocalID) {
3465         // We didn't find anything. If the class definition is in this module
3466         // file, then the module files it depends on cannot have any categories,
3467         // so suppress further lookup.
3468         return Reader.isDeclIDFromModule(InterfaceID, M);
3469       }
3470 
3471       // We found something. Dig out all of the categories.
3472       unsigned Offset = Result->Offset;
3473       unsigned N = M.ObjCCategories[Offset];
3474       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
3475       for (unsigned I = 0; I != N; ++I)
3476         add(cast_or_null<ObjCCategoryDecl>(
3477               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
3478       return true;
3479     }
3480   };
3481 }
3482 
3483 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
3484                                    ObjCInterfaceDecl *D,
3485                                    unsigned PreviousGeneration) {
3486   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
3487                                 PreviousGeneration);
3488   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
3489 }
3490 
3491 namespace {
3492 /// Iterator over the redeclarations of a declaration that have already
3493 /// been merged into the same redeclaration chain.
3494 template<typename DeclT>
3495 class MergedRedeclIterator {
3496   DeclT *Start, *Canonical, *Current;
3497 public:
3498   MergedRedeclIterator() : Current(nullptr) {}
3499   MergedRedeclIterator(DeclT *Start)
3500       : Start(Start), Canonical(nullptr), Current(Start) {}
3501 
3502   DeclT *operator*() { return Current; }
3503 
3504   MergedRedeclIterator &operator++() {
3505     if (Current->isFirstDecl()) {
3506       Canonical = Current;
3507       Current = Current->getMostRecentDecl();
3508     } else
3509       Current = Current->getPreviousDecl();
3510 
3511     // If we started in the merged portion, we'll reach our start position
3512     // eventually. Otherwise, we'll never reach it, but the second declaration
3513     // we reached was the canonical declaration, so stop when we see that one
3514     // again.
3515     if (Current == Start || Current == Canonical)
3516       Current = nullptr;
3517     return *this;
3518   }
3519 
3520   friend bool operator!=(const MergedRedeclIterator &A,
3521                          const MergedRedeclIterator &B) {
3522     return A.Current != B.Current;
3523   }
3524 };
3525 }
3526 template<typename DeclT>
3527 llvm::iterator_range<MergedRedeclIterator<DeclT>> merged_redecls(DeclT *D) {
3528   return llvm::iterator_range<MergedRedeclIterator<DeclT>>(
3529       MergedRedeclIterator<DeclT>(D),
3530       MergedRedeclIterator<DeclT>());
3531 }
3532 
3533 template<typename DeclT, typename Fn>
3534 static void forAllLaterRedecls(DeclT *D, Fn F) {
3535   F(D);
3536 
3537   // Check whether we've already merged D into its redeclaration chain.
3538   // MostRecent may or may not be nullptr if D has not been merged. If
3539   // not, walk the merged redecl chain and see if it's there.
3540   auto *MostRecent = D->getMostRecentDecl();
3541   bool Found = false;
3542   for (auto *Redecl = MostRecent; Redecl && !Found;
3543        Redecl = Redecl->getPreviousDecl())
3544     Found = (Redecl == D);
3545 
3546   // If this declaration is merged, apply the functor to all later decls.
3547   if (Found) {
3548     for (auto *Redecl = MostRecent; Redecl != D;
3549          Redecl = Redecl->getPreviousDecl())
3550       F(Redecl);
3551   }
3552 }
3553 
3554 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
3555                                const RecordData &Record) {
3556   while (Idx < Record.size()) {
3557     switch ((DeclUpdateKind)Record[Idx++]) {
3558     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
3559       auto *RD = cast<CXXRecordDecl>(D);
3560       // FIXME: If we also have an update record for instantiating the
3561       // definition of D, we need that to happen before we get here.
3562       Decl *MD = Reader.ReadDecl(ModuleFile, Record, Idx);
3563       assert(MD && "couldn't read decl from update record");
3564       // FIXME: We should call addHiddenDecl instead, to add the member
3565       // to its DeclContext.
3566       RD->addedMember(MD);
3567 
3568       // If we've added a new special member to a class definition that is not
3569       // the canonical definition, then we need special member lookups in the
3570       // canonical definition to also look into our class.
3571       auto *DD = RD->DefinitionData.getNotUpdated();
3572       if (DD && DD->Definition != RD) {
3573         auto &Merged = Reader.MergedLookups[DD->Definition];
3574         // FIXME: Avoid the linear-time scan here.
3575         if (std::find(Merged.begin(), Merged.end(), RD) == Merged.end())
3576           Merged.push_back(RD);
3577       }
3578       break;
3579     }
3580 
3581     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3582       // It will be added to the template's specializations set when loaded.
3583       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
3584       break;
3585 
3586     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
3587       NamespaceDecl *Anon
3588         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
3589 
3590       // Each module has its own anonymous namespace, which is disjoint from
3591       // any other module's anonymous namespaces, so don't attach the anonymous
3592       // namespace at all.
3593       if (ModuleFile.Kind != MK_ImplicitModule &&
3594           ModuleFile.Kind != MK_ExplicitModule) {
3595         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
3596           TU->setAnonymousNamespace(Anon);
3597         else
3598           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
3599       }
3600       break;
3601     }
3602 
3603     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
3604       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
3605           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3606       break;
3607 
3608     case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
3609       FunctionDecl *FD = cast<FunctionDecl>(D);
3610       if (Reader.PendingBodies[FD]) {
3611         // FIXME: Maybe check for ODR violations.
3612         // It's safe to stop now because this update record is always last.
3613         return;
3614       }
3615 
3616       if (Record[Idx++]) {
3617         // Maintain AST consistency: any later redeclarations of this function
3618         // are inline if this one is. (We might have merged another declaration
3619         // into this one.)
3620         forAllLaterRedecls(FD, [](FunctionDecl *FD) {
3621           FD->setImplicitlyInline();
3622         });
3623       }
3624       FD->setInnerLocStart(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3625       if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
3626         std::tie(CD->CtorInitializers, CD->NumCtorInitializers) =
3627             Reader.ReadCXXCtorInitializers(ModuleFile, Record, Idx);
3628       if (auto *DD = dyn_cast<CXXDestructorDecl>(FD))
3629         // FIXME: Check consistency.
3630         DD->setOperatorDelete(Reader.ReadDeclAs<FunctionDecl>(ModuleFile,
3631                                                               Record, Idx));
3632       // Store the offset of the body so we can lazily load it later.
3633       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
3634       HasPendingBody = true;
3635       assert(Idx == Record.size() && "lazy body must be last");
3636       break;
3637     }
3638 
3639     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
3640       auto *RD = cast<CXXRecordDecl>(D);
3641       bool HadRealDefinition = RD->getDefinition() &&
3642                                !Reader.PendingFakeDefinitionData.count(
3643                                    RD->DefinitionData.getNotUpdated());
3644       ReadCXXRecordDefinition(RD);
3645       // Visible update is handled separately.
3646       uint64_t LexicalOffset = Record[Idx++];
3647       if (!HadRealDefinition && LexicalOffset) {
3648         RD->setHasExternalLexicalStorage(true);
3649         Reader.ReadDeclContextStorage(ModuleFile, ModuleFile.DeclsCursor,
3650                                           std::make_pair(LexicalOffset, 0),
3651                                           ModuleFile.DeclContextInfos[RD]);
3652         Reader.PendingDefinitions.insert(RD);
3653       }
3654 
3655       auto TSK = (TemplateSpecializationKind)Record[Idx++];
3656       SourceLocation POI = Reader.ReadSourceLocation(ModuleFile, Record, Idx);
3657       if (MemberSpecializationInfo *MSInfo =
3658               RD->getMemberSpecializationInfo()) {
3659         MSInfo->setTemplateSpecializationKind(TSK);
3660         MSInfo->setPointOfInstantiation(POI);
3661       } else {
3662         ClassTemplateSpecializationDecl *Spec =
3663             cast<ClassTemplateSpecializationDecl>(RD);
3664         Spec->setTemplateSpecializationKind(TSK);
3665         Spec->setPointOfInstantiation(POI);
3666 
3667         if (Record[Idx++]) {
3668           auto PartialSpec =
3669               ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx);
3670           SmallVector<TemplateArgument, 8> TemplArgs;
3671           Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
3672           auto *TemplArgList = TemplateArgumentList::CreateCopy(
3673               Reader.getContext(), TemplArgs.data(), TemplArgs.size());
3674 
3675           // FIXME: If we already have a partial specialization set,
3676           // check that it matches.
3677           if (!Spec->getSpecializedTemplateOrPartial()
3678                    .is<ClassTemplatePartialSpecializationDecl *>())
3679             Spec->setInstantiationOf(PartialSpec, TemplArgList);
3680         }
3681       }
3682 
3683       RD->setTagKind((TagTypeKind)Record[Idx++]);
3684       RD->setLocation(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3685       RD->setLocStart(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3686       RD->setRBraceLoc(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3687 
3688       if (Record[Idx++]) {
3689         AttrVec Attrs;
3690         Reader.ReadAttributes(F, Attrs, Record, Idx);
3691         D->setAttrsImpl(Attrs, Reader.getContext());
3692       }
3693       break;
3694     }
3695 
3696     case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
3697       // FIXME: This doesn't send the right notifications if there are
3698       // ASTMutationListeners other than an ASTWriter.
3699       FunctionProtoType::ExceptionSpecInfo ESI;
3700       SmallVector<QualType, 8> ExceptionStorage;
3701       Reader.readExceptionSpec(ModuleFile, ExceptionStorage, ESI, Record, Idx);
3702       for (auto *Redecl : merged_redecls(D)) {
3703         auto *FD = cast<FunctionDecl>(Redecl);
3704         auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3705         if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
3706           // AST invariant: if any exception spec in the redecl chain is
3707           // resolved, all are resolved. We don't need to go any further.
3708           // FIXME: If the exception spec is resolved, check that it matches.
3709           break;
3710         }
3711         FD->setType(Reader.Context.getFunctionType(
3712             FPT->getReturnType(), FPT->getParamTypes(),
3713             FPT->getExtProtoInfo().withExceptionSpec(ESI)));
3714       }
3715       break;
3716     }
3717 
3718     case UPD_CXX_DEDUCED_RETURN_TYPE: {
3719       // FIXME: Also do this when merging redecls.
3720       QualType DeducedResultType = Reader.readType(ModuleFile, Record, Idx);
3721       for (auto *Redecl : merged_redecls(D)) {
3722         // FIXME: If the return type is already deduced, check that it matches.
3723         FunctionDecl *FD = cast<FunctionDecl>(Redecl);
3724         Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType);
3725       }
3726       break;
3727     }
3728 
3729     case UPD_DECL_MARKED_USED: {
3730       // FIXME: This doesn't send the right notifications if there are
3731       // ASTMutationListeners other than an ASTWriter.
3732 
3733       // Maintain AST consistency: any later redeclarations are used too.
3734       forAllLaterRedecls(D, [](Decl *D) { D->Used = true; });
3735       break;
3736     }
3737 
3738     case UPD_MANGLING_NUMBER:
3739       Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record[Idx++]);
3740       break;
3741 
3742     case UPD_STATIC_LOCAL_NUMBER:
3743       Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record[Idx++]);
3744       break;
3745     case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
3746       D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3747           Reader.Context, ReadSourceRange(Record, Idx)));
3748       break;
3749     }
3750   }
3751 }
3752