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