Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Serialization/ASTReaderDecl.cpp
Warning:line 2629, column 16
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTReaderDecl.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-29-125212-15910-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Serialization/ASTReaderDecl.cpp
1//===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTReader::readDeclRecord method, which is the
10// entrypoint for loading a decl.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenMP.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DeclVisitor.h"
27#include "clang/AST/DeclarationName.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LambdaCapture.h"
31#include "clang/AST/NestedNameSpecifier.h"
32#include "clang/AST/OpenMPClause.h"
33#include "clang/AST/Redeclarable.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/UnresolvedSet.h"
38#include "clang/Basic/AttrKinds.h"
39#include "clang/Basic/DiagnosticSema.h"
40#include "clang/Basic/ExceptionSpecificationType.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/Lambda.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/Linkage.h"
46#include "clang/Basic/Module.h"
47#include "clang/Basic/PragmaKinds.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/Specifiers.h"
50#include "clang/Sema/IdentifierResolver.h"
51#include "clang/Serialization/ASTBitCodes.h"
52#include "clang/Serialization/ASTRecordReader.h"
53#include "clang/Serialization/ContinuousRangeMap.h"
54#include "clang/Serialization/ModuleFile.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/FoldingSet.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallPtrSet.h"
59#include "llvm/ADT/SmallVector.h"
60#include "llvm/ADT/iterator_range.h"
61#include "llvm/Bitstream/BitstreamReader.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include <algorithm>
66#include <cassert>
67#include <cstdint>
68#include <cstring>
69#include <string>
70#include <utility>
71
72using namespace clang;
73using namespace serialization;
74
75//===----------------------------------------------------------------------===//
76// Declaration deserialization
77//===----------------------------------------------------------------------===//
78
79namespace clang {
80
81 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
82 ASTReader &Reader;
83 ASTRecordReader &Record;
84 ASTReader::RecordLocation Loc;
85 const DeclID ThisDeclID;
86 const SourceLocation ThisDeclLoc;
87
88 using RecordData = ASTReader::RecordData;
89
90 TypeID DeferredTypeID = 0;
91 unsigned AnonymousDeclNumber;
92 GlobalDeclID NamedDeclForTagDecl = 0;
93 IdentifierInfo *TypedefNameForLinkage = nullptr;
94
95 bool HasPendingBody = false;
96
97 ///A flag to carry the information for a decl from the entity is
98 /// used. We use it to delay the marking of the canonical decl as used until
99 /// the entire declaration is deserialized and merged.
100 bool IsDeclMarkedUsed = false;
101
102 uint64_t GetCurrentCursorOffset();
103
104 uint64_t ReadLocalOffset() {
105 uint64_t LocalOffset = Record.readInt();
106 assert(LocalOffset < Loc.Offset && "offset point after current record")(static_cast <bool> (LocalOffset < Loc.Offset &&
"offset point after current record") ? void (0) : __assert_fail
("LocalOffset < Loc.Offset && \"offset point after current record\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 106, __extension__
__PRETTY_FUNCTION__))
;
107 return LocalOffset ? Loc.Offset - LocalOffset : 0;
108 }
109
110 uint64_t ReadGlobalOffset() {
111 uint64_t Local = ReadLocalOffset();
112 return Local ? Record.getGlobalBitOffset(Local) : 0;
113 }
114
115 SourceLocation readSourceLocation() {
116 return Record.readSourceLocation();
117 }
118
119 SourceRange readSourceRange() {
120 return Record.readSourceRange();
121 }
122
123 TypeSourceInfo *readTypeSourceInfo() {
124 return Record.readTypeSourceInfo();
125 }
126
127 serialization::DeclID readDeclID() {
128 return Record.readDeclID();
129 }
130
131 std::string readString() {
132 return Record.readString();
133 }
134
135 void readDeclIDList(SmallVectorImpl<DeclID> &IDs) {
136 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
137 IDs.push_back(readDeclID());
138 }
139
140 Decl *readDecl() {
141 return Record.readDecl();
142 }
143
144 template<typename T>
145 T *readDeclAs() {
146 return Record.readDeclAs<T>();
147 }
148
149 serialization::SubmoduleID readSubmoduleID() {
150 if (Record.getIdx() == Record.size())
151 return 0;
152
153 return Record.getGlobalSubmoduleID(Record.readInt());
154 }
155
156 Module *readModule() {
157 return Record.getSubmodule(readSubmoduleID());
158 }
159
160 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
161 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
162 const CXXRecordDecl *D);
163 void MergeDefinitionData(CXXRecordDecl *D,
164 struct CXXRecordDecl::DefinitionData &&NewDD);
165 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
166 void MergeDefinitionData(ObjCInterfaceDecl *D,
167 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
168 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
169 void MergeDefinitionData(ObjCProtocolDecl *D,
170 struct ObjCProtocolDecl::DefinitionData &&NewDD);
171
172 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
173
174 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
175 DeclContext *DC,
176 unsigned Index);
177 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
178 unsigned Index, NamedDecl *D);
179
180 /// Results from loading a RedeclarableDecl.
181 class RedeclarableResult {
182 Decl *MergeWith;
183 GlobalDeclID FirstID;
184 bool IsKeyDecl;
185
186 public:
187 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
188 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
189
190 /// Retrieve the first ID.
191 GlobalDeclID getFirstID() const { return FirstID; }
192
193 /// Is this declaration a key declaration?
194 bool isKeyDecl() const { return IsKeyDecl; }
195
196 /// Get a known declaration that this should be merged with, if
197 /// any.
198 Decl *getKnownMergeTarget() const { return MergeWith; }
199 };
200
201 /// Class used to capture the result of searching for an existing
202 /// declaration of a specific kind and name, along with the ability
203 /// to update the place where this result was found (the declaration
204 /// chain hanging off an identifier or the DeclContext we searched in)
205 /// if requested.
206 class FindExistingResult {
207 ASTReader &Reader;
208 NamedDecl *New = nullptr;
209 NamedDecl *Existing = nullptr;
210 bool AddResult = false;
211 unsigned AnonymousDeclNumber = 0;
212 IdentifierInfo *TypedefNameForLinkage = nullptr;
213
214 public:
215 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
216
217 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
218 unsigned AnonymousDeclNumber,
219 IdentifierInfo *TypedefNameForLinkage)
220 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
221 AnonymousDeclNumber(AnonymousDeclNumber),
222 TypedefNameForLinkage(TypedefNameForLinkage) {}
223
224 FindExistingResult(FindExistingResult &&Other)
225 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
226 AddResult(Other.AddResult),
227 AnonymousDeclNumber(Other.AnonymousDeclNumber),
228 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
229 Other.AddResult = false;
230 }
231
232 FindExistingResult &operator=(FindExistingResult &&) = delete;
233 ~FindExistingResult();
234
235 /// Suppress the addition of this result into the known set of
236 /// names.
237 void suppress() { AddResult = false; }
238
239 operator NamedDecl*() const { return Existing; }
240
241 template<typename T>
242 operator T*() const { return dyn_cast_or_null<T>(Existing); }
243 };
244
245 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
246 DeclContext *DC);
247 FindExistingResult findExisting(NamedDecl *D);
248
249 public:
250 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
251 ASTReader::RecordLocation Loc,
252 DeclID thisDeclID, SourceLocation ThisDeclLoc)
253 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
254 ThisDeclLoc(ThisDeclLoc) {}
255
256 template <typename T> static
257 void AddLazySpecializations(T *D,
258 SmallVectorImpl<serialization::DeclID>& IDs) {
259 if (IDs.empty())
260 return;
261
262 // FIXME: We should avoid this pattern of getting the ASTContext.
263 ASTContext &C = D->getASTContext();
264
265 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
266
267 if (auto &Old = LazySpecializations) {
268 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
269 llvm::sort(IDs);
270 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
271 }
272
273 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
274 *Result = IDs.size();
275 std::copy(IDs.begin(), IDs.end(), Result + 1);
276
277 LazySpecializations = Result;
278 }
279
280 template <typename DeclT>
281 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
282 static Decl *getMostRecentDeclImpl(...);
283 static Decl *getMostRecentDecl(Decl *D);
284
285 static void mergeInheritableAttributes(ASTReader &Reader, Decl *D,
286 Decl *Previous);
287
288 template <typename DeclT>
289 static void attachPreviousDeclImpl(ASTReader &Reader,
290 Redeclarable<DeclT> *D, Decl *Previous,
291 Decl *Canon);
292 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
293 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
294 Decl *Canon);
295
296 template <typename DeclT>
297 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
298 static void attachLatestDeclImpl(...);
299 static void attachLatestDecl(Decl *D, Decl *latest);
300
301 template <typename DeclT>
302 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
303 static void markIncompleteDeclChainImpl(...);
304
305 /// Determine whether this declaration has a pending body.
306 bool hasPendingBody() const { return HasPendingBody; }
307
308 void ReadFunctionDefinition(FunctionDecl *FD);
309 void Visit(Decl *D);
310
311 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
312
313 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
314 ObjCCategoryDecl *Next) {
315 Cat->NextClassCategory = Next;
316 }
317
318 void VisitDecl(Decl *D);
319 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
320 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
321 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
322 void VisitNamedDecl(NamedDecl *ND);
323 void VisitLabelDecl(LabelDecl *LD);
324 void VisitNamespaceDecl(NamespaceDecl *D);
325 void VisitHLSLBufferDecl(HLSLBufferDecl *D);
326 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
327 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
328 void VisitTypeDecl(TypeDecl *TD);
329 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
330 void VisitTypedefDecl(TypedefDecl *TD);
331 void VisitTypeAliasDecl(TypeAliasDecl *TD);
332 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
333 void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);
334 RedeclarableResult VisitTagDecl(TagDecl *TD);
335 void VisitEnumDecl(EnumDecl *ED);
336 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
337 void VisitRecordDecl(RecordDecl *RD);
338 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
339 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
340 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
341 ClassTemplateSpecializationDecl *D);
342
343 void VisitClassTemplateSpecializationDecl(
344 ClassTemplateSpecializationDecl *D) {
345 VisitClassTemplateSpecializationDeclImpl(D);
346 }
347
348 void VisitClassTemplatePartialSpecializationDecl(
349 ClassTemplatePartialSpecializationDecl *D);
350 void VisitClassScopeFunctionSpecializationDecl(
351 ClassScopeFunctionSpecializationDecl *D);
352 RedeclarableResult
353 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
354
355 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
356 VisitVarTemplateSpecializationDeclImpl(D);
357 }
358
359 void VisitVarTemplatePartialSpecializationDecl(
360 VarTemplatePartialSpecializationDecl *D);
361 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
362 void VisitValueDecl(ValueDecl *VD);
363 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
364 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
365 void VisitDeclaratorDecl(DeclaratorDecl *DD);
366 void VisitFunctionDecl(FunctionDecl *FD);
367 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
368 void VisitCXXMethodDecl(CXXMethodDecl *D);
369 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
370 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
371 void VisitCXXConversionDecl(CXXConversionDecl *D);
372 void VisitFieldDecl(FieldDecl *FD);
373 void VisitMSPropertyDecl(MSPropertyDecl *FD);
374 void VisitMSGuidDecl(MSGuidDecl *D);
375 void VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl *D);
376 void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);
377 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
378 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
379 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
380 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
381 void VisitParmVarDecl(ParmVarDecl *PD);
382 void VisitDecompositionDecl(DecompositionDecl *DD);
383 void VisitBindingDecl(BindingDecl *BD);
384 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
385 DeclID VisitTemplateDecl(TemplateDecl *D);
386 void VisitConceptDecl(ConceptDecl *D);
387 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
388 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
389 void VisitClassTemplateDecl(ClassTemplateDecl *D);
390 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
391 void VisitVarTemplateDecl(VarTemplateDecl *D);
392 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
393 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
394 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
395 void VisitUsingDecl(UsingDecl *D);
396 void VisitUsingEnumDecl(UsingEnumDecl *D);
397 void VisitUsingPackDecl(UsingPackDecl *D);
398 void VisitUsingShadowDecl(UsingShadowDecl *D);
399 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
400 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
401 void VisitExportDecl(ExportDecl *D);
402 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
403 void VisitImportDecl(ImportDecl *D);
404 void VisitAccessSpecDecl(AccessSpecDecl *D);
405 void VisitFriendDecl(FriendDecl *D);
406 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
407 void VisitStaticAssertDecl(StaticAssertDecl *D);
408 void VisitBlockDecl(BlockDecl *BD);
409 void VisitCapturedDecl(CapturedDecl *CD);
410 void VisitEmptyDecl(EmptyDecl *D);
411 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
412
413 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
414
415 template<typename T>
416 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
417
418 template<typename T>
419 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
420 DeclID TemplatePatternID = 0);
421
422 template<typename T>
423 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
424 RedeclarableResult &Redecl,
425 DeclID TemplatePatternID = 0);
426
427 template<typename T>
428 void mergeMergeable(Mergeable<T> *D);
429
430 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
431
432 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
433 RedeclarableTemplateDecl *Existing,
434 DeclID DsID, bool IsKeyDecl);
435
436 ObjCTypeParamList *ReadObjCTypeParamList();
437
438 // FIXME: Reorder according to DeclNodes.td?
439 void VisitObjCMethodDecl(ObjCMethodDecl *D);
440 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
441 void VisitObjCContainerDecl(ObjCContainerDecl *D);
442 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
443 void VisitObjCIvarDecl(ObjCIvarDecl *D);
444 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
445 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
446 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
447 void VisitObjCImplDecl(ObjCImplDecl *D);
448 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
449 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
450 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
451 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
452 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
453 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
454 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
455 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
456 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
457 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
458 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
459 };
460
461} // namespace clang
462
463namespace {
464
465/// Iterator over the redeclarations of a declaration that have already
466/// been merged into the same redeclaration chain.
467template<typename DeclT>
468class MergedRedeclIterator {
469 DeclT *Start;
470 DeclT *Canonical = nullptr;
471 DeclT *Current = nullptr;
472
473public:
474 MergedRedeclIterator() = default;
475 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
476
477 DeclT *operator*() { return Current; }
478
479 MergedRedeclIterator &operator++() {
480 if (Current->isFirstDecl()) {
481 Canonical = Current;
482 Current = Current->getMostRecentDecl();
483 } else
484 Current = Current->getPreviousDecl();
485
486 // If we started in the merged portion, we'll reach our start position
487 // eventually. Otherwise, we'll never reach it, but the second declaration
488 // we reached was the canonical declaration, so stop when we see that one
489 // again.
490 if (Current == Start || Current == Canonical)
491 Current = nullptr;
492 return *this;
493 }
494
495 friend bool operator!=(const MergedRedeclIterator &A,
496 const MergedRedeclIterator &B) {
497 return A.Current != B.Current;
498 }
499};
500
501} // namespace
502
503template <typename DeclT>
504static llvm::iterator_range<MergedRedeclIterator<DeclT>>
505merged_redecls(DeclT *D) {
506 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
507 MergedRedeclIterator<DeclT>());
508}
509
510uint64_t ASTDeclReader::GetCurrentCursorOffset() {
511 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
512}
513
514void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
515 if (Record.readInt()) {
516 Reader.DefinitionSource[FD] =
517 Loc.F->Kind == ModuleKind::MK_MainFile ||
518 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
519 }
520 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
521 CD->setNumCtorInitializers(Record.readInt());
522 if (CD->getNumCtorInitializers())
523 CD->CtorInitializers = ReadGlobalOffset();
524 }
525 // Store the offset of the body so we can lazily load it later.
526 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
527 HasPendingBody = true;
528}
529
530void ASTDeclReader::Visit(Decl *D) {
531 DeclVisitor<ASTDeclReader, void>::Visit(D);
532
533 // At this point we have deserialized and merged the decl and it is safe to
534 // update its canonical decl to signal that the entire entity is used.
535 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
536 IsDeclMarkedUsed = false;
537
538 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
539 if (auto *TInfo = DD->getTypeSourceInfo())
540 Record.readTypeLoc(TInfo->getTypeLoc());
541 }
542
543 if (auto *TD = dyn_cast<TypeDecl>(D)) {
544 // We have a fully initialized TypeDecl. Read its type now.
545 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
546
547 // If this is a tag declaration with a typedef name for linkage, it's safe
548 // to load that typedef now.
549 if (NamedDeclForTagDecl)
550 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
551 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
552 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
553 // if we have a fully initialized TypeDecl, we can safely read its type now.
554 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
555 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
556 // FunctionDecl's body was written last after all other Stmts/Exprs.
557 // We only read it if FD doesn't already have a body (e.g., from another
558 // module).
559 // FIXME: Can we diagnose ODR violations somehow?
560 if (Record.readInt())
561 ReadFunctionDefinition(FD);
562 }
563}
564
565void ASTDeclReader::VisitDecl(Decl *D) {
566 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
567 isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
568 // We don't want to deserialize the DeclContext of a template
569 // parameter or of a parameter of a function template immediately. These
570 // entities might be used in the formulation of its DeclContext (for
571 // example, a function parameter can be used in decltype() in trailing
572 // return type of the function). Use the translation unit DeclContext as a
573 // placeholder.
574 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
575 GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
576 if (!LexicalDCIDForTemplateParmDecl)
577 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
578 Reader.addPendingDeclContextInfo(D,
579 SemaDCIDForTemplateParmDecl,
580 LexicalDCIDForTemplateParmDecl);
581 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
582 } else {
583 auto *SemaDC = readDeclAs<DeclContext>();
584 auto *LexicalDC = readDeclAs<DeclContext>();
585 if (!LexicalDC)
586 LexicalDC = SemaDC;
587 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
588 // Avoid calling setLexicalDeclContext() directly because it uses
589 // Decl::getASTContext() internally which is unsafe during derialization.
590 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
591 Reader.getContext());
592 }
593 D->setLocation(ThisDeclLoc);
594 D->InvalidDecl = Record.readInt();
595 if (Record.readInt()) { // hasAttrs
596 AttrVec Attrs;
597 Record.readAttributes(Attrs);
598 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
599 // internally which is unsafe during derialization.
600 D->setAttrsImpl(Attrs, Reader.getContext());
601 }
602 D->setImplicit(Record.readInt());
603 D->Used = Record.readInt();
604 IsDeclMarkedUsed |= D->Used;
605 D->setReferenced(Record.readInt());
606 D->setTopLevelDeclInObjCContainer(Record.readInt());
607 D->setAccess((AccessSpecifier)Record.readInt());
608 D->FromASTFile = true;
609 auto ModuleOwnership = (Decl::ModuleOwnershipKind)Record.readInt();
610 bool ModulePrivate =
611 (ModuleOwnership == Decl::ModuleOwnershipKind::ModulePrivate);
612
613 // Determine whether this declaration is part of a (sub)module. If so, it
614 // may not yet be visible.
615 if (unsigned SubmoduleID = readSubmoduleID()) {
616
617 switch (ModuleOwnership) {
618 case Decl::ModuleOwnershipKind::Visible:
619 ModuleOwnership = Decl::ModuleOwnershipKind::VisibleWhenImported;
620 break;
621 case Decl::ModuleOwnershipKind::Unowned:
622 case Decl::ModuleOwnershipKind::VisibleWhenImported:
623 case Decl::ModuleOwnershipKind::ReachableWhenImported:
624 case Decl::ModuleOwnershipKind::ModulePrivate:
625 break;
626 }
627
628 D->setModuleOwnershipKind(ModuleOwnership);
629 // Store the owning submodule ID in the declaration.
630 D->setOwningModuleID(SubmoduleID);
631
632 if (ModulePrivate) {
633 // Module-private declarations are never visible, so there is no work to
634 // do.
635 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
636 // If local visibility is being tracked, this declaration will become
637 // hidden and visible as the owning module does.
638 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
639 // Mark the declaration as visible when its owning module becomes visible.
640 if (Owner->NameVisibility == Module::AllVisible)
641 D->setVisibleDespiteOwningModule();
642 else
643 Reader.HiddenNamesMap[Owner].push_back(D);
644 }
645 } else if (ModulePrivate) {
646 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
647 }
648}
649
650void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
651 VisitDecl(D);
652 D->setLocation(readSourceLocation());
653 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
654 std::string Arg = readString();
655 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
656 D->getTrailingObjects<char>()[Arg.size()] = '\0';
657}
658
659void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
660 VisitDecl(D);
661 D->setLocation(readSourceLocation());
662 std::string Name = readString();
663 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
664 D->getTrailingObjects<char>()[Name.size()] = '\0';
665
666 D->ValueStart = Name.size() + 1;
667 std::string Value = readString();
668 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
669 Value.size());
670 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
671}
672
673void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
674 llvm_unreachable("Translation units are not serialized")::llvm::llvm_unreachable_internal("Translation units are not serialized"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 674)
;
675}
676
677void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
678 VisitDecl(ND);
679 ND->setDeclName(Record.readDeclarationName());
680 AnonymousDeclNumber = Record.readInt();
681}
682
683void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
684 VisitNamedDecl(TD);
685 TD->setLocStart(readSourceLocation());
686 // Delay type reading until after we have fully initialized the decl.
687 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
688}
689
690ASTDeclReader::RedeclarableResult
691ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
692 RedeclarableResult Redecl = VisitRedeclarable(TD);
693 VisitTypeDecl(TD);
694 TypeSourceInfo *TInfo = readTypeSourceInfo();
695 if (Record.readInt()) { // isModed
696 QualType modedT = Record.readType();
697 TD->setModedTypeSourceInfo(TInfo, modedT);
698 } else
699 TD->setTypeSourceInfo(TInfo);
700 // Read and discard the declaration for which this is a typedef name for
701 // linkage, if it exists. We cannot rely on our type to pull in this decl,
702 // because it might have been merged with a type from another module and
703 // thus might not refer to our version of the declaration.
704 readDecl();
705 return Redecl;
706}
707
708void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
709 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
710 mergeRedeclarable(TD, Redecl);
711}
712
713void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
714 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
715 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
716 // Merged when we merge the template.
717 TD->setDescribedAliasTemplate(Template);
718 else
719 mergeRedeclarable(TD, Redecl);
720}
721
722ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
723 RedeclarableResult Redecl = VisitRedeclarable(TD);
724 VisitTypeDecl(TD);
725
726 TD->IdentifierNamespace = Record.readInt();
727 TD->setTagKind((TagDecl::TagKind)Record.readInt());
728 if (!isa<CXXRecordDecl>(TD))
729 TD->setCompleteDefinition(Record.readInt());
730 TD->setEmbeddedInDeclarator(Record.readInt());
731 TD->setFreeStanding(Record.readInt());
732 TD->setCompleteDefinitionRequired(Record.readInt());
733 TD->setBraceRange(readSourceRange());
734
735 switch (Record.readInt()) {
736 case 0:
737 break;
738 case 1: { // ExtInfo
739 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
740 Record.readQualifierInfo(*Info);
741 TD->TypedefNameDeclOrQualifier = Info;
742 break;
743 }
744 case 2: // TypedefNameForAnonDecl
745 NamedDeclForTagDecl = readDeclID();
746 TypedefNameForLinkage = Record.readIdentifier();
747 break;
748 default:
749 llvm_unreachable("unexpected tag info kind")::llvm::llvm_unreachable_internal("unexpected tag info kind",
"clang/lib/Serialization/ASTReaderDecl.cpp", 749)
;
750 }
751
752 if (!isa<CXXRecordDecl>(TD))
753 mergeRedeclarable(TD, Redecl);
754 return Redecl;
755}
756
757void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
758 VisitTagDecl(ED);
759 if (TypeSourceInfo *TI = readTypeSourceInfo())
760 ED->setIntegerTypeSourceInfo(TI);
761 else
762 ED->setIntegerType(Record.readType());
763 ED->setPromotionType(Record.readType());
764 ED->setNumPositiveBits(Record.readInt());
765 ED->setNumNegativeBits(Record.readInt());
766 ED->setScoped(Record.readInt());
767 ED->setScopedUsingClassTag(Record.readInt());
768 ED->setFixed(Record.readInt());
769
770 ED->setHasODRHash(true);
771 ED->ODRHash = Record.readInt();
772
773 // If this is a definition subject to the ODR, and we already have a
774 // definition, merge this one into it.
775 if (ED->isCompleteDefinition() &&
776 Reader.getContext().getLangOpts().Modules &&
777 Reader.getContext().getLangOpts().CPlusPlus) {
778 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
779 if (!OldDef) {
780 // This is the first time we've seen an imported definition. Look for a
781 // local definition before deciding that we are the first definition.
782 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
783 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
784 OldDef = D;
785 break;
786 }
787 }
788 }
789 if (OldDef) {
790 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
791 ED->demoteThisDefinitionToDeclaration();
792 Reader.mergeDefinitionVisibility(OldDef, ED);
793 if (OldDef->getODRHash() != ED->getODRHash())
794 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
795 } else {
796 OldDef = ED;
797 }
798 }
799
800 if (auto *InstED = readDeclAs<EnumDecl>()) {
801 auto TSK = (TemplateSpecializationKind)Record.readInt();
802 SourceLocation POI = readSourceLocation();
803 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
804 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
805 }
806}
807
808ASTDeclReader::RedeclarableResult
809ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
810 RedeclarableResult Redecl = VisitTagDecl(RD);
811 RD->setHasFlexibleArrayMember(Record.readInt());
812 RD->setAnonymousStructOrUnion(Record.readInt());
813 RD->setHasObjectMember(Record.readInt());
814 RD->setHasVolatileMember(Record.readInt());
815 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
816 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
817 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
818 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
819 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
820 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
821 RD->setParamDestroyedInCallee(Record.readInt());
822 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
823 return Redecl;
824}
825
826void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
827 VisitRecordDeclImpl(RD);
828
829 // Maintain the invariant of a redeclaration chain containing only
830 // a single definition.
831 if (RD->isCompleteDefinition()) {
832 RecordDecl *Canon = static_cast<RecordDecl *>(RD->getCanonicalDecl());
833 RecordDecl *&OldDef = Reader.RecordDefinitions[Canon];
834 if (!OldDef) {
835 // This is the first time we've seen an imported definition. Look for a
836 // local definition before deciding that we are the first definition.
837 for (auto *D : merged_redecls(Canon)) {
838 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
839 OldDef = D;
840 break;
841 }
842 }
843 }
844 if (OldDef) {
845 Reader.MergedDeclContexts.insert(std::make_pair(RD, OldDef));
846 RD->demoteThisDefinitionToDeclaration();
847 Reader.mergeDefinitionVisibility(OldDef, RD);
848 } else {
849 OldDef = RD;
850 }
851 }
852}
853
854void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
855 VisitNamedDecl(VD);
856 // For function declarations, defer reading the type in case the function has
857 // a deduced return type that references an entity declared within the
858 // function.
859 if (isa<FunctionDecl>(VD))
860 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
861 else
862 VD->setType(Record.readType());
863}
864
865void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
866 VisitValueDecl(ECD);
867 if (Record.readInt())
868 ECD->setInitExpr(Record.readExpr());
869 ECD->setInitVal(Record.readAPSInt());
870 mergeMergeable(ECD);
871}
872
873void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
874 VisitValueDecl(DD);
875 DD->setInnerLocStart(readSourceLocation());
876 if (Record.readInt()) { // hasExtInfo
877 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
878 Record.readQualifierInfo(*Info);
879 Info->TrailingRequiresClause = Record.readExpr();
880 DD->DeclInfo = Info;
881 }
882 QualType TSIType = Record.readType();
883 DD->setTypeSourceInfo(
884 TSIType.isNull() ? nullptr
885 : Reader.getContext().CreateTypeSourceInfo(TSIType));
886}
887
888void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
889 RedeclarableResult Redecl = VisitRedeclarable(FD);
890 VisitDeclaratorDecl(FD);
891
892 // Attach a type to this function. Use the real type if possible, but fall
893 // back to the type as written if it involves a deduced return type.
894 if (FD->getTypeSourceInfo() &&
895 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
896 ->getReturnType()->getContainedAutoType()) {
897 // We'll set up the real type in Visit, once we've finished loading the
898 // function.
899 FD->setType(FD->getTypeSourceInfo()->getType());
900 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
901 } else {
902 FD->setType(Reader.GetType(DeferredTypeID));
903 }
904 DeferredTypeID = 0;
905
906 FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
907 FD->IdentifierNamespace = Record.readInt();
908
909 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
910 // after everything else is read.
911
912 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
913 FD->setInlineSpecified(Record.readInt());
914 FD->setImplicitlyInline(Record.readInt());
915 FD->setVirtualAsWritten(Record.readInt());
916 // We defer calling `FunctionDecl::setPure()` here as for methods of
917 // `CXXTemplateSpecializationDecl`s, we may not have connected up the
918 // definition (which is required for `setPure`).
919 const bool Pure = Record.readInt();
920 FD->setHasInheritedPrototype(Record.readInt());
921 FD->setHasWrittenPrototype(Record.readInt());
922 FD->setDeletedAsWritten(Record.readInt());
923 FD->setTrivial(Record.readInt());
924 FD->setTrivialForCall(Record.readInt());
925 FD->setDefaulted(Record.readInt());
926 FD->setExplicitlyDefaulted(Record.readInt());
927 FD->setHasImplicitReturnZero(Record.readInt());
928 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
929 FD->setUsesSEHTry(Record.readInt());
930 FD->setHasSkippedBody(Record.readInt());
931 FD->setIsMultiVersion(Record.readInt());
932 FD->setLateTemplateParsed(Record.readInt());
933 FD->setFriendConstraintRefersToEnclosingTemplate(Record.readInt());
934
935 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
936 FD->EndRangeLoc = readSourceLocation();
937
938 FD->ODRHash = Record.readInt();
939 FD->setHasODRHash(true);
940
941 if (FD->isDefaulted()) {
942 if (unsigned NumLookups = Record.readInt()) {
943 SmallVector<DeclAccessPair, 8> Lookups;
944 for (unsigned I = 0; I != NumLookups; ++I) {
945 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
946 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
947 Lookups.push_back(DeclAccessPair::make(ND, AS));
948 }
949 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
950 Reader.getContext(), Lookups));
951 }
952 }
953
954 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
955 case FunctionDecl::TK_NonTemplate:
956 mergeRedeclarable(FD, Redecl);
957 break;
958 case FunctionDecl::TK_DependentNonTemplate:
959 mergeRedeclarable(FD, Redecl);
960 FD->setInstantiatedFromDecl(readDeclAs<FunctionDecl>());
961 break;
962 case FunctionDecl::TK_FunctionTemplate:
963 // Merged when we merge the template.
964 FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
965 break;
966 case FunctionDecl::TK_MemberSpecialization: {
967 auto *InstFD = readDeclAs<FunctionDecl>();
968 auto TSK = (TemplateSpecializationKind)Record.readInt();
969 SourceLocation POI = readSourceLocation();
970 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
971 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
972 mergeRedeclarable(FD, Redecl);
973 break;
974 }
975 case FunctionDecl::TK_FunctionTemplateSpecialization: {
976 auto *Template = readDeclAs<FunctionTemplateDecl>();
977 auto TSK = (TemplateSpecializationKind)Record.readInt();
978
979 // Template arguments.
980 SmallVector<TemplateArgument, 8> TemplArgs;
981 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
982
983 // Template args as written.
984 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
985 SourceLocation LAngleLoc, RAngleLoc;
986 bool HasTemplateArgumentsAsWritten = Record.readInt();
987 if (HasTemplateArgumentsAsWritten) {
988 unsigned NumTemplateArgLocs = Record.readInt();
989 TemplArgLocs.reserve(NumTemplateArgLocs);
990 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
991 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
992
993 LAngleLoc = readSourceLocation();
994 RAngleLoc = readSourceLocation();
995 }
996
997 SourceLocation POI = readSourceLocation();
998
999 ASTContext &C = Reader.getContext();
1000 TemplateArgumentList *TemplArgList
1001 = TemplateArgumentList::CreateCopy(C, TemplArgs);
1002 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
1003 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
1004 TemplArgsInfo.addArgument(TemplArgLocs[i]);
1005
1006 MemberSpecializationInfo *MSInfo = nullptr;
1007 if (Record.readInt()) {
1008 auto *FD = readDeclAs<FunctionDecl>();
1009 auto TSK = (TemplateSpecializationKind)Record.readInt();
1010 SourceLocation POI = readSourceLocation();
1011
1012 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
1013 MSInfo->setPointOfInstantiation(POI);
1014 }
1015
1016 FunctionTemplateSpecializationInfo *FTInfo =
1017 FunctionTemplateSpecializationInfo::Create(
1018 C, FD, Template, TSK, TemplArgList,
1019 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
1020 MSInfo);
1021 FD->TemplateOrSpecialization = FTInfo;
1022
1023 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
1024 // The template that contains the specializations set. It's not safe to
1025 // use getCanonicalDecl on Template since it may still be initializing.
1026 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
1027 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
1028 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
1029 // FunctionTemplateSpecializationInfo's Profile().
1030 // We avoid getASTContext because a decl in the parent hierarchy may
1031 // be initializing.
1032 llvm::FoldingSetNodeID ID;
1033 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
1034 void *InsertPos = nullptr;
1035 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
1036 FunctionTemplateSpecializationInfo *ExistingInfo =
1037 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
1038 if (InsertPos)
1039 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
1040 else {
1041 assert(Reader.getContext().getLangOpts().Modules &&(static_cast <bool> (Reader.getContext().getLangOpts().
Modules && "already deserialized this template specialization"
) ? void (0) : __assert_fail ("Reader.getContext().getLangOpts().Modules && \"already deserialized this template specialization\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1042, __extension__
__PRETTY_FUNCTION__))
1042 "already deserialized this template specialization")(static_cast <bool> (Reader.getContext().getLangOpts().
Modules && "already deserialized this template specialization"
) ? void (0) : __assert_fail ("Reader.getContext().getLangOpts().Modules && \"already deserialized this template specialization\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1042, __extension__
__PRETTY_FUNCTION__))
;
1043 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
1044 }
1045 }
1046 break;
1047 }
1048 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
1049 // Templates.
1050 UnresolvedSet<8> TemplDecls;
1051 unsigned NumTemplates = Record.readInt();
1052 while (NumTemplates--)
1053 TemplDecls.addDecl(readDeclAs<NamedDecl>());
1054
1055 // Templates args.
1056 TemplateArgumentListInfo TemplArgs;
1057 unsigned NumArgs = Record.readInt();
1058 while (NumArgs--)
1059 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1060 TemplArgs.setLAngleLoc(readSourceLocation());
1061 TemplArgs.setRAngleLoc(readSourceLocation());
1062
1063 FD->setDependentTemplateSpecialization(Reader.getContext(),
1064 TemplDecls, TemplArgs);
1065 // These are not merged; we don't need to merge redeclarations of dependent
1066 // template friends.
1067 break;
1068 }
1069 }
1070
1071 // Defer calling `setPure` until merging above has guaranteed we've set
1072 // `DefinitionData` (as this will need to access it).
1073 FD->setPure(Pure);
1074
1075 // Read in the parameters.
1076 unsigned NumParams = Record.readInt();
1077 SmallVector<ParmVarDecl *, 16> Params;
1078 Params.reserve(NumParams);
1079 for (unsigned I = 0; I != NumParams; ++I)
1080 Params.push_back(readDeclAs<ParmVarDecl>());
1081 FD->setParams(Reader.getContext(), Params);
1082}
1083
1084void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1085 VisitNamedDecl(MD);
1086 if (Record.readInt()) {
1087 // Load the body on-demand. Most clients won't care, because method
1088 // definitions rarely show up in headers.
1089 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1090 HasPendingBody = true;
1091 }
1092 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1093 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1094 MD->setInstanceMethod(Record.readInt());
1095 MD->setVariadic(Record.readInt());
1096 MD->setPropertyAccessor(Record.readInt());
1097 MD->setSynthesizedAccessorStub(Record.readInt());
1098 MD->setDefined(Record.readInt());
1099 MD->setOverriding(Record.readInt());
1100 MD->setHasSkippedBody(Record.readInt());
1101
1102 MD->setIsRedeclaration(Record.readInt());
1103 MD->setHasRedeclaration(Record.readInt());
1104 if (MD->hasRedeclaration())
1105 Reader.getContext().setObjCMethodRedeclaration(MD,
1106 readDeclAs<ObjCMethodDecl>());
1107
1108 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1109 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1110 MD->setRelatedResultType(Record.readInt());
1111 MD->setReturnType(Record.readType());
1112 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1113 MD->DeclEndLoc = readSourceLocation();
1114 unsigned NumParams = Record.readInt();
1115 SmallVector<ParmVarDecl *, 16> Params;
1116 Params.reserve(NumParams);
1117 for (unsigned I = 0; I != NumParams; ++I)
1118 Params.push_back(readDeclAs<ParmVarDecl>());
1119
1120 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1121 unsigned NumStoredSelLocs = Record.readInt();
1122 SmallVector<SourceLocation, 16> SelLocs;
1123 SelLocs.reserve(NumStoredSelLocs);
1124 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1125 SelLocs.push_back(readSourceLocation());
1126
1127 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1128}
1129
1130void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1131 VisitTypedefNameDecl(D);
1132
1133 D->Variance = Record.readInt();
1134 D->Index = Record.readInt();
1135 D->VarianceLoc = readSourceLocation();
1136 D->ColonLoc = readSourceLocation();
1137}
1138
1139void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1140 VisitNamedDecl(CD);
1141 CD->setAtStartLoc(readSourceLocation());
1142 CD->setAtEndRange(readSourceRange());
1143}
1144
1145ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1146 unsigned numParams = Record.readInt();
1147 if (numParams == 0)
1148 return nullptr;
1149
1150 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1151 typeParams.reserve(numParams);
1152 for (unsigned i = 0; i != numParams; ++i) {
1153 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1154 if (!typeParam)
1155 return nullptr;
1156
1157 typeParams.push_back(typeParam);
1158 }
1159
1160 SourceLocation lAngleLoc = readSourceLocation();
1161 SourceLocation rAngleLoc = readSourceLocation();
1162
1163 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1164 typeParams, rAngleLoc);
1165}
1166
1167void ASTDeclReader::ReadObjCDefinitionData(
1168 struct ObjCInterfaceDecl::DefinitionData &Data) {
1169 // Read the superclass.
1170 Data.SuperClassTInfo = readTypeSourceInfo();
1171
1172 Data.EndLoc = readSourceLocation();
1173 Data.HasDesignatedInitializers = Record.readInt();
1174
1175 // Read the directly referenced protocols and their SourceLocations.
1176 unsigned NumProtocols = Record.readInt();
1177 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1178 Protocols.reserve(NumProtocols);
1179 for (unsigned I = 0; I != NumProtocols; ++I)
1180 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1181 SmallVector<SourceLocation, 16> ProtoLocs;
1182 ProtoLocs.reserve(NumProtocols);
1183 for (unsigned I = 0; I != NumProtocols; ++I)
1184 ProtoLocs.push_back(readSourceLocation());
1185 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1186 Reader.getContext());
1187
1188 // Read the transitive closure of protocols referenced by this class.
1189 NumProtocols = Record.readInt();
1190 Protocols.clear();
1191 Protocols.reserve(NumProtocols);
1192 for (unsigned I = 0; I != NumProtocols; ++I)
1193 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1194 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1195 Reader.getContext());
1196}
1197
1198void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1199 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1200 struct ObjCInterfaceDecl::DefinitionData &DD = D->data();
1201 if (DD.Definition != NewDD.Definition) {
1202 Reader.MergedDeclContexts.insert(
1203 std::make_pair(NewDD.Definition, DD.Definition));
1204 Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);
1205 }
1206
1207 // FIXME: odr checking?
1208}
1209
1210void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1211 RedeclarableResult Redecl = VisitRedeclarable(ID);
1212 VisitObjCContainerDecl(ID);
1213 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1214 mergeRedeclarable(ID, Redecl);
1215
1216 ID->TypeParamList = ReadObjCTypeParamList();
1217 if (Record.readInt()) {
1218 // Read the definition.
1219 ID->allocateDefinitionData();
1220
1221 ReadObjCDefinitionData(ID->data());
1222 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1223 if (Canon->Data.getPointer()) {
1224 // If we already have a definition, keep the definition invariant and
1225 // merge the data.
1226 MergeDefinitionData(Canon, std::move(ID->data()));
1227 ID->Data = Canon->Data;
1228 } else {
1229 // Set the definition data of the canonical declaration, so other
1230 // redeclarations will see it.
1231 ID->getCanonicalDecl()->Data = ID->Data;
1232
1233 // We will rebuild this list lazily.
1234 ID->setIvarList(nullptr);
1235 }
1236
1237 // Note that we have deserialized a definition.
1238 Reader.PendingDefinitions.insert(ID);
1239
1240 // Note that we've loaded this Objective-C class.
1241 Reader.ObjCClassesLoaded.push_back(ID);
1242 } else {
1243 ID->Data = ID->getCanonicalDecl()->Data;
1244 }
1245}
1246
1247void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1248 VisitFieldDecl(IVD);
1249 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1250 // This field will be built lazily.
1251 IVD->setNextIvar(nullptr);
1252 bool synth = Record.readInt();
1253 IVD->setSynthesize(synth);
1254
1255 // Check ivar redeclaration.
1256 if (IVD->isInvalidDecl())
1257 return;
1258 // Don't check ObjCInterfaceDecl as interfaces are named and mismatches can be
1259 // detected in VisitObjCInterfaceDecl. Here we are looking for redeclarations
1260 // in extensions.
1261 if (isa<ObjCInterfaceDecl>(IVD->getDeclContext()))
1262 return;
1263 ObjCInterfaceDecl *CanonIntf =
1264 IVD->getContainingInterface()->getCanonicalDecl();
1265 IdentifierInfo *II = IVD->getIdentifier();
1266 ObjCIvarDecl *PrevIvar = CanonIntf->lookupInstanceVariable(II);
1267 if (PrevIvar && PrevIvar != IVD) {
1268 auto *ParentExt = dyn_cast<ObjCCategoryDecl>(IVD->getDeclContext());
1269 auto *PrevParentExt =
1270 dyn_cast<ObjCCategoryDecl>(PrevIvar->getDeclContext());
1271 if (ParentExt && PrevParentExt) {
1272 // Postpone diagnostic as we should merge identical extensions from
1273 // different modules.
1274 Reader
1275 .PendingObjCExtensionIvarRedeclarations[std::make_pair(ParentExt,
1276 PrevParentExt)]
1277 .push_back(std::make_pair(IVD, PrevIvar));
1278 } else if (ParentExt || PrevParentExt) {
1279 // Duplicate ivars in extension + implementation are never compatible.
1280 // Compatibility of implementation + implementation should be handled in
1281 // VisitObjCImplementationDecl.
1282 Reader.Diag(IVD->getLocation(), diag::err_duplicate_ivar_declaration)
1283 << II;
1284 Reader.Diag(PrevIvar->getLocation(), diag::note_previous_definition);
1285 }
1286 }
1287}
1288
1289void ASTDeclReader::ReadObjCDefinitionData(
1290 struct ObjCProtocolDecl::DefinitionData &Data) {
1291 unsigned NumProtoRefs = Record.readInt();
1292 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1293 ProtoRefs.reserve(NumProtoRefs);
1294 for (unsigned I = 0; I != NumProtoRefs; ++I)
1295 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1296 SmallVector<SourceLocation, 16> ProtoLocs;
1297 ProtoLocs.reserve(NumProtoRefs);
1298 for (unsigned I = 0; I != NumProtoRefs; ++I)
1299 ProtoLocs.push_back(readSourceLocation());
1300 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1301 ProtoLocs.data(), Reader.getContext());
1302}
1303
1304void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1305 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1306 struct ObjCProtocolDecl::DefinitionData &DD = D->data();
1307 if (DD.Definition != NewDD.Definition) {
1308 Reader.MergedDeclContexts.insert(
1309 std::make_pair(NewDD.Definition, DD.Definition));
1310 Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);
1311 }
1312
1313 // FIXME: odr checking?
1314}
1315
1316void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1317 RedeclarableResult Redecl = VisitRedeclarable(PD);
1318 VisitObjCContainerDecl(PD);
1319 mergeRedeclarable(PD, Redecl);
1320
1321 if (Record.readInt()) {
1322 // Read the definition.
1323 PD->allocateDefinitionData();
1324
1325 ReadObjCDefinitionData(PD->data());
1326
1327 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1328 if (Canon->Data.getPointer()) {
1329 // If we already have a definition, keep the definition invariant and
1330 // merge the data.
1331 MergeDefinitionData(Canon, std::move(PD->data()));
1332 PD->Data = Canon->Data;
1333 } else {
1334 // Set the definition data of the canonical declaration, so other
1335 // redeclarations will see it.
1336 PD->getCanonicalDecl()->Data = PD->Data;
1337 }
1338 // Note that we have deserialized a definition.
1339 Reader.PendingDefinitions.insert(PD);
1340 } else {
1341 PD->Data = PD->getCanonicalDecl()->Data;
1342 }
1343}
1344
1345void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1346 VisitFieldDecl(FD);
1347}
1348
1349void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1350 VisitObjCContainerDecl(CD);
1351 CD->setCategoryNameLoc(readSourceLocation());
1352 CD->setIvarLBraceLoc(readSourceLocation());
1353 CD->setIvarRBraceLoc(readSourceLocation());
1354
1355 // Note that this category has been deserialized. We do this before
1356 // deserializing the interface declaration, so that it will consider this
1357 /// category.
1358 Reader.CategoriesDeserialized.insert(CD);
1359
1360 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1361 CD->TypeParamList = ReadObjCTypeParamList();
1362 unsigned NumProtoRefs = Record.readInt();
1363 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1364 ProtoRefs.reserve(NumProtoRefs);
1365 for (unsigned I = 0; I != NumProtoRefs; ++I)
1366 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1367 SmallVector<SourceLocation, 16> ProtoLocs;
1368 ProtoLocs.reserve(NumProtoRefs);
1369 for (unsigned I = 0; I != NumProtoRefs; ++I)
1370 ProtoLocs.push_back(readSourceLocation());
1371 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1372 Reader.getContext());
1373
1374 // Protocols in the class extension belong to the class.
1375 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1376 CD->ClassInterface->mergeClassExtensionProtocolList(
1377 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1378 Reader.getContext());
1379}
1380
1381void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1382 VisitNamedDecl(CAD);
1383 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1384}
1385
1386void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1387 VisitNamedDecl(D);
1388 D->setAtLoc(readSourceLocation());
1389 D->setLParenLoc(readSourceLocation());
1390 QualType T = Record.readType();
1391 TypeSourceInfo *TSI = readTypeSourceInfo();
1392 D->setType(T, TSI);
1393 D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1394 D->setPropertyAttributesAsWritten(
1395 (ObjCPropertyAttribute::Kind)Record.readInt());
1396 D->setPropertyImplementation(
1397 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1398 DeclarationName GetterName = Record.readDeclarationName();
1399 SourceLocation GetterLoc = readSourceLocation();
1400 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1401 DeclarationName SetterName = Record.readDeclarationName();
1402 SourceLocation SetterLoc = readSourceLocation();
1403 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1404 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1405 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1406 D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1407}
1408
1409void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1410 VisitObjCContainerDecl(D);
1411 D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1412}
1413
1414void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1415 VisitObjCImplDecl(D);
1416 D->CategoryNameLoc = readSourceLocation();
1417}
1418
1419void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1420 VisitObjCImplDecl(D);
1421 D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1422 D->SuperLoc = readSourceLocation();
1423 D->setIvarLBraceLoc(readSourceLocation());
1424 D->setIvarRBraceLoc(readSourceLocation());
1425 D->setHasNonZeroConstructors(Record.readInt());
1426 D->setHasDestructors(Record.readInt());
1427 D->NumIvarInitializers = Record.readInt();
1428 if (D->NumIvarInitializers)
1429 D->IvarInitializers = ReadGlobalOffset();
1430}
1431
1432void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1433 VisitDecl(D);
1434 D->setAtLoc(readSourceLocation());
1435 D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1436 D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1437 D->IvarLoc = readSourceLocation();
1438 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1439 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1440 D->setGetterCXXConstructor(Record.readExpr());
1441 D->setSetterCXXAssignment(Record.readExpr());
1442}
1443
1444void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1445 VisitDeclaratorDecl(FD);
1446 FD->Mutable = Record.readInt();
1447
1448 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1449 FD->InitStorage.setInt(ISK);
1450 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1451 ? Record.readType().getAsOpaquePtr()
1452 : Record.readExpr());
1453 }
1454
1455 if (auto *BW = Record.readExpr())
1456 FD->setBitWidth(BW);
1457
1458 if (!FD->getDeclName()) {
1459 if (auto *Tmpl = readDeclAs<FieldDecl>())
1460 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1461 }
1462 mergeMergeable(FD);
1463}
1464
1465void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1466 VisitDeclaratorDecl(PD);
1467 PD->GetterId = Record.readIdentifier();
1468 PD->SetterId = Record.readIdentifier();
1469}
1470
1471void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1472 VisitValueDecl(D);
1473 D->PartVal.Part1 = Record.readInt();
1474 D->PartVal.Part2 = Record.readInt();
1475 D->PartVal.Part3 = Record.readInt();
1476 for (auto &C : D->PartVal.Part4And5)
1477 C = Record.readInt();
1478
1479 // Add this GUID to the AST context's lookup structure, and merge if needed.
1480 if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))
1481 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1482}
1483
1484void ASTDeclReader::VisitUnnamedGlobalConstantDecl(
1485 UnnamedGlobalConstantDecl *D) {
1486 VisitValueDecl(D);
1487 D->Value = Record.readAPValue();
1488
1489 // Add this to the AST context's lookup structure, and merge if needed.
1490 if (UnnamedGlobalConstantDecl *Existing =
1491 Reader.getContext().UnnamedGlobalConstantDecls.GetOrInsertNode(D))
1492 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1493}
1494
1495void ASTDeclReader::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1496 VisitValueDecl(D);
1497 D->Value = Record.readAPValue();
1498
1499 // Add this template parameter object to the AST context's lookup structure,
1500 // and merge if needed.
1501 if (TemplateParamObjectDecl *Existing =
1502 Reader.getContext().TemplateParamObjectDecls.GetOrInsertNode(D))
1503 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1504}
1505
1506void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1507 VisitValueDecl(FD);
1508
1509 FD->ChainingSize = Record.readInt();
1510 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2")(static_cast <bool> (FD->ChainingSize >= 2 &&
"Anonymous chaining must be >= 2") ? void (0) : __assert_fail
("FD->ChainingSize >= 2 && \"Anonymous chaining must be >= 2\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1510, __extension__
__PRETTY_FUNCTION__))
;
1511 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1512
1513 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1514 FD->Chaining[I] = readDeclAs<NamedDecl>();
1515
1516 mergeMergeable(FD);
1517}
1518
1519ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1520 RedeclarableResult Redecl = VisitRedeclarable(VD);
1521 VisitDeclaratorDecl(VD);
1522
1523 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1524 VD->VarDeclBits.TSCSpec = Record.readInt();
1525 VD->VarDeclBits.InitStyle = Record.readInt();
1526 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1527 if (!isa<ParmVarDecl>(VD)) {
1528 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1529 Record.readInt();
1530 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1531 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1532 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1533 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1534 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1535 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1536 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1537 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1538 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1539 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1540 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1541 }
1542 auto VarLinkage = Linkage(Record.readInt());
1543 VD->setCachedLinkage(VarLinkage);
1544
1545 // Reconstruct the one piece of the IdentifierNamespace that we need.
1546 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1547 VD->getLexicalDeclContext()->isFunctionOrMethod())
1548 VD->setLocalExternDecl();
1549
1550 if (uint64_t Val = Record.readInt()) {
1551 VD->setInit(Record.readExpr());
1552 if (Val != 1) {
1553 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1554 Eval->HasConstantInitialization = (Val & 2) != 0;
1555 Eval->HasConstantDestruction = (Val & 4) != 0;
1556 }
1557 }
1558
1559 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1560 Expr *CopyExpr = Record.readExpr();
1561 if (CopyExpr)
1562 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1563 }
1564
1565 if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1566 Reader.DefinitionSource[VD] =
1567 Loc.F->Kind == ModuleKind::MK_MainFile ||
1568 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1569 }
1570
1571 enum VarKind {
1572 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1573 };
1574 switch ((VarKind)Record.readInt()) {
1575 case VarNotTemplate:
1576 // Only true variables (not parameters or implicit parameters) can be
1577 // merged; the other kinds are not really redeclarable at all.
1578 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1579 !isa<VarTemplateSpecializationDecl>(VD))
1580 mergeRedeclarable(VD, Redecl);
1581 break;
1582 case VarTemplate:
1583 // Merged when we merge the template.
1584 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1585 break;
1586 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1587 auto *Tmpl = readDeclAs<VarDecl>();
1588 auto TSK = (TemplateSpecializationKind)Record.readInt();
1589 SourceLocation POI = readSourceLocation();
1590 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1591 mergeRedeclarable(VD, Redecl);
1592 break;
1593 }
1594 }
1595
1596 return Redecl;
1597}
1598
1599void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1600 VisitVarDecl(PD);
1601}
1602
1603void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1604 VisitVarDecl(PD);
1605 unsigned isObjCMethodParam = Record.readInt();
1606 unsigned scopeDepth = Record.readInt();
1607 unsigned scopeIndex = Record.readInt();
1608 unsigned declQualifier = Record.readInt();
1609 if (isObjCMethodParam) {
1610 assert(scopeDepth == 0)(static_cast <bool> (scopeDepth == 0) ? void (0) : __assert_fail
("scopeDepth == 0", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 1610, __extension__ __PRETTY_FUNCTION__))
;
1611 PD->setObjCMethodScopeInfo(scopeIndex);
1612 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1613 } else {
1614 PD->setScopeInfo(scopeDepth, scopeIndex);
1615 }
1616 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1617 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1618 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1619 PD->setUninstantiatedDefaultArg(Record.readExpr());
1620
1621 // FIXME: If this is a redeclaration of a function from another module, handle
1622 // inheritance of default arguments.
1623}
1624
1625void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1626 VisitVarDecl(DD);
1627 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1628 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1629 BDs[I] = readDeclAs<BindingDecl>();
1630 BDs[I]->setDecomposedDecl(DD);
1631 }
1632}
1633
1634void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1635 VisitValueDecl(BD);
1636 BD->Binding = Record.readExpr();
1637}
1638
1639void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1640 VisitDecl(AD);
1641 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1642 AD->setRParenLoc(readSourceLocation());
1643}
1644
1645void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1646 VisitDecl(BD);
1647 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1648 BD->setSignatureAsWritten(readTypeSourceInfo());
1649 unsigned NumParams = Record.readInt();
1650 SmallVector<ParmVarDecl *, 16> Params;
1651 Params.reserve(NumParams);
1652 for (unsigned I = 0; I != NumParams; ++I)
1653 Params.push_back(readDeclAs<ParmVarDecl>());
1654 BD->setParams(Params);
1655
1656 BD->setIsVariadic(Record.readInt());
1657 BD->setBlockMissingReturnType(Record.readInt());
1658 BD->setIsConversionFromLambda(Record.readInt());
1659 BD->setDoesNotEscape(Record.readInt());
1660 BD->setCanAvoidCopyToHeap(Record.readInt());
1661
1662 bool capturesCXXThis = Record.readInt();
1663 unsigned numCaptures = Record.readInt();
1664 SmallVector<BlockDecl::Capture, 16> captures;
1665 captures.reserve(numCaptures);
1666 for (unsigned i = 0; i != numCaptures; ++i) {
1667 auto *decl = readDeclAs<VarDecl>();
1668 unsigned flags = Record.readInt();
1669 bool byRef = (flags & 1);
1670 bool nested = (flags & 2);
1671 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1672
1673 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1674 }
1675 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1676}
1677
1678void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1679 VisitDecl(CD);
1680 unsigned ContextParamPos = Record.readInt();
1681 CD->setNothrow(Record.readInt() != 0);
1682 // Body is set by VisitCapturedStmt.
1683 for (unsigned I = 0; I < CD->NumParams; ++I) {
1684 if (I != ContextParamPos)
1685 CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1686 else
1687 CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1688 }
1689}
1690
1691void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1692 VisitDecl(D);
1693 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1694 D->setExternLoc(readSourceLocation());
1695 D->setRBraceLoc(readSourceLocation());
1696}
1697
1698void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1699 VisitDecl(D);
1700 D->RBraceLoc = readSourceLocation();
1701}
1702
1703void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1704 VisitNamedDecl(D);
1705 D->setLocStart(readSourceLocation());
1706}
1707
1708void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1709 RedeclarableResult Redecl = VisitRedeclarable(D);
1710 VisitNamedDecl(D);
1711 D->setInline(Record.readInt());
1712 D->LocStart = readSourceLocation();
1713 D->RBraceLoc = readSourceLocation();
1714
1715 // Defer loading the anonymous namespace until we've finished merging
1716 // this namespace; loading it might load a later declaration of the
1717 // same namespace, and we have an invariant that older declarations
1718 // get merged before newer ones try to merge.
1719 GlobalDeclID AnonNamespace = 0;
1720 if (Redecl.getFirstID() == ThisDeclID) {
1721 AnonNamespace = readDeclID();
1722 } else {
1723 // Link this namespace back to the first declaration, which has already
1724 // been deserialized.
1725 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1726 }
1727
1728 mergeRedeclarable(D, Redecl);
1729
1730 if (AnonNamespace) {
1731 // Each module has its own anonymous namespace, which is disjoint from
1732 // any other module's anonymous namespaces, so don't attach the anonymous
1733 // namespace at all.
1734 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1735 if (!Record.isModule())
1736 D->setAnonymousNamespace(Anon);
1737 }
1738}
1739
1740void ASTDeclReader::VisitHLSLBufferDecl(HLSLBufferDecl *D) {
1741 VisitNamedDecl(D);
1742 VisitDeclContext(D);
1743 D->IsCBuffer = Record.readBool();
1744 D->KwLoc = readSourceLocation();
1745 D->LBraceLoc = readSourceLocation();
1746 D->RBraceLoc = readSourceLocation();
1747}
1748
1749void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1750 RedeclarableResult Redecl = VisitRedeclarable(D);
1751 VisitNamedDecl(D);
1752 D->NamespaceLoc = readSourceLocation();
1753 D->IdentLoc = readSourceLocation();
1754 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1755 D->Namespace = readDeclAs<NamedDecl>();
1756 mergeRedeclarable(D, Redecl);
1757}
1758
1759void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1760 VisitNamedDecl(D);
1761 D->setUsingLoc(readSourceLocation());
1762 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1763 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1764 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1765 D->setTypename(Record.readInt());
1766 if (auto *Pattern = readDeclAs<NamedDecl>())
1767 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1768 mergeMergeable(D);
1769}
1770
1771void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {
1772 VisitNamedDecl(D);
1773 D->setUsingLoc(readSourceLocation());
1774 D->setEnumLoc(readSourceLocation());
1775 D->Enum = readDeclAs<EnumDecl>();
1776 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1777 if (auto *Pattern = readDeclAs<UsingEnumDecl>())
1778 Reader.getContext().setInstantiatedFromUsingEnumDecl(D, Pattern);
1779 mergeMergeable(D);
1780}
1781
1782void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1783 VisitNamedDecl(D);
1784 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1785 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1786 for (unsigned I = 0; I != D->NumExpansions; ++I)
1787 Expansions[I] = readDeclAs<NamedDecl>();
1788 mergeMergeable(D);
1789}
1790
1791void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1792 RedeclarableResult Redecl = VisitRedeclarable(D);
1793 VisitNamedDecl(D);
1794 D->Underlying = readDeclAs<NamedDecl>();
1795 D->IdentifierNamespace = Record.readInt();
1796 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1797 auto *Pattern = readDeclAs<UsingShadowDecl>();
1798 if (Pattern)
1799 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1800 mergeRedeclarable(D, Redecl);
1801}
1802
1803void ASTDeclReader::VisitConstructorUsingShadowDecl(
1804 ConstructorUsingShadowDecl *D) {
1805 VisitUsingShadowDecl(D);
1806 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1807 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1808 D->IsVirtual = Record.readInt();
1809}
1810
1811void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1812 VisitNamedDecl(D);
1813 D->UsingLoc = readSourceLocation();
1814 D->NamespaceLoc = readSourceLocation();
1815 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1816 D->NominatedNamespace = readDeclAs<NamedDecl>();
1817 D->CommonAncestor = readDeclAs<DeclContext>();
1818}
1819
1820void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1821 VisitValueDecl(D);
1822 D->setUsingLoc(readSourceLocation());
1823 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1824 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1825 D->EllipsisLoc = readSourceLocation();
1826 mergeMergeable(D);
1827}
1828
1829void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1830 UnresolvedUsingTypenameDecl *D) {
1831 VisitTypeDecl(D);
1832 D->TypenameLocation = readSourceLocation();
1833 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1834 D->EllipsisLoc = readSourceLocation();
1835 mergeMergeable(D);
1836}
1837
1838void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(
1839 UnresolvedUsingIfExistsDecl *D) {
1840 VisitNamedDecl(D);
1841}
1842
1843void ASTDeclReader::ReadCXXDefinitionData(
1844 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1845 #define FIELD(Name, Width, Merge) \
1846 Data.Name = Record.readInt();
1847 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1848
1849 // Note: the caller has deserialized the IsLambda bit already.
1850 Data.ODRHash = Record.readInt();
1851 Data.HasODRHash = true;
1852
1853 if (Record.readInt()) {
1854 Reader.DefinitionSource[D] =
1855 Loc.F->Kind == ModuleKind::MK_MainFile ||
1856 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1857 }
1858
1859 Data.NumBases = Record.readInt();
1860 if (Data.NumBases)
1861 Data.Bases = ReadGlobalOffset();
1862 Data.NumVBases = Record.readInt();
1863 if (Data.NumVBases)
1864 Data.VBases = ReadGlobalOffset();
1865
1866 Record.readUnresolvedSet(Data.Conversions);
1867 Data.ComputedVisibleConversions = Record.readInt();
1868 if (Data.ComputedVisibleConversions)
1869 Record.readUnresolvedSet(Data.VisibleConversions);
1870 assert(Data.Definition && "Data.Definition should be already set!")(static_cast <bool> (Data.Definition && "Data.Definition should be already set!"
) ? void (0) : __assert_fail ("Data.Definition && \"Data.Definition should be already set!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1870, __extension__
__PRETTY_FUNCTION__))
;
1871 Data.FirstFriend = readDeclID();
1872
1873 if (Data.IsLambda) {
1874 using Capture = LambdaCapture;
1875
1876 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1877 Lambda.DependencyKind = Record.readInt();
1878 Lambda.IsGenericLambda = Record.readInt();
1879 Lambda.CaptureDefault = Record.readInt();
1880 Lambda.NumCaptures = Record.readInt();
1881 Lambda.NumExplicitCaptures = Record.readInt();
1882 Lambda.HasKnownInternalLinkage = Record.readInt();
1883 Lambda.ManglingNumber = Record.readInt();
1884 D->setDeviceLambdaManglingNumber(Record.readInt());
1885 Lambda.ContextDecl = readDeclID();
1886 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1887 sizeof(Capture) * Lambda.NumCaptures);
1888 Capture *ToCapture = Lambda.Captures;
1889 Lambda.MethodTyInfo = readTypeSourceInfo();
1890 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1891 SourceLocation Loc = readSourceLocation();
1892 bool IsImplicit = Record.readInt();
1893 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1894 switch (Kind) {
1895 case LCK_StarThis:
1896 case LCK_This:
1897 case LCK_VLAType:
1898 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1899 break;
1900 case LCK_ByCopy:
1901 case LCK_ByRef:
1902 auto *Var = readDeclAs<VarDecl>();
1903 SourceLocation EllipsisLoc = readSourceLocation();
1904 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1905 break;
1906 }
1907 }
1908 }
1909}
1910
1911void ASTDeclReader::MergeDefinitionData(
1912 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1913 assert(D->DefinitionData &&(static_cast <bool> (D->DefinitionData && "merging class definition into non-definition"
) ? void (0) : __assert_fail ("D->DefinitionData && \"merging class definition into non-definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1914, __extension__
__PRETTY_FUNCTION__))
1914 "merging class definition into non-definition")(static_cast <bool> (D->DefinitionData && "merging class definition into non-definition"
) ? void (0) : __assert_fail ("D->DefinitionData && \"merging class definition into non-definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1914, __extension__
__PRETTY_FUNCTION__))
;
1915 auto &DD = *D->DefinitionData;
1916
1917 if (DD.Definition != MergeDD.Definition) {
1918 // Track that we merged the definitions.
1919 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1920 DD.Definition));
1921 Reader.PendingDefinitions.erase(MergeDD.Definition);
1922 MergeDD.Definition->setCompleteDefinition(false);
1923 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1924 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&(static_cast <bool> (Reader.Lookups.find(MergeDD.Definition
) == Reader.Lookups.end() && "already loaded pending lookups for merged definition"
) ? void (0) : __assert_fail ("Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() && \"already loaded pending lookups for merged definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1925, __extension__
__PRETTY_FUNCTION__))
1925 "already loaded pending lookups for merged definition")(static_cast <bool> (Reader.Lookups.find(MergeDD.Definition
) == Reader.Lookups.end() && "already loaded pending lookups for merged definition"
) ? void (0) : __assert_fail ("Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() && \"already loaded pending lookups for merged definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1925, __extension__
__PRETTY_FUNCTION__))
;
1926 }
1927
1928 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1929 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1930 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1931 // We faked up this definition data because we found a class for which we'd
1932 // not yet loaded the definition. Replace it with the real thing now.
1933 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?")(static_cast <bool> (!DD.IsLambda && !MergeDD.IsLambda
&& "faked up lambda definition?") ? void (0) : __assert_fail
("!DD.IsLambda && !MergeDD.IsLambda && \"faked up lambda definition?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1933, __extension__
__PRETTY_FUNCTION__))
;
1934 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1935
1936 // Don't change which declaration is the definition; that is required
1937 // to be invariant once we select it.
1938 auto *Def = DD.Definition;
1939 DD = std::move(MergeDD);
1940 DD.Definition = Def;
1941 return;
1942 }
1943
1944 bool DetectedOdrViolation = false;
1945
1946 #define FIELD(Name, Width, Merge) Merge(Name)
1947 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1948 #define NO_MERGE(Field) \
1949 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1950 MERGE_OR(Field)
1951 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1952 NO_MERGE(IsLambda)
1953 #undef NO_MERGE
1954 #undef MERGE_OR
1955
1956 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1957 DetectedOdrViolation = true;
1958 // FIXME: Issue a diagnostic if the base classes don't match when we come
1959 // to lazily load them.
1960
1961 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1962 // match when we come to lazily load them.
1963 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1964 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1965 DD.ComputedVisibleConversions = true;
1966 }
1967
1968 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1969 // lazily load it.
1970
1971 if (DD.IsLambda) {
1972 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1973 // when they occur within the body of a function template specialization).
1974 }
1975
1976 if (D->getODRHash() != MergeDD.ODRHash) {
1977 DetectedOdrViolation = true;
1978 }
1979
1980 if (DetectedOdrViolation)
1981 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1982 {MergeDD.Definition, &MergeDD});
1983}
1984
1985void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1986 struct CXXRecordDecl::DefinitionData *DD;
1987 ASTContext &C = Reader.getContext();
1988
1989 // Determine whether this is a lambda closure type, so that we can
1990 // allocate the appropriate DefinitionData structure.
1991 bool IsLambda = Record.readInt();
1992 if (IsLambda)
1993 DD = new (C) CXXRecordDecl::LambdaDefinitionData(
1994 D, nullptr, CXXRecordDecl::LDK_Unknown, false, LCD_None);
1995 else
1996 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1997
1998 CXXRecordDecl *Canon = D->getCanonicalDecl();
1999 // Set decl definition data before reading it, so that during deserialization
2000 // when we read CXXRecordDecl, it already has definition data and we don't
2001 // set fake one.
2002 if (!Canon->DefinitionData)
2003 Canon->DefinitionData = DD;
2004 D->DefinitionData = Canon->DefinitionData;
2005 ReadCXXDefinitionData(*DD, D);
2006
2007 // We might already have a different definition for this record. This can
2008 // happen either because we're reading an update record, or because we've
2009 // already done some merging. Either way, just merge into it.
2010 if (Canon->DefinitionData != DD) {
2011 MergeDefinitionData(Canon, std::move(*DD));
2012 return;
2013 }
2014
2015 // Mark this declaration as being a definition.
2016 D->setCompleteDefinition(true);
2017
2018 // If this is not the first declaration or is an update record, we can have
2019 // other redeclarations already. Make a note that we need to propagate the
2020 // DefinitionData pointer onto them.
2021 if (Update || Canon != D)
2022 Reader.PendingDefinitions.insert(D);
2023}
2024
2025ASTDeclReader::RedeclarableResult
2026ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
2027 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
2028
2029 ASTContext &C = Reader.getContext();
2030
2031 enum CXXRecKind {
2032 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
2033 };
2034 switch ((CXXRecKind)Record.readInt()) {
2035 case CXXRecNotTemplate:
2036 // Merged when we merge the folding set entry in the primary template.
2037 if (!isa<ClassTemplateSpecializationDecl>(D))
2038 mergeRedeclarable(D, Redecl);
2039 break;
2040 case CXXRecTemplate: {
2041 // Merged when we merge the template.
2042 auto *Template = readDeclAs<ClassTemplateDecl>();
2043 D->TemplateOrInstantiation = Template;
2044 if (!Template->getTemplatedDecl()) {
2045 // We've not actually loaded the ClassTemplateDecl yet, because we're
2046 // currently being loaded as its pattern. Rely on it to set up our
2047 // TypeForDecl (see VisitClassTemplateDecl).
2048 //
2049 // Beware: we do not yet know our canonical declaration, and may still
2050 // get merged once the surrounding class template has got off the ground.
2051 DeferredTypeID = 0;
2052 }
2053 break;
2054 }
2055 case CXXRecMemberSpecialization: {
2056 auto *RD = readDeclAs<CXXRecordDecl>();
2057 auto TSK = (TemplateSpecializationKind)Record.readInt();
2058 SourceLocation POI = readSourceLocation();
2059 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
2060 MSI->setPointOfInstantiation(POI);
2061 D->TemplateOrInstantiation = MSI;
2062 mergeRedeclarable(D, Redecl);
2063 break;
2064 }
2065 }
2066
2067 bool WasDefinition = Record.readInt();
2068 if (WasDefinition)
2069 ReadCXXRecordDefinition(D, /*Update*/false);
2070 else
2071 // Propagate DefinitionData pointer from the canonical declaration.
2072 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
2073
2074 // Lazily load the key function to avoid deserializing every method so we can
2075 // compute it.
2076 if (WasDefinition) {
2077 DeclID KeyFn = readDeclID();
2078 if (KeyFn && D->isCompleteDefinition())
2079 // FIXME: This is wrong for the ARM ABI, where some other module may have
2080 // made this function no longer be a key function. We need an update
2081 // record or similar for that case.
2082 C.KeyFunctions[D] = KeyFn;
2083 }
2084
2085 return Redecl;
2086}
2087
2088void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2089 D->setExplicitSpecifier(Record.readExplicitSpec());
2090 D->Ctor = readDeclAs<CXXConstructorDecl>();
2091 VisitFunctionDecl(D);
2092 D->setIsCopyDeductionCandidate(Record.readInt());
2093}
2094
2095void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
2096 VisitFunctionDecl(D);
2097
2098 unsigned NumOverridenMethods = Record.readInt();
2099 if (D->isCanonicalDecl()) {
2100 while (NumOverridenMethods--) {
2101 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
2102 // MD may be initializing.
2103 if (auto *MD = readDeclAs<CXXMethodDecl>())
2104 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
2105 }
2106 } else {
2107 // We don't care about which declarations this used to override; we get
2108 // the relevant information from the canonical declaration.
2109 Record.skipInts(NumOverridenMethods);
2110 }
2111}
2112
2113void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2114 // We need the inherited constructor information to merge the declaration,
2115 // so we have to read it before we call VisitCXXMethodDecl.
2116 D->setExplicitSpecifier(Record.readExplicitSpec());
2117 if (D->isInheritingConstructor()) {
2118 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
2119 auto *Ctor = readDeclAs<CXXConstructorDecl>();
2120 *D->getTrailingObjects<InheritedConstructor>() =
2121 InheritedConstructor(Shadow, Ctor);
2122 }
2123
2124 VisitCXXMethodDecl(D);
2125}
2126
2127void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2128 VisitCXXMethodDecl(D);
2129
2130 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
2131 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2132 auto *ThisArg = Record.readExpr();
2133 // FIXME: Check consistency if we have an old and new operator delete.
2134 if (!Canon->OperatorDelete) {
2135 Canon->OperatorDelete = OperatorDelete;
2136 Canon->OperatorDeleteThisArg = ThisArg;
2137 }
2138 }
2139}
2140
2141void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2142 D->setExplicitSpecifier(Record.readExplicitSpec());
2143 VisitCXXMethodDecl(D);
2144}
2145
2146void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2147 VisitDecl(D);
2148 D->ImportedModule = readModule();
2149 D->setImportComplete(Record.readInt());
2150 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
2151 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2152 StoredLocs[I] = readSourceLocation();
2153 Record.skipInts(1); // The number of stored source locations.
2154}
2155
2156void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2157 VisitDecl(D);
2158 D->setColonLoc(readSourceLocation());
2159}
2160
2161void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2162 VisitDecl(D);
2163 if (Record.readInt()) // hasFriendDecl
2164 D->Friend = readDeclAs<NamedDecl>();
2165 else
2166 D->Friend = readTypeSourceInfo();
2167 for (unsigned i = 0; i != D->NumTPLists; ++i)
2168 D->getTrailingObjects<TemplateParameterList *>()[i] =
2169 Record.readTemplateParameterList();
2170 D->NextFriend = readDeclID();
2171 D->UnsupportedFriend = (Record.readInt() != 0);
2172 D->FriendLoc = readSourceLocation();
2173}
2174
2175void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2176 VisitDecl(D);
2177 unsigned NumParams = Record.readInt();
2178 D->NumParams = NumParams;
2179 D->Params = new (Reader.getContext()) TemplateParameterList *[NumParams];
2180 for (unsigned i = 0; i != NumParams; ++i)
2181 D->Params[i] = Record.readTemplateParameterList();
2182 if (Record.readInt()) // HasFriendDecl
2183 D->Friend = readDeclAs<NamedDecl>();
2184 else
2185 D->Friend = readTypeSourceInfo();
2186 D->FriendLoc = readSourceLocation();
2187}
2188
2189DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2190 VisitNamedDecl(D);
2191
2192 DeclID PatternID = readDeclID();
2193 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2194 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2195 D->init(TemplatedDecl, TemplateParams);
2196
2197 return PatternID;
2198}
2199
2200void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2201 VisitTemplateDecl(D);
2202 D->ConstraintExpr = Record.readExpr();
2203 mergeMergeable(D);
2204}
2205
2206void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2207}
2208
2209ASTDeclReader::RedeclarableResult
2210ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2211 RedeclarableResult Redecl = VisitRedeclarable(D);
2212
2213 // Make sure we've allocated the Common pointer first. We do this before
2214 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2215 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2216 if (!CanonD->Common) {
2217 CanonD->Common = CanonD->newCommon(Reader.getContext());
2218 Reader.PendingDefinitions.insert(CanonD);
2219 }
2220 D->Common = CanonD->Common;
2221
2222 // If this is the first declaration of the template, fill in the information
2223 // for the 'common' pointer.
2224 if (ThisDeclID == Redecl.getFirstID()) {
2225 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2226 assert(RTD->getKind() == D->getKind() &&(static_cast <bool> (RTD->getKind() == D->getKind
() && "InstantiatedFromMemberTemplate kind mismatch")
? void (0) : __assert_fail ("RTD->getKind() == D->getKind() && \"InstantiatedFromMemberTemplate kind mismatch\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2227, __extension__
__PRETTY_FUNCTION__))
2227 "InstantiatedFromMemberTemplate kind mismatch")(static_cast <bool> (RTD->getKind() == D->getKind
() && "InstantiatedFromMemberTemplate kind mismatch")
? void (0) : __assert_fail ("RTD->getKind() == D->getKind() && \"InstantiatedFromMemberTemplate kind mismatch\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2227, __extension__
__PRETTY_FUNCTION__))
;
2228 D->setInstantiatedFromMemberTemplate(RTD);
2229 if (Record.readInt())
2230 D->setMemberSpecialization();
2231 }
2232 }
2233
2234 DeclID PatternID = VisitTemplateDecl(D);
2235 D->IdentifierNamespace = Record.readInt();
2236
2237 mergeRedeclarable(D, Redecl, PatternID);
2238
2239 // If we merged the template with a prior declaration chain, merge the common
2240 // pointer.
2241 // FIXME: Actually merge here, don't just overwrite.
2242 D->Common = D->getCanonicalDecl()->Common;
2243
2244 return Redecl;
2245}
2246
2247void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2248 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2249
2250 if (ThisDeclID == Redecl.getFirstID()) {
2251 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2252 // the specializations.
2253 SmallVector<serialization::DeclID, 32> SpecIDs;
2254 readDeclIDList(SpecIDs);
2255 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2256 }
2257
2258 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2259 // We were loaded before our templated declaration was. We've not set up
2260 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2261 // it now.
2262 Reader.getContext().getInjectedClassNameType(
2263 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2264 }
2265}
2266
2267void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2268 llvm_unreachable("BuiltinTemplates are not serialized")::llvm::llvm_unreachable_internal("BuiltinTemplates are not serialized"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2268)
;
2269}
2270
2271/// TODO: Unify with ClassTemplateDecl version?
2272/// May require unifying ClassTemplateDecl and
2273/// VarTemplateDecl beyond TemplateDecl...
2274void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2275 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2276
2277 if (ThisDeclID == Redecl.getFirstID()) {
2278 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2279 // the specializations.
2280 SmallVector<serialization::DeclID, 32> SpecIDs;
2281 readDeclIDList(SpecIDs);
2282 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2283 }
2284}
2285
2286ASTDeclReader::RedeclarableResult
2287ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2288 ClassTemplateSpecializationDecl *D) {
2289 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2290
2291 ASTContext &C = Reader.getContext();
2292 if (Decl *InstD = readDecl()) {
2293 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2294 D->SpecializedTemplate = CTD;
2295 } else {
2296 SmallVector<TemplateArgument, 8> TemplArgs;
2297 Record.readTemplateArgumentList(TemplArgs);
2298 TemplateArgumentList *ArgList
2299 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2300 auto *PS =
2301 new (C) ClassTemplateSpecializationDecl::
2302 SpecializedPartialSpecialization();
2303 PS->PartialSpecialization
2304 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2305 PS->TemplateArgs = ArgList;
2306 D->SpecializedTemplate = PS;
2307 }
2308 }
2309
2310 SmallVector<TemplateArgument, 8> TemplArgs;
2311 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2312 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2313 D->PointOfInstantiation = readSourceLocation();
2314 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2315
2316 bool writtenAsCanonicalDecl = Record.readInt();
2317 if (writtenAsCanonicalDecl) {
2318 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2319 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2320 // Set this as, or find, the canonical declaration for this specialization
2321 ClassTemplateSpecializationDecl *CanonSpec;
2322 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2323 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2324 .GetOrInsertNode(Partial);
2325 } else {
2326 CanonSpec =
2327 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2328 }
2329 // If there was already a canonical specialization, merge into it.
2330 if (CanonSpec != D) {
2331 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2332
2333 // This declaration might be a definition. Merge with any existing
2334 // definition.
2335 if (auto *DDD = D->DefinitionData) {
2336 if (CanonSpec->DefinitionData)
2337 MergeDefinitionData(CanonSpec, std::move(*DDD));
2338 else
2339 CanonSpec->DefinitionData = D->DefinitionData;
2340 }
2341 D->DefinitionData = CanonSpec->DefinitionData;
2342 }
2343 }
2344 }
2345
2346 // Explicit info.
2347 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2348 auto *ExplicitInfo =
2349 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2350 ExplicitInfo->TypeAsWritten = TyInfo;
2351 ExplicitInfo->ExternLoc = readSourceLocation();
2352 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2353 D->ExplicitInfo = ExplicitInfo;
2354 }
2355
2356 return Redecl;
2357}
2358
2359void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2360 ClassTemplatePartialSpecializationDecl *D) {
2361 // We need to read the template params first because redeclarable is going to
2362 // need them for profiling
2363 TemplateParameterList *Params = Record.readTemplateParameterList();
2364 D->TemplateParams = Params;
2365 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2366
2367 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2368
2369 // These are read/set from/to the first declaration.
2370 if (ThisDeclID == Redecl.getFirstID()) {
2371 D->InstantiatedFromMember.setPointer(
2372 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2373 D->InstantiatedFromMember.setInt(Record.readInt());
2374 }
2375}
2376
2377void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2378 ClassScopeFunctionSpecializationDecl *D) {
2379 VisitDecl(D);
2380 D->Specialization = readDeclAs<CXXMethodDecl>();
2381 if (Record.readInt())
2382 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2383}
2384
2385void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2386 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2387
2388 if (ThisDeclID == Redecl.getFirstID()) {
2389 // This FunctionTemplateDecl owns a CommonPtr; read it.
2390 SmallVector<serialization::DeclID, 32> SpecIDs;
2391 readDeclIDList(SpecIDs);
2392 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2393 }
2394}
2395
2396/// TODO: Unify with ClassTemplateSpecializationDecl version?
2397/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2398/// VarTemplate(Partial)SpecializationDecl with a new data
2399/// structure Template(Partial)SpecializationDecl, and
2400/// using Template(Partial)SpecializationDecl as input type.
2401ASTDeclReader::RedeclarableResult
2402ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2403 VarTemplateSpecializationDecl *D) {
2404 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2405
2406 ASTContext &C = Reader.getContext();
2407 if (Decl *InstD = readDecl()) {
2408 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2409 D->SpecializedTemplate = VTD;
2410 } else {
2411 SmallVector<TemplateArgument, 8> TemplArgs;
2412 Record.readTemplateArgumentList(TemplArgs);
2413 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2414 C, TemplArgs);
2415 auto *PS =
2416 new (C)
2417 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2418 PS->PartialSpecialization =
2419 cast<VarTemplatePartialSpecializationDecl>(InstD);
2420 PS->TemplateArgs = ArgList;
2421 D->SpecializedTemplate = PS;
2422 }
2423 }
2424
2425 // Explicit info.
2426 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2427 auto *ExplicitInfo =
2428 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2429 ExplicitInfo->TypeAsWritten = TyInfo;
2430 ExplicitInfo->ExternLoc = readSourceLocation();
2431 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2432 D->ExplicitInfo = ExplicitInfo;
2433 }
2434
2435 SmallVector<TemplateArgument, 8> TemplArgs;
2436 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2437 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2438 D->PointOfInstantiation = readSourceLocation();
2439 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2440 D->IsCompleteDefinition = Record.readInt();
2441
2442 bool writtenAsCanonicalDecl = Record.readInt();
2443 if (writtenAsCanonicalDecl) {
2444 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2445 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2446 VarTemplateSpecializationDecl *CanonSpec;
2447 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2448 CanonSpec = CanonPattern->getCommonPtr()
2449 ->PartialSpecializations.GetOrInsertNode(Partial);
2450 } else {
2451 CanonSpec =
2452 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2453 }
2454 // If we already have a matching specialization, merge it.
2455 if (CanonSpec != D)
2456 mergeRedeclarable<VarDecl>(D, CanonSpec, Redecl);
2457 }
2458 }
2459
2460 return Redecl;
2461}
2462
2463/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2464/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2465/// VarTemplate(Partial)SpecializationDecl with a new data
2466/// structure Template(Partial)SpecializationDecl, and
2467/// using Template(Partial)SpecializationDecl as input type.
2468void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2469 VarTemplatePartialSpecializationDecl *D) {
2470 TemplateParameterList *Params = Record.readTemplateParameterList();
2471 D->TemplateParams = Params;
2472 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2473
2474 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2475
2476 // These are read/set from/to the first declaration.
2477 if (ThisDeclID == Redecl.getFirstID()) {
2478 D->InstantiatedFromMember.setPointer(
2479 readDeclAs<VarTemplatePartialSpecializationDecl>());
2480 D->InstantiatedFromMember.setInt(Record.readInt());
2481 }
2482}
2483
2484void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2485 VisitTypeDecl(D);
2486
2487 D->setDeclaredWithTypename(Record.readInt());
2488
2489 if (Record.readBool()) {
2490 NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2491 DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2492 ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2493 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2494 if (Record.readBool())
2495 ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2496 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2497 D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2498 ArgsAsWritten, ImmediatelyDeclaredConstraint);
2499 if ((D->ExpandedParameterPack = Record.readInt()))
2500 D->NumExpanded = Record.readInt();
2501 }
2502
2503 if (Record.readInt())
2504 D->setDefaultArgument(readTypeSourceInfo());
2505}
2506
2507void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2508 VisitDeclaratorDecl(D);
2509 // TemplateParmPosition.
2510 D->setDepth(Record.readInt());
2511 D->setPosition(Record.readInt());
2512 if (D->hasPlaceholderTypeConstraint())
2513 D->setPlaceholderTypeConstraint(Record.readExpr());
2514 if (D->isExpandedParameterPack()) {
2515 auto TypesAndInfos =
2516 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2517 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2518 new (&TypesAndInfos[I].first) QualType(Record.readType());
2519 TypesAndInfos[I].second = readTypeSourceInfo();
2520 }
2521 } else {
2522 // Rest of NonTypeTemplateParmDecl.
2523 D->ParameterPack = Record.readInt();
2524 if (Record.readInt())
2525 D->setDefaultArgument(Record.readExpr());
2526 }
2527}
2528
2529void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2530 VisitTemplateDecl(D);
2531 // TemplateParmPosition.
2532 D->setDepth(Record.readInt());
2533 D->setPosition(Record.readInt());
2534 if (D->isExpandedParameterPack()) {
2535 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2536 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2537 I != N; ++I)
2538 Data[I] = Record.readTemplateParameterList();
2539 } else {
2540 // Rest of TemplateTemplateParmDecl.
2541 D->ParameterPack = Record.readInt();
2542 if (Record.readInt())
2543 D->setDefaultArgument(Reader.getContext(),
2544 Record.readTemplateArgumentLoc());
2545 }
2546}
2547
2548void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2549 VisitRedeclarableTemplateDecl(D);
2550}
2551
2552void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2553 VisitDecl(D);
2554 D->AssertExprAndFailed.setPointer(Record.readExpr());
2555 D->AssertExprAndFailed.setInt(Record.readInt());
2556 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2557 D->RParenLoc = readSourceLocation();
2558}
2559
2560void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2561 VisitDecl(D);
2562}
2563
2564void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2565 LifetimeExtendedTemporaryDecl *D) {
2566 VisitDecl(D);
2567 D->ExtendingDecl = readDeclAs<ValueDecl>();
2568 D->ExprWithTemporary = Record.readStmt();
2569 if (Record.readInt()) {
2570 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2571 D->getASTContext().addDestruction(D->Value);
2572 }
2573 D->ManglingNumber = Record.readInt();
2574 mergeMergeable(D);
2575}
2576
2577std::pair<uint64_t, uint64_t>
2578ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2579 uint64_t LexicalOffset = ReadLocalOffset();
2580 uint64_t VisibleOffset = ReadLocalOffset();
2581 return std::make_pair(LexicalOffset, VisibleOffset);
2582}
2583
2584template <typename T>
2585ASTDeclReader::RedeclarableResult
2586ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2587 DeclID FirstDeclID = readDeclID();
2588 Decl *MergeWith = nullptr;
2589
2590 bool IsKeyDecl = ThisDeclID == FirstDeclID;
1
Assuming 'FirstDeclID' is not equal to field 'ThisDeclID'
2591 bool IsFirstLocalDecl = false;
2592
2593 uint64_t RedeclOffset = 0;
2594
2595 // 0 indicates that this declaration was the only declaration of its entity,
2596 // and is used for space optimization.
2597 if (FirstDeclID == 0) {
2
Assuming 'FirstDeclID' is equal to 0
3
Taking true branch
2598 FirstDeclID = ThisDeclID;
2599 IsKeyDecl = true;
2600 IsFirstLocalDecl = true;
2601 } else if (unsigned N = Record.readInt()) {
2602 // This declaration was the first local declaration, but may have imported
2603 // other declarations.
2604 IsKeyDecl = N == 1;
2605 IsFirstLocalDecl = true;
2606
2607 // We have some declarations that must be before us in our redeclaration
2608 // chain. Read them now, and remember that we ought to merge with one of
2609 // them.
2610 // FIXME: Provide a known merge target to the second and subsequent such
2611 // declaration.
2612 for (unsigned I = 0; I != N - 1; ++I)
2613 MergeWith = readDecl();
2614
2615 RedeclOffset = ReadLocalOffset();
2616 } else {
2617 // This declaration was not the first local declaration. Read the first
2618 // local declaration now, to trigger the import of other redeclarations.
2619 (void)readDecl();
2620 }
2621
2622 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
4
Assuming null pointer is passed into cast
5
'FirstDecl' initialized to a null pointer value
2623 if (FirstDecl != D) {
6
Assuming 'FirstDecl' is not equal to 'D'
7
Taking true branch
2624 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2625 // We temporarily set the first (canonical) declaration as the previous one
2626 // which is the one that matters and mark the real previous DeclID to be
2627 // loaded & attached later on.
2628 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2629 D->First = FirstDecl->getCanonicalDecl();
8
Called C++ object pointer is null
2630 }
2631
2632 auto *DAsT = static_cast<T *>(D);
2633
2634 // Note that we need to load local redeclarations of this decl and build a
2635 // decl chain for them. This must happen *after* we perform the preloading
2636 // above; this ensures that the redeclaration chain is built in the correct
2637 // order.
2638 if (IsFirstLocalDecl)
2639 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2640
2641 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2642}
2643
2644/// Attempts to merge the given declaration (D) with another declaration
2645/// of the same entity.
2646template<typename T>
2647void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2648 RedeclarableResult &Redecl,
2649 DeclID TemplatePatternID) {
2650 // If modules are not available, there is no reason to perform this merge.
2651 if (!Reader.getContext().getLangOpts().Modules)
2652 return;
2653
2654 // If we're not the canonical declaration, we don't need to merge.
2655 if (!DBase->isFirstDecl())
2656 return;
2657
2658 auto *D = static_cast<T *>(DBase);
2659
2660 if (auto *Existing = Redecl.getKnownMergeTarget())
2661 // We already know of an existing declaration we should merge with.
2662 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2663 else if (FindExistingResult ExistingRes = findExisting(D))
2664 if (T *Existing = ExistingRes)
2665 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2666}
2667
2668/// "Cast" to type T, asserting if we don't have an implicit conversion.
2669/// We use this to put code in a template that will only be valid for certain
2670/// instantiations.
2671template<typename T> static T assert_cast(T t) { return t; }
2672template<typename T> static T assert_cast(...) {
2673 llvm_unreachable("bad assert_cast")::llvm::llvm_unreachable_internal("bad assert_cast", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 2673)
;
2674}
2675
2676/// Merge together the pattern declarations from two template
2677/// declarations.
2678void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2679 RedeclarableTemplateDecl *Existing,
2680 DeclID DsID, bool IsKeyDecl) {
2681 auto *DPattern = D->getTemplatedDecl();
2682 auto *ExistingPattern = Existing->getTemplatedDecl();
2683 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2684 DPattern->getCanonicalDecl()->getGlobalID(),
2685 IsKeyDecl);
2686
2687 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2688 // Merge with any existing definition.
2689 // FIXME: This is duplicated in several places. Refactor.
2690 auto *ExistingClass =
2691 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2692 if (auto *DDD = DClass->DefinitionData) {
2693 if (ExistingClass->DefinitionData) {
2694 MergeDefinitionData(ExistingClass, std::move(*DDD));
2695 } else {
2696 ExistingClass->DefinitionData = DClass->DefinitionData;
2697 // We may have skipped this before because we thought that DClass
2698 // was the canonical declaration.
2699 Reader.PendingDefinitions.insert(DClass);
2700 }
2701 }
2702 DClass->DefinitionData = ExistingClass->DefinitionData;
2703
2704 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2705 Result);
2706 }
2707 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2708 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2709 Result);
2710 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2711 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2712 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2713 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2714 Result);
2715 llvm_unreachable("merged an unknown kind of redeclarable template")::llvm::llvm_unreachable_internal("merged an unknown kind of redeclarable template"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2715)
;
2716}
2717
2718/// Attempts to merge the given declaration (D) with another declaration
2719/// of the same entity.
2720template<typename T>
2721void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2722 RedeclarableResult &Redecl,
2723 DeclID TemplatePatternID) {
2724 auto *D = static_cast<T *>(DBase);
2725 T *ExistingCanon = Existing->getCanonicalDecl();
2726 T *DCanon = D->getCanonicalDecl();
2727 if (ExistingCanon != DCanon) {
2728 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&(static_cast <bool> (DCanon->getGlobalID() == Redecl
.getFirstID() && "already merged this declaration") ?
void (0) : __assert_fail ("DCanon->getGlobalID() == Redecl.getFirstID() && \"already merged this declaration\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2729, __extension__
__PRETTY_FUNCTION__))
2729 "already merged this declaration")(static_cast <bool> (DCanon->getGlobalID() == Redecl
.getFirstID() && "already merged this declaration") ?
void (0) : __assert_fail ("DCanon->getGlobalID() == Redecl.getFirstID() && \"already merged this declaration\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2729, __extension__
__PRETTY_FUNCTION__))
;
2730
2731 // Have our redeclaration link point back at the canonical declaration
2732 // of the existing declaration, so that this declaration has the
2733 // appropriate canonical declaration.
2734 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2735 D->First = ExistingCanon;
2736 ExistingCanon->Used |= D->Used;
2737 D->Used = false;
2738
2739 // When we merge a namespace, update its pointer to the first namespace.
2740 // We cannot have loaded any redeclarations of this declaration yet, so
2741 // there's nothing else that needs to be updated.
2742 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2743 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2744 assert_cast<NamespaceDecl*>(ExistingCanon));
2745
2746 // When we merge a template, merge its pattern.
2747 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2748 mergeTemplatePattern(
2749 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2750 TemplatePatternID, Redecl.isKeyDecl());
2751
2752 // If this declaration is a key declaration, make a note of that.
2753 if (Redecl.isKeyDecl())
2754 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2755 }
2756}
2757
2758/// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2759/// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2760/// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2761/// that some types are mergeable during deserialization, otherwise name
2762/// lookup fails. This is the case for EnumConstantDecl.
2763static bool allowODRLikeMergeInC(NamedDecl *ND) {
2764 if (!ND)
2765 return false;
2766 // TODO: implement merge for other necessary decls.
2767 if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(ND))
2768 return true;
2769 return false;
2770}
2771
2772/// Attempts to merge LifetimeExtendedTemporaryDecl with
2773/// identical class definitions from two different modules.
2774void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2775 // If modules are not available, there is no reason to perform this merge.
2776 if (!Reader.getContext().getLangOpts().Modules)
2777 return;
2778
2779 LifetimeExtendedTemporaryDecl *LETDecl = D;
2780
2781 LifetimeExtendedTemporaryDecl *&LookupResult =
2782 Reader.LETemporaryForMerging[std::make_pair(
2783 LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2784 if (LookupResult)
2785 Reader.getContext().setPrimaryMergedDecl(LETDecl,
2786 LookupResult->getCanonicalDecl());
2787 else
2788 LookupResult = LETDecl;
2789}
2790
2791/// Attempts to merge the given declaration (D) with another declaration
2792/// of the same entity, for the case where the entity is not actually
2793/// redeclarable. This happens, for instance, when merging the fields of
2794/// identical class definitions from two different modules.
2795template<typename T>
2796void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2797 // If modules are not available, there is no reason to perform this merge.
2798 if (!Reader.getContext().getLangOpts().Modules)
2799 return;
2800
2801 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2802 // Note that C identically-named things in different translation units are
2803 // not redeclarations, but may still have compatible types, where ODR-like
2804 // semantics may apply.
2805 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2806 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2807 return;
2808
2809 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2810 if (T *Existing = ExistingRes)
2811 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2812 Existing->getCanonicalDecl());
2813}
2814
2815void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2816 Record.readOMPChildren(D->Data);
2817 VisitDecl(D);
2818}
2819
2820void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2821 Record.readOMPChildren(D->Data);
2822 VisitDecl(D);
2823}
2824
2825void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2826 Record.readOMPChildren(D->Data);
2827 VisitDecl(D);
2828}
2829
2830void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2831 VisitValueDecl(D);
2832 D->setLocation(readSourceLocation());
2833 Expr *In = Record.readExpr();
2834 Expr *Out = Record.readExpr();
2835 D->setCombinerData(In, Out);
2836 Expr *Combiner = Record.readExpr();
2837 D->setCombiner(Combiner);
2838 Expr *Orig = Record.readExpr();
2839 Expr *Priv = Record.readExpr();
2840 D->setInitializerData(Orig, Priv);
2841 Expr *Init = Record.readExpr();
2842 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2843 D->setInitializer(Init, IK);
2844 D->PrevDeclInScope = readDeclID();
2845}
2846
2847void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2848 Record.readOMPChildren(D->Data);
2849 VisitValueDecl(D);
2850 D->VarName = Record.readDeclarationName();
2851 D->PrevDeclInScope = readDeclID();
2852}
2853
2854void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2855 VisitVarDecl(D);
2856}
2857
2858//===----------------------------------------------------------------------===//
2859// Attribute Reading
2860//===----------------------------------------------------------------------===//
2861
2862namespace {
2863class AttrReader {
2864 ASTRecordReader &Reader;
2865
2866public:
2867 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2868
2869 uint64_t readInt() {
2870 return Reader.readInt();
2871 }
2872
2873 bool readBool() { return Reader.readBool(); }
2874
2875 SourceRange readSourceRange() {
2876 return Reader.readSourceRange();
2877 }
2878
2879 SourceLocation readSourceLocation() {
2880 return Reader.readSourceLocation();
2881 }
2882
2883 Expr *readExpr() { return Reader.readExpr(); }
2884
2885 std::string readString() {
2886 return Reader.readString();
2887 }
2888
2889 TypeSourceInfo *readTypeSourceInfo() {
2890 return Reader.readTypeSourceInfo();
2891 }
2892
2893 IdentifierInfo *readIdentifier() {
2894 return Reader.readIdentifier();
2895 }
2896
2897 VersionTuple readVersionTuple() {
2898 return Reader.readVersionTuple();
2899 }
2900
2901 OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
2902
2903 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2904 return Reader.GetLocalDeclAs<T>(LocalID);
2905 }
2906};
2907}
2908
2909Attr *ASTRecordReader::readAttr() {
2910 AttrReader Record(*this);
2911 auto V = Record.readInt();
2912 if (!V)
2913 return nullptr;
2914
2915 Attr *New = nullptr;
2916 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2917 // Attr pointer.
2918 auto Kind = static_cast<attr::Kind>(V - 1);
2919 ASTContext &Context = getContext();
2920
2921 IdentifierInfo *AttrName = Record.readIdentifier();
2922 IdentifierInfo *ScopeName = Record.readIdentifier();
2923 SourceRange AttrRange = Record.readSourceRange();
2924 SourceLocation ScopeLoc = Record.readSourceLocation();
2925 unsigned ParsedKind = Record.readInt();
2926 unsigned Syntax = Record.readInt();
2927 unsigned SpellingIndex = Record.readInt();
2928
2929 AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2930 AttributeCommonInfo::Kind(ParsedKind),
2931 AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2932
2933#include "clang/Serialization/AttrPCHRead.inc"
2934
2935 assert(New && "Unable to decode attribute?")(static_cast <bool> (New && "Unable to decode attribute?"
) ? void (0) : __assert_fail ("New && \"Unable to decode attribute?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2935, __extension__
__PRETTY_FUNCTION__))
;
2936 return New;
2937}
2938
2939/// Reads attributes from the current stream position.
2940void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2941 for (unsigned I = 0, E = readInt(); I != E; ++I)
2942 if (auto *A = readAttr())
2943 Attrs.push_back(A);
2944}
2945
2946//===----------------------------------------------------------------------===//
2947// ASTReader Implementation
2948//===----------------------------------------------------------------------===//
2949
2950/// Note that we have loaded the declaration with the given
2951/// Index.
2952///
2953/// This routine notes that this declaration has already been loaded,
2954/// so that future GetDecl calls will return this declaration rather
2955/// than trying to load a new declaration.
2956inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2957 assert(!DeclsLoaded[Index] && "Decl loaded twice?")(static_cast <bool> (!DeclsLoaded[Index] && "Decl loaded twice?"
) ? void (0) : __assert_fail ("!DeclsLoaded[Index] && \"Decl loaded twice?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2957, __extension__
__PRETTY_FUNCTION__))
;
2958 DeclsLoaded[Index] = D;
2959}
2960
2961/// Determine whether the consumer will be interested in seeing
2962/// this declaration (via HandleTopLevelDecl).
2963///
2964/// This routine should return true for anything that might affect
2965/// code generation, e.g., inline function definitions, Objective-C
2966/// declarations with metadata, etc.
2967static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2968 // An ObjCMethodDecl is never considered as "interesting" because its
2969 // implementation container always is.
2970
2971 // An ImportDecl or VarDecl imported from a module map module will get
2972 // emitted when we import the relevant module.
2973 if (isPartOfPerModuleInitializer(D)) {
2974 auto *M = D->getImportedOwningModule();
2975 if (M && M->Kind == Module::ModuleMapModule &&
2976 Ctx.DeclMustBeEmitted(D))
2977 return false;
2978 }
2979
2980 if (isa<FileScopeAsmDecl>(D) ||
2981 isa<ObjCProtocolDecl>(D) ||
2982 isa<ObjCImplDecl>(D) ||
2983 isa<ImportDecl>(D) ||
2984 isa<PragmaCommentDecl>(D) ||
2985 isa<PragmaDetectMismatchDecl>(D))
2986 return true;
2987 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2988 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D) ||
2989 isa<OMPRequiresDecl>(D))
2990 return !D->getDeclContext()->isFunctionOrMethod();
2991 if (const auto *Var = dyn_cast<VarDecl>(D))
2992 return Var->isFileVarDecl() &&
2993 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2994 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2995 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2996 return Func->doesThisDeclarationHaveABody() || HasBody;
2997
2998 if (auto *ES = D->getASTContext().getExternalSource())
2999 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3000 return true;
3001
3002 return false;
3003}
3004
3005/// Get the correct cursor and offset for loading a declaration.
3006ASTReader::RecordLocation
3007ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
3008 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
3009 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map")(static_cast <bool> (I != GlobalDeclMap.end() &&
"Corrupted global declaration map") ? void (0) : __assert_fail
("I != GlobalDeclMap.end() && \"Corrupted global declaration map\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3009, __extension__
__PRETTY_FUNCTION__))
;
3010 ModuleFile *M = I->second;
3011 const DeclOffset &DOffs =
3012 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
3013 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
3014 return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));
3015}
3016
3017ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
3018 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
3019
3020 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map")(static_cast <bool> (I != GlobalBitOffsetsMap.end() &&
"Corrupted global bit offsets map") ? void (0) : __assert_fail
("I != GlobalBitOffsetsMap.end() && \"Corrupted global bit offsets map\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3020, __extension__
__PRETTY_FUNCTION__))
;
3021 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
3022}
3023
3024uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
3025 return LocalOffset + M.GlobalBitOffset;
3026}
3027
3028/// Find the context in which we should search for previous declarations when
3029/// looking for declarations to merge.
3030DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3031 DeclContext *DC) {
3032 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3033 return ND->getOriginalNamespace();
3034
3035 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3036 // Try to dig out the definition.
3037 auto *DD = RD->DefinitionData;
3038 if (!DD)
3039 DD = RD->getCanonicalDecl()->DefinitionData;
3040
3041 // If there's no definition yet, then DC's definition is added by an update
3042 // record, but we've not yet loaded that update record. In this case, we
3043 // commit to DC being the canonical definition now, and will fix this when
3044 // we load the update record.
3045 if (!DD) {
3046 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3047 RD->setCompleteDefinition(true);
3048 RD->DefinitionData = DD;
3049 RD->getCanonicalDecl()->DefinitionData = DD;
3050
3051 // Track that we did this horrible thing so that we can fix it later.
3052 Reader.PendingFakeDefinitionData.insert(
3053 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3054 }
3055
3056 return DD->Definition;
3057 }
3058
3059 if (auto *RD = dyn_cast<RecordDecl>(DC))
3060 return RD->getDefinition();
3061
3062 if (auto *ED = dyn_cast<EnumDecl>(DC))
3063 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3064 : nullptr;
3065
3066 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(DC))
3067 return OID->getDefinition();
3068
3069 // We can see the TU here only if we have no Sema object. In that case,
3070 // there's no TU scope to look in, so using the DC alone is sufficient.
3071 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3072 return TU;
3073
3074 return nullptr;
3075}
3076
3077ASTDeclReader::FindExistingResult::~FindExistingResult() {
3078 // Record that we had a typedef name for linkage whether or not we merge
3079 // with that declaration.
3080 if (TypedefNameForLinkage) {
3081 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3082 Reader.ImportedTypedefNamesForLinkage.insert(
3083 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3084 return;
3085 }
3086
3087 if (!AddResult || Existing)
3088 return;
3089
3090 DeclarationName Name = New->getDeclName();
3091 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3092 if (needsAnonymousDeclarationNumber(New)) {
3093 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3094 AnonymousDeclNumber, New);
3095 } else if (DC->isTranslationUnit() &&
3096 !Reader.getContext().getLangOpts().CPlusPlus) {
3097 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3098 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3099 .push_back(New);
3100 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3101 // Add the declaration to its redeclaration context so later merging
3102 // lookups will find it.
3103 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3104 }
3105}
3106
3107/// Find the declaration that should be merged into, given the declaration found
3108/// by name lookup. If we're merging an anonymous declaration within a typedef,
3109/// we need a matching typedef, and we merge with the type inside it.
3110static NamedDecl *getDeclForMerging(NamedDecl *Found,
3111 bool IsTypedefNameForLinkage) {
3112 if (!IsTypedefNameForLinkage)
3113 return Found;
3114
3115 // If we found a typedef declaration that gives a name to some other
3116 // declaration, then we want that inner declaration. Declarations from
3117 // AST files are handled via ImportedTypedefNamesForLinkage.
3118 if (Found->isFromASTFile())
3119 return nullptr;
3120
3121 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3122 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3123
3124 return nullptr;
3125}
3126
3127/// Find the declaration to use to populate the anonymous declaration table
3128/// for the given lexical DeclContext. We only care about finding local
3129/// definitions of the context; we'll merge imported ones as we go.
3130DeclContext *
3131ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3132 // For classes, we track the definition as we merge.
3133 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3134 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3135 return DD ? DD->Definition : nullptr;
3136 } else if (auto *OID = dyn_cast<ObjCInterfaceDecl>(LexicalDC)) {
3137 return OID->getCanonicalDecl()->getDefinition();
3138 }
3139
3140 // For anything else, walk its merged redeclarations looking for a definition.
3141 // Note that we can't just call getDefinition here because the redeclaration
3142 // chain isn't wired up.
3143 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3144 if (auto *FD = dyn_cast<FunctionDecl>(D))
3145 if (FD->isThisDeclarationADefinition())
3146 return FD;
3147 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3148 if (MD->isThisDeclarationADefinition())
3149 return MD;
3150 if (auto *RD = dyn_cast<RecordDecl>(D))
3151 if (RD->isThisDeclarationADefinition())
3152 return RD;
3153 }
3154
3155 // No merged definition yet.
3156 return nullptr;
3157}
3158
3159NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3160 DeclContext *DC,
3161 unsigned Index) {
3162 // If the lexical context has been merged, look into the now-canonical
3163 // definition.
3164 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3165
3166 // If we've seen this before, return the canonical declaration.
3167 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3168 if (Index < Previous.size() && Previous[Index])
3169 return Previous[Index];
3170
3171 // If this is the first time, but we have parsed a declaration of the context,
3172 // build the anonymous declaration list from the parsed declaration.
3173 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3174 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3175 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3176 if (Previous.size() == Number)
3177 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3178 else
3179 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3180 });
3181 }
3182
3183 return Index < Previous.size() ? Previous[Index] : nullptr;
3184}
3185
3186void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3187 DeclContext *DC, unsigned Index,
3188 NamedDecl *D) {
3189 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3190
3191 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3192 if (Index >= Previous.size())
3193 Previous.resize(Index + 1);
3194 if (!Previous[Index])
3195 Previous[Index] = D;
3196}
3197
3198ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3199 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3200 : D->getDeclName();
3201
3202 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3203 // Don't bother trying to find unnamed declarations that are in
3204 // unmergeable contexts.
3205 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3206 AnonymousDeclNumber, TypedefNameForLinkage);
3207 Result.suppress();
3208 return Result;
3209 }
3210
3211 ASTContext &C = Reader.getContext();
3212 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3213 if (TypedefNameForLinkage) {
3214 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3215 std::make_pair(DC, TypedefNameForLinkage));
3216 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3217 if (C.isSameEntity(It->second, D))
3218 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3219 TypedefNameForLinkage);
3220 // Go on to check in other places in case an existing typedef name
3221 // was not imported.
3222 }
3223
3224 if (needsAnonymousDeclarationNumber(D)) {
3225 // This is an anonymous declaration that we may need to merge. Look it up
3226 // in its context by number.
3227 if (auto *Existing = getAnonymousDeclForMerging(
3228 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3229 if (C.isSameEntity(Existing, D))
3230 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3231 TypedefNameForLinkage);
3232 } else if (DC->isTranslationUnit() &&
3233 !Reader.getContext().getLangOpts().CPlusPlus) {
3234 IdentifierResolver &IdResolver = Reader.getIdResolver();
3235
3236 // Temporarily consider the identifier to be up-to-date. We don't want to
3237 // cause additional lookups here.
3238 class UpToDateIdentifierRAII {
3239 IdentifierInfo *II;
3240 bool WasOutToDate = false;
3241
3242 public:
3243 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3244 if (II) {
3245 WasOutToDate = II->isOutOfDate();
3246 if (WasOutToDate)
3247 II->setOutOfDate(false);
3248 }
3249 }
3250
3251 ~UpToDateIdentifierRAII() {
3252 if (WasOutToDate)
3253 II->setOutOfDate(true);
3254 }
3255 } UpToDate(Name.getAsIdentifierInfo());
3256
3257 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3258 IEnd = IdResolver.end();
3259 I != IEnd; ++I) {
3260 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3261 if (C.isSameEntity(Existing, D))
3262 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3263 TypedefNameForLinkage);
3264 }
3265 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3266 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3267 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3268 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3269 if (C.isSameEntity(Existing, D))
3270 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3271 TypedefNameForLinkage);
3272 }
3273 } else {
3274 // Not in a mergeable context.
3275 return FindExistingResult(Reader);
3276 }
3277
3278 // If this declaration is from a merged context, make a note that we need to
3279 // check that the canonical definition of that context contains the decl.
3280 //
3281 // FIXME: We should do something similar if we merge two definitions of the
3282 // same template specialization into the same CXXRecordDecl.
3283 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3284 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3285 MergedDCIt->second == D->getDeclContext())
3286 Reader.PendingOdrMergeChecks.push_back(D);
3287
3288 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3289 AnonymousDeclNumber, TypedefNameForLinkage);
3290}
3291
3292template<typename DeclT>
3293Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3294 return D->RedeclLink.getLatestNotUpdated();
3295}
3296
3297Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3298 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration")::llvm::llvm_unreachable_internal("getMostRecentDecl on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3298)
;
3299}
3300
3301Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3302 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3302, __extension__
__PRETTY_FUNCTION__))
;
3303
3304 switch (D->getKind()) {
3305#define ABSTRACT_DECL(TYPE)
3306#define DECL(TYPE, BASE) \
3307 case Decl::TYPE: \
3308 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3309#include "clang/AST/DeclNodes.inc"
3310 }
3311 llvm_unreachable("unknown decl kind")::llvm::llvm_unreachable_internal("unknown decl kind", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 3311)
;
3312}
3313
3314Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3315 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3316}
3317
3318void ASTDeclReader::mergeInheritableAttributes(ASTReader &Reader, Decl *D,
3319 Decl *Previous) {
3320 InheritableAttr *NewAttr = nullptr;
3321 ASTContext &Context = Reader.getContext();
3322 const auto *IA = Previous->getAttr<MSInheritanceAttr>();
3323
3324 if (IA && !D->hasAttr<MSInheritanceAttr>()) {
3325 NewAttr = cast<InheritableAttr>(IA->clone(Context));
3326 NewAttr->setInherited(true);
3327 D->addAttr(NewAttr);
3328 }
3329
3330 const auto *AA = Previous->getAttr<AvailabilityAttr>();
3331 if (AA && !D->hasAttr<AvailabilityAttr>()) {
3332 NewAttr = AA->clone(Context);
3333 NewAttr->setInherited(true);
3334 D->addAttr(NewAttr);
3335 }
3336}
3337
3338template<typename DeclT>
3339void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3340 Redeclarable<DeclT> *D,
3341 Decl *Previous, Decl *Canon) {
3342 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3343 D->First = cast<DeclT>(Previous)->First;
3344}
3345
3346namespace clang {
3347
3348template<>
3349void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3350 Redeclarable<VarDecl> *D,
3351 Decl *Previous, Decl *Canon) {
3352 auto *VD = static_cast<VarDecl *>(D);
3353 auto *PrevVD = cast<VarDecl>(Previous);
3354 D->RedeclLink.setPrevious(PrevVD);
3355 D->First = PrevVD->First;
3356
3357 // We should keep at most one definition on the chain.
3358 // FIXME: Cache the definition once we've found it. Building a chain with
3359 // N definitions currently takes O(N^2) time here.
3360 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3361 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3362 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3363 Reader.mergeDefinitionVisibility(CurD, VD);
3364 VD->demoteThisDefinitionToDeclaration();
3365 break;
3366 }
3367 }
3368 }
3369}
3370
3371static bool isUndeducedReturnType(QualType T) {
3372 auto *DT = T->getContainedDeducedType();
3373 return DT && !DT->isDeduced();
3374}
3375
3376template<>
3377void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3378 Redeclarable<FunctionDecl> *D,
3379 Decl *Previous, Decl *Canon) {
3380 auto *FD = static_cast<FunctionDecl *>(D);
3381 auto *PrevFD = cast<FunctionDecl>(Previous);
3382
3383 FD->RedeclLink.setPrevious(PrevFD);
3384 FD->First = PrevFD->First;
3385
3386 // If the previous declaration is an inline function declaration, then this
3387 // declaration is too.
3388 if (PrevFD->isInlined() != FD->isInlined()) {
3389 // FIXME: [dcl.fct.spec]p4:
3390 // If a function with external linkage is declared inline in one
3391 // translation unit, it shall be declared inline in all translation
3392 // units in which it appears.
3393 //
3394 // Be careful of this case:
3395 //
3396 // module A:
3397 // template<typename T> struct X { void f(); };
3398 // template<typename T> inline void X<T>::f() {}
3399 //
3400 // module B instantiates the declaration of X<int>::f
3401 // module C instantiates the definition of X<int>::f
3402 //
3403 // If module B and C are merged, we do not have a violation of this rule.
3404 FD->setImplicitlyInline(true);
3405 }
3406
3407 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3408 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3409 if (FPT && PrevFPT) {
3410 // If we need to propagate an exception specification along the redecl
3411 // chain, make a note of that so that we can do so later.
3412 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3413 bool WasUnresolved =
3414 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3415 if (IsUnresolved != WasUnresolved)
3416 Reader.PendingExceptionSpecUpdates.insert(
3417 {Canon, IsUnresolved ? PrevFD : FD});
3418
3419 // If we need to propagate a deduced return type along the redecl chain,
3420 // make a note of that so that we can do it later.
3421 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3422 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3423 if (IsUndeduced != WasUndeduced)
3424 Reader.PendingDeducedTypeUpdates.insert(
3425 {cast<FunctionDecl>(Canon),
3426 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3427 }
3428}
3429
3430} // namespace clang
3431
3432void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3433 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration")::llvm::llvm_unreachable_internal("attachPreviousDecl on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3433)
;
3434}
3435
3436/// Inherit the default template argument from \p From to \p To. Returns
3437/// \c false if there is no default template for \p From.
3438template <typename ParmDecl>
3439static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3440 Decl *ToD) {
3441 auto *To = cast<ParmDecl>(ToD);
3442 if (!From->hasDefaultArgument())
3443 return false;
3444 To->setInheritedDefaultArgument(Context, From);
3445 return true;
3446}
3447
3448static void inheritDefaultTemplateArguments(ASTContext &Context,
3449 TemplateDecl *From,
3450 TemplateDecl *To) {
3451 auto *FromTP = From->getTemplateParameters();
3452 auto *ToTP = To->getTemplateParameters();
3453 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?")(static_cast <bool> (FromTP->size() == ToTP->size
() && "merged mismatched templates?") ? void (0) : __assert_fail
("FromTP->size() == ToTP->size() && \"merged mismatched templates?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3453, __extension__
__PRETTY_FUNCTION__))
;
3454
3455 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3456 NamedDecl *FromParam = FromTP->getParam(I);
3457 NamedDecl *ToParam = ToTP->getParam(I);
3458
3459 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3460 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3461 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3462 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3463 else
3464 inheritDefaultTemplateArgument(
3465 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3466 }
3467}
3468
3469void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3470 Decl *Previous, Decl *Canon) {
3471 assert(D && Previous)(static_cast <bool> (D && Previous) ? void (0) :
__assert_fail ("D && Previous", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
;
3472
3473 switch (D->getKind()) {
3474#define ABSTRACT_DECL(TYPE)
3475#define DECL(TYPE, BASE) \
3476 case Decl::TYPE: \
3477 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3478 break;
3479#include "clang/AST/DeclNodes.inc"
3480 }
3481
3482 // If the declaration was visible in one module, a redeclaration of it in
3483 // another module remains visible even if it wouldn't be visible by itself.
3484 //
3485 // FIXME: In this case, the declaration should only be visible if a module
3486 // that makes it visible has been imported.
3487 D->IdentifierNamespace |=
3488 Previous->IdentifierNamespace &
3489 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3490
3491 // If the declaration declares a template, it may inherit default arguments
3492 // from the previous declaration.
3493 if (auto *TD = dyn_cast<TemplateDecl>(D))
3494 inheritDefaultTemplateArguments(Reader.getContext(),
3495 cast<TemplateDecl>(Previous), TD);
3496
3497 // If any of the declaration in the chain contains an Inheritable attribute,
3498 // it needs to be added to all the declarations in the redeclarable chain.
3499 // FIXME: Only the logic of merging MSInheritableAttr is present, it should
3500 // be extended for all inheritable attributes.
3501 mergeInheritableAttributes(Reader, D, Previous);
3502}
3503
3504template<typename DeclT>
3505void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3506 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3507}
3508
3509void ASTDeclReader::attachLatestDeclImpl(...) {
3510 llvm_unreachable("attachLatestDecl on non-redeclarable declaration")::llvm::llvm_unreachable_internal("attachLatestDecl on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3510)
;
3511}
3512
3513void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3514 assert(D && Latest)(static_cast <bool> (D && Latest) ? void (0) : __assert_fail
("D && Latest", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 3514, __extension__ __PRETTY_FUNCTION__))
;
3515
3516 switch (D->getKind()) {
3517#define ABSTRACT_DECL(TYPE)
3518#define DECL(TYPE, BASE) \
3519 case Decl::TYPE: \
3520 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3521 break;
3522#include "clang/AST/DeclNodes.inc"
3523 }
3524}
3525
3526template<typename DeclT>
3527void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3528 D->RedeclLink.markIncomplete();
3529}
3530
3531void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3532 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration")::llvm::llvm_unreachable_internal("markIncompleteDeclChain on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3532)
;
3533}
3534
3535void ASTReader::markIncompleteDeclChain(Decl *D) {
3536 switch (D->getKind()) {
3537#define ABSTRACT_DECL(TYPE)
3538#define DECL(TYPE, BASE) \
3539 case Decl::TYPE: \
3540 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3541 break;
3542#include "clang/AST/DeclNodes.inc"
3543 }
3544}
3545
3546/// Read the declaration at the given offset from the AST file.
3547Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3548 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3549 SourceLocation DeclLoc;
3550 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3551 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3552 // Keep track of where we are in the stream, then jump back there
3553 // after reading this declaration.
3554 SavedStreamPosition SavedPosition(DeclsCursor);
3555
3556 ReadingKindTracker ReadingKind(Read_Decl, *this);
3557
3558 // Note that we are loading a declaration record.
3559 Deserializing ADecl(this);
3560
3561 auto Fail = [](const char *what, llvm::Error &&Err) {
3562 llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3563 ": " + toString(std::move(Err)));
3564 };
3565
3566 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3567 Fail("jumping", std::move(JumpFailed));
3568 ASTRecordReader Record(*this, *Loc.F);
3569 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3570 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3571 if (!MaybeCode)
3572 Fail("reading code", MaybeCode.takeError());
3573 unsigned Code = MaybeCode.get();
3574
3575 ASTContext &Context = getContext();
3576 Decl *D = nullptr;
3577 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3578 if (!MaybeDeclCode)
3579 llvm::report_fatal_error(
3580 Twine("ASTReader::readDeclRecord failed reading decl code: ") +
3581 toString(MaybeDeclCode.takeError()));
3582 switch ((DeclCode)MaybeDeclCode.get()) {
3583 case DECL_CONTEXT_LEXICAL:
3584 case DECL_CONTEXT_VISIBLE:
3585 llvm_unreachable("Record cannot be de-serialized with readDeclRecord")::llvm::llvm_unreachable_internal("Record cannot be de-serialized with readDeclRecord"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3585)
;
3586 case DECL_TYPEDEF:
3587 D = TypedefDecl::CreateDeserialized(Context, ID);
3588 break;
3589 case DECL_TYPEALIAS:
3590 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3591 break;
3592 case DECL_ENUM:
3593 D = EnumDecl::CreateDeserialized(Context, ID);
3594 break;
3595 case DECL_RECORD:
3596 D = RecordDecl::CreateDeserialized(Context, ID);
3597 break;
3598 case DECL_ENUM_CONSTANT:
3599 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3600 break;
3601 case DECL_FUNCTION:
3602 D = FunctionDecl::CreateDeserialized(Context, ID);
3603 break;
3604 case DECL_LINKAGE_SPEC:
3605 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3606 break;
3607 case DECL_EXPORT:
3608 D = ExportDecl::CreateDeserialized(Context, ID);
3609 break;
3610 case DECL_LABEL:
3611 D = LabelDecl::CreateDeserialized(Context, ID);
3612 break;
3613 case DECL_NAMESPACE:
3614 D = NamespaceDecl::CreateDeserialized(Context, ID);
3615 break;
3616 case DECL_NAMESPACE_ALIAS:
3617 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3618 break;
3619 case DECL_USING:
3620 D = UsingDecl::CreateDeserialized(Context, ID);
3621 break;
3622 case DECL_USING_PACK:
3623 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3624 break;
3625 case DECL_USING_SHADOW:
3626 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3627 break;
3628 case DECL_USING_ENUM:
3629 D = UsingEnumDecl::CreateDeserialized(Context, ID);
3630 break;
3631 case DECL_CONSTRUCTOR_USING_SHADOW:
3632 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3633 break;
3634 case DECL_USING_DIRECTIVE:
3635 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3636 break;
3637 case DECL_UNRESOLVED_USING_VALUE:
3638 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3639 break;
3640 case DECL_UNRESOLVED_USING_TYPENAME:
3641 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3642 break;
3643 case DECL_UNRESOLVED_USING_IF_EXISTS:
3644 D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Context, ID);
3645 break;
3646 case DECL_CXX_RECORD:
3647 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3648 break;
3649 case DECL_CXX_DEDUCTION_GUIDE:
3650 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3651 break;
3652 case DECL_CXX_METHOD:
3653 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3654 break;
3655 case DECL_CXX_CONSTRUCTOR:
3656 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3657 break;
3658 case DECL_CXX_DESTRUCTOR:
3659 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3660 break;
3661 case DECL_CXX_CONVERSION:
3662 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3663 break;
3664 case DECL_ACCESS_SPEC:
3665 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3666 break;
3667 case DECL_FRIEND:
3668 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3669 break;
3670 case DECL_FRIEND_TEMPLATE:
3671 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3672 break;
3673 case DECL_CLASS_TEMPLATE:
3674 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3675 break;
3676 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3677 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3678 break;
3679 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3680 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3681 break;
3682 case DECL_VAR_TEMPLATE:
3683 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3684 break;
3685 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3686 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3687 break;
3688 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3689 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3690 break;
3691 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3692 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3693 break;
3694 case DECL_FUNCTION_TEMPLATE:
3695 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3696 break;
3697 case DECL_TEMPLATE_TYPE_PARM: {
3698 bool HasTypeConstraint = Record.readInt();
3699 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3700 HasTypeConstraint);
3701 break;
3702 }
3703 case DECL_NON_TYPE_TEMPLATE_PARM: {
3704 bool HasTypeConstraint = Record.readInt();
3705 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3706 HasTypeConstraint);
3707 break;
3708 }
3709 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3710 bool HasTypeConstraint = Record.readInt();
3711 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3712 Record.readInt(),
3713 HasTypeConstraint);
3714 break;
3715 }
3716 case DECL_TEMPLATE_TEMPLATE_PARM:
3717 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3718 break;
3719 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3720 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3721 Record.readInt());
3722 break;
3723 case DECL_TYPE_ALIAS_TEMPLATE:
3724 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3725 break;
3726 case DECL_CONCEPT:
3727 D = ConceptDecl::CreateDeserialized(Context, ID);
3728 break;
3729 case DECL_REQUIRES_EXPR_BODY:
3730 D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
3731 break;
3732 case DECL_STATIC_ASSERT:
3733 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3734 break;
3735 case DECL_OBJC_METHOD:
3736 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3737 break;
3738 case DECL_OBJC_INTERFACE:
3739 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3740 break;
3741 case DECL_OBJC_IVAR:
3742 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3743 break;
3744 case DECL_OBJC_PROTOCOL:
3745 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3746 break;
3747 case DECL_OBJC_AT_DEFS_FIELD:
3748 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3749 break;
3750 case DECL_OBJC_CATEGORY:
3751 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3752 break;
3753 case DECL_OBJC_CATEGORY_IMPL:
3754 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3755 break;
3756 case DECL_OBJC_IMPLEMENTATION:
3757 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3758 break;
3759 case DECL_OBJC_COMPATIBLE_ALIAS:
3760 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3761 break;
3762 case DECL_OBJC_PROPERTY:
3763 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3764 break;
3765 case DECL_OBJC_PROPERTY_IMPL:
3766 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3767 break;
3768 case DECL_FIELD:
3769 D = FieldDecl::CreateDeserialized(Context, ID);
3770 break;
3771 case DECL_INDIRECTFIELD:
3772 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3773 break;
3774 case DECL_VAR:
3775 D = VarDecl::CreateDeserialized(Context, ID);
3776 break;
3777 case DECL_IMPLICIT_PARAM:
3778 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3779 break;
3780 case DECL_PARM_VAR:
3781 D = ParmVarDecl::CreateDeserialized(Context, ID);
3782 break;
3783 case DECL_DECOMPOSITION:
3784 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3785 break;
3786 case DECL_BINDING:
3787 D = BindingDecl::CreateDeserialized(Context, ID);
3788 break;
3789 case DECL_FILE_SCOPE_ASM:
3790 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3791 break;
3792 case DECL_BLOCK:
3793 D = BlockDecl::CreateDeserialized(Context, ID);
3794 break;
3795 case DECL_MS_PROPERTY:
3796 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3797 break;
3798 case DECL_MS_GUID:
3799 D = MSGuidDecl::CreateDeserialized(Context, ID);
3800 break;
3801 case DECL_UNNAMED_GLOBAL_CONSTANT:
3802 D = UnnamedGlobalConstantDecl::CreateDeserialized(Context, ID);
3803 break;
3804 case DECL_TEMPLATE_PARAM_OBJECT:
3805 D = TemplateParamObjectDecl::CreateDeserialized(Context, ID);
3806 break;
3807 case DECL_CAPTURED:
3808 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3809 break;
3810 case DECL_CXX_BASE_SPECIFIERS:
3811 Error("attempt to read a C++ base-specifier record as a declaration");
3812 return nullptr;
3813 case DECL_CXX_CTOR_INITIALIZERS:
3814 Error("attempt to read a C++ ctor initializer record as a declaration");
3815 return nullptr;
3816 case DECL_IMPORT:
3817 // Note: last entry of the ImportDecl record is the number of stored source
3818 // locations.
3819 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3820 break;
3821 case DECL_OMP_THREADPRIVATE: {
3822 Record.skipInts(1);
3823 unsigned NumChildren = Record.readInt();
3824 Record.skipInts(1);
3825 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, NumChildren);
3826 break;
3827 }
3828 case DECL_OMP_ALLOCATE: {
3829 unsigned NumClauses = Record.readInt();
3830 unsigned NumVars = Record.readInt();
3831 Record.skipInts(1);
3832 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
3833 break;
3834 }
3835 case DECL_OMP_REQUIRES: {
3836 unsigned NumClauses = Record.readInt();
3837 Record.skipInts(2);
3838 D = OMPRequiresDecl::CreateDeserialized(Context, ID, NumClauses);
3839 break;
3840 }
3841 case DECL_OMP_DECLARE_REDUCTION:
3842 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3843 break;
3844 case DECL_OMP_DECLARE_MAPPER: {
3845 unsigned NumClauses = Record.readInt();
3846 Record.skipInts(2);
3847 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, NumClauses);
3848 break;
3849 }
3850 case DECL_OMP_CAPTUREDEXPR:
3851 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3852 break;
3853 case DECL_PRAGMA_COMMENT:
3854 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3855 break;
3856 case DECL_PRAGMA_DETECT_MISMATCH:
3857 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3858 Record.readInt());
3859 break;
3860 case DECL_EMPTY:
3861 D = EmptyDecl::CreateDeserialized(Context, ID);
3862 break;
3863 case DECL_LIFETIME_EXTENDED_TEMPORARY:
3864 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
3865 break;
3866 case DECL_OBJC_TYPE_PARAM:
3867 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3868 break;
3869 case DECL_HLSL_BUFFER:
3870 D = HLSLBufferDecl::CreateDeserialized(Context, ID);
3871 break;
3872 }
3873
3874 assert(D && "Unknown declaration reading AST file")(static_cast <bool> (D && "Unknown declaration reading AST file"
) ? void (0) : __assert_fail ("D && \"Unknown declaration reading AST file\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3874, __extension__
__PRETTY_FUNCTION__))
;
3875 LoadedDecl(Index, D);
3876 // Set the DeclContext before doing any deserialization, to make sure internal
3877 // calls to Decl::getASTContext() by Decl's methods will find the
3878 // TranslationUnitDecl without crashing.
3879 D->setDeclContext(Context.getTranslationUnitDecl());
3880 Reader.Visit(D);
3881
3882 // If this declaration is also a declaration context, get the
3883 // offsets for its tables of lexical and visible declarations.
3884 if (auto *DC = dyn_cast<DeclContext>(D)) {
3885 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3886 if (Offsets.first &&
3887 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3888 return nullptr;
3889 if (Offsets.second &&
3890 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3891 return nullptr;
3892 }
3893 assert(Record.getIdx() == Record.size())(static_cast <bool> (Record.getIdx() == Record.size()) ?
void (0) : __assert_fail ("Record.getIdx() == Record.size()"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3893, __extension__
__PRETTY_FUNCTION__))
;
3894
3895 // Load any relevant update records.
3896 PendingUpdateRecords.push_back(
3897 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3898
3899 // Load the categories after recursive loading is finished.
3900 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
3901 // If we already have a definition when deserializing the ObjCInterfaceDecl,
3902 // we put the Decl in PendingDefinitions so we can pull the categories here.
3903 if (Class->isThisDeclarationADefinition() ||
3904 PendingDefinitions.count(Class))
3905 loadObjCCategories(ID, Class);
3906
3907 // If we have deserialized a declaration that has a definition the
3908 // AST consumer might need to know about, queue it.
3909 // We don't pass it to the consumer immediately because we may be in recursive
3910 // loading, and some declarations may still be initializing.
3911 PotentiallyInterestingDecls.push_back(
3912 InterestingDecl(D, Reader.hasPendingBody()));
3913
3914 return D;
3915}
3916
3917void ASTReader::PassInterestingDeclsToConsumer() {
3918 assert(Consumer)(static_cast <bool> (Consumer) ? void (0) : __assert_fail
("Consumer", "clang/lib/Serialization/ASTReaderDecl.cpp", 3918
, __extension__ __PRETTY_FUNCTION__))
;
3919
3920 if (PassingDeclsToConsumer)
3921 return;
3922
3923 // Guard variable to avoid recursively redoing the process of passing
3924 // decls to consumer.
3925 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
3926 true);
3927
3928 // Ensure that we've loaded all potentially-interesting declarations
3929 // that need to be eagerly loaded.
3930 for (auto ID : EagerlyDeserializedDecls)
3931 GetDecl(ID);
3932 EagerlyDeserializedDecls.clear();
3933
3934 while (!PotentiallyInterestingDecls.empty()) {
3935 InterestingDecl D = PotentiallyInterestingDecls.front();
3936 PotentiallyInterestingDecls.pop_front();
3937 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
3938 PassInterestingDeclToConsumer(D.getDecl());
3939 }
3940}
3941
3942void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
3943 // The declaration may have been modified by files later in the chain.
3944 // If this is the case, read the record containing the updates from each file
3945 // and pass it to ASTDeclReader to make the modifications.
3946 serialization::GlobalDeclID ID = Record.ID;
3947 Decl *D = Record.D;
3948 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3949 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3950
3951 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
3952
3953 if (UpdI != DeclUpdateOffsets.end()) {
3954 auto UpdateOffsets = std::move(UpdI->second);
3955 DeclUpdateOffsets.erase(UpdI);
3956
3957 // Check if this decl was interesting to the consumer. If we just loaded
3958 // the declaration, then we know it was interesting and we skip the call
3959 // to isConsumerInterestedIn because it is unsafe to call in the
3960 // current ASTReader state.
3961 bool WasInteresting =
3962 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
3963 for (auto &FileAndOffset : UpdateOffsets) {
3964 ModuleFile *F = FileAndOffset.first;
3965 uint64_t Offset = FileAndOffset.second;
3966 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3967 SavedStreamPosition SavedPosition(Cursor);
3968 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
3969 // FIXME don't do a fatal error.
3970 llvm::report_fatal_error(
3971 Twine("ASTReader::loadDeclUpdateRecords failed jumping: ") +
3972 toString(std::move(JumpFailed)));
3973 Expected<unsigned> MaybeCode = Cursor.ReadCode();
3974 if (!MaybeCode)
3975 llvm::report_fatal_error(
3976 Twine("ASTReader::loadDeclUpdateRecords failed reading code: ") +
3977 toString(MaybeCode.takeError()));
3978 unsigned Code = MaybeCode.get();
3979 ASTRecordReader Record(*this, *F);
3980 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
3981 assert(MaybeRecCode.get() == DECL_UPDATES &&(static_cast <bool> (MaybeRecCode.get() == DECL_UPDATES
&& "Expected DECL_UPDATES record!") ? void (0) : __assert_fail
("MaybeRecCode.get() == DECL_UPDATES && \"Expected DECL_UPDATES record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3982, __extension__
__PRETTY_FUNCTION__))
3982 "Expected DECL_UPDATES record!")(static_cast <bool> (MaybeRecCode.get() == DECL_UPDATES
&& "Expected DECL_UPDATES record!") ? void (0) : __assert_fail
("MaybeRecCode.get() == DECL_UPDATES && \"Expected DECL_UPDATES record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3982, __extension__
__PRETTY_FUNCTION__))
;
3983 else
3984 llvm::report_fatal_error(
3985 Twine("ASTReader::loadDeclUpdateRecords failed reading rec code: ") +
3986 toString(MaybeCode.takeError()));
3987
3988 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3989 SourceLocation());
3990 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
3991
3992 // We might have made this declaration interesting. If so, remember that
3993 // we need to hand it off to the consumer.
3994 if (!WasInteresting &&
3995 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
3996 PotentiallyInterestingDecls.push_back(
3997 InterestingDecl(D, Reader.hasPendingBody()));
3998 WasInteresting = true;
3999 }
4000 }
4001 }
4002 // Add the lazy specializations to the template.
4003 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||(static_cast <bool> ((PendingLazySpecializationIDs.empty
() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl
>(D) || isa<VarTemplateDecl>(D)) && "Must not have pending specializations"
) ? void (0) : __assert_fail ("(PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && \"Must not have pending specializations\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4005, __extension__
__PRETTY_FUNCTION__))
4004 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&(static_cast <bool> ((PendingLazySpecializationIDs.empty
() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl
>(D) || isa<VarTemplateDecl>(D)) && "Must not have pending specializations"
) ? void (0) : __assert_fail ("(PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && \"Must not have pending specializations\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4005, __extension__
__PRETTY_FUNCTION__))
4005 "Must not have pending specializations")(static_cast <bool> ((PendingLazySpecializationIDs.empty
() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl
>(D) || isa<VarTemplateDecl>(D)) && "Must not have pending specializations"
) ? void (0) : __assert_fail ("(PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && \"Must not have pending specializations\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4005, __extension__
__PRETTY_FUNCTION__))
;
4006 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4007 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4008 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4009 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4010 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4011 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4012 PendingLazySpecializationIDs.clear();
4013
4014 // Load the pending visible updates for this decl context, if it has any.
4015 auto I = PendingVisibleUpdates.find(ID);
4016 if (I != PendingVisibleUpdates.end()) {
4017 auto VisibleUpdates = std::move(I->second);
4018 PendingVisibleUpdates.erase(I);
4019
4020 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4021 for (const auto &Update : VisibleUpdates)
4022 Lookups[DC].Table.add(
4023 Update.Mod, Update.Data,
4024 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4025 DC->setHasExternalVisibleStorage(true);
4026 }
4027}
4028
4029void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4030 // Attach FirstLocal to the end of the decl chain.
4031 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4032 if (FirstLocal != CanonDecl) {
4033 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4034 ASTDeclReader::attachPreviousDecl(
4035 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4036 CanonDecl);
4037 }
4038
4039 if (!LocalOffset) {
4040 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4041 return;
4042 }
4043
4044 // Load the list of other redeclarations from this module file.
4045 ModuleFile *M = getOwningModuleFile(FirstLocal);
4046 assert(M && "imported decl from no module file")(static_cast <bool> (M && "imported decl from no module file"
) ? void (0) : __assert_fail ("M && \"imported decl from no module file\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4046, __extension__
__PRETTY_FUNCTION__))
;
4047
4048 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4049 SavedStreamPosition SavedPosition(Cursor);
4050 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4051 llvm::report_fatal_error(
4052 Twine("ASTReader::loadPendingDeclChain failed jumping: ") +
4053 toString(std::move(JumpFailed)));
4054
4055 RecordData Record;
4056 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4057 if (!MaybeCode)
4058 llvm::report_fatal_error(
4059 Twine("ASTReader::loadPendingDeclChain failed reading code: ") +
4060 toString(MaybeCode.takeError()));
4061 unsigned Code = MaybeCode.get();
4062 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4063 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&(static_cast <bool> (MaybeRecCode.get() == LOCAL_REDECLARATIONS
&& "expected LOCAL_REDECLARATIONS record!") ? void (
0) : __assert_fail ("MaybeRecCode.get() == LOCAL_REDECLARATIONS && \"expected LOCAL_REDECLARATIONS record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4064, __extension__
__PRETTY_FUNCTION__))
4064 "expected LOCAL_REDECLARATIONS record!")(static_cast <bool> (MaybeRecCode.get() == LOCAL_REDECLARATIONS
&& "expected LOCAL_REDECLARATIONS record!") ? void (
0) : __assert_fail ("MaybeRecCode.get() == LOCAL_REDECLARATIONS && \"expected LOCAL_REDECLARATIONS record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4064, __extension__
__PRETTY_FUNCTION__))
;
4065 else
4066 llvm::report_fatal_error(
4067 Twine("ASTReader::loadPendingDeclChain failed reading rec code: ") +
4068 toString(MaybeCode.takeError()));
4069
4070 // FIXME: We have several different dispatches on decl kind here; maybe
4071 // we should instead generate one loop per kind and dispatch up-front?
4072 Decl *MostRecent = FirstLocal;
4073 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4074 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4075 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4076 MostRecent = D;
4077 }
4078 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4079}
4080
4081namespace {
4082
4083 /// Given an ObjC interface, goes through the modules and links to the
4084 /// interface all the categories for it.
4085 class ObjCCategoriesVisitor {
4086 ASTReader &Reader;
4087 ObjCInterfaceDecl *Interface;
4088 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4089 ObjCCategoryDecl *Tail = nullptr;
4090 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4091 serialization::GlobalDeclID InterfaceID;
4092 unsigned PreviousGeneration;
4093
4094 void add(ObjCCategoryDecl *Cat) {
4095 // Only process each category once.
4096 if (!Deserialized.erase(Cat))
4097 return;
4098
4099 // Check for duplicate categories.
4100 if (Cat->getDeclName()) {
4101 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4102 if (Existing &&
4103 Reader.getOwningModuleFile(Existing)
4104 != Reader.getOwningModuleFile(Cat)) {
4105 // FIXME: We should not warn for duplicates in diamond:
4106 //
4107 // MT //
4108 // / \ //
4109 // ML MR //
4110 // \ / //
4111 // MB //
4112 //
4113 // If there are duplicates in ML/MR, there will be warning when
4114 // creating MB *and* when importing MB. We should not warn when
4115 // importing.
4116 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4117 << Interface->getDeclName() << Cat->getDeclName();
4118 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4119 } else if (!Existing) {
4120 // Record this category.
4121 Existing = Cat;
4122 }
4123 }
4124
4125 // Add this category to the end of the chain.
4126 if (Tail)
4127 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4128 else
4129 Interface->setCategoryListRaw(Cat);
4130 Tail = Cat;
4131 }
4132
4133 public:
4134 ObjCCategoriesVisitor(ASTReader &Reader,
4135 ObjCInterfaceDecl *Interface,
4136 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4137 serialization::GlobalDeclID InterfaceID,
4138 unsigned PreviousGeneration)
4139 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4140 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4141 // Populate the name -> category map with the set of known categories.
4142 for (auto *Cat : Interface->known_categories()) {
4143 if (Cat->getDeclName())
4144 NameCategoryMap[Cat->getDeclName()] = Cat;
4145
4146 // Keep track of the tail of the category list.
4147 Tail = Cat;
4148 }
4149 }
4150
4151 bool operator()(ModuleFile &M) {
4152 // If we've loaded all of the category information we care about from
4153 // this module file, we're done.
4154 if (M.Generation <= PreviousGeneration)
4155 return true;
4156
4157 // Map global ID of the definition down to the local ID used in this
4158 // module file. If there is no such mapping, we'll find nothing here
4159 // (or in any module it imports).
4160 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4161 if (!LocalID)
4162 return true;
4163
4164 // Perform a binary search to find the local redeclarations for this
4165 // declaration (if any).
4166 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4167 const ObjCCategoriesInfo *Result
4168 = std::lower_bound(M.ObjCCategoriesMap,
4169 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4170 Compare);
4171 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4172 Result->DefinitionID != LocalID) {
4173 // We didn't find anything. If the class definition is in this module
4174 // file, then the module files it depends on cannot have any categories,
4175 // so suppress further lookup.
4176 return Reader.isDeclIDFromModule(InterfaceID, M);
4177 }
4178
4179 // We found something. Dig out all of the categories.
4180 unsigned Offset = Result->Offset;
4181 unsigned N = M.ObjCCategories[Offset];
4182 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4183 for (unsigned I = 0; I != N; ++I)
4184 add(cast_or_null<ObjCCategoryDecl>(
4185 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4186 return true;
4187 }
4188 };
4189
4190} // namespace
4191
4192void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4193 ObjCInterfaceDecl *D,
4194 unsigned PreviousGeneration) {
4195 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4196 PreviousGeneration);
4197 ModuleMgr.visit(Visitor);
4198}
4199
4200template<typename DeclT, typename Fn>
4201static void forAllLaterRedecls(DeclT *D, Fn F) {
4202 F(D);
4203
4204 // Check whether we've already merged D into its redeclaration chain.
4205 // MostRecent may or may not be nullptr if D has not been merged. If
4206 // not, walk the merged redecl chain and see if it's there.
4207 auto *MostRecent = D->getMostRecentDecl();
4208 bool Found = false;
4209 for (auto *Redecl = MostRecent; Redecl && !Found;
4210 Redecl = Redecl->getPreviousDecl())
4211 Found = (Redecl == D);
4212
4213 // If this declaration is merged, apply the functor to all later decls.
4214 if (Found) {
4215 for (auto *Redecl = MostRecent; Redecl != D;
4216 Redecl = Redecl->getPreviousDecl())
4217 F(Redecl);
4218 }
4219}
4220
4221void ASTDeclReader::UpdateDecl(Decl *D,
4222 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4223 while (Record.getIdx() < Record.size()) {
4224 switch ((DeclUpdateKind)Record.readInt()) {
4225 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4226 auto *RD = cast<CXXRecordDecl>(D);
4227 // FIXME: If we also have an update record for instantiating the
4228 // definition of D, we need that to happen before we get here.
4229 Decl *MD = Record.readDecl();
4230 assert(MD && "couldn't read decl from update record")(static_cast <bool> (MD && "couldn't read decl from update record"
) ? void (0) : __assert_fail ("MD && \"couldn't read decl from update record\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4230, __extension__
__PRETTY_FUNCTION__))
;
4231 // FIXME: We should call addHiddenDecl instead, to add the member
4232 // to its DeclContext.
4233 RD->addedMember(MD);
4234 break;
4235 }
4236
4237 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4238 // It will be added to the template's lazy specialization set.
4239 PendingLazySpecializationIDs.push_back(readDeclID());
4240 break;
4241
4242 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4243 auto *Anon = readDeclAs<NamespaceDecl>();
4244
4245 // Each module has its own anonymous namespace, which is disjoint from
4246 // any other module's anonymous namespaces, so don't attach the anonymous
4247 // namespace at all.
4248 if (!Record.isModule()) {
4249 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4250 TU->setAnonymousNamespace(Anon);
4251 else
4252 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4253 }
4254 break;
4255 }
4256
4257 case UPD_CXX_ADDED_VAR_DEFINITION: {
4258 auto *VD = cast<VarDecl>(D);
4259 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4260 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4261 uint64_t Val = Record.readInt();
4262 if (Val && !VD->getInit()) {
4263 VD->setInit(Record.readExpr());
4264 if (Val != 1) {
4265 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4266 Eval->HasConstantInitialization = (Val & 2) != 0;
4267 Eval->HasConstantDestruction = (Val & 4) != 0;
4268 }
4269 }
4270 break;
4271 }
4272
4273 case UPD_CXX_POINT_OF_INSTANTIATION: {
4274 SourceLocation POI = Record.readSourceLocation();
4275 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4276 VTSD->setPointOfInstantiation(POI);
4277 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4278 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4279 } else {
4280 auto *FD = cast<FunctionDecl>(D);
4281 if (auto *FTSInfo = FD->TemplateOrSpecialization
4282 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4283 FTSInfo->setPointOfInstantiation(POI);
4284 else
4285 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4286 ->setPointOfInstantiation(POI);
4287 }
4288 break;
4289 }
4290
4291 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4292 auto *Param = cast<ParmVarDecl>(D);
4293
4294 // We have to read the default argument regardless of whether we use it
4295 // so that hypothetical further update records aren't messed up.
4296 // TODO: Add a function to skip over the next expr record.
4297 auto *DefaultArg = Record.readExpr();
4298
4299 // Only apply the update if the parameter still has an uninstantiated
4300 // default argument.
4301 if (Param->hasUninstantiatedDefaultArg())
4302 Param->setDefaultArg(DefaultArg);
4303 break;
4304 }
4305
4306 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4307 auto *FD = cast<FieldDecl>(D);
4308 auto *DefaultInit = Record.readExpr();
4309
4310 // Only apply the update if the field still has an uninstantiated
4311 // default member initializer.
4312 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4313 if (DefaultInit)
4314 FD->setInClassInitializer(DefaultInit);
4315 else
4316 // Instantiation failed. We can get here if we serialized an AST for
4317 // an invalid program.
4318 FD->removeInClassInitializer();
4319 }
4320 break;
4321 }
4322
4323 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4324 auto *FD = cast<FunctionDecl>(D);
4325 if (Reader.PendingBodies[FD]) {
4326 // FIXME: Maybe check for ODR violations.
4327 // It's safe to stop now because this update record is always last.
4328 return;
4329 }
4330
4331 if (Record.readInt()) {
4332 // Maintain AST consistency: any later redeclarations of this function
4333 // are inline if this one is. (We might have merged another declaration
4334 // into this one.)
4335 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4336 FD->setImplicitlyInline();
4337 });
4338 }
4339 FD->setInnerLocStart(readSourceLocation());
4340 ReadFunctionDefinition(FD);
4341 assert(Record.getIdx() == Record.size() && "lazy body must be last")(static_cast <bool> (Record.getIdx() == Record.size() &&
"lazy body must be last") ? void (0) : __assert_fail ("Record.getIdx() == Record.size() && \"lazy body must be last\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4341, __extension__
__PRETTY_FUNCTION__))
;
4342 break;
4343 }
4344
4345 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4346 auto *RD = cast<CXXRecordDecl>(D);
4347 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4348 bool HadRealDefinition =
4349 OldDD && (OldDD->Definition != RD ||
4350 !Reader.PendingFakeDefinitionData.count(OldDD));
4351 RD->setParamDestroyedInCallee(Record.readInt());
4352 RD->setArgPassingRestrictions(
4353 (RecordDecl::ArgPassingKind)Record.readInt());
4354 ReadCXXRecordDefinition(RD, /*Update*/true);
4355
4356 // Visible update is handled separately.
4357 uint64_t LexicalOffset = ReadLocalOffset();
4358 if (!HadRealDefinition && LexicalOffset) {
4359 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4360 Reader.PendingFakeDefinitionData.erase(OldDD);
4361 }
4362
4363 auto TSK = (TemplateSpecializationKind)Record.readInt();
4364 SourceLocation POI = readSourceLocation();
4365 if (MemberSpecializationInfo *MSInfo =
4366 RD->getMemberSpecializationInfo()) {
4367 MSInfo->setTemplateSpecializationKind(TSK);
4368 MSInfo->setPointOfInstantiation(POI);
4369 } else {
4370 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4371 Spec->setTemplateSpecializationKind(TSK);
4372 Spec->setPointOfInstantiation(POI);
4373
4374 if (Record.readInt()) {
4375 auto *PartialSpec =
4376 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4377 SmallVector<TemplateArgument, 8> TemplArgs;
4378 Record.readTemplateArgumentList(TemplArgs);
4379 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4380 Reader.getContext(), TemplArgs);
4381
4382 // FIXME: If we already have a partial specialization set,
4383 // check that it matches.
4384 if (!Spec->getSpecializedTemplateOrPartial()
4385 .is<ClassTemplatePartialSpecializationDecl *>())
4386 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4387 }
4388 }
4389
4390 RD->setTagKind((TagTypeKind)Record.readInt());
4391 RD->setLocation(readSourceLocation());
4392 RD->setLocStart(readSourceLocation());
4393 RD->setBraceRange(readSourceRange());
4394
4395 if (Record.readInt()) {
4396 AttrVec Attrs;
4397 Record.readAttributes(Attrs);
4398 // If the declaration already has attributes, we assume that some other
4399 // AST file already loaded them.
4400 if (!D->hasAttrs())
4401 D->setAttrsImpl(Attrs, Reader.getContext());
4402 }
4403 break;
4404 }
4405
4406 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4407 // Set the 'operator delete' directly to avoid emitting another update
4408 // record.
4409 auto *Del = readDeclAs<FunctionDecl>();
4410 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4411 auto *ThisArg = Record.readExpr();
4412 // FIXME: Check consistency if we have an old and new operator delete.
4413 if (!First->OperatorDelete) {
4414 First->OperatorDelete = Del;
4415 First->OperatorDeleteThisArg = ThisArg;
4416 }
4417 break;
4418 }
4419
4420 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4421 SmallVector<QualType, 8> ExceptionStorage;
4422 auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4423
4424 // Update this declaration's exception specification, if needed.
4425 auto *FD = cast<FunctionDecl>(D);
4426 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4427 // FIXME: If the exception specification is already present, check that it
4428 // matches.
4429 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4430 FD->setType(Reader.getContext().getFunctionType(
4431 FPT->getReturnType(), FPT->getParamTypes(),
4432 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4433
4434 // When we get to the end of deserializing, see if there are other decls
4435 // that we need to propagate this exception specification onto.
4436 Reader.PendingExceptionSpecUpdates.insert(
4437 std::make_pair(FD->getCanonicalDecl(), FD));
4438 }
4439 break;
4440 }
4441
4442 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4443 auto *FD = cast<FunctionDecl>(D);
4444 QualType DeducedResultType = Record.readType();
4445 Reader.PendingDeducedTypeUpdates.insert(
4446 {FD->getCanonicalDecl(), DeducedResultType});
4447 break;
4448 }
4449
4450 case UPD_DECL_MARKED_USED:
4451 // Maintain AST consistency: any later redeclarations are used too.
4452 D->markUsed(Reader.getContext());
4453 break;
4454
4455 case UPD_MANGLING_NUMBER:
4456 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4457 Record.readInt());
4458 break;
4459
4460 case UPD_STATIC_LOCAL_NUMBER:
4461 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4462 Record.readInt());
4463 break;
4464
4465 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4466 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4467 Reader.getContext(), readSourceRange(),
4468 AttributeCommonInfo::AS_Pragma));
4469 break;
4470
4471 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4472 auto AllocatorKind =
4473 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4474 Expr *Allocator = Record.readExpr();
4475 Expr *Alignment = Record.readExpr();
4476 SourceRange SR = readSourceRange();
4477 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4478 Reader.getContext(), AllocatorKind, Allocator, Alignment, SR,
4479 AttributeCommonInfo::AS_Pragma));
4480 break;
4481 }
4482
4483 case UPD_DECL_EXPORTED: {
4484 unsigned SubmoduleID = readSubmoduleID();
4485 auto *Exported = cast<NamedDecl>(D);
4486 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4487 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4488 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4489 break;
4490 }
4491
4492 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4493 auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();
4494 auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();
4495 Expr *IndirectE = Record.readExpr();
4496 bool Indirect = Record.readBool();
4497 unsigned Level = Record.readInt();
4498 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4499 Reader.getContext(), MapType, DevType, IndirectE, Indirect, Level,
4500 readSourceRange(), AttributeCommonInfo::AS_Pragma));
4501 break;
4502 }
4503
4504 case UPD_ADDED_ATTR_TO_RECORD:
4505 AttrVec Attrs;
4506 Record.readAttributes(Attrs);
4507 assert(Attrs.size() == 1)(static_cast <bool> (Attrs.size() == 1) ? void (0) : __assert_fail
("Attrs.size() == 1", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 4507, __extension__ __PRETTY_FUNCTION__))
;
4508 D->addAttr(Attrs[0]);
4509 break;
4510 }
4511 }
4512}