Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 2546, column 5
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 -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -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-13/lib/clang/13.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 -O2 -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-06-13-111025-38230-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp

1//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
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 defines the ASTImporter class which imports AST nodes from one
10// context into another context.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTImporter.h"
15#include "clang/AST/ASTImporterSharedState.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclAccessPair.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclFriend.h"
25#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/DeclVisitor.h"
29#include "clang/AST/DeclarationName.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
32#include "clang/AST/ExprObjC.h"
33#include "clang/AST/ExternalASTSource.h"
34#include "clang/AST/LambdaCapture.h"
35#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/OperationKinds.h"
37#include "clang/AST/Stmt.h"
38#include "clang/AST/StmtCXX.h"
39#include "clang/AST/StmtObjC.h"
40#include "clang/AST/StmtVisitor.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
44#include "clang/AST/TypeLoc.h"
45#include "clang/AST/TypeVisitor.h"
46#include "clang/AST/UnresolvedSet.h"
47#include "clang/Basic/Builtins.h"
48#include "clang/Basic/ExceptionSpecificationType.h"
49#include "clang/Basic/FileManager.h"
50#include "clang/Basic/IdentifierTable.h"
51#include "clang/Basic/LLVM.h"
52#include "clang/Basic/LangOptions.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "llvm/ADT/APSInt.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/None.h"
60#include "llvm/ADT/Optional.h"
61#include "llvm/ADT/ScopeExit.h"
62#include "llvm/ADT/STLExtras.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
67#include <algorithm>
68#include <cassert>
69#include <cstddef>
70#include <memory>
71#include <type_traits>
72#include <utility>
73
74namespace clang {
75
76 using llvm::make_error;
77 using llvm::Error;
78 using llvm::Expected;
79 using ExpectedType = llvm::Expected<QualType>;
80 using ExpectedStmt = llvm::Expected<Stmt *>;
81 using ExpectedExpr = llvm::Expected<Expr *>;
82 using ExpectedDecl = llvm::Expected<Decl *>;
83 using ExpectedSLoc = llvm::Expected<SourceLocation>;
84 using ExpectedName = llvm::Expected<DeclarationName>;
85
86 std::string ImportError::toString() const {
87 // FIXME: Improve error texts.
88 switch (Error) {
89 case NameConflict:
90 return "NameConflict";
91 case UnsupportedConstruct:
92 return "UnsupportedConstruct";
93 case Unknown:
94 return "Unknown error";
95 }
96 llvm_unreachable("Invalid error code.")::llvm::llvm_unreachable_internal("Invalid error code.", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 96)
;
97 return "Invalid error code.";
98 }
99
100 void ImportError::log(raw_ostream &OS) const {
101 OS << toString();
102 }
103
104 std::error_code ImportError::convertToErrorCode() const {
105 llvm_unreachable("Function not implemented.")::llvm::llvm_unreachable_internal("Function not implemented."
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 105)
;
106 }
107
108 char ImportError::ID;
109
110 template <class T>
111 SmallVector<Decl *, 2>
112 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
113 SmallVector<Decl *, 2> Redecls;
114 for (auto *R : D->getFirstDecl()->redecls()) {
115 if (R != D->getFirstDecl())
116 Redecls.push_back(R);
117 }
118 Redecls.push_back(D->getFirstDecl());
119 std::reverse(Redecls.begin(), Redecls.end());
120 return Redecls;
121 }
122
123 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
124 if (auto *FD = dyn_cast<FunctionDecl>(D))
125 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
126 if (auto *VD = dyn_cast<VarDecl>(D))
127 return getCanonicalForwardRedeclChain<VarDecl>(VD);
128 if (auto *TD = dyn_cast<TagDecl>(D))
129 return getCanonicalForwardRedeclChain<TagDecl>(TD);
130 llvm_unreachable("Bad declaration kind")::llvm::llvm_unreachable_internal("Bad declaration kind", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 130)
;
131 }
132
133 void updateFlags(const Decl *From, Decl *To) {
134 // Check if some flags or attrs are new in 'From' and copy into 'To'.
135 // FIXME: Other flags or attrs?
136 if (From->isUsed(false) && !To->isUsed(false))
137 To->setIsUsed();
138 }
139
140 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
141 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
142 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
143 ASTImporter &Importer;
144
145 // Use this instead of Importer.importInto .
146 template <typename ImportT>
147 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT &To, const ImportT &From) {
148 return Importer.importInto(To, From);
149 }
150
151 // Use this to import pointers of specific type.
152 template <typename ImportT>
153 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT *&To, ImportT *From) {
154 auto ToOrErr = Importer.Import(From);
155 if (ToOrErr)
156 To = cast_or_null<ImportT>(*ToOrErr);
157 return ToOrErr.takeError();
158 }
159
160 // Call the import function of ASTImporter for a baseclass of type `T` and
161 // cast the return value to `T`.
162 template <typename T>
163 Expected<T *> import(T *From) {
164 auto ToOrErr = Importer.Import(From);
1
Calling 'ASTImporter::Import'
165 if (!ToOrErr)
166 return ToOrErr.takeError();
167 return cast_or_null<T>(*ToOrErr);
168 }
169
170 template <typename T>
171 Expected<T *> import(const T *From) {
172 return import(const_cast<T *>(From));
173 }
174
175 // Call the import function of ASTImporter for type `T`.
176 template <typename T>
177 Expected<T> import(const T &From) {
178 return Importer.Import(From);
179 }
180
181 // Import an Optional<T> by importing the contained T, if any.
182 template<typename T>
183 Expected<Optional<T>> import(Optional<T> From) {
184 if (!From)
185 return Optional<T>();
186 return import(*From);
187 }
188
189 // Helper for chaining together multiple imports. If an error is detected,
190 // subsequent imports will return default constructed nodes, so that failure
191 // can be detected with a single conditional branch after a sequence of
192 // imports.
193 template <typename T> T importChecked(Error &Err, const T &From) {
194 // Don't attempt to import nodes if we hit an error earlier.
195 if (Err)
196 return T{};
197 Expected<T> MaybeVal = import(From);
198 if (!MaybeVal) {
199 Err = MaybeVal.takeError();
200 return T{};
201 }
202 return *MaybeVal;
203 }
204
205 ExplicitSpecifier importExplicitSpecifier(Error &Err,
206 ExplicitSpecifier ESpec);
207
208 // Wrapper for an overload set.
209 template <typename ToDeclT> struct CallOverloadedCreateFun {
210 template <typename... Args> decltype(auto) operator()(Args &&... args) {
211 return ToDeclT::Create(std::forward<Args>(args)...);
212 }
213 };
214
215 // Always use these functions to create a Decl during import. There are
216 // certain tasks which must be done after the Decl was created, e.g. we
217 // must immediately register that as an imported Decl. The parameter `ToD`
218 // will be set to the newly created Decl or if had been imported before
219 // then to the already imported Decl. Returns a bool value set to true if
220 // the `FromD` had been imported before.
221 template <typename ToDeclT, typename FromDeclT, typename... Args>
222 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
223 Args &&... args) {
224 // There may be several overloads of ToDeclT::Create. We must make sure
225 // to call the one which would be chosen by the arguments, thus we use a
226 // wrapper for the overload set.
227 CallOverloadedCreateFun<ToDeclT> OC;
228 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
229 std::forward<Args>(args)...);
230 }
231 // Use this overload if a special Type is needed to be created. E.g if we
232 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
233 // then:
234 // TypedefNameDecl *ToTypedef;
235 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
236 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
237 typename... Args>
238 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
239 Args &&... args) {
240 CallOverloadedCreateFun<NewDeclT> OC;
241 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
33
Calling 'ASTNodeImporter::GetImportedOrCreateSpecialDecl'
39
Returning from 'ASTNodeImporter::GetImportedOrCreateSpecialDecl'
40
Returning zero, which participates in a condition later
242 std::forward<Args>(args)...);
243 }
244 // Use this version if a special create function must be
245 // used, e.g. CXXRecordDecl::CreateLambda .
246 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
247 typename... Args>
248 LLVM_NODISCARD[[clang::warn_unused_result]] bool
249 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
250 FromDeclT *FromD, Args &&... args) {
251 if (Importer.getImportDeclErrorIfAny(FromD)) {
34
Assuming the condition is false
35
Taking false branch
252 ToD = nullptr;
253 return true; // Already imported but with error.
254 }
255 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
36
Assuming null pointer is passed into cast
256 if (ToD
36.1
'ToD' is null
36.1
'ToD' is null
36.1
'ToD' is null
)
37
Taking false branch
257 return true; // Already imported.
258 ToD = CreateFun(std::forward<Args>(args)...);
259 // Keep track of imported Decls.
260 Importer.RegisterImportedDecl(FromD, ToD);
261 InitializeImportedDecl(FromD, ToD);
262 return false; // A new Decl is created.
38
Returning zero, which participates in a condition later
263 }
264
265 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
266 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
267 if (FromD->isUsed())
268 ToD->setIsUsed();
269 if (FromD->isImplicit())
270 ToD->setImplicit();
271 }
272
273 // Check if we have found an existing definition. Returns with that
274 // definition if yes, otherwise returns null.
275 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
276 const FunctionDecl *Definition = nullptr;
277 if (D->doesThisDeclarationHaveABody() &&
278 FoundFunction->hasBody(Definition))
279 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
280 return nullptr;
281 }
282
283 void addDeclToContexts(Decl *FromD, Decl *ToD) {
284 if (Importer.isMinimalImport()) {
285 // In minimal import case the decl must be added even if it is not
286 // contained in original context, for LLDB compatibility.
287 // FIXME: Check if a better solution is possible.
288 if (!FromD->getDescribedTemplate() &&
289 FromD->getFriendObjectKind() == Decl::FOK_None)
290 ToD->getLexicalDeclContext()->addDeclInternal(ToD);
291 return;
292 }
293
294 DeclContext *FromDC = FromD->getDeclContext();
295 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
296 DeclContext *ToDC = ToD->getDeclContext();
297 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
298
299 bool Visible = false;
300 if (FromDC->containsDeclAndLoad(FromD)) {
301 ToDC->addDeclInternal(ToD);
302 Visible = true;
303 }
304 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
305 ToLexicalDC->addDeclInternal(ToD);
306 Visible = true;
307 }
308
309 // If the Decl was added to any context, it was made already visible.
310 // Otherwise it is still possible that it should be visible.
311 if (!Visible) {
312 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
313 auto *ToNamed = cast<NamedDecl>(ToD);
314 DeclContextLookupResult FromLookup =
315 FromDC->lookup(FromNamed->getDeclName());
316 for (NamedDecl *ND : FromLookup)
317 if (ND == FromNamed) {
318 ToDC->makeDeclVisibleInContext(ToNamed);
319 break;
320 }
321 }
322 }
323 }
324
325 public:
326 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
327
328 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
329 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
330 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
331
332 // Importing types
333 ExpectedType VisitType(const Type *T);
334 ExpectedType VisitAtomicType(const AtomicType *T);
335 ExpectedType VisitBuiltinType(const BuiltinType *T);
336 ExpectedType VisitDecayedType(const DecayedType *T);
337 ExpectedType VisitComplexType(const ComplexType *T);
338 ExpectedType VisitPointerType(const PointerType *T);
339 ExpectedType VisitBlockPointerType(const BlockPointerType *T);
340 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
341 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
342 ExpectedType VisitMemberPointerType(const MemberPointerType *T);
343 ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
344 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
345 ExpectedType VisitVariableArrayType(const VariableArrayType *T);
346 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
347 // FIXME: DependentSizedExtVectorType
348 ExpectedType VisitVectorType(const VectorType *T);
349 ExpectedType VisitExtVectorType(const ExtVectorType *T);
350 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
351 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
352 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
353 ExpectedType VisitParenType(const ParenType *T);
354 ExpectedType VisitTypedefType(const TypedefType *T);
355 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
356 // FIXME: DependentTypeOfExprType
357 ExpectedType VisitTypeOfType(const TypeOfType *T);
358 ExpectedType VisitDecltypeType(const DecltypeType *T);
359 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
360 ExpectedType VisitAutoType(const AutoType *T);
361 ExpectedType VisitDeducedTemplateSpecializationType(
362 const DeducedTemplateSpecializationType *T);
363 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
364 // FIXME: DependentDecltypeType
365 ExpectedType VisitRecordType(const RecordType *T);
366 ExpectedType VisitEnumType(const EnumType *T);
367 ExpectedType VisitAttributedType(const AttributedType *T);
368 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
369 ExpectedType VisitSubstTemplateTypeParmType(
370 const SubstTemplateTypeParmType *T);
371 ExpectedType VisitTemplateSpecializationType(
372 const TemplateSpecializationType *T);
373 ExpectedType VisitElaboratedType(const ElaboratedType *T);
374 ExpectedType VisitDependentNameType(const DependentNameType *T);
375 ExpectedType VisitPackExpansionType(const PackExpansionType *T);
376 ExpectedType VisitDependentTemplateSpecializationType(
377 const DependentTemplateSpecializationType *T);
378 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
379 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
380 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
381
382 // Importing declarations
383 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
384 SourceLocation &Loc);
385 Error ImportDeclParts(
386 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
387 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
388 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
389 Error ImportDeclarationNameLoc(
390 const DeclarationNameInfo &From, DeclarationNameInfo &To);
391 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
392 Error ImportDeclContext(
393 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
394 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
395
396 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
397 Expected<APValue> ImportAPValue(const APValue &FromValue);
398
399 using Designator = DesignatedInitExpr::Designator;
400
401 /// What we should import from the definition.
402 enum ImportDefinitionKind {
403 /// Import the default subset of the definition, which might be
404 /// nothing (if minimal import is set) or might be everything (if minimal
405 /// import is not set).
406 IDK_Default,
407 /// Import everything.
408 IDK_Everything,
409 /// Import only the bare bones needed to establish a valid
410 /// DeclContext.
411 IDK_Basic
412 };
413
414 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
415 return IDK == IDK_Everything ||
416 (IDK == IDK_Default && !Importer.isMinimalImport());
417 }
418
419 Error ImportInitializer(VarDecl *From, VarDecl *To);
420 Error ImportDefinition(
421 RecordDecl *From, RecordDecl *To,
422 ImportDefinitionKind Kind = IDK_Default);
423 Error ImportDefinition(
424 EnumDecl *From, EnumDecl *To,
425 ImportDefinitionKind Kind = IDK_Default);
426 Error ImportDefinition(
427 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
428 ImportDefinitionKind Kind = IDK_Default);
429 Error ImportDefinition(
430 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
431 ImportDefinitionKind Kind = IDK_Default);
432 Error ImportTemplateArguments(
433 const TemplateArgument *FromArgs, unsigned NumFromArgs,
434 SmallVectorImpl<TemplateArgument> &ToArgs);
435 Expected<TemplateArgument>
436 ImportTemplateArgument(const TemplateArgument &From);
437
438 template <typename InContainerTy>
439 Error ImportTemplateArgumentListInfo(
440 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
441
442 template<typename InContainerTy>
443 Error ImportTemplateArgumentListInfo(
444 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
445 const InContainerTy &Container, TemplateArgumentListInfo &Result);
446
447 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
448 using FunctionTemplateAndArgsTy =
449 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
450 Expected<FunctionTemplateAndArgsTy>
451 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
452 FunctionDecl *FromFD);
453 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
454 DeclaratorDecl *ToD);
455
456 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
457
458 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
459
460 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
461 ParmVarDecl *ToParam);
462
463 template <typename T>
464 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
465
466 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
467 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
468 bool Complain = true);
469 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
470 bool Complain = true);
471 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
472 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
473 bool IsStructuralMatch(FunctionTemplateDecl *From,
474 FunctionTemplateDecl *To);
475 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
476 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
477 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
478 ExpectedDecl VisitDecl(Decl *D);
479 ExpectedDecl VisitImportDecl(ImportDecl *D);
480 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
481 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
482 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
483 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
484 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
485 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
486 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
487 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
488 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
489 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
490 ExpectedDecl VisitLabelDecl(LabelDecl *D);
491 ExpectedDecl VisitEnumDecl(EnumDecl *D);
492 ExpectedDecl VisitRecordDecl(RecordDecl *D);
493 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
494 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
495 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
496 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
497 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
498 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
499 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
500 ExpectedDecl VisitFieldDecl(FieldDecl *D);
501 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
502 ExpectedDecl VisitFriendDecl(FriendDecl *D);
503 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
504 ExpectedDecl VisitVarDecl(VarDecl *D);
505 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
506 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
507 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
508 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
509 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
510 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
511 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
512 ExpectedDecl VisitUsingDecl(UsingDecl *D);
513 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
514 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
515 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
516 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
517 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
518 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
519 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
520 ExpectedDecl
521 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
522
523 Expected<ObjCTypeParamList *>
524 ImportObjCTypeParamList(ObjCTypeParamList *list);
525
526 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
527 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
528 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
529 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
530 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
531 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
532 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
533 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
534 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
535 ExpectedDecl VisitClassTemplateSpecializationDecl(
536 ClassTemplateSpecializationDecl *D);
537 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
538 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
539 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
540
541 // Importing statements
542 ExpectedStmt VisitStmt(Stmt *S);
543 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
544 ExpectedStmt VisitDeclStmt(DeclStmt *S);
545 ExpectedStmt VisitNullStmt(NullStmt *S);
546 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
547 ExpectedStmt VisitCaseStmt(CaseStmt *S);
548 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
549 ExpectedStmt VisitLabelStmt(LabelStmt *S);
550 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
551 ExpectedStmt VisitIfStmt(IfStmt *S);
552 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
553 ExpectedStmt VisitWhileStmt(WhileStmt *S);
554 ExpectedStmt VisitDoStmt(DoStmt *S);
555 ExpectedStmt VisitForStmt(ForStmt *S);
556 ExpectedStmt VisitGotoStmt(GotoStmt *S);
557 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
558 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
559 ExpectedStmt VisitBreakStmt(BreakStmt *S);
560 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
561 // FIXME: MSAsmStmt
562 // FIXME: SEHExceptStmt
563 // FIXME: SEHFinallyStmt
564 // FIXME: SEHTryStmt
565 // FIXME: SEHLeaveStmt
566 // FIXME: CapturedStmt
567 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
568 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
569 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
570 // FIXME: MSDependentExistsStmt
571 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
572 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
573 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
574 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
575 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
576 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
577 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
578
579 // Importing expressions
580 ExpectedStmt VisitExpr(Expr *E);
581 ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E);
582 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
583 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
584 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
585 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
586 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
587 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
588 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
589 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
590 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
591 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
592 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
593 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
594 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
595 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
596 ExpectedStmt VisitStringLiteral(StringLiteral *E);
597 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
598 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
599 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
600 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
601 ExpectedStmt VisitParenExpr(ParenExpr *E);
602 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
603 ExpectedStmt VisitStmtExpr(StmtExpr *E);
604 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
605 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
606 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
607 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
608 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
609 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
610 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
611 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
612 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
613 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
614 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
615 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
616 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
617 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
618 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
619 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
620 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
621 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
622 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
623 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
624 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
625 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
626 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
627 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
628 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
629 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
630 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
631 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
632 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
633 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
634 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
635 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
636 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
637 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
638 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
639 ExpectedStmt VisitMemberExpr(MemberExpr *E);
640 ExpectedStmt VisitCallExpr(CallExpr *E);
641 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
642 ExpectedStmt VisitInitListExpr(InitListExpr *E);
643 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
644 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
645 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
646 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
647 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
648 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
649 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
650 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
651 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
652 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
653
654 template<typename IIter, typename OIter>
655 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
656 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
657 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
658 Expected<ItemT> ToOrErr = import(*Ibegin);
659 if (!ToOrErr)
660 return ToOrErr.takeError();
661 *Obegin = *ToOrErr;
662 }
663 return Error::success();
664 }
665
666 // Import every item from a container structure into an output container.
667 // If error occurs, stops at first error and returns the error.
668 // The output container should have space for all needed elements (it is not
669 // expanded, new items are put into from the beginning).
670 template<typename InContainerTy, typename OutContainerTy>
671 Error ImportContainerChecked(
672 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
673 return ImportArrayChecked(
674 InContainer.begin(), InContainer.end(), OutContainer.begin());
675 }
676
677 template<typename InContainerTy, typename OIter>
678 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
679 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
680 }
681
682 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
683 CXXMethodDecl *FromMethod);
684
685 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
686 FunctionDecl *FromFD);
687
688 // Returns true if the given function has a placeholder return type and
689 // that type is declared inside the body of the function.
690 // E.g. auto f() { struct X{}; return X(); }
691 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
692 };
693
694template <typename InContainerTy>
695Error ASTNodeImporter::ImportTemplateArgumentListInfo(
696 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
697 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
698 auto ToLAngleLocOrErr = import(FromLAngleLoc);
699 if (!ToLAngleLocOrErr)
700 return ToLAngleLocOrErr.takeError();
701 auto ToRAngleLocOrErr = import(FromRAngleLoc);
702 if (!ToRAngleLocOrErr)
703 return ToRAngleLocOrErr.takeError();
704
705 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
706 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
707 return Err;
708 Result = ToTAInfo;
709 return Error::success();
710}
711
712template <>
713Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
714 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
715 return ImportTemplateArgumentListInfo(
716 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
717}
718
719template <>
720Error ASTNodeImporter::ImportTemplateArgumentListInfo<
721 ASTTemplateArgumentListInfo>(
722 const ASTTemplateArgumentListInfo &From,
723 TemplateArgumentListInfo &Result) {
724 return ImportTemplateArgumentListInfo(
725 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
726}
727
728Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
729ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
730 FunctionDecl *FromFD) {
731 assert(FromFD->getTemplatedKind() ==(static_cast <bool> (FromFD->getTemplatedKind() == FunctionDecl
::TK_FunctionTemplateSpecialization) ? void (0) : __assert_fail
("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 732, __extension__ __PRETTY_FUNCTION__))
732 FunctionDecl::TK_FunctionTemplateSpecialization)(static_cast <bool> (FromFD->getTemplatedKind() == FunctionDecl
::TK_FunctionTemplateSpecialization) ? void (0) : __assert_fail
("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 732, __extension__ __PRETTY_FUNCTION__))
;
733
734 FunctionTemplateAndArgsTy Result;
735
736 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
737 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
738 return std::move(Err);
739
740 // Import template arguments.
741 auto TemplArgs = FTSInfo->TemplateArguments->asArray();
742 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
743 std::get<1>(Result)))
744 return std::move(Err);
745
746 return Result;
747}
748
749template <>
750Expected<TemplateParameterList *>
751ASTNodeImporter::import(TemplateParameterList *From) {
752 SmallVector<NamedDecl *, 4> To(From->size());
753 if (Error Err = ImportContainerChecked(*From, To))
754 return std::move(Err);
755
756 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
757 if (!ToRequiresClause)
758 return ToRequiresClause.takeError();
759
760 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
761 if (!ToTemplateLocOrErr)
762 return ToTemplateLocOrErr.takeError();
763 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
764 if (!ToLAngleLocOrErr)
765 return ToLAngleLocOrErr.takeError();
766 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
767 if (!ToRAngleLocOrErr)
768 return ToRAngleLocOrErr.takeError();
769
770 return TemplateParameterList::Create(
771 Importer.getToContext(),
772 *ToTemplateLocOrErr,
773 *ToLAngleLocOrErr,
774 To,
775 *ToRAngleLocOrErr,
776 *ToRequiresClause);
777}
778
779template <>
780Expected<TemplateArgument>
781ASTNodeImporter::import(const TemplateArgument &From) {
782 switch (From.getKind()) {
783 case TemplateArgument::Null:
784 return TemplateArgument();
785
786 case TemplateArgument::Type: {
787 ExpectedType ToTypeOrErr = import(From.getAsType());
788 if (!ToTypeOrErr)
789 return ToTypeOrErr.takeError();
790 return TemplateArgument(*ToTypeOrErr);
791 }
792
793 case TemplateArgument::Integral: {
794 ExpectedType ToTypeOrErr = import(From.getIntegralType());
795 if (!ToTypeOrErr)
796 return ToTypeOrErr.takeError();
797 return TemplateArgument(From, *ToTypeOrErr);
798 }
799
800 case TemplateArgument::Declaration: {
801 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
802 if (!ToOrErr)
803 return ToOrErr.takeError();
804 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
805 if (!ToTypeOrErr)
806 return ToTypeOrErr.takeError();
807 return TemplateArgument(*ToOrErr, *ToTypeOrErr);
808 }
809
810 case TemplateArgument::NullPtr: {
811 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
812 if (!ToTypeOrErr)
813 return ToTypeOrErr.takeError();
814 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
815 }
816
817 case TemplateArgument::Template: {
818 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
819 if (!ToTemplateOrErr)
820 return ToTemplateOrErr.takeError();
821
822 return TemplateArgument(*ToTemplateOrErr);
823 }
824
825 case TemplateArgument::TemplateExpansion: {
826 Expected<TemplateName> ToTemplateOrErr =
827 import(From.getAsTemplateOrTemplatePattern());
828 if (!ToTemplateOrErr)
829 return ToTemplateOrErr.takeError();
830
831 return TemplateArgument(
832 *ToTemplateOrErr, From.getNumTemplateExpansions());
833 }
834
835 case TemplateArgument::Expression:
836 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
837 return TemplateArgument(*ToExpr);
838 else
839 return ToExpr.takeError();
840
841 case TemplateArgument::Pack: {
842 SmallVector<TemplateArgument, 2> ToPack;
843 ToPack.reserve(From.pack_size());
844 if (Error Err = ImportTemplateArguments(
845 From.pack_begin(), From.pack_size(), ToPack))
846 return std::move(Err);
847
848 return TemplateArgument(
849 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
850 }
851 }
852
853 llvm_unreachable("Invalid template argument kind")::llvm::llvm_unreachable_internal("Invalid template argument kind"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 853)
;
854}
855
856template <>
857Expected<TemplateArgumentLoc>
858ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
859 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
860 if (!ArgOrErr)
861 return ArgOrErr.takeError();
862 TemplateArgument Arg = *ArgOrErr;
863
864 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
865
866 TemplateArgumentLocInfo ToInfo;
867 if (Arg.getKind() == TemplateArgument::Expression) {
868 ExpectedExpr E = import(FromInfo.getAsExpr());
869 if (!E)
870 return E.takeError();
871 ToInfo = TemplateArgumentLocInfo(*E);
872 } else if (Arg.getKind() == TemplateArgument::Type) {
873 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
874 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
875 else
876 return TSIOrErr.takeError();
877 } else {
878 auto ToTemplateQualifierLocOrErr =
879 import(FromInfo.getTemplateQualifierLoc());
880 if (!ToTemplateQualifierLocOrErr)
881 return ToTemplateQualifierLocOrErr.takeError();
882 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
883 if (!ToTemplateNameLocOrErr)
884 return ToTemplateNameLocOrErr.takeError();
885 auto ToTemplateEllipsisLocOrErr =
886 import(FromInfo.getTemplateEllipsisLoc());
887 if (!ToTemplateEllipsisLocOrErr)
888 return ToTemplateEllipsisLocOrErr.takeError();
889 ToInfo = TemplateArgumentLocInfo(
890 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
891 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
892 }
893
894 return TemplateArgumentLoc(Arg, ToInfo);
895}
896
897template <>
898Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
899 if (DG.isNull())
900 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
901 size_t NumDecls = DG.end() - DG.begin();
902 SmallVector<Decl *, 1> ToDecls;
903 ToDecls.reserve(NumDecls);
904 for (Decl *FromD : DG) {
905 if (auto ToDOrErr = import(FromD))
906 ToDecls.push_back(*ToDOrErr);
907 else
908 return ToDOrErr.takeError();
909 }
910 return DeclGroupRef::Create(Importer.getToContext(),
911 ToDecls.begin(),
912 NumDecls);
913}
914
915template <>
916Expected<ASTNodeImporter::Designator>
917ASTNodeImporter::import(const Designator &D) {
918 if (D.isFieldDesignator()) {
919 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
920
921 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
922 if (!ToDotLocOrErr)
923 return ToDotLocOrErr.takeError();
924
925 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
926 if (!ToFieldLocOrErr)
927 return ToFieldLocOrErr.takeError();
928
929 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
930 }
931
932 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
933 if (!ToLBracketLocOrErr)
934 return ToLBracketLocOrErr.takeError();
935
936 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
937 if (!ToRBracketLocOrErr)
938 return ToRBracketLocOrErr.takeError();
939
940 if (D.isArrayDesignator())
941 return Designator(D.getFirstExprIndex(),
942 *ToLBracketLocOrErr, *ToRBracketLocOrErr);
943
944 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
945 if (!ToEllipsisLocOrErr)
946 return ToEllipsisLocOrErr.takeError();
947
948 assert(D.isArrayRangeDesignator())(static_cast <bool> (D.isArrayRangeDesignator()) ? void
(0) : __assert_fail ("D.isArrayRangeDesignator()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 948, __extension__ __PRETTY_FUNCTION__))
;
949 return Designator(
950 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
951 *ToRBracketLocOrErr);
952}
953
954template <>
955Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
956 VarDecl *Var = nullptr;
957 if (From.capturesVariable()) {
958 if (auto VarOrErr = import(From.getCapturedVar()))
959 Var = *VarOrErr;
960 else
961 return VarOrErr.takeError();
962 }
963
964 auto LocationOrErr = import(From.getLocation());
965 if (!LocationOrErr)
966 return LocationOrErr.takeError();
967
968 SourceLocation EllipsisLoc;
969 if (From.isPackExpansion())
970 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
971 return std::move(Err);
972
973 return LambdaCapture(
974 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
975 EllipsisLoc);
976}
977
978template <typename T>
979bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
980 if (Found->getLinkageInternal() != From->getLinkageInternal())
981 return false;
982
983 if (From->hasExternalFormalLinkage())
984 return Found->hasExternalFormalLinkage();
985 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
986 return false;
987 if (From->isInAnonymousNamespace())
988 return Found->isInAnonymousNamespace();
989 else
990 return !Found->isInAnonymousNamespace() &&
991 !Found->hasExternalFormalLinkage();
992}
993
994template <>
995bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
996 TypedefNameDecl *From) {
997 if (Found->getLinkageInternal() != From->getLinkageInternal())
998 return false;
999
1000 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1001 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1002 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1003}
1004
1005} // namespace clang
1006
1007//----------------------------------------------------------------------------
1008// Import Types
1009//----------------------------------------------------------------------------
1010
1011using namespace clang;
1012
1013ExpectedType ASTNodeImporter::VisitType(const Type *T) {
1014 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1015 << T->getTypeClassName();
1016 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1017}
1018
1019ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1020 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1021 if (!UnderlyingTypeOrErr)
1022 return UnderlyingTypeOrErr.takeError();
1023
1024 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1025}
1026
1027ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1028 switch (T->getKind()) {
1029#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1030 case BuiltinType::Id: \
1031 return Importer.getToContext().SingletonId;
1032#include "clang/Basic/OpenCLImageTypes.def"
1033#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1034 case BuiltinType::Id: \
1035 return Importer.getToContext().Id##Ty;
1036#include "clang/Basic/OpenCLExtensionTypes.def"
1037#define SVE_TYPE(Name, Id, SingletonId) \
1038 case BuiltinType::Id: \
1039 return Importer.getToContext().SingletonId;
1040#include "clang/Basic/AArch64SVEACLETypes.def"
1041#define PPC_VECTOR_TYPE(Name, Id, Size) \
1042 case BuiltinType::Id: \
1043 return Importer.getToContext().Id##Ty;
1044#include "clang/Basic/PPCTypes.def"
1045#define RVV_TYPE(Name, Id, SingletonId) \
1046 case BuiltinType::Id: \
1047 return Importer.getToContext().SingletonId;
1048#include "clang/Basic/RISCVVTypes.def"
1049#define SHARED_SINGLETON_TYPE(Expansion)
1050#define BUILTIN_TYPE(Id, SingletonId) \
1051 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1052#include "clang/AST/BuiltinTypes.def"
1053
1054 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1055 // context supports C++.
1056
1057 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1058 // context supports ObjC.
1059
1060 case BuiltinType::Char_U:
1061 // The context we're importing from has an unsigned 'char'. If we're
1062 // importing into a context with a signed 'char', translate to
1063 // 'unsigned char' instead.
1064 if (Importer.getToContext().getLangOpts().CharIsSigned)
1065 return Importer.getToContext().UnsignedCharTy;
1066
1067 return Importer.getToContext().CharTy;
1068
1069 case BuiltinType::Char_S:
1070 // The context we're importing from has an unsigned 'char'. If we're
1071 // importing into a context with a signed 'char', translate to
1072 // 'unsigned char' instead.
1073 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1074 return Importer.getToContext().SignedCharTy;
1075
1076 return Importer.getToContext().CharTy;
1077
1078 case BuiltinType::WChar_S:
1079 case BuiltinType::WChar_U:
1080 // FIXME: If not in C++, shall we translate to the C equivalent of
1081 // wchar_t?
1082 return Importer.getToContext().WCharTy;
1083 }
1084
1085 llvm_unreachable("Invalid BuiltinType Kind!")::llvm::llvm_unreachable_internal("Invalid BuiltinType Kind!"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 1085)
;
1086}
1087
1088ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1089 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1090 if (!ToOriginalTypeOrErr)
1091 return ToOriginalTypeOrErr.takeError();
1092
1093 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1094}
1095
1096ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1097 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1098 if (!ToElementTypeOrErr)
1099 return ToElementTypeOrErr.takeError();
1100
1101 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1102}
1103
1104ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1105 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1106 if (!ToPointeeTypeOrErr)
1107 return ToPointeeTypeOrErr.takeError();
1108
1109 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1110}
1111
1112ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1113 // FIXME: Check for blocks support in "to" context.
1114 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1115 if (!ToPointeeTypeOrErr)
1116 return ToPointeeTypeOrErr.takeError();
1117
1118 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1119}
1120
1121ExpectedType
1122ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1123 // FIXME: Check for C++ support in "to" context.
1124 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1125 if (!ToPointeeTypeOrErr)
1126 return ToPointeeTypeOrErr.takeError();
1127
1128 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1129}
1130
1131ExpectedType
1132ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1133 // FIXME: Check for C++0x support in "to" context.
1134 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1135 if (!ToPointeeTypeOrErr)
1136 return ToPointeeTypeOrErr.takeError();
1137
1138 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1139}
1140
1141ExpectedType
1142ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1143 // FIXME: Check for C++ support in "to" context.
1144 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1145 if (!ToPointeeTypeOrErr)
1146 return ToPointeeTypeOrErr.takeError();
1147
1148 ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1149 if (!ClassTypeOrErr)
1150 return ClassTypeOrErr.takeError();
1151
1152 return Importer.getToContext().getMemberPointerType(
1153 *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1154}
1155
1156ExpectedType
1157ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1158 Error Err = Error::success();
1159 auto ToElementType = importChecked(Err, T->getElementType());
1160 auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1161 if (Err)
1162 return std::move(Err);
1163
1164 return Importer.getToContext().getConstantArrayType(
1165 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1166 T->getIndexTypeCVRQualifiers());
1167}
1168
1169ExpectedType
1170ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1171 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1172 if (!ToElementTypeOrErr)
1173 return ToElementTypeOrErr.takeError();
1174
1175 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1176 T->getSizeModifier(),
1177 T->getIndexTypeCVRQualifiers());
1178}
1179
1180ExpectedType
1181ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1182 Error Err = Error::success();
1183 QualType ToElementType = importChecked(Err, T->getElementType());
1184 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1185 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1186 if (Err)
1187 return std::move(Err);
1188 return Importer.getToContext().getVariableArrayType(
1189 ToElementType, ToSizeExpr, T->getSizeModifier(),
1190 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1191}
1192
1193ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1194 const DependentSizedArrayType *T) {
1195 Error Err = Error::success();
1196 QualType ToElementType = importChecked(Err, T->getElementType());
1197 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1198 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1199 if (Err)
1200 return std::move(Err);
1201 // SizeExpr may be null if size is not specified directly.
1202 // For example, 'int a[]'.
1203
1204 return Importer.getToContext().getDependentSizedArrayType(
1205 ToElementType, ToSizeExpr, T->getSizeModifier(),
1206 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1207}
1208
1209ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1210 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1211 if (!ToElementTypeOrErr)
1212 return ToElementTypeOrErr.takeError();
1213
1214 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1215 T->getNumElements(),
1216 T->getVectorKind());
1217}
1218
1219ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1220 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1221 if (!ToElementTypeOrErr)
1222 return ToElementTypeOrErr.takeError();
1223
1224 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1225 T->getNumElements());
1226}
1227
1228ExpectedType
1229ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1230 // FIXME: What happens if we're importing a function without a prototype
1231 // into C++? Should we make it variadic?
1232 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1233 if (!ToReturnTypeOrErr)
1234 return ToReturnTypeOrErr.takeError();
1235
1236 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1237 T->getExtInfo());
1238}
1239
1240ExpectedType
1241ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1242 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1243 if (!ToReturnTypeOrErr)
1244 return ToReturnTypeOrErr.takeError();
1245
1246 // Import argument types
1247 SmallVector<QualType, 4> ArgTypes;
1248 for (const auto &A : T->param_types()) {
1249 ExpectedType TyOrErr = import(A);
1250 if (!TyOrErr)
1251 return TyOrErr.takeError();
1252 ArgTypes.push_back(*TyOrErr);
1253 }
1254
1255 // Import exception types
1256 SmallVector<QualType, 4> ExceptionTypes;
1257 for (const auto &E : T->exceptions()) {
1258 ExpectedType TyOrErr = import(E);
1259 if (!TyOrErr)
1260 return TyOrErr.takeError();
1261 ExceptionTypes.push_back(*TyOrErr);
1262 }
1263
1264 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1265 Error Err = Error::success();
1266 FunctionProtoType::ExtProtoInfo ToEPI;
1267 ToEPI.ExtInfo = FromEPI.ExtInfo;
1268 ToEPI.Variadic = FromEPI.Variadic;
1269 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1270 ToEPI.TypeQuals = FromEPI.TypeQuals;
1271 ToEPI.RefQualifier = FromEPI.RefQualifier;
1272 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1273 ToEPI.ExceptionSpec.NoexceptExpr =
1274 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
1275 ToEPI.ExceptionSpec.SourceDecl =
1276 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1277 ToEPI.ExceptionSpec.SourceTemplate =
1278 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
1279 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1280
1281 if (Err)
1282 return std::move(Err);
1283
1284 return Importer.getToContext().getFunctionType(
1285 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1286}
1287
1288ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1289 const UnresolvedUsingType *T) {
1290 Error Err = Error::success();
1291 auto ToD = importChecked(Err, T->getDecl());
1292 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1293 if (Err)
1294 return std::move(Err);
1295
1296 return Importer.getToContext().getTypeDeclType(
1297 ToD, cast_or_null<TypeDecl>(ToPrevD));
1298}
1299
1300ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1301 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1302 if (!ToInnerTypeOrErr)
1303 return ToInnerTypeOrErr.takeError();
1304
1305 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1306}
1307
1308ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1309 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1310 if (!ToDeclOrErr)
1311 return ToDeclOrErr.takeError();
1312
1313 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1314}
1315
1316ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1317 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1318 if (!ToExprOrErr)
1319 return ToExprOrErr.takeError();
1320
1321 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1322}
1323
1324ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1325 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1326 if (!ToUnderlyingTypeOrErr)
1327 return ToUnderlyingTypeOrErr.takeError();
1328
1329 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1330}
1331
1332ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1333 // FIXME: Make sure that the "to" context supports C++0x!
1334 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1335 if (!ToExprOrErr)
1336 return ToExprOrErr.takeError();
1337
1338 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1339 if (!ToUnderlyingTypeOrErr)
1340 return ToUnderlyingTypeOrErr.takeError();
1341
1342 return Importer.getToContext().getDecltypeType(
1343 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1344}
1345
1346ExpectedType
1347ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1348 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1349 if (!ToBaseTypeOrErr)
1350 return ToBaseTypeOrErr.takeError();
1351
1352 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1353 if (!ToUnderlyingTypeOrErr)
1354 return ToUnderlyingTypeOrErr.takeError();
1355
1356 return Importer.getToContext().getUnaryTransformType(
1357 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1358}
1359
1360ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1361 // FIXME: Make sure that the "to" context supports C++11!
1362 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1363 if (!ToDeducedTypeOrErr)
1364 return ToDeducedTypeOrErr.takeError();
1365
1366 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1367 if (!ToTypeConstraintConcept)
1368 return ToTypeConstraintConcept.takeError();
1369
1370 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1371 ArrayRef<TemplateArgument> FromTemplateArgs = T->getTypeConstraintArguments();
1372 if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(),
1373 FromTemplateArgs.size(),
1374 ToTemplateArgs))
1375 return std::move(Err);
1376
1377 return Importer.getToContext().getAutoType(
1378 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1379 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1380 ToTemplateArgs);
1381}
1382
1383ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1384 const DeducedTemplateSpecializationType *T) {
1385 // FIXME: Make sure that the "to" context supports C++17!
1386 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1387 if (!ToTemplateNameOrErr)
1388 return ToTemplateNameOrErr.takeError();
1389 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1390 if (!ToDeducedTypeOrErr)
1391 return ToDeducedTypeOrErr.takeError();
1392
1393 return Importer.getToContext().getDeducedTemplateSpecializationType(
1394 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1395}
1396
1397ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1398 const InjectedClassNameType *T) {
1399 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1400 if (!ToDeclOrErr)
1401 return ToDeclOrErr.takeError();
1402
1403 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1404 if (!ToInjTypeOrErr)
1405 return ToInjTypeOrErr.takeError();
1406
1407 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1408 // See comments in InjectedClassNameType definition for details
1409 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1410 enum {
1411 TypeAlignmentInBits = 4,
1412 TypeAlignment = 1 << TypeAlignmentInBits
1413 };
1414
1415 return QualType(new (Importer.getToContext(), TypeAlignment)
1416 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1417}
1418
1419ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1420 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1421 if (!ToDeclOrErr)
1422 return ToDeclOrErr.takeError();
1423
1424 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1425}
1426
1427ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1428 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1429 if (!ToDeclOrErr)
1430 return ToDeclOrErr.takeError();
1431
1432 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1433}
1434
1435ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1436 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1437 if (!ToModifiedTypeOrErr)
1438 return ToModifiedTypeOrErr.takeError();
1439 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1440 if (!ToEquivalentTypeOrErr)
1441 return ToEquivalentTypeOrErr.takeError();
1442
1443 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1444 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1445}
1446
1447ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1448 const TemplateTypeParmType *T) {
1449 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1450 if (!ToDeclOrErr)
1451 return ToDeclOrErr.takeError();
1452
1453 return Importer.getToContext().getTemplateTypeParmType(
1454 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1455}
1456
1457ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1458 const SubstTemplateTypeParmType *T) {
1459 ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1460 if (!ReplacedOrErr)
1461 return ReplacedOrErr.takeError();
1462 const TemplateTypeParmType *Replaced =
1463 cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1464
1465 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1466 if (!ToReplacementTypeOrErr)
1467 return ToReplacementTypeOrErr.takeError();
1468
1469 return Importer.getToContext().getSubstTemplateTypeParmType(
1470 Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1471}
1472
1473ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1474 const TemplateSpecializationType *T) {
1475 auto ToTemplateOrErr = import(T->getTemplateName());
1476 if (!ToTemplateOrErr)
1477 return ToTemplateOrErr.takeError();
1478
1479 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1480 if (Error Err = ImportTemplateArguments(
1481 T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1482 return std::move(Err);
1483
1484 QualType ToCanonType;
1485 if (!QualType(T, 0).isCanonical()) {
1486 QualType FromCanonType
1487 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1488 if (ExpectedType TyOrErr = import(FromCanonType))
1489 ToCanonType = *TyOrErr;
1490 else
1491 return TyOrErr.takeError();
1492 }
1493 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1494 ToTemplateArgs,
1495 ToCanonType);
1496}
1497
1498ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1499 // Note: the qualifier in an ElaboratedType is optional.
1500 auto ToQualifierOrErr = import(T->getQualifier());
1501 if (!ToQualifierOrErr)
1502 return ToQualifierOrErr.takeError();
1503
1504 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1505 if (!ToNamedTypeOrErr)
1506 return ToNamedTypeOrErr.takeError();
1507
1508 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1509 if (!ToOwnedTagDeclOrErr)
1510 return ToOwnedTagDeclOrErr.takeError();
1511
1512 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1513 *ToQualifierOrErr,
1514 *ToNamedTypeOrErr,
1515 *ToOwnedTagDeclOrErr);
1516}
1517
1518ExpectedType
1519ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1520 ExpectedType ToPatternOrErr = import(T->getPattern());
1521 if (!ToPatternOrErr)
1522 return ToPatternOrErr.takeError();
1523
1524 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1525 T->getNumExpansions(),
1526 /*ExpactPack=*/false);
1527}
1528
1529ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1530 const DependentTemplateSpecializationType *T) {
1531 auto ToQualifierOrErr = import(T->getQualifier());
1532 if (!ToQualifierOrErr)
1533 return ToQualifierOrErr.takeError();
1534
1535 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1536
1537 SmallVector<TemplateArgument, 2> ToPack;
1538 ToPack.reserve(T->getNumArgs());
1539 if (Error Err = ImportTemplateArguments(
1540 T->getArgs(), T->getNumArgs(), ToPack))
1541 return std::move(Err);
1542
1543 return Importer.getToContext().getDependentTemplateSpecializationType(
1544 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1545}
1546
1547ExpectedType
1548ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1549 auto ToQualifierOrErr = import(T->getQualifier());
1550 if (!ToQualifierOrErr)
1551 return ToQualifierOrErr.takeError();
1552
1553 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1554
1555 QualType Canon;
1556 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1557 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1558 Canon = (*TyOrErr).getCanonicalType();
1559 else
1560 return TyOrErr.takeError();
1561 }
1562
1563 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1564 *ToQualifierOrErr,
1565 Name, Canon);
1566}
1567
1568ExpectedType
1569ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1570 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1571 if (!ToDeclOrErr)
1572 return ToDeclOrErr.takeError();
1573
1574 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1575}
1576
1577ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1578 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1579 if (!ToBaseTypeOrErr)
1580 return ToBaseTypeOrErr.takeError();
1581
1582 SmallVector<QualType, 4> TypeArgs;
1583 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1584 if (ExpectedType TyOrErr = import(TypeArg))
1585 TypeArgs.push_back(*TyOrErr);
1586 else
1587 return TyOrErr.takeError();
1588 }
1589
1590 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1591 for (auto *P : T->quals()) {
1592 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1593 Protocols.push_back(*ProtocolOrErr);
1594 else
1595 return ProtocolOrErr.takeError();
1596
1597 }
1598
1599 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1600 Protocols,
1601 T->isKindOfTypeAsWritten());
1602}
1603
1604ExpectedType
1605ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1606 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1607 if (!ToPointeeTypeOrErr)
1608 return ToPointeeTypeOrErr.takeError();
1609
1610 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1611}
1612
1613//----------------------------------------------------------------------------
1614// Import Declarations
1615//----------------------------------------------------------------------------
1616Error ASTNodeImporter::ImportDeclParts(
1617 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1618 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1619 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1620 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1621 // FIXME: We could support these constructs by importing a different type of
1622 // this parameter and by importing the original type of the parameter only
1623 // after the FunctionDecl is created. See
1624 // VisitFunctionDecl::UsedDifferentProtoType.
1625 DeclContext *OrigDC = D->getDeclContext();
1626 FunctionDecl *FunDecl;
1627 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1628 FunDecl->hasBody()) {
1629 auto getLeafPointeeType = [](const Type *T) {
1630 while (T->isPointerType() || T->isArrayType()) {
1631 T = T->getPointeeOrArrayElementType();
1632 }
1633 return T;
1634 };
1635 for (const ParmVarDecl *P : FunDecl->parameters()) {
1636 const Type *LeafT =
1637 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1638 auto *RT = dyn_cast<RecordType>(LeafT);
1639 if (RT && RT->getDecl() == D) {
1640 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1641 << D->getDeclKindName();
1642 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1643 }
1644 }
1645 }
1646
1647 // Import the context of this declaration.
1648 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1649 return Err;
1650
1651 // Import the name of this declaration.
1652 if (Error Err = importInto(Name, D->getDeclName()))
1653 return Err;
1654
1655 // Import the location of this declaration.
1656 if (Error Err = importInto(Loc, D->getLocation()))
1657 return Err;
1658
1659 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1660 if (ToD)
1661 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1662 return Err;
1663
1664 return Error::success();
1665}
1666
1667Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
1668 NamedDecl *&ToD, SourceLocation &Loc) {
1669
1670 // Import the name of this declaration.
1671 if (Error Err = importInto(Name, D->getDeclName()))
13
Assuming the condition is false
14
Taking false branch
1672 return Err;
1673
1674 // Import the location of this declaration.
1675 if (Error Err = importInto(Loc, D->getLocation()))
15
Assuming the condition is false
16
Taking false branch
1676 return Err;
1677
1678 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
17
Assuming null pointer is passed into cast
18
Null pointer value stored to 'ToD', which participates in a condition later
1679 if (ToD
18.1
'ToD' is null
18.1
'ToD' is null
18.1
'ToD' is null
)
19
Taking false branch
1680 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1681 return Err;
1682
1683 return Error::success();
1684}
1685
1686Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1687 if (!FromD)
1688 return Error::success();
1689
1690 if (!ToD)
1691 if (Error Err = importInto(ToD, FromD))
1692 return Err;
1693
1694 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1695 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1696 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1697 !ToRecord->getDefinition()) {
1698 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1699 return Err;
1700 }
1701 }
1702 return Error::success();
1703 }
1704
1705 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1706 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1707 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1708 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1709 return Err;
1710 }
1711 }
1712 return Error::success();
1713 }
1714
1715 return Error::success();
1716}
1717
1718Error
1719ASTNodeImporter::ImportDeclarationNameLoc(
1720 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1721 // NOTE: To.Name and To.Loc are already imported.
1722 // We only have to import To.LocInfo.
1723 switch (To.getName().getNameKind()) {
1724 case DeclarationName::Identifier:
1725 case DeclarationName::ObjCZeroArgSelector:
1726 case DeclarationName::ObjCOneArgSelector:
1727 case DeclarationName::ObjCMultiArgSelector:
1728 case DeclarationName::CXXUsingDirective:
1729 case DeclarationName::CXXDeductionGuideName:
1730 return Error::success();
1731
1732 case DeclarationName::CXXOperatorName: {
1733 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1734 To.setCXXOperatorNameRange(*ToRangeOrErr);
1735 else
1736 return ToRangeOrErr.takeError();
1737 return Error::success();
1738 }
1739 case DeclarationName::CXXLiteralOperatorName: {
1740 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1741 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1742 else
1743 return LocOrErr.takeError();
1744 return Error::success();
1745 }
1746 case DeclarationName::CXXConstructorName:
1747 case DeclarationName::CXXDestructorName:
1748 case DeclarationName::CXXConversionFunctionName: {
1749 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1750 To.setNamedTypeInfo(*ToTInfoOrErr);
1751 else
1752 return ToTInfoOrErr.takeError();
1753 return Error::success();
1754 }
1755 }
1756 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 1756)
;
1757}
1758
1759Error
1760ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1761 if (Importer.isMinimalImport() && !ForceImport) {
1762 auto ToDCOrErr = Importer.ImportContext(FromDC);
1763 return ToDCOrErr.takeError();
1764 }
1765
1766 // We use strict error handling in case of records and enums, but not
1767 // with e.g. namespaces.
1768 //
1769 // FIXME Clients of the ASTImporter should be able to choose an
1770 // appropriate error handling strategy for their needs. For instance,
1771 // they may not want to mark an entire namespace as erroneous merely
1772 // because there is an ODR error with two typedefs. As another example,
1773 // the client may allow EnumConstantDecls with same names but with
1774 // different values in two distinct translation units.
1775 bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1776
1777 Error ChildErrors = Error::success();
1778 for (auto *From : FromDC->decls()) {
1779 ExpectedDecl ImportedOrErr = import(From);
1780
1781 // If we are in the process of ImportDefinition(...) for a RecordDecl we
1782 // want to make sure that we are also completing each FieldDecl. There
1783 // are currently cases where this does not happen and this is correctness
1784 // fix since operations such as code generation will expect this to be so.
1785 if (ImportedOrErr) {
1786 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
1787 Decl *ImportedDecl = *ImportedOrErr;
1788 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
1789 if (FieldFrom && FieldTo) {
1790 RecordDecl *FromRecordDecl = nullptr;
1791 RecordDecl *ToRecordDecl = nullptr;
1792 // If we have a field that is an ArrayType we need to check if the array
1793 // element is a RecordDecl and if so we need to import the defintion.
1794 if (FieldFrom->getType()->isArrayType()) {
1795 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
1796 FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1797 ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1798 }
1799
1800 if (!FromRecordDecl || !ToRecordDecl) {
1801 const RecordType *RecordFrom =
1802 FieldFrom->getType()->getAs<RecordType>();
1803 const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
1804
1805 if (RecordFrom && RecordTo) {
1806 FromRecordDecl = RecordFrom->getDecl();
1807 ToRecordDecl = RecordTo->getDecl();
1808 }
1809 }
1810
1811 if (FromRecordDecl && ToRecordDecl) {
1812 if (FromRecordDecl->isCompleteDefinition() &&
1813 !ToRecordDecl->isCompleteDefinition()) {
1814 Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
1815
1816 if (Err && AccumulateChildErrors)
1817 ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err));
1818 else
1819 consumeError(std::move(Err));
1820 }
1821 }
1822 }
1823 } else {
1824 if (AccumulateChildErrors)
1825 ChildErrors =
1826 joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1827 else
1828 consumeError(ImportedOrErr.takeError());
1829 }
1830 }
1831
1832 // We reorder declarations in RecordDecls because they may have another order
1833 // in the "to" context than they have in the "from" context. This may happen
1834 // e.g when we import a class like this:
1835 // struct declToImport {
1836 // int a = c + b;
1837 // int b = 1;
1838 // int c = 2;
1839 // };
1840 // During the import of `a` we import first the dependencies in sequence,
1841 // thus the order would be `c`, `b`, `a`. We will get the normal order by
1842 // first removing the already imported members and then adding them in the
1843 // order as they apper in the "from" context.
1844 //
1845 // Keeping field order is vital because it determines structure layout.
1846 //
1847 // Here and below, we cannot call field_begin() method and its callers on
1848 // ToDC if it has an external storage. Calling field_begin() will
1849 // automatically load all the fields by calling
1850 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1851 // call ASTImporter::Import(). This is because the ExternalASTSource
1852 // interface in LLDB is implemented by the means of the ASTImporter. However,
1853 // calling an import at this point would result in an uncontrolled import, we
1854 // must avoid that.
1855 const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1856 if (!FromRD)
1857 return ChildErrors;
1858
1859 auto ToDCOrErr = Importer.ImportContext(FromDC);
1860 if (!ToDCOrErr) {
1861 consumeError(std::move(ChildErrors));
1862 return ToDCOrErr.takeError();
1863 }
1864
1865 DeclContext *ToDC = *ToDCOrErr;
1866 // Remove all declarations, which may be in wrong order in the
1867 // lexical DeclContext and then add them in the proper order.
1868 for (auto *D : FromRD->decls()) {
1869 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1870 assert(D && "DC contains a null decl")(static_cast <bool> (D && "DC contains a null decl"
) ? void (0) : __assert_fail ("D && \"DC contains a null decl\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 1870, __extension__ __PRETTY_FUNCTION__))
;
1871 Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1872 // Remove only the decls which we successfully imported.
1873 if (ToD) {
1874 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD))(static_cast <bool> (ToDC == ToD->getLexicalDeclContext
() && ToDC->containsDecl(ToD)) ? void (0) : __assert_fail
("ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD)"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 1874, __extension__ __PRETTY_FUNCTION__))
;
1875 // Remove the decl from its wrong place in the linked list.
1876 ToDC->removeDecl(ToD);
1877 // Add the decl to the end of the linked list.
1878 // This time it will be at the proper place because the enclosing for
1879 // loop iterates in the original (good) order of the decls.
1880 ToDC->addDeclInternal(ToD);
1881 }
1882 }
1883 }
1884
1885 return ChildErrors;
1886}
1887
1888Error ASTNodeImporter::ImportDeclContext(
1889 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1890 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1891 if (!ToDCOrErr)
44
Taking true branch
1892 return ToDCOrErr.takeError();
45
Returning without writing to 'ToLexicalDC'
1893 ToDC = *ToDCOrErr;
1894
1895 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1896 auto ToLexicalDCOrErr = Importer.ImportContext(
1897 FromD->getLexicalDeclContext());
1898 if (!ToLexicalDCOrErr)
1899 return ToLexicalDCOrErr.takeError();
1900 ToLexicalDC = *ToLexicalDCOrErr;
1901 } else
1902 ToLexicalDC = ToDC;
1903
1904 return Error::success();
1905}
1906
1907Error ASTNodeImporter::ImportImplicitMethods(
1908 const CXXRecordDecl *From, CXXRecordDecl *To) {
1909 assert(From->isCompleteDefinition() && To->getDefinition() == To &&(static_cast <bool> (From->isCompleteDefinition() &&
To->getDefinition() == To && "Import implicit methods to or from non-definition"
) ? void (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 1910, __extension__ __PRETTY_FUNCTION__))
1910 "Import implicit methods to or from non-definition")(static_cast <bool> (From->isCompleteDefinition() &&
To->getDefinition() == To && "Import implicit methods to or from non-definition"
) ? void (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 1910, __extension__ __PRETTY_FUNCTION__))
;
1911
1912 for (CXXMethodDecl *FromM : From->methods())
1913 if (FromM->isImplicit()) {
1914 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1915 if (!ToMOrErr)
1916 return ToMOrErr.takeError();
1917 }
1918
1919 return Error::success();
1920}
1921
1922static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
1923 ASTImporter &Importer) {
1924 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1925 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1926 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1927 else
1928 return ToTypedefOrErr.takeError();
1929 }
1930 return Error::success();
1931}
1932
1933Error ASTNodeImporter::ImportDefinition(
1934 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
1935 auto DefinitionCompleter = [To]() {
1936 // There are cases in LLDB when we first import a class without its
1937 // members. The class will have DefinitionData, but no members. Then,
1938 // importDefinition is called from LLDB, which tries to get the members, so
1939 // when we get here, the class already has the DefinitionData set, so we
1940 // must unset the CompleteDefinition here to be able to complete again the
1941 // definition.
1942 To->setCompleteDefinition(false);
1943 To->completeDefinition();
1944 };
1945
1946 if (To->getDefinition() || To->isBeingDefined()) {
1947 if (Kind == IDK_Everything ||
1948 // In case of lambdas, the class already has a definition ptr set, but
1949 // the contained decls are not imported yet. Also, isBeingDefined was
1950 // set in CXXRecordDecl::CreateLambda. We must import the contained
1951 // decls here and finish the definition.
1952 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
1953 if (To->isLambda()) {
1954 auto *FromCXXRD = cast<CXXRecordDecl>(From);
1955 SmallVector<LambdaCapture, 8> ToCaptures;
1956 ToCaptures.reserve(FromCXXRD->capture_size());
1957 for (const auto &FromCapture : FromCXXRD->captures()) {
1958 if (auto ToCaptureOrErr = import(FromCapture))
1959 ToCaptures.push_back(*ToCaptureOrErr);
1960 else
1961 return ToCaptureOrErr.takeError();
1962 }
1963 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
1964 ToCaptures);
1965 }
1966
1967 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
1968 // Finish the definition of the lambda, set isBeingDefined to false.
1969 if (To->isLambda())
1970 DefinitionCompleter();
1971 return Result;
1972 }
1973
1974 return Error::success();
1975 }
1976
1977 To->startDefinition();
1978 // Complete the definition even if error is returned.
1979 // The RecordDecl may be already part of the AST so it is better to
1980 // have it in complete state even if something is wrong with it.
1981 auto DefinitionCompleterScopeExit =
1982 llvm::make_scope_exit(DefinitionCompleter);
1983
1984 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1985 return Err;
1986
1987 // Add base classes.
1988 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1989 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1990 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1991
1992 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1993 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1994
1995 #define FIELD(Name, Width, Merge) \
1996 ToData.Name = FromData.Name;
1997 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1998
1999 // Copy over the data stored in RecordDeclBits
2000 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2001
2002 SmallVector<CXXBaseSpecifier *, 4> Bases;
2003 for (const auto &Base1 : FromCXX->bases()) {
2004 ExpectedType TyOrErr = import(Base1.getType());
2005 if (!TyOrErr)
2006 return TyOrErr.takeError();
2007
2008 SourceLocation EllipsisLoc;
2009 if (Base1.isPackExpansion()) {
2010 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2011 EllipsisLoc = *LocOrErr;
2012 else
2013 return LocOrErr.takeError();
2014 }
2015
2016 // Ensure that we have a definition for the base.
2017 if (Error Err =
2018 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2019 return Err;
2020
2021 auto RangeOrErr = import(Base1.getSourceRange());
2022 if (!RangeOrErr)
2023 return RangeOrErr.takeError();
2024
2025 auto TSIOrErr = import(Base1.getTypeSourceInfo());
2026 if (!TSIOrErr)
2027 return TSIOrErr.takeError();
2028
2029 Bases.push_back(
2030 new (Importer.getToContext()) CXXBaseSpecifier(
2031 *RangeOrErr,
2032 Base1.isVirtual(),
2033 Base1.isBaseOfClass(),
2034 Base1.getAccessSpecifierAsWritten(),
2035 *TSIOrErr,
2036 EllipsisLoc));
2037 }
2038 if (!Bases.empty())
2039 ToCXX->setBases(Bases.data(), Bases.size());
2040 }
2041
2042 if (shouldForceImportDeclContext(Kind))
2043 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2044 return Err;
2045
2046 return Error::success();
2047}
2048
2049Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
2050 if (To->getAnyInitializer())
2051 return Error::success();
2052
2053 Expr *FromInit = From->getInit();
2054 if (!FromInit)
2055 return Error::success();
2056
2057 ExpectedExpr ToInitOrErr = import(FromInit);
2058 if (!ToInitOrErr)
2059 return ToInitOrErr.takeError();
2060
2061 To->setInit(*ToInitOrErr);
2062 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2063 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2064 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2065 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2066 // FIXME: Also import the initializer value.
2067 }
2068
2069 // FIXME: Other bits to merge?
2070 return Error::success();
2071}
2072
2073Error ASTNodeImporter::ImportDefinition(
2074 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2075 if (To->getDefinition() || To->isBeingDefined()) {
2076 if (Kind == IDK_Everything)
2077 return ImportDeclContext(From, /*ForceImport=*/true);
2078 return Error::success();
2079 }
2080
2081 To->startDefinition();
2082
2083 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2084 return Err;
2085
2086 ExpectedType ToTypeOrErr =
2087 import(Importer.getFromContext().getTypeDeclType(From));
2088 if (!ToTypeOrErr)
2089 return ToTypeOrErr.takeError();
2090
2091 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2092 if (!ToPromotionTypeOrErr)
2093 return ToPromotionTypeOrErr.takeError();
2094
2095 if (shouldForceImportDeclContext(Kind))
2096 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2097 return Err;
2098
2099 // FIXME: we might need to merge the number of positive or negative bits
2100 // if the enumerator lists don't match.
2101 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2102 From->getNumPositiveBits(),
2103 From->getNumNegativeBits());
2104 return Error::success();
2105}
2106
2107Error ASTNodeImporter::ImportTemplateArguments(
2108 const TemplateArgument *FromArgs, unsigned NumFromArgs,
2109 SmallVectorImpl<TemplateArgument> &ToArgs) {
2110 for (unsigned I = 0; I != NumFromArgs; ++I) {
2111 if (auto ToOrErr = import(FromArgs[I]))
2112 ToArgs.push_back(*ToOrErr);
2113 else
2114 return ToOrErr.takeError();
2115 }
2116
2117 return Error::success();
2118}
2119
2120// FIXME: Do not forget to remove this and use only 'import'.
2121Expected<TemplateArgument>
2122ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2123 return import(From);
2124}
2125
2126template <typename InContainerTy>
2127Error ASTNodeImporter::ImportTemplateArgumentListInfo(
2128 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2129 for (const auto &FromLoc : Container) {
2130 if (auto ToLocOrErr = import(FromLoc))
2131 ToTAInfo.addArgument(*ToLocOrErr);
2132 else
2133 return ToLocOrErr.takeError();
2134 }
2135 return Error::success();
2136}
2137
2138static StructuralEquivalenceKind
2139getStructuralEquivalenceKind(const ASTImporter &Importer) {
2140 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
2141 : StructuralEquivalenceKind::Default;
2142}
2143
2144bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
2145 StructuralEquivalenceContext Ctx(
2146 Importer.getFromContext(), Importer.getToContext(),
2147 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2148 false, Complain);
2149 return Ctx.IsEquivalent(From, To);
2150}
2151
2152bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2153 RecordDecl *ToRecord, bool Complain) {
2154 // Eliminate a potential failure point where we attempt to re-import
2155 // something we're trying to import while completing ToRecord.
2156 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2157 if (ToOrigin) {
2158 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2159 if (ToOriginRecord)
2160 ToRecord = ToOriginRecord;
2161 }
2162
2163 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2164 ToRecord->getASTContext(),
2165 Importer.getNonEquivalentDecls(),
2166 getStructuralEquivalenceKind(Importer),
2167 false, Complain);
2168 return Ctx.IsEquivalent(FromRecord, ToRecord);
2169}
2170
2171bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2172 bool Complain) {
2173 StructuralEquivalenceContext Ctx(
2174 Importer.getFromContext(), Importer.getToContext(),
2175 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2176 false, Complain);
2177 return Ctx.IsEquivalent(FromVar, ToVar);
2178}
2179
2180bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2181 // Eliminate a potential failure point where we attempt to re-import
2182 // something we're trying to import while completing ToEnum.
2183 if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2184 if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2185 ToEnum = ToOriginEnum;
2186
2187 StructuralEquivalenceContext Ctx(
2188 Importer.getFromContext(), Importer.getToContext(),
2189 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2190 return Ctx.IsEquivalent(FromEnum, ToEnum);
2191}
2192
2193bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
2194 FunctionTemplateDecl *To) {
2195 StructuralEquivalenceContext Ctx(
2196 Importer.getFromContext(), Importer.getToContext(),
2197 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2198 false, false);
2199 return Ctx.IsEquivalent(From, To);
2200}
2201
2202bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
2203 StructuralEquivalenceContext Ctx(
2204 Importer.getFromContext(), Importer.getToContext(),
2205 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2206 false, false);
2207 return Ctx.IsEquivalent(From, To);
2208}
2209
2210bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2211 EnumConstantDecl *ToEC) {
2212 const llvm::APSInt &FromVal = FromEC->getInitVal();
2213 const llvm::APSInt &ToVal = ToEC->getInitVal();
2214
2215 return FromVal.isSigned() == ToVal.isSigned() &&
2216 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2217 FromVal == ToVal;
2218}
2219
2220bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2221 ClassTemplateDecl *To) {
2222 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2223 Importer.getToContext(),
2224 Importer.getNonEquivalentDecls(),
2225 getStructuralEquivalenceKind(Importer));
2226 return Ctx.IsEquivalent(From, To);
2227}
2228
2229bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2230 VarTemplateDecl *To) {
2231 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2232 Importer.getToContext(),
2233 Importer.getNonEquivalentDecls(),
2234 getStructuralEquivalenceKind(Importer));
2235 return Ctx.IsEquivalent(From, To);
2236}
2237
2238ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2239 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2240 << D->getDeclKindName();
2241 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2242}
2243
2244ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2245 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2246 << D->getDeclKindName();
2247 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2248}
2249
2250ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2251 // Import the context of this declaration.
2252 DeclContext *DC, *LexicalDC;
2253 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2254 return std::move(Err);
2255
2256 // Import the location of this declaration.
2257 ExpectedSLoc LocOrErr = import(D->getLocation());
2258 if (!LocOrErr)
2259 return LocOrErr.takeError();
2260
2261 EmptyDecl *ToD;
2262 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2263 return ToD;
2264
2265 ToD->setLexicalDeclContext(LexicalDC);
2266 LexicalDC->addDeclInternal(ToD);
2267 return ToD;
2268}
2269
2270ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2271 TranslationUnitDecl *ToD =
2272 Importer.getToContext().getTranslationUnitDecl();
2273
2274 Importer.MapImported(D, ToD);
2275
2276 return ToD;
2277}
2278
2279ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2280 ExpectedSLoc LocOrErr = import(D->getLocation());
2281 if (!LocOrErr)
2282 return LocOrErr.takeError();
2283 auto ColonLocOrErr = import(D->getColonLoc());
2284 if (!ColonLocOrErr)
2285 return ColonLocOrErr.takeError();
2286
2287 // Import the context of this declaration.
2288 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2289 if (!DCOrErr)
2290 return DCOrErr.takeError();
2291 DeclContext *DC = *DCOrErr;
2292
2293 AccessSpecDecl *ToD;
2294 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2295 DC, *LocOrErr, *ColonLocOrErr))
2296 return ToD;
2297
2298 // Lexical DeclContext and Semantic DeclContext
2299 // is always the same for the accessSpec.
2300 ToD->setLexicalDeclContext(DC);
2301 DC->addDeclInternal(ToD);
2302
2303 return ToD;
2304}
2305
2306ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2307 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2308 if (!DCOrErr)
2309 return DCOrErr.takeError();
2310 DeclContext *DC = *DCOrErr;
2311 DeclContext *LexicalDC = DC;
2312
2313 Error Err = Error::success();
2314 auto ToLocation = importChecked(Err, D->getLocation());
2315 auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2316 auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2317 auto ToMessage = importChecked(Err, D->getMessage());
2318 if (Err)
2319 return std::move(Err);
2320
2321 StaticAssertDecl *ToD;
2322 if (GetImportedOrCreateDecl(
2323 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2324 ToRParenLoc, D->isFailed()))
2325 return ToD;
2326
2327 ToD->setLexicalDeclContext(LexicalDC);
2328 LexicalDC->addDeclInternal(ToD);
2329 return ToD;
2330}
2331
2332ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2333 // Import the major distinguishing characteristics of this namespace.
2334 DeclContext *DC, *LexicalDC;
2335 DeclarationName Name;
2336 SourceLocation Loc;
2337 NamedDecl *ToD;
2338 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2339 return std::move(Err);
2340 if (ToD)
2341 return ToD;
2342
2343 NamespaceDecl *MergeWithNamespace = nullptr;
2344 if (!Name) {
2345 // This is an anonymous namespace. Adopt an existing anonymous
2346 // namespace if we can.
2347 // FIXME: Not testable.
2348 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2349 MergeWithNamespace = TU->getAnonymousNamespace();
2350 else
2351 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2352 } else {
2353 SmallVector<NamedDecl *, 4> ConflictingDecls;
2354 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2355 for (auto *FoundDecl : FoundDecls) {
2356 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2357 continue;
2358
2359 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2360 MergeWithNamespace = FoundNS;
2361 ConflictingDecls.clear();
2362 break;
2363 }
2364
2365 ConflictingDecls.push_back(FoundDecl);
2366 }
2367
2368 if (!ConflictingDecls.empty()) {
2369 ExpectedName NameOrErr = Importer.HandleNameConflict(
2370 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2371 ConflictingDecls.size());
2372 if (NameOrErr)
2373 Name = NameOrErr.get();
2374 else
2375 return NameOrErr.takeError();
2376 }
2377 }
2378
2379 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2380 if (!BeginLocOrErr)
2381 return BeginLocOrErr.takeError();
2382 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2383 if (!RBraceLocOrErr)
2384 return RBraceLocOrErr.takeError();
2385
2386 // Create the "to" namespace, if needed.
2387 NamespaceDecl *ToNamespace = MergeWithNamespace;
2388 if (!ToNamespace) {
2389 if (GetImportedOrCreateDecl(
2390 ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2391 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2392 /*PrevDecl=*/nullptr))
2393 return ToNamespace;
2394 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2395 ToNamespace->setLexicalDeclContext(LexicalDC);
2396 LexicalDC->addDeclInternal(ToNamespace);
2397
2398 // If this is an anonymous namespace, register it as the anonymous
2399 // namespace within its context.
2400 if (!Name) {
2401 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2402 TU->setAnonymousNamespace(ToNamespace);
2403 else
2404 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2405 }
2406 }
2407 Importer.MapImported(D, ToNamespace);
2408
2409 if (Error Err = ImportDeclContext(D))
2410 return std::move(Err);
2411
2412 return ToNamespace;
2413}
2414
2415ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2416 // Import the major distinguishing characteristics of this namespace.
2417 DeclContext *DC, *LexicalDC;
2418 DeclarationName Name;
2419 SourceLocation Loc;
2420 NamedDecl *LookupD;
2421 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2422 return std::move(Err);
2423 if (LookupD)
2424 return LookupD;
2425
2426 // NOTE: No conflict resolution is done for namespace aliases now.
2427
2428 Error Err = Error::success();
2429 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2430 auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2431 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2432 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2433 auto ToNamespace = importChecked(Err, D->getNamespace());
2434 if (Err)
2435 return std::move(Err);
2436
2437 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2438
2439 NamespaceAliasDecl *ToD;
2440 if (GetImportedOrCreateDecl(
2441 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2442 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2443 return ToD;
2444
2445 ToD->setLexicalDeclContext(LexicalDC);
2446 LexicalDC->addDeclInternal(ToD);
2447
2448 return ToD;
2449}
2450
2451ExpectedDecl
2452ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2453 // Import the major distinguishing characteristics of this typedef.
2454 DeclarationName Name;
2455 SourceLocation Loc;
2456 NamedDecl *ToD;
2457 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2458 // is created.
2459 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
12
Calling 'ASTNodeImporter::ImportDeclParts'
20
Returning from 'ASTNodeImporter::ImportDeclParts'
21
Assuming the condition is false
22
Taking false branch
2460 return std::move(Err);
2461 if (ToD
22.1
'ToD' is null
22.1
'ToD' is null
22.1
'ToD' is null
)
23
Taking false branch
2462 return ToD;
2463
2464 DeclContext *DC = cast_or_null<DeclContext>(
25
Assuming null pointer is passed into cast
2465 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
24
The object is a 'Decl'
2466 DeclContext *LexicalDC =
28
'LexicalDC' initialized to a null pointer value
2467 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
27
Assuming null pointer is passed into cast
2468 cast<Decl>(D->getLexicalDeclContext())));
26
The object is a 'Decl'
2469
2470 // If this typedef is not in block scope, determine whether we've
2471 // seen a typedef with the same name (that we can merge with) or any
2472 // other entity by that name (which name lookup could conflict with).
2473 // Note: Repeated typedefs are not valid in C99:
2474 // 'typedef int T; typedef int T;' is invalid
2475 // We do not care about this now.
2476 if (DC
28.1
'DC' is null
28.1
'DC' is null
28.1
'DC' is null
&& !DC->isFunctionOrMethod()) {
2477 SmallVector<NamedDecl *, 4> ConflictingDecls;
2478 unsigned IDNS = Decl::IDNS_Ordinary;
2479 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2480 for (auto *FoundDecl : FoundDecls) {
2481 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2482 continue;
2483 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2484 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2485 continue;
2486
2487 QualType FromUT = D->getUnderlyingType();
2488 QualType FoundUT = FoundTypedef->getUnderlyingType();
2489 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2490 // If the "From" context has a complete underlying type but we
2491 // already have a complete underlying type then return with that.
2492 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2493 return Importer.MapImported(D, FoundTypedef);
2494 // FIXME Handle redecl chain. When you do that make consistent changes
2495 // in ASTImporterLookupTable too.
2496 } else {
2497 ConflictingDecls.push_back(FoundDecl);
2498 }
2499 }
2500 }
2501
2502 if (!ConflictingDecls.empty()) {
2503 ExpectedName NameOrErr = Importer.HandleNameConflict(
2504 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2505 if (NameOrErr)
2506 Name = NameOrErr.get();
2507 else
2508 return NameOrErr.takeError();
2509 }
2510 }
2511
2512 Error Err = Error::success();
2513 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
2514 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2515 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2516 if (Err)
29
Assuming the condition is false
30
Taking false branch
2517 return std::move(Err);
2518
2519 // Create the new typedef node.
2520 // FIXME: ToUnderlyingType is not used.
2521 (void)ToUnderlyingType;
2522 TypedefNameDecl *ToTypedef;
2523 if (IsAlias
30.1
'IsAlias' is false
30.1
'IsAlias' is false
30.1
'IsAlias' is false
) {
31
Taking false branch
2524 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2525 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2526 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2527 return ToTypedef;
2528 } else if (GetImportedOrCreateDecl<TypedefDecl>(
32
Calling 'ASTNodeImporter::GetImportedOrCreateDecl'
41
Returning from 'ASTNodeImporter::GetImportedOrCreateDecl'
42
Taking false branch
2529 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2530 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2531 return ToTypedef;
2532
2533 // Import the DeclContext and set it to the Typedef.
2534 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
43
Calling 'ASTNodeImporter::ImportDeclContext'
46
Returning from 'ASTNodeImporter::ImportDeclContext'
47
Assuming the condition is false
48
Taking false branch
2535 return std::move(Err);
2536 ToTypedef->setDeclContext(DC);
2537 ToTypedef->setLexicalDeclContext(LexicalDC);
2538 // Add to the lookupTable because we could not do that in MapImported.
2539 Importer.AddToLookupTable(ToTypedef);
2540
2541 ToTypedef->setAccess(D->getAccess());
2542
2543 // Templated declarations should not appear in DeclContext.
2544 TypeAliasDecl *FromAlias = IsAlias
48.1
'IsAlias' is false
48.1
'IsAlias' is false
48.1
'IsAlias' is false
? cast<TypeAliasDecl>(D) : nullptr;
49
'?' condition is false
2545 if (!FromAlias
49.1
'FromAlias' is null
49.1
'FromAlias' is null
49.1
'FromAlias' is null
|| !FromAlias->getDescribedAliasTemplate())
2546 LexicalDC->addDeclInternal(ToTypedef);
50
Called C++ object pointer is null
2547
2548 return ToTypedef;
2549}
2550
2551ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2552 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
11
Calling 'ASTNodeImporter::VisitTypedefNameDecl'
2553}
2554
2555ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2556 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2557}
2558
2559ExpectedDecl
2560ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2561 // Import the major distinguishing characteristics of this typedef.
2562 DeclContext *DC, *LexicalDC;
2563 DeclarationName Name;
2564 SourceLocation Loc;
2565 NamedDecl *FoundD;
2566 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2567 return std::move(Err);
2568 if (FoundD)
2569 return FoundD;
2570
2571 // If this typedef is not in block scope, determine whether we've
2572 // seen a typedef with the same name (that we can merge with) or any
2573 // other entity by that name (which name lookup could conflict with).
2574 if (!DC->isFunctionOrMethod()) {
2575 SmallVector<NamedDecl *, 4> ConflictingDecls;
2576 unsigned IDNS = Decl::IDNS_Ordinary;
2577 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2578 for (auto *FoundDecl : FoundDecls) {
2579 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2580 continue;
2581 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2582 return Importer.MapImported(D, FoundAlias);
2583 ConflictingDecls.push_back(FoundDecl);
2584 }
2585
2586 if (!ConflictingDecls.empty()) {
2587 ExpectedName NameOrErr = Importer.HandleNameConflict(
2588 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2589 if (NameOrErr)
2590 Name = NameOrErr.get();
2591 else
2592 return NameOrErr.takeError();
2593 }
2594 }
2595
2596 Error Err = Error::success();
2597 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2598 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2599 if (Err)
2600 return std::move(Err);
2601
2602 TypeAliasTemplateDecl *ToAlias;
2603 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2604 Name, ToTemplateParameters, ToTemplatedDecl))
2605 return ToAlias;
2606
2607 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2608
2609 ToAlias->setAccess(D->getAccess());
2610 ToAlias->setLexicalDeclContext(LexicalDC);
2611 LexicalDC->addDeclInternal(ToAlias);
2612 return ToAlias;
2613}
2614
2615ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2616 // Import the major distinguishing characteristics of this label.
2617 DeclContext *DC, *LexicalDC;
2618 DeclarationName Name;
2619 SourceLocation Loc;
2620 NamedDecl *ToD;
2621 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2622 return std::move(Err);
2623 if (ToD)
2624 return ToD;
2625
2626 assert(LexicalDC->isFunctionOrMethod())(static_cast <bool> (LexicalDC->isFunctionOrMethod()
) ? void (0) : __assert_fail ("LexicalDC->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 2626, __extension__ __PRETTY_FUNCTION__))
;
2627
2628 LabelDecl *ToLabel;
2629 if (D->isGnuLocal()) {
2630 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2631 if (!BeginLocOrErr)
2632 return BeginLocOrErr.takeError();
2633 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2634 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2635 return ToLabel;
2636
2637 } else {
2638 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2639 Name.getAsIdentifierInfo()))
2640 return ToLabel;
2641
2642 }
2643
2644 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2645 if (!ToStmtOrErr)
2646 return ToStmtOrErr.takeError();
2647
2648 ToLabel->setStmt(*ToStmtOrErr);
2649 ToLabel->setLexicalDeclContext(LexicalDC);
2650 LexicalDC->addDeclInternal(ToLabel);
2651 return ToLabel;
2652}
2653
2654ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2655 // Import the major distinguishing characteristics of this enum.
2656 DeclContext *DC, *LexicalDC;
2657 DeclarationName Name;
2658 SourceLocation Loc;
2659 NamedDecl *ToD;
2660 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2661 return std::move(Err);
2662 if (ToD)
2663 return ToD;
2664
2665 // Figure out what enum name we're looking for.
2666 unsigned IDNS = Decl::IDNS_Tag;
2667 DeclarationName SearchName = Name;
2668 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2669 if (Error Err = importInto(
2670 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2671 return std::move(Err);
2672 IDNS = Decl::IDNS_Ordinary;
2673 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2674 IDNS |= Decl::IDNS_Ordinary;
2675
2676 // We may already have an enum of the same name; try to find and match it.
2677 EnumDecl *PrevDecl = nullptr;
2678 if (!DC->isFunctionOrMethod() && SearchName) {
2679 SmallVector<NamedDecl *, 4> ConflictingDecls;
2680 auto FoundDecls =
2681 Importer.findDeclsInToCtx(DC, SearchName);
2682 for (auto *FoundDecl : FoundDecls) {
2683 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2684 continue;
2685
2686 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2687 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2688 FoundDecl = Tag->getDecl();
2689 }
2690
2691 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2692 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2693 continue;
2694 if (IsStructuralMatch(D, FoundEnum)) {
2695 EnumDecl *FoundDef = FoundEnum->getDefinition();
2696 if (D->isThisDeclarationADefinition() && FoundDef)
2697 return Importer.MapImported(D, FoundDef);
2698 PrevDecl = FoundEnum->getMostRecentDecl();
2699 break;
2700 }
2701 ConflictingDecls.push_back(FoundDecl);
2702 }
2703 }
2704
2705 if (!ConflictingDecls.empty()) {
2706 ExpectedName NameOrErr = Importer.HandleNameConflict(
2707 SearchName, DC, IDNS, ConflictingDecls.data(),
2708 ConflictingDecls.size());
2709 if (NameOrErr)
2710 Name = NameOrErr.get();
2711 else
2712 return NameOrErr.takeError();
2713 }
2714 }
2715
2716 Error Err = Error::success();
2717 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2718 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2719 auto ToIntegerType = importChecked(Err, D->getIntegerType());
2720 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2721 if (Err)
2722 return std::move(Err);
2723
2724 // Create the enum declaration.
2725 EnumDecl *D2;
2726 if (GetImportedOrCreateDecl(
2727 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2728 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2729 D->isScopedUsingClassTag(), D->isFixed()))
2730 return D2;
2731
2732 D2->setQualifierInfo(ToQualifierLoc);
2733 D2->setIntegerType(ToIntegerType);
2734 D2->setBraceRange(ToBraceRange);
2735 D2->setAccess(D->getAccess());
2736 D2->setLexicalDeclContext(LexicalDC);
2737 addDeclToContexts(D, D2);
2738
2739 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
2740 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2741 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2742 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
2743 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
2744 else
2745 return ToInstOrErr.takeError();
2746 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
2747 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
2748 else
2749 return POIOrErr.takeError();
2750 }
2751
2752 // Import the definition
2753 if (D->isCompleteDefinition())
2754 if (Error Err = ImportDefinition(D, D2))
2755 return std::move(Err);
2756
2757 return D2;
2758}
2759
2760ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2761 bool IsFriendTemplate = false;
2762 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2763 IsFriendTemplate =
2764 DCXX->getDescribedClassTemplate() &&
2765 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2766 Decl::FOK_None;
2767 }
2768
2769 // Import the major distinguishing characteristics of this record.
2770 DeclContext *DC = nullptr, *LexicalDC = nullptr;
2771 DeclarationName Name;
2772 SourceLocation Loc;
2773 NamedDecl *ToD = nullptr;
2774 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2775 return std::move(Err);
2776 if (ToD)
2777 return ToD;
2778
2779 // Figure out what structure name we're looking for.
2780 unsigned IDNS = Decl::IDNS_Tag;
2781 DeclarationName SearchName = Name;
2782 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2783 if (Error Err = importInto(
2784 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2785 return std::move(Err);
2786 IDNS = Decl::IDNS_Ordinary;
2787 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2788 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
2789
2790 // We may already have a record of the same name; try to find and match it.
2791 RecordDecl *PrevDecl = nullptr;
2792 if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2793 SmallVector<NamedDecl *, 4> ConflictingDecls;
2794 auto FoundDecls =
2795 Importer.findDeclsInToCtx(DC, SearchName);
2796 if (!FoundDecls.empty()) {
2797 // We're going to have to compare D against potentially conflicting Decls,
2798 // so complete it.
2799 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2800 D->getASTContext().getExternalSource()->CompleteType(D);
2801 }
2802
2803 for (auto *FoundDecl : FoundDecls) {
2804 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2805 continue;
2806
2807 Decl *Found = FoundDecl;
2808 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2809 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2810 Found = Tag->getDecl();
2811 }
2812
2813 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2814 // Do not emit false positive diagnostic in case of unnamed
2815 // struct/union and in case of anonymous structs. Would be false
2816 // because there may be several anonymous/unnamed structs in a class.
2817 // E.g. these are both valid:
2818 // struct A { // unnamed structs
2819 // struct { struct A *next; } entry0;
2820 // struct { struct A *next; } entry1;
2821 // };
2822 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2823 if (!SearchName)
2824 if (!IsStructuralMatch(D, FoundRecord, false))
2825 continue;
2826
2827 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
2828 continue;
2829
2830 if (IsStructuralMatch(D, FoundRecord)) {
2831 RecordDecl *FoundDef = FoundRecord->getDefinition();
2832 if (D->isThisDeclarationADefinition() && FoundDef) {
2833 // FIXME: Structural equivalence check should check for same
2834 // user-defined methods.
2835 Importer.MapImported(D, FoundDef);
2836 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2837 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2838 assert(FoundCXX && "Record type mismatch")(static_cast <bool> (FoundCXX && "Record type mismatch"
) ? void (0) : __assert_fail ("FoundCXX && \"Record type mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 2838, __extension__ __PRETTY_FUNCTION__))
;
2839
2840 if (!Importer.isMinimalImport())
2841 // FoundDef may not have every implicit method that D has
2842 // because implicit methods are created only if they are used.
2843 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2844 return std::move(Err);
2845 }
2846 }
2847 PrevDecl = FoundRecord->getMostRecentDecl();
2848 break;
2849 }
2850 ConflictingDecls.push_back(FoundDecl);
2851 } // kind is RecordDecl
2852 } // for
2853
2854 if (!ConflictingDecls.empty() && SearchName) {
2855 ExpectedName NameOrErr = Importer.HandleNameConflict(
2856 SearchName, DC, IDNS, ConflictingDecls.data(),
2857 ConflictingDecls.size());
2858 if (NameOrErr)
2859 Name = NameOrErr.get();
2860 else
2861 return NameOrErr.takeError();
2862 }
2863 }
2864
2865 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2866 if (!BeginLocOrErr)
2867 return BeginLocOrErr.takeError();
2868
2869 // Create the record declaration.
2870 RecordDecl *D2 = nullptr;
2871 CXXRecordDecl *D2CXX = nullptr;
2872 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2873 if (DCXX->isLambda()) {
2874 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2875 if (!TInfoOrErr)
2876 return TInfoOrErr.takeError();
2877 if (GetImportedOrCreateSpecialDecl(
2878 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2879 DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2880 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2881 return D2CXX;
2882 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2883 if (!CDeclOrErr)
2884 return CDeclOrErr.takeError();
2885 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
2886 DCXX->hasKnownLambdaInternalLinkage());
2887 D2CXX->setDeviceLambdaManglingNumber(
2888 DCXX->getDeviceLambdaManglingNumber());
2889 } else if (DCXX->isInjectedClassName()) {
2890 // We have to be careful to do a similar dance to the one in
2891 // Sema::ActOnStartCXXMemberDeclarations
2892 const bool DelayTypeCreation = true;
2893 if (GetImportedOrCreateDecl(
2894 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2895 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2896 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2897 return D2CXX;
2898 Importer.getToContext().getTypeDeclType(
2899 D2CXX, dyn_cast<CXXRecordDecl>(DC));
2900 } else {
2901 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2902 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2903 Name.getAsIdentifierInfo(),
2904 cast_or_null<CXXRecordDecl>(PrevDecl)))
2905 return D2CXX;
2906 }
2907
2908 D2 = D2CXX;
2909 D2->setAccess(D->getAccess());
2910 D2->setLexicalDeclContext(LexicalDC);
2911 addDeclToContexts(D, D2);
2912
2913 if (ClassTemplateDecl *FromDescribed =
2914 DCXX->getDescribedClassTemplate()) {
2915 ClassTemplateDecl *ToDescribed;
2916 if (Error Err = importInto(ToDescribed, FromDescribed))
2917 return std::move(Err);
2918 D2CXX->setDescribedClassTemplate(ToDescribed);
2919 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2920 // In a record describing a template the type should be an
2921 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2922 // previously set type to the correct value here (ToDescribed is not
2923 // available at record create).
2924 // FIXME: The previous type is cleared but not removed from
2925 // ASTContext's internal storage.
2926 CXXRecordDecl *Injected = nullptr;
2927 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2928 auto *Record = dyn_cast<CXXRecordDecl>(Found);
2929 if (Record && Record->isInjectedClassName()) {
2930 Injected = Record;
2931 break;
2932 }
2933 }
2934 // Create an injected type for the whole redecl chain.
2935 SmallVector<Decl *, 2> Redecls =
2936 getCanonicalForwardRedeclChain(D2CXX);
2937 for (auto *R : Redecls) {
2938 auto *RI = cast<CXXRecordDecl>(R);
2939 RI->setTypeForDecl(nullptr);
2940 // Below we create a new injected type and assign that to the
2941 // canonical decl, subsequent declarations in the chain will reuse
2942 // that type.
2943 Importer.getToContext().getInjectedClassNameType(
2944 RI, ToDescribed->getInjectedClassNameSpecialization());
2945 }
2946 // Set the new type for the previous injected decl too.
2947 if (Injected) {
2948 Injected->setTypeForDecl(nullptr);
2949 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2950 }
2951 }
2952 } else if (MemberSpecializationInfo *MemberInfo =
2953 DCXX->getMemberSpecializationInfo()) {
2954 TemplateSpecializationKind SK =
2955 MemberInfo->getTemplateSpecializationKind();
2956 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2957
2958 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2959 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2960 else
2961 return ToInstOrErr.takeError();
2962
2963 if (ExpectedSLoc POIOrErr =
2964 import(MemberInfo->getPointOfInstantiation()))
2965 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
2966 *POIOrErr);
2967 else
2968 return POIOrErr.takeError();
2969 }
2970
2971 } else {
2972 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2973 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2974 Name.getAsIdentifierInfo(), PrevDecl))
2975 return D2;
2976 D2->setLexicalDeclContext(LexicalDC);
2977 addDeclToContexts(D, D2);
2978 }
2979
2980 if (auto BraceRangeOrErr = import(D->getBraceRange()))
2981 D2->setBraceRange(*BraceRangeOrErr);
2982 else
2983 return BraceRangeOrErr.takeError();
2984 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2985 D2->setQualifierInfo(*QualifierLocOrErr);
2986 else
2987 return QualifierLocOrErr.takeError();
2988
2989 if (D->isAnonymousStructOrUnion())
2990 D2->setAnonymousStructOrUnion(true);
2991
2992 if (D->isCompleteDefinition())
2993 if (Error Err = ImportDefinition(D, D2, IDK_Default))
2994 return std::move(Err);
2995
2996 return D2;
2997}
2998
2999ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
3000 // Import the major distinguishing characteristics of this enumerator.
3001 DeclContext *DC, *LexicalDC;
3002 DeclarationName Name;
3003 SourceLocation Loc;
3004 NamedDecl *ToD;
3005 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3006 return std::move(Err);
3007 if (ToD)
3008 return ToD;
3009
3010 // Determine whether there are any other declarations with the same name and
3011 // in the same context.
3012 if (!LexicalDC->isFunctionOrMethod()) {
3013 SmallVector<NamedDecl *, 4> ConflictingDecls;
3014 unsigned IDNS = Decl::IDNS_Ordinary;
3015 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3016 for (auto *FoundDecl : FoundDecls) {
3017 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3018 continue;
3019
3020 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3021 if (IsStructuralMatch(D, FoundEnumConstant))
3022 return Importer.MapImported(D, FoundEnumConstant);
3023 ConflictingDecls.push_back(FoundDecl);
3024 }
3025 }
3026
3027 if (!ConflictingDecls.empty()) {
3028 ExpectedName NameOrErr = Importer.HandleNameConflict(
3029 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3030 if (NameOrErr)
3031 Name = NameOrErr.get();
3032 else
3033 return NameOrErr.takeError();
3034 }
3035 }
3036
3037 ExpectedType TypeOrErr = import(D->getType());
3038 if (!TypeOrErr)
3039 return TypeOrErr.takeError();
3040
3041 ExpectedExpr InitOrErr = import(D->getInitExpr());
3042 if (!InitOrErr)
3043 return InitOrErr.takeError();
3044
3045 EnumConstantDecl *ToEnumerator;
3046 if (GetImportedOrCreateDecl(
3047 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3048 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3049 return ToEnumerator;
3050
3051 ToEnumerator->setAccess(D->getAccess());
3052 ToEnumerator->setLexicalDeclContext(LexicalDC);
3053 LexicalDC->addDeclInternal(ToEnumerator);
3054 return ToEnumerator;
3055}
3056
3057Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
3058 DeclaratorDecl *ToD) {
3059 unsigned int Num = FromD->getNumTemplateParameterLists();
3060 if (Num == 0)
3061 return Error::success();
3062 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
3063 for (unsigned int I = 0; I < Num; ++I)
3064 if (Expected<TemplateParameterList *> ToTPListOrErr =
3065 import(FromD->getTemplateParameterList(I)))
3066 ToTPLists[I] = *ToTPListOrErr;
3067 else
3068 return ToTPListOrErr.takeError();
3069 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3070 return Error::success();
3071}
3072
3073Error ASTNodeImporter::ImportTemplateInformation(
3074 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3075 switch (FromFD->getTemplatedKind()) {
3076 case FunctionDecl::TK_NonTemplate:
3077 case FunctionDecl::TK_FunctionTemplate:
3078 return Error::success();
3079
3080 case FunctionDecl::TK_MemberSpecialization: {
3081 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
3082
3083 if (Expected<FunctionDecl *> InstFDOrErr =
3084 import(FromFD->getInstantiatedFromMemberFunction()))
3085 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3086 else
3087 return InstFDOrErr.takeError();
3088
3089 if (ExpectedSLoc POIOrErr = import(
3090 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
3091 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3092 else
3093 return POIOrErr.takeError();
3094
3095 return Error::success();
3096 }
3097
3098 case FunctionDecl::TK_FunctionTemplateSpecialization: {
3099 auto FunctionAndArgsOrErr =
3100 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3101 if (!FunctionAndArgsOrErr)
3102 return FunctionAndArgsOrErr.takeError();
3103
3104 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
3105 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3106
3107 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3108 TemplateArgumentListInfo ToTAInfo;
3109 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3110 if (FromTAArgsAsWritten)
3111 if (Error Err = ImportTemplateArgumentListInfo(
3112 *FromTAArgsAsWritten, ToTAInfo))
3113 return Err;
3114
3115 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3116 if (!POIOrErr)
3117 return POIOrErr.takeError();
3118
3119 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3120 return Err;
3121
3122 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3123 ToFD->setFunctionTemplateSpecialization(
3124 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3125 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3126 return Error::success();
3127 }
3128
3129 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
3130 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3131 UnresolvedSet<8> TemplDecls;
3132 unsigned NumTemplates = FromInfo->getNumTemplates();
3133 for (unsigned I = 0; I < NumTemplates; I++) {
3134 if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
3135 import(FromInfo->getTemplate(I)))
3136 TemplDecls.addDecl(*ToFTDOrErr);
3137 else
3138 return ToFTDOrErr.takeError();
3139 }
3140
3141 // Import TemplateArgumentListInfo.
3142 TemplateArgumentListInfo ToTAInfo;
3143 if (Error Err = ImportTemplateArgumentListInfo(
3144 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
3145 llvm::makeArrayRef(
3146 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
3147 ToTAInfo))
3148 return Err;
3149
3150 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
3151 TemplDecls, ToTAInfo);
3152 return Error::success();
3153 }
3154 }
3155 llvm_unreachable("All cases should be covered!")::llvm::llvm_unreachable_internal("All cases should be covered!"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3155)
;
3156}
3157
3158Expected<FunctionDecl *>
3159ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
3160 auto FunctionAndArgsOrErr =
3161 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3162 if (!FunctionAndArgsOrErr)
3163 return FunctionAndArgsOrErr.takeError();
3164
3165 FunctionTemplateDecl *Template;
3166 TemplateArgsTy ToTemplArgs;
3167 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3168 void *InsertPos = nullptr;
3169 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3170 return FoundSpec;
3171}
3172
3173Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
3174 FunctionDecl *ToFD) {
3175 if (Stmt *FromBody = FromFD->getBody()) {
3176 if (ExpectedStmt ToBodyOrErr = import(FromBody))
3177 ToFD->setBody(*ToBodyOrErr);
3178 else
3179 return ToBodyOrErr.takeError();
3180 }
3181 return Error::success();
3182}
3183
3184// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3185// which is equal to the given DC.
3186static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3187 const DeclContext *DCi = D->getDeclContext();
3188 while (DCi != D->getTranslationUnitDecl()) {
3189 if (DCi == DC)
3190 return true;
3191 DCi = DCi->getParent();
3192 }
3193 return false;
3194}
3195
3196bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
3197 QualType FromTy = D->getType();
3198 const FunctionProtoType *FromFPT = FromTy->getAs<FunctionProtoType>();
3199 assert(FromFPT && "Must be called on FunctionProtoType")(static_cast <bool> (FromFPT && "Must be called on FunctionProtoType"
) ? void (0) : __assert_fail ("FromFPT && \"Must be called on FunctionProtoType\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3199, __extension__ __PRETTY_FUNCTION__))
;
3200 if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) {
3201 QualType DeducedT = AutoT->getDeducedType();
3202 if (const RecordType *RecordT =
3203 DeducedT.isNull() ? nullptr : dyn_cast<RecordType>(DeducedT)) {
3204 RecordDecl *RD = RecordT->getDecl();
3205 assert(RD)(static_cast <bool> (RD) ? void (0) : __assert_fail ("RD"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3205, __extension__ __PRETTY_FUNCTION__))
;
3206 if (isAncestorDeclContextOf(D, RD)) {
3207 assert(RD->getLexicalDeclContext() == RD->getDeclContext())(static_cast <bool> (RD->getLexicalDeclContext() == RD
->getDeclContext()) ? void (0) : __assert_fail ("RD->getLexicalDeclContext() == RD->getDeclContext()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3207, __extension__ __PRETTY_FUNCTION__))
;
3208 return true;
3209 }
3210 }
3211 }
3212 if (const TypedefType *TypedefT =
3213 dyn_cast<TypedefType>(FromFPT->getReturnType())) {
3214 TypedefNameDecl *TD = TypedefT->getDecl();
3215 assert(TD)(static_cast <bool> (TD) ? void (0) : __assert_fail ("TD"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3215, __extension__ __PRETTY_FUNCTION__))
;
3216 if (isAncestorDeclContextOf(D, TD)) {
3217 assert(TD->getLexicalDeclContext() == TD->getDeclContext())(static_cast <bool> (TD->getLexicalDeclContext() == TD
->getDeclContext()) ? void (0) : __assert_fail ("TD->getLexicalDeclContext() == TD->getDeclContext()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3217, __extension__ __PRETTY_FUNCTION__))
;
3218 return true;
3219 }
3220 }
3221 return false;
3222}
3223
3224ExplicitSpecifier
3225ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3226 Expr *ExplicitExpr = ESpec.getExpr();
3227 if (ExplicitExpr)
3228 ExplicitExpr = importChecked(Err, ESpec.getExpr());
3229 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3230}
3231
3232ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3233
3234 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
3235 auto RedeclIt = Redecls.begin();
3236 // Import the first part of the decl chain. I.e. import all previous
3237 // declarations starting from the canonical decl.
3238 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3239 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3240 if (!ToRedeclOrErr)
3241 return ToRedeclOrErr.takeError();
3242 }
3243 assert(*RedeclIt == D)(static_cast <bool> (*RedeclIt == D) ? void (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3243, __extension__ __PRETTY_FUNCTION__))
;
3244
3245 // Import the major distinguishing characteristics of this function.
3246 DeclContext *DC, *LexicalDC;
3247 DeclarationName Name;
3248 SourceLocation Loc;
3249 NamedDecl *ToD;
3250 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3251 return std::move(Err);
3252 if (ToD)
3253 return ToD;
3254
3255 FunctionDecl *FoundByLookup = nullptr;
3256 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3257
3258 // If this is a function template specialization, then try to find the same
3259 // existing specialization in the "to" context. The lookup below will not
3260 // find any specialization, but would find the primary template; thus, we
3261 // have to skip normal lookup in case of specializations.
3262 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3263 if (D->getTemplatedKind() ==
3264 FunctionDecl::TK_FunctionTemplateSpecialization) {
3265 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3266 if (!FoundFunctionOrErr)
3267 return FoundFunctionOrErr.takeError();
3268 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3269 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3270 return Def;
3271 FoundByLookup = FoundFunction;
3272 }
3273 }
3274 // Try to find a function in our own ("to") context with the same name, same
3275 // type, and in the same context as the function we're importing.
3276 else if (!LexicalDC->isFunctionOrMethod()) {
3277 SmallVector<NamedDecl *, 4> ConflictingDecls;
3278 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3279 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3280 for (auto *FoundDecl : FoundDecls) {
3281 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3282 continue;
3283
3284 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3285 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3286 continue;
3287
3288 if (IsStructuralMatch(D, FoundFunction)) {
3289 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3290 return Def;
3291 FoundByLookup = FoundFunction;
3292 break;
3293 }
3294 // FIXME: Check for overloading more carefully, e.g., by boosting
3295 // Sema::IsOverload out to the AST library.
3296
3297 // Function overloading is okay in C++.
3298 if (Importer.getToContext().getLangOpts().CPlusPlus)
3299 continue;
3300
3301 // Complain about inconsistent function types.
3302 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3303 << Name << D->getType() << FoundFunction->getType();
3304 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3305 << FoundFunction->getType();
3306 ConflictingDecls.push_back(FoundDecl);
3307 }
3308 }
3309
3310 if (!ConflictingDecls.empty()) {
3311 ExpectedName NameOrErr = Importer.HandleNameConflict(
3312 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3313 if (NameOrErr)
3314 Name = NameOrErr.get();
3315 else
3316 return NameOrErr.takeError();
3317 }
3318 }
3319
3320 // We do not allow more than one in-class declaration of a function. This is
3321 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3322 // assumes there is only one in-class declaration. Building a redecl
3323 // chain would result in more than one in-class declaration for
3324 // overrides (even if they are part of the same redecl chain inside the
3325 // derived class.)
3326 if (FoundByLookup) {
3327 if (isa<CXXMethodDecl>(FoundByLookup)) {
3328 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3329 if (!D->doesThisDeclarationHaveABody()) {
3330 if (FunctionTemplateDecl *DescribedD =
3331 D->getDescribedFunctionTemplate()) {
3332 // Handle a "templated" function together with its described
3333 // template. This avoids need for a similar check at import of the
3334 // described template.
3335 assert(FoundByLookup->getDescribedFunctionTemplate() &&(static_cast <bool> (FoundByLookup->getDescribedFunctionTemplate
() && "Templated function mapped to non-templated?") ?
void (0) : __assert_fail ("FoundByLookup->getDescribedFunctionTemplate() && \"Templated function mapped to non-templated?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3336, __extension__ __PRETTY_FUNCTION__))
3336 "Templated function mapped to non-templated?")(static_cast <bool> (FoundByLookup->getDescribedFunctionTemplate
() && "Templated function mapped to non-templated?") ?
void (0) : __assert_fail ("FoundByLookup->getDescribedFunctionTemplate() && \"Templated function mapped to non-templated?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3336, __extension__ __PRETTY_FUNCTION__))
;
3337 Importer.MapImported(DescribedD,
3338 FoundByLookup->getDescribedFunctionTemplate());
3339 }
3340 return Importer.MapImported(D, FoundByLookup);
3341 } else {
3342 // Let's continue and build up the redecl chain in this case.
3343 // FIXME Merge the functions into one decl.
3344 }
3345 }
3346 }
3347 }
3348
3349 DeclarationNameInfo NameInfo(Name, Loc);
3350 // Import additional name location/type info.
3351 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3352 return std::move(Err);
3353
3354 QualType FromTy = D->getType();
3355 // Set to true if we do not import the type of the function as is. There are
3356 // cases when the original type would result in an infinite recursion during
3357 // the import. To avoid an infinite recursion when importing, we create the
3358 // FunctionDecl with a simplified function type and update it only after the
3359 // relevant AST nodes are already imported.
3360 bool UsedDifferentProtoType = false;
3361 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3362 QualType FromReturnTy = FromFPT->getReturnType();
3363 // Functions with auto return type may define a struct inside their body
3364 // and the return type could refer to that struct.
3365 // E.g.: auto foo() { struct X{}; return X(); }
3366 // To avoid an infinite recursion when importing, create the FunctionDecl
3367 // with a simplified return type.
3368 if (hasAutoReturnTypeDeclaredInside(D)) {
3369 FromReturnTy = Importer.getFromContext().VoidTy;
3370 UsedDifferentProtoType = true;
3371 }
3372 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3373 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3374 // FunctionDecl that we are importing the FunctionProtoType for.
3375 // To avoid an infinite recursion when importing, create the FunctionDecl
3376 // with a simplified function type.
3377 if (FromEPI.ExceptionSpec.SourceDecl ||
3378 FromEPI.ExceptionSpec.SourceTemplate ||
3379 FromEPI.ExceptionSpec.NoexceptExpr) {
3380 FunctionProtoType::ExtProtoInfo DefaultEPI;
3381 FromEPI = DefaultEPI;
3382 UsedDifferentProtoType = true;
3383 }
3384 FromTy = Importer.getFromContext().getFunctionType(
3385 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3386 }
3387
3388 Error Err = Error::success();
3389 auto T = importChecked(Err, FromTy);
3390 auto TInfo = importChecked(Err, D->getTypeSourceInfo());
3391 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3392 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3393 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3394 auto TrailingRequiresClause =
3395 importChecked(Err, D->getTrailingRequiresClause());
3396 if (Err)
3397 return std::move(Err);
3398
3399 // Import the function parameters.
3400 SmallVector<ParmVarDecl *, 8> Parameters;
3401 for (auto P : D->parameters()) {
3402 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3403 Parameters.push_back(*ToPOrErr);
3404 else
3405 return ToPOrErr.takeError();
3406 }
3407
3408 // Create the imported function.
3409 FunctionDecl *ToFunction = nullptr;
3410 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3411 ExplicitSpecifier ESpec =
3412 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3413 if (Err)
3414 return std::move(Err);
3415 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3416 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3417 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->isInlineSpecified(),
3418 D->isImplicit(), D->getConstexprKind(),
3419 InheritedConstructor(), // FIXME: Properly import inherited
3420 // constructor info
3421 TrailingRequiresClause))
3422 return ToFunction;
3423 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3424
3425 Error Err = Error::success();
3426 auto ToOperatorDelete = importChecked(
3427 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3428 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3429 if (Err)
3430 return std::move(Err);
3431
3432 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3433 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3434 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3435 D->isImplicit(), D->getConstexprKind(), TrailingRequiresClause))
3436 return ToFunction;
3437
3438 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3439
3440 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3441 } else if (CXXConversionDecl *FromConversion =
3442 dyn_cast<CXXConversionDecl>(D)) {
3443 ExplicitSpecifier ESpec =
3444 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3445 if (Err)
3446 return std::move(Err);
3447 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3448 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3449 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), ESpec,
3450 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3451 return ToFunction;
3452 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3453 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3454 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3455 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3456 Method->isInlineSpecified(), D->getConstexprKind(),
3457 SourceLocation(), TrailingRequiresClause))
3458 return ToFunction;
3459 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3460 ExplicitSpecifier ESpec =
3461 importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3462 CXXConstructorDecl *Ctor =
3463 importChecked(Err, Guide->getCorrespondingConstructor());
3464 if (Err)
3465 return std::move(Err);
3466 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3467 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3468 NameInfo, T, TInfo, ToEndLoc, Ctor))
3469 return ToFunction;
3470 cast<CXXDeductionGuideDecl>(ToFunction)
3471 ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
3472 } else {
3473 if (GetImportedOrCreateDecl(
3474 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3475 NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(),
3476 D->hasWrittenPrototype(), D->getConstexprKind(),
3477 TrailingRequiresClause))
3478 return ToFunction;
3479 }
3480
3481 // Connect the redecl chain.
3482 if (FoundByLookup) {
3483 auto *Recent = const_cast<FunctionDecl *>(
3484 FoundByLookup->getMostRecentDecl());
3485 ToFunction->setPreviousDecl(Recent);
3486 // FIXME Probably we should merge exception specifications. E.g. In the
3487 // "To" context the existing function may have exception specification with
3488 // noexcept-unevaluated, while the newly imported function may have an
3489 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3490 // decl and its redeclarations may be required.
3491 }
3492
3493 ToFunction->setQualifierInfo(ToQualifierLoc);
3494 ToFunction->setAccess(D->getAccess());
3495 ToFunction->setLexicalDeclContext(LexicalDC);
3496 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3497 ToFunction->setTrivial(D->isTrivial());
3498 ToFunction->setPure(D->isPure());
3499 ToFunction->setDefaulted(D->isDefaulted());
3500 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3501 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3502 ToFunction->setRangeEnd(ToEndLoc);
3503
3504 // Set the parameters.
3505 for (auto *Param : Parameters) {
3506 Param->setOwningFunction(ToFunction);
3507 ToFunction->addDeclInternal(Param);
3508 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3509 LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3510 }
3511 ToFunction->setParams(Parameters);
3512
3513 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3514 // params it refers to.
3515 if (TInfo) {
3516 if (auto ProtoLoc =
3517 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3518 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3519 ProtoLoc.setParam(I, Parameters[I]);
3520 }
3521 }
3522
3523 // Import the describing template function, if any.
3524 if (FromFT) {
3525 auto ToFTOrErr = import(FromFT);
3526 if (!ToFTOrErr)
3527 return ToFTOrErr.takeError();
3528 }
3529
3530 // Import Ctor initializers.
3531 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3532 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3533 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3534 // Import first, then allocate memory and copy if there was no error.
3535 if (Error Err = ImportContainerChecked(
3536 FromConstructor->inits(), CtorInitializers))
3537 return std::move(Err);
3538 auto **Memory =
3539 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3540 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3541 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3542 ToCtor->setCtorInitializers(Memory);
3543 ToCtor->setNumCtorInitializers(NumInitializers);
3544 }
3545 }
3546
3547 if (D->doesThisDeclarationHaveABody()) {
3548 Error Err = ImportFunctionDeclBody(D, ToFunction);
3549
3550 if (Err)
3551 return std::move(Err);
3552 }
3553
3554 // Import and set the original type in case we used another type.
3555 if (UsedDifferentProtoType) {
3556 if (ExpectedType TyOrErr = import(D->getType()))
3557 ToFunction->setType(*TyOrErr);
3558 else
3559 return TyOrErr.takeError();
3560 }
3561
3562 // FIXME: Other bits to merge?
3563
3564 // If it is a template, import all related things.
3565 if (Error Err = ImportTemplateInformation(D, ToFunction))
3566 return std::move(Err);
3567
3568 addDeclToContexts(D, ToFunction);
3569
3570 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3571 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3572 FromCXXMethod))
3573 return std::move(Err);
3574
3575 // Import the rest of the chain. I.e. import all subsequent declarations.
3576 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3577 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3578 if (!ToRedeclOrErr)
3579 return ToRedeclOrErr.takeError();
3580 }
3581
3582 return ToFunction;
3583}
3584
3585ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3586 return VisitFunctionDecl(D);
3587}
3588
3589ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3590 return VisitCXXMethodDecl(D);
3591}
3592
3593ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3594 return VisitCXXMethodDecl(D);
3595}
3596
3597ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3598 return VisitCXXMethodDecl(D);
3599}
3600
3601ExpectedDecl
3602ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3603 return VisitFunctionDecl(D);
3604}
3605
3606ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3607 // Import the major distinguishing characteristics of a variable.
3608 DeclContext *DC, *LexicalDC;
3609 DeclarationName Name;
3610 SourceLocation Loc;
3611 NamedDecl *ToD;
3612 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3613 return std::move(Err);
3614 if (ToD)
3615 return ToD;
3616
3617 // Determine whether we've already imported this field.
3618 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3619 for (auto *FoundDecl : FoundDecls) {
3620 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3621 // For anonymous fields, match up by index.
3622 if (!Name &&
3623 ASTImporter::getFieldIndex(D) !=
3624 ASTImporter::getFieldIndex(FoundField))
3625 continue;
3626
3627 if (Importer.IsStructurallyEquivalent(D->getType(),
3628 FoundField->getType())) {
3629 Importer.MapImported(D, FoundField);
3630 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3631 // initializer of a FieldDecl might not had been instantiated in the
3632 // "To" context. However, the "From" context might instantiated that,
3633 // thus we have to merge that.
3634 if (Expr *FromInitializer = D->getInClassInitializer()) {
3635 // We don't have yet the initializer set.
3636 if (FoundField->hasInClassInitializer() &&
3637 !FoundField->getInClassInitializer()) {
3638 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3639 FoundField->setInClassInitializer(*ToInitializerOrErr);
3640 else {
3641 // We can't return error here,
3642 // since we already mapped D as imported.
3643 // FIXME: warning message?
3644 consumeError(ToInitializerOrErr.takeError());
3645 return FoundField;
3646 }
3647 }
3648 }
3649 return FoundField;
3650 }
3651
3652 // FIXME: Why is this case not handled with calling HandleNameConflict?
3653 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3654 << Name << D->getType() << FoundField->getType();
3655 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3656 << FoundField->getType();
3657
3658 return make_error<ImportError>(ImportError::NameConflict);
3659 }
3660 }
3661
3662 Error Err = Error::success();
3663 auto ToType = importChecked(Err, D->getType());
3664 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
3665 auto ToBitWidth = importChecked(Err, D->getBitWidth());
3666 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3667 auto ToInitializer = importChecked(Err, D->getInClassInitializer());
3668 if (Err)
3669 return std::move(Err);
3670 const Type *ToCapturedVLAType = nullptr;
3671 if (Error Err = Importer.importInto(
3672 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
3673 return std::move(Err);
3674
3675 FieldDecl *ToField;
3676 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3677 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3678 ToType, ToTInfo, ToBitWidth, D->isMutable(),
3679 D->getInClassInitStyle()))
3680 return ToField;
3681
3682 ToField->setAccess(D->getAccess());
3683 ToField->setLexicalDeclContext(LexicalDC);
3684 if (ToInitializer)
3685 ToField->setInClassInitializer(ToInitializer);
3686 ToField->setImplicit(D->isImplicit());
3687 if (ToCapturedVLAType)
3688 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
3689 LexicalDC->addDeclInternal(ToField);
3690 return ToField;
3691}
3692
3693ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3694 // Import the major distinguishing characteristics of a variable.
3695 DeclContext *DC, *LexicalDC;
3696 DeclarationName Name;
3697 SourceLocation Loc;
3698 NamedDecl *ToD;
3699 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3700 return std::move(Err);
3701 if (ToD)
3702 return ToD;
3703
3704 // Determine whether we've already imported this field.
3705 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3706 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3707 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3708 // For anonymous indirect fields, match up by index.
3709 if (!Name &&
3710 ASTImporter::getFieldIndex(D) !=
3711 ASTImporter::getFieldIndex(FoundField))
3712 continue;
3713
3714 if (Importer.IsStructurallyEquivalent(D->getType(),
3715 FoundField->getType(),
3716 !Name.isEmpty())) {
3717 Importer.MapImported(D, FoundField);
3718 return FoundField;
3719 }
3720
3721 // If there are more anonymous fields to check, continue.
3722 if (!Name && I < N-1)
3723 continue;
3724
3725 // FIXME: Why is this case not handled with calling HandleNameConflict?
3726 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3727 << Name << D->getType() << FoundField->getType();
3728 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3729 << FoundField->getType();
3730
3731 return make_error<ImportError>(ImportError::NameConflict);
3732 }
3733 }
3734
3735 // Import the type.
3736 auto TypeOrErr = import(D->getType());
3737 if (!TypeOrErr)
3738 return TypeOrErr.takeError();
3739
3740 auto **NamedChain =
3741 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3742
3743 unsigned i = 0;
3744 for (auto *PI : D->chain())
3745 if (Expected<NamedDecl *> ToD = import(PI))
3746 NamedChain[i++] = *ToD;
3747 else
3748 return ToD.takeError();
3749
3750 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3751 IndirectFieldDecl *ToIndirectField;
3752 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3753 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3754 // FIXME here we leak `NamedChain` which is allocated before
3755 return ToIndirectField;
3756
3757 ToIndirectField->setAccess(D->getAccess());
3758 ToIndirectField->setLexicalDeclContext(LexicalDC);
3759 LexicalDC->addDeclInternal(ToIndirectField);
3760 return ToIndirectField;
3761}
3762
3763/// Used as return type of getFriendCountAndPosition.
3764struct FriendCountAndPosition {
3765 /// Number of similar looking friends.
3766 unsigned int TotalCount;
3767 /// Index of the specific FriendDecl.
3768 unsigned int IndexOfDecl;
3769};
3770
3771template <class T>
3772static FriendCountAndPosition getFriendCountAndPosition(
3773 const FriendDecl *FD,
3774 llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
3775 unsigned int FriendCount = 0;
3776 llvm::Optional<unsigned int> FriendPosition;
3777 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
3778
3779 T TypeOrDecl = GetCanTypeOrDecl(FD);
3780
3781 for (const FriendDecl *FoundFriend : RD->friends()) {
3782 if (FoundFriend == FD) {
3783 FriendPosition = FriendCount;
3784 ++FriendCount;
3785 } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
3786 GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
3787 ++FriendCount;
3788 }
3789 }
3790
3791 assert(FriendPosition && "Friend decl not found in own parent.")(static_cast <bool> (FriendPosition && "Friend decl not found in own parent."
) ? void (0) : __assert_fail ("FriendPosition && \"Friend decl not found in own parent.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3791, __extension__ __PRETTY_FUNCTION__))
;
3792
3793 return {FriendCount, *FriendPosition};
3794}
3795
3796static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
3797 if (FD->getFriendType())
3798 return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
3799 if (TypeSourceInfo *TSI = F->getFriendType())
3800 return TSI->getType().getCanonicalType();
3801 llvm_unreachable("Wrong friend object type.")::llvm::llvm_unreachable_internal("Wrong friend object type."
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3801)
;
3802 });
3803 else
3804 return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
3805 if (Decl *D = F->getFriendDecl())
3806 return D->getCanonicalDecl();
3807 llvm_unreachable("Wrong friend object type.")::llvm::llvm_unreachable_internal("Wrong friend object type."
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3807)
;
3808 });
3809}
3810
3811ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
3812 // Import the major distinguishing characteristics of a declaration.
3813 DeclContext *DC, *LexicalDC;
3814 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3815 return std::move(Err);
3816
3817 // Determine whether we've already imported this decl.
3818 // FriendDecl is not a NamedDecl so we cannot use lookup.
3819 // We try to maintain order and count of redundant friend declarations.
3820 const auto *RD = cast<CXXRecordDecl>(DC);
3821 FriendDecl *ImportedFriend = RD->getFirstFriend();
3822 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
3823
3824 while (ImportedFriend) {
3825 bool Match = false;
3826 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3827 Match =
3828 IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3829 /*Complain=*/false);
3830 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3831 Match = Importer.IsStructurallyEquivalent(
3832 D->getFriendType()->getType(),
3833 ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
3834 }
3835 if (Match)
3836 ImportedEquivalentFriends.push_back(ImportedFriend);
3837
3838 ImportedFriend = ImportedFriend->getNextFriend();
3839 }
3840 FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
3841
3842 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&(static_cast <bool> (ImportedEquivalentFriends.size() <=
CountAndPosition.TotalCount && "Class with non-matching friends is imported, ODR check wrong?"
) ? void (0) : __assert_fail ("ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && \"Class with non-matching friends is imported, ODR check wrong?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3843, __extension__ __PRETTY_FUNCTION__))
3843 "Class with non-matching friends is imported, ODR check wrong?")(static_cast <bool> (ImportedEquivalentFriends.size() <=
CountAndPosition.TotalCount && "Class with non-matching friends is imported, ODR check wrong?"
) ? void (0) : __assert_fail ("ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && \"Class with non-matching friends is imported, ODR check wrong?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3843, __extension__ __PRETTY_FUNCTION__))
;
3844 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
3845 return Importer.MapImported(
3846 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
3847
3848 // Not found. Create it.
3849 // The declarations will be put into order later by ImportDeclContext.
3850 FriendDecl::FriendUnion ToFU;
3851 if (NamedDecl *FriendD = D->getFriendDecl()) {
3852 NamedDecl *ToFriendD;
3853 if (Error Err = importInto(ToFriendD, FriendD))
3854 return std::move(Err);
3855
3856 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3857 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3858 ToFriendD->setObjectOfFriendDecl(false);
3859
3860 ToFU = ToFriendD;
3861 } else { // The friend is a type, not a decl.
3862 if (auto TSIOrErr = import(D->getFriendType()))
3863 ToFU = *TSIOrErr;
3864 else
3865 return TSIOrErr.takeError();
3866 }
3867
3868 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3869 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3870 for (unsigned I = 0; I < D->NumTPLists; I++) {
3871 if (auto ListOrErr = import(FromTPLists[I]))
3872 ToTPLists[I] = *ListOrErr;
3873 else
3874 return ListOrErr.takeError();
3875 }
3876
3877 auto LocationOrErr = import(D->getLocation());
3878 if (!LocationOrErr)
3879 return LocationOrErr.takeError();
3880 auto FriendLocOrErr = import(D->getFriendLoc());
3881 if (!FriendLocOrErr)
3882 return FriendLocOrErr.takeError();
3883
3884 FriendDecl *FrD;
3885 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3886 *LocationOrErr, ToFU,
3887 *FriendLocOrErr, ToTPLists))
3888 return FrD;
3889
3890 FrD->setAccess(D->getAccess());
3891 FrD->setLexicalDeclContext(LexicalDC);
3892 LexicalDC->addDeclInternal(FrD);
3893 return FrD;
3894}
3895
3896ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3897 // Import the major distinguishing characteristics of an ivar.
3898 DeclContext *DC, *LexicalDC;
3899 DeclarationName Name;
3900 SourceLocation Loc;
3901 NamedDecl *ToD;
3902 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3903 return std::move(Err);
3904 if (ToD)
3905 return ToD;
3906
3907 // Determine whether we've already imported this ivar
3908 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3909 for (auto *FoundDecl : FoundDecls) {
3910 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3911 if (Importer.IsStructurallyEquivalent(D->getType(),
3912 FoundIvar->getType())) {
3913 Importer.MapImported(D, FoundIvar);
3914 return FoundIvar;
3915 }
3916
3917 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3918 << Name << D->getType() << FoundIvar->getType();
3919 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3920 << FoundIvar->getType();
3921
3922 return make_error<ImportError>(ImportError::NameConflict);
3923 }
3924 }
3925
3926 Error Err = Error::success();
3927 auto ToType = importChecked(Err, D->getType());
3928 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
3929 auto ToBitWidth = importChecked(Err, D->getBitWidth());
3930 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3931 if (Err)
3932 return std::move(Err);
3933
3934 ObjCIvarDecl *ToIvar;
3935 if (GetImportedOrCreateDecl(
3936 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3937 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3938 ToType, ToTypeSourceInfo,
3939 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3940 return ToIvar;
3941
3942 ToIvar->setLexicalDeclContext(LexicalDC);
3943 LexicalDC->addDeclInternal(ToIvar);
3944 return ToIvar;
3945}
3946
3947ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3948
3949 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
3950 auto RedeclIt = Redecls.begin();
3951 // Import the first part of the decl chain. I.e. import all previous
3952 // declarations starting from the canonical decl.
3953 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3954 ExpectedDecl RedeclOrErr = import(*RedeclIt);
3955 if (!RedeclOrErr)
3956 return RedeclOrErr.takeError();
3957 }
3958 assert(*RedeclIt == D)(static_cast <bool> (*RedeclIt == D) ? void (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 3958, __extension__ __PRETTY_FUNCTION__))
;
3959
3960 // Import the major distinguishing characteristics of a variable.
3961 DeclContext *DC, *LexicalDC;
3962 DeclarationName Name;
3963 SourceLocation Loc;
3964 NamedDecl *ToD;
3965 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3966 return std::move(Err);
3967 if (ToD)
3968 return ToD;
3969
3970 // Try to find a variable in our own ("to") context with the same name and
3971 // in the same context as the variable we're importing.
3972 VarDecl *FoundByLookup = nullptr;
3973 if (D->isFileVarDecl()) {
3974 SmallVector<NamedDecl *, 4> ConflictingDecls;
3975 unsigned IDNS = Decl::IDNS_Ordinary;
3976 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3977 for (auto *FoundDecl : FoundDecls) {
3978 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3979 continue;
3980
3981 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3982 if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
3983 continue;
3984 if (Importer.IsStructurallyEquivalent(D->getType(),
3985 FoundVar->getType())) {
3986
3987 // The VarDecl in the "From" context has a definition, but in the
3988 // "To" context we already have a definition.
3989 VarDecl *FoundDef = FoundVar->getDefinition();
3990 if (D->isThisDeclarationADefinition() && FoundDef)
3991 // FIXME Check for ODR error if the two definitions have
3992 // different initializers?
3993 return Importer.MapImported(D, FoundDef);
3994
3995 // The VarDecl in the "From" context has an initializer, but in the
3996 // "To" context we already have an initializer.
3997 const VarDecl *FoundDInit = nullptr;
3998 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3999 // FIXME Diagnose ODR error if the two initializers are different?
4000 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4001
4002 FoundByLookup = FoundVar;
4003 break;
4004 }
4005
4006 const ArrayType *FoundArray
4007 = Importer.getToContext().getAsArrayType(FoundVar->getType());
4008 const ArrayType *TArray
4009 = Importer.getToContext().getAsArrayType(D->getType());
4010 if (FoundArray && TArray) {
4011 if (isa<IncompleteArrayType>(FoundArray) &&
4012 isa<ConstantArrayType>(TArray)) {
4013 // Import the type.
4014 if (auto TyOrErr = import(D->getType()))
4015 FoundVar->setType(*TyOrErr);
4016 else
4017 return TyOrErr.takeError();
4018
4019 FoundByLookup = FoundVar;
4020 break;
4021 } else if (isa<IncompleteArrayType>(TArray) &&
4022 isa<ConstantArrayType>(FoundArray)) {
4023 FoundByLookup = FoundVar;
4024 break;
4025 }
4026 }
4027
4028 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4029 << Name << D->getType() << FoundVar->getType();
4030 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4031 << FoundVar->getType();
4032 ConflictingDecls.push_back(FoundDecl);
4033 }
4034 }
4035
4036 if (!ConflictingDecls.empty()) {
4037 ExpectedName NameOrErr = Importer.HandleNameConflict(
4038 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4039 if (NameOrErr)
4040 Name = NameOrErr.get();
4041 else
4042 return NameOrErr.takeError();
4043 }
4044 }
4045
4046 Error Err = Error::success();
4047 auto ToType = importChecked(Err, D->getType());
4048 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4049 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4050 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4051 if (Err)
4052 return std::move(Err);
4053
4054 // Create the imported variable.
4055 VarDecl *ToVar;
4056 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4057 ToInnerLocStart, Loc,
4058 Name.getAsIdentifierInfo(),
4059 ToType, ToTypeSourceInfo,
4060 D->getStorageClass()))
4061 return ToVar;
4062
4063 ToVar->setTSCSpec(D->getTSCSpec());
4064 ToVar->setQualifierInfo(ToQualifierLoc);
4065 ToVar->setAccess(D->getAccess());
4066 ToVar->setLexicalDeclContext(LexicalDC);
4067
4068 if (FoundByLookup) {
4069 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4070 ToVar->setPreviousDecl(Recent);
4071 }
4072
4073 // Import the described template, if any.
4074 if (D->getDescribedVarTemplate()) {
4075 auto ToVTOrErr = import(D->getDescribedVarTemplate());
4076 if (!ToVTOrErr)
4077 return ToVTOrErr.takeError();
4078 }
4079
4080 if (Error Err = ImportInitializer(D, ToVar))
4081 return std::move(Err);
4082
4083 if (D->isConstexpr())
4084 ToVar->setConstexpr(true);
4085
4086 addDeclToContexts(D, ToVar);
4087
4088 // Import the rest of the chain. I.e. import all subsequent declarations.
4089 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4090 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4091 if (!RedeclOrErr)
4092 return RedeclOrErr.takeError();
4093 }
4094
4095 return ToVar;
4096}
4097
4098ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
4099 // Parameters are created in the translation unit's context, then moved
4100 // into the function declaration's context afterward.
4101 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4102
4103 Error Err = Error::success();
4104 auto ToDeclName = importChecked(Err, D->getDeclName());
4105 auto ToLocation = importChecked(Err, D->getLocation());
4106 auto ToType = importChecked(Err, D->getType());
4107 if (Err)
4108 return std::move(Err);
4109
4110 // Create the imported parameter.
4111 ImplicitParamDecl *ToParm = nullptr;
4112 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4113 ToLocation, ToDeclName.getAsIdentifierInfo(),
4114 ToType, D->getParameterKind()))
4115 return ToParm;
4116 return ToParm;
4117}
4118
4119Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
4120 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4121 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4122 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4123
4124 if (FromParam->hasUninstantiatedDefaultArg()) {
4125 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4126 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4127 else
4128 return ToDefArgOrErr.takeError();
4129 } else if (FromParam->hasUnparsedDefaultArg()) {
4130 ToParam->setUnparsedDefaultArg();
4131 } else if (FromParam->hasDefaultArg()) {
4132 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4133 ToParam->setDefaultArg(*ToDefArgOrErr);
4134 else
4135 return ToDefArgOrErr.takeError();
4136 }
4137
4138 return Error::success();
4139}
4140
4141ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
4142 // Parameters are created in the translation unit's context, then moved
4143 // into the function declaration's context afterward.
4144 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4145
4146 Error Err = Error::success();
4147 auto ToDeclName = importChecked(Err, D->getDeclName());
4148 auto ToLocation = importChecked(Err, D->getLocation());
4149 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4150 auto ToType = importChecked(Err, D->getType());
4151 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4152 if (Err)
4153 return std::move(Err);
4154
4155 ParmVarDecl *ToParm;
4156 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4157 ToInnerLocStart, ToLocation,
4158 ToDeclName.getAsIdentifierInfo(), ToType,
4159 ToTypeSourceInfo, D->getStorageClass(),
4160 /*DefaultArg*/ nullptr))
4161 return ToParm;
4162
4163 // Set the default argument. It should be no problem if it was already done.
4164 // Do not import the default expression before GetImportedOrCreateDecl call
4165 // to avoid possible infinite import loop because circular dependency.
4166 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4167 return std::move(Err);
4168
4169 if (D->isObjCMethodParameter()) {
4170 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4171 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4172 } else {
4173 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4174 D->getFunctionScopeIndex());
4175 }
4176
4177 return ToParm;
4178}
4179
4180ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
4181 // Import the major distinguishing characteristics of a method.
4182 DeclContext *DC, *LexicalDC;
4183 DeclarationName Name;
4184 SourceLocation Loc;
4185 NamedDecl *ToD;
4186 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4187 return std::move(Err);
4188 if (ToD)
4189 return ToD;
4190
4191 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4192 for (auto *FoundDecl : FoundDecls) {
4193 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4194 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4195 continue;
4196
4197 // Check return types.
4198 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4199 FoundMethod->getReturnType())) {
4200 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4201 << D->isInstanceMethod() << Name << D->getReturnType()
4202 << FoundMethod->getReturnType();
4203 Importer.ToDiag(FoundMethod->getLocation(),
4204 diag::note_odr_objc_method_here)
4205 << D->isInstanceMethod() << Name;
4206
4207 return make_error<ImportError>(ImportError::NameConflict);
4208 }
4209
4210 // Check the number of parameters.
4211 if (D->param_size() != FoundMethod->param_size()) {
4212 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4213 << D->isInstanceMethod() << Name
4214 << D->param_size() << FoundMethod->param_size();
4215 Importer.ToDiag(FoundMethod->getLocation(),
4216 diag::note_odr_objc_method_here)
4217 << D->isInstanceMethod() << Name;
4218
4219 return make_error<ImportError>(ImportError::NameConflict);
4220 }
4221
4222 // Check parameter types.
4223 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4224 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4225 P != PEnd; ++P, ++FoundP) {
4226 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4227 (*FoundP)->getType())) {
4228 Importer.FromDiag((*P)->getLocation(),
4229 diag::warn_odr_objc_method_param_type_inconsistent)
4230 << D->isInstanceMethod() << Name
4231 << (*P)->getType() << (*FoundP)->getType();
4232 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4233 << (*FoundP)->getType();
4234
4235 return make_error<ImportError>(ImportError::NameConflict);
4236 }
4237 }
4238
4239 // Check variadic/non-variadic.
4240 // Check the number of parameters.
4241 if (D->isVariadic() != FoundMethod->isVariadic()) {
4242 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4243 << D->isInstanceMethod() << Name;
4244 Importer.ToDiag(FoundMethod->getLocation(),
4245 diag::note_odr_objc_method_here)
4246 << D->isInstanceMethod() << Name;
4247
4248 return make_error<ImportError>(ImportError::NameConflict);
4249 }
4250
4251 // FIXME: Any other bits we need to merge?
4252 return Importer.MapImported(D, FoundMethod);
4253 }
4254 }
4255
4256 Error Err = Error::success();
4257 auto ToEndLoc = importChecked(Err, D->getEndLoc());
4258 auto ToReturnType = importChecked(Err, D->getReturnType());
4259 auto ToReturnTypeSourceInfo =
4260 importChecked(Err, D->getReturnTypeSourceInfo());
4261 if (Err)
4262 return std::move(Err);
4263
4264 ObjCMethodDecl *ToMethod;
4265 if (GetImportedOrCreateDecl(
4266 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4267 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4268 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
4269 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
4270 D->getImplementationControl(), D->hasRelatedResultType()))
4271 return ToMethod;
4272
4273 // FIXME: When we decide to merge method definitions, we'll need to
4274 // deal with implicit parameters.
4275
4276 // Import the parameters
4277 SmallVector<ParmVarDecl *, 5> ToParams;
4278 for (auto *FromP : D->parameters()) {
4279 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4280 ToParams.push_back(*ToPOrErr);
4281 else
4282 return ToPOrErr.takeError();
4283 }
4284
4285 // Set the parameters.
4286 for (auto *ToParam : ToParams) {
4287 ToParam->setOwningFunction(ToMethod);
4288 ToMethod->addDeclInternal(ToParam);
4289 }
4290
4291 SmallVector<SourceLocation, 12> FromSelLocs;
4292 D->getSelectorLocs(FromSelLocs);
4293 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4294 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4295 return std::move(Err);
4296
4297 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4298
4299 ToMethod->setLexicalDeclContext(LexicalDC);
4300 LexicalDC->addDeclInternal(ToMethod);
4301
4302 // Implicit params are declared when Sema encounters the definition but this
4303 // never happens when the method is imported. Manually declare the implicit
4304 // params now that the MethodDecl knows its class interface.
4305 if (D->getSelfDecl())
4306 ToMethod->createImplicitParams(Importer.getToContext(),
4307 ToMethod->getClassInterface());
4308
4309 return ToMethod;
4310}
4311
4312ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
4313 // Import the major distinguishing characteristics of a category.
4314 DeclContext *DC, *LexicalDC;
4315 DeclarationName Name;
4316 SourceLocation Loc;
4317 NamedDecl *ToD;
4318 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4319 return std::move(Err);
4320 if (ToD)
4321 return ToD;
4322
4323 Error Err = Error::success();
4324 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4325 auto ToLocation = importChecked(Err, D->getLocation());
4326 auto ToColonLoc = importChecked(Err, D->getColonLoc());
4327 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4328 if (Err)
4329 return std::move(Err);
4330
4331 ObjCTypeParamDecl *Result;
4332 if (GetImportedOrCreateDecl(
4333 Result, D, Importer.getToContext(), DC, D->getVariance(),
4334 ToVarianceLoc, D->getIndex(),
4335 ToLocation, Name.getAsIdentifierInfo(),
4336 ToColonLoc, ToTypeSourceInfo))
4337 return Result;
4338
4339 Result->setLexicalDeclContext(LexicalDC);
4340 return Result;
4341}
4342
4343ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
4344 // Import the major distinguishing characteristics of a category.
4345 DeclContext *DC, *LexicalDC;
4346 DeclarationName Name;
4347 SourceLocation Loc;
4348 NamedDecl *ToD;
4349 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4350 return std::move(Err);
4351 if (ToD)
4352 return ToD;
4353
4354 ObjCInterfaceDecl *ToInterface;
4355 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4356 return std::move(Err);
4357
4358 // Determine if we've already encountered this category.
4359 ObjCCategoryDecl *MergeWithCategory
4360 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4361 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4362 if (!ToCategory) {
4363
4364 Error Err = Error::success();
4365 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4366 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4367 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4368 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4369 if (Err)
4370 return std::move(Err);
4371
4372 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4373 ToAtStartLoc, Loc,
4374 ToCategoryNameLoc,
4375 Name.getAsIdentifierInfo(), ToInterface,
4376 /*TypeParamList=*/nullptr,
4377 ToIvarLBraceLoc,
4378 ToIvarRBraceLoc))
4379 return ToCategory;
4380
4381 ToCategory->setLexicalDeclContext(LexicalDC);
4382 LexicalDC->addDeclInternal(ToCategory);
4383 // Import the type parameter list after MapImported, to avoid
4384 // loops when bringing in their DeclContext.
4385 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4386 ToCategory->setTypeParamList(*PListOrErr);
4387 else
4388 return PListOrErr.takeError();
4389
4390 // Import protocols
4391 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4392 SmallVector<SourceLocation, 4> ProtocolLocs;
4393 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4394 = D->protocol_loc_begin();
4395 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4396 FromProtoEnd = D->protocol_end();
4397 FromProto != FromProtoEnd;
4398 ++FromProto, ++FromProtoLoc) {
4399 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4400 Protocols.push_back(*ToProtoOrErr);
4401 else
4402 return ToProtoOrErr.takeError();
4403
4404 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4405 ProtocolLocs.push_back(*ToProtoLocOrErr);
4406 else
4407 return ToProtoLocOrErr.takeError();
4408 }
4409
4410 // FIXME: If we're merging, make sure that the protocol list is the same.
4411 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4412 ProtocolLocs.data(), Importer.getToContext());
4413
4414 } else {
4415 Importer.MapImported(D, ToCategory);
4416 }
4417
4418 // Import all of the members of this category.
4419 if (Error Err = ImportDeclContext(D))
4420 return std::move(Err);
4421
4422 // If we have an implementation, import it as well.
4423 if (D->getImplementation()) {
4424 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4425 import(D->getImplementation()))
4426 ToCategory->setImplementation(*ToImplOrErr);
4427 else
4428 return ToImplOrErr.takeError();
4429 }
4430
4431 return ToCategory;
4432}
4433
4434Error ASTNodeImporter::ImportDefinition(
4435 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4436 if (To->getDefinition()) {
4437 if (shouldForceImportDeclContext(Kind))
4438 if (Error Err = ImportDeclContext(From))
4439 return Err;
4440 return Error::success();
4441 }
4442
4443 // Start the protocol definition
4444 To->startDefinition();
4445
4446 // Import protocols
4447 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4448 SmallVector<SourceLocation, 4> ProtocolLocs;
4449 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4450 From->protocol_loc_begin();
4451 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4452 FromProtoEnd = From->protocol_end();
4453 FromProto != FromProtoEnd;
4454 ++FromProto, ++FromProtoLoc) {
4455 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4456 Protocols.push_back(*ToProtoOrErr);
4457 else
4458 return ToProtoOrErr.takeError();
4459
4460 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4461 ProtocolLocs.push_back(*ToProtoLocOrErr);
4462 else
4463 return ToProtoLocOrErr.takeError();
4464
4465 }
4466
4467 // FIXME: If we're merging, make sure that the protocol list is the same.
4468 To->setProtocolList(Protocols.data(), Protocols.size(),
4469 ProtocolLocs.data(), Importer.getToContext());
4470
4471 if (shouldForceImportDeclContext(Kind)) {
4472 // Import all of the members of this protocol.
4473 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4474 return Err;
4475 }
4476 return Error::success();
4477}
4478
4479ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4480 // If this protocol has a definition in the translation unit we're coming
4481 // from, but this particular declaration is not that definition, import the
4482 // definition and map to that.
4483 ObjCProtocolDecl *Definition = D->getDefinition();
4484 if (Definition && Definition != D) {
4485 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4486 return Importer.MapImported(D, *ImportedDefOrErr);
4487 else
4488 return ImportedDefOrErr.takeError();
4489 }
4490
4491 // Import the major distinguishing characteristics of a protocol.
4492 DeclContext *DC, *LexicalDC;
4493 DeclarationName Name;
4494 SourceLocation Loc;
4495 NamedDecl *ToD;
4496 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4497 return std::move(Err);
4498 if (ToD)
4499 return ToD;
4500
4501 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4502 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4503 for (auto *FoundDecl : FoundDecls) {
4504 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4505 continue;
4506
4507 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4508 break;
4509 }
4510
4511 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4512 if (!ToProto) {
4513 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4514 if (!ToAtBeginLocOrErr)
4515 return ToAtBeginLocOrErr.takeError();
4516
4517 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4518 Name.getAsIdentifierInfo(), Loc,
4519 *ToAtBeginLocOrErr,
4520 /*PrevDecl=*/nullptr))
4521 return ToProto;
4522 ToProto->setLexicalDeclContext(LexicalDC);
4523 LexicalDC->addDeclInternal(ToProto);
4524 }
4525
4526 Importer.MapImported(D, ToProto);
4527
4528 if (D->isThisDeclarationADefinition())
4529 if (Error Err = ImportDefinition(D, ToProto))
4530 return std::move(Err);
4531
4532 return ToProto;
4533}
4534
4535ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4536 DeclContext *DC, *LexicalDC;
4537 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4538 return std::move(Err);
4539
4540 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4541 if (!ExternLocOrErr)
4542 return ExternLocOrErr.takeError();
4543
4544 ExpectedSLoc LangLocOrErr = import(D->getLocation());
4545 if (!LangLocOrErr)
4546 return LangLocOrErr.takeError();
4547
4548 bool HasBraces = D->hasBraces();
4549
4550 LinkageSpecDecl *ToLinkageSpec;
4551 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4552 *ExternLocOrErr, *LangLocOrErr,
4553 D->getLanguage(), HasBraces))
4554 return ToLinkageSpec;
4555
4556 if (HasBraces) {
4557 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4558 if (!RBraceLocOrErr)
4559 return RBraceLocOrErr.takeError();
4560 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4561 }
4562
4563 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4564 LexicalDC->addDeclInternal(ToLinkageSpec);
4565
4566 return ToLinkageSpec;
4567}
4568
4569ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D,
4570 BaseUsingDecl *ToSI) {
4571 for (UsingShadowDecl *FromShadow : D->shadows()) {
4572 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4573 ToSI->addShadowDecl(*ToShadowOrErr);
4574 else
4575 // FIXME: We return error here but the definition is already created
4576 // and available with lookups. How to fix this?..
4577 return ToShadowOrErr.takeError();
4578 }
4579 return ToSI;
4580}
4581
4582ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
4583 DeclContext *DC, *LexicalDC;
4584 DeclarationName Name;
4585 SourceLocation Loc;
4586 NamedDecl *ToD = nullptr;
4587 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4588 return std::move(Err);
4589 if (ToD)
4590 return ToD;
4591
4592 Error Err = Error::success();
4593 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4594 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4595 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4596 if (Err)
4597 return std::move(Err);
4598
4599 DeclarationNameInfo NameInfo(Name, ToLoc);
4600 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4601 return std::move(Err);
4602
4603 UsingDecl *ToUsing;
4604 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4605 ToUsingLoc, ToQualifierLoc, NameInfo,
4606 D->hasTypename()))
4607 return ToUsing;
4608
4609 ToUsing->setLexicalDeclContext(LexicalDC);
4610 LexicalDC->addDeclInternal(ToUsing);
4611
4612 if (NamedDecl *FromPattern =
4613 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4614 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4615 Importer.getToContext().setInstantiatedFromUsingDecl(
4616 ToUsing, *ToPatternOrErr);
4617 else
4618 return ToPatternOrErr.takeError();
4619 }
4620
4621 return ImportUsingShadowDecls(D, ToUsing);
4622}
4623
4624ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) {
4625 DeclContext *DC, *LexicalDC;
4626 DeclarationName Name;
4627 SourceLocation Loc;
4628 NamedDecl *ToD = nullptr;
4629 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4630 return std::move(Err);
4631 if (ToD)
4632 return ToD;
4633
4634 Error Err = Error::success();
4635 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4636 auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
4637 auto ToEnumDecl = importChecked(Err, D->getEnumDecl());
4638 if (Err)
4639 return std::move(Err);
4640
4641 UsingEnumDecl *ToUsingEnum;
4642 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
4643 ToUsingLoc, ToEnumLoc, Loc, ToEnumDecl))
4644 return ToUsingEnum;
4645
4646 ToUsingEnum->setLexicalDeclContext(LexicalDC);
4647 LexicalDC->addDeclInternal(ToUsingEnum);
4648
4649 if (UsingEnumDecl *FromPattern =
4650 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(D)) {
4651 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
4652 Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
4653 *ToPatternOrErr);
4654 else
4655 return ToPatternOrErr.takeError();
4656 }
4657
4658 return ImportUsingShadowDecls(D, ToUsingEnum);
4659}
4660
4661ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
4662 DeclContext *DC, *LexicalDC;
4663 DeclarationName Name;
4664 SourceLocation Loc;
4665 NamedDecl *ToD = nullptr;
4666 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4667 return std::move(Err);
4668 if (ToD)
4669 return ToD;
4670
4671 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
4672 if (!ToIntroducerOrErr)
4673 return ToIntroducerOrErr.takeError();
4674
4675 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4676 if (!ToTargetOrErr)
4677 return ToTargetOrErr.takeError();
4678
4679 UsingShadowDecl *ToShadow;
4680 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4681 Name, *ToIntroducerOrErr, *ToTargetOrErr))
4682 return ToShadow;
4683
4684 ToShadow->setLexicalDeclContext(LexicalDC);
4685 ToShadow->setAccess(D->getAccess());
4686
4687 if (UsingShadowDecl *FromPattern =
4688 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4689 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4690 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4691 ToShadow, *ToPatternOrErr);
4692 else
4693 // FIXME: We return error here but the definition is already created
4694 // and available with lookups. How to fix this?..
4695 return ToPatternOrErr.takeError();
4696 }
4697
4698 LexicalDC->addDeclInternal(ToShadow);
4699
4700 return ToShadow;
4701}
4702
4703ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4704 DeclContext *DC, *LexicalDC;
4705 DeclarationName Name;
4706 SourceLocation Loc;
4707 NamedDecl *ToD = nullptr;
4708 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4709 return std::move(Err);
4710 if (ToD)
4711 return ToD;
4712
4713 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4714 if (!ToComAncestorOrErr)
4715 return ToComAncestorOrErr.takeError();
4716
4717 Error Err = Error::success();
4718 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
4719 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4720 auto ToNamespaceKeyLocation =
4721 importChecked(Err, D->getNamespaceKeyLocation());
4722 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4723 auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
4724 if (Err)
4725 return std::move(Err);
4726
4727 UsingDirectiveDecl *ToUsingDir;
4728 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4729 ToUsingLoc,
4730 ToNamespaceKeyLocation,
4731 ToQualifierLoc,
4732 ToIdentLocation,
4733 ToNominatedNamespace, *ToComAncestorOrErr))
4734 return ToUsingDir;
4735
4736 ToUsingDir->setLexicalDeclContext(LexicalDC);
4737 LexicalDC->addDeclInternal(ToUsingDir);
4738
4739 return ToUsingDir;
4740}
4741
4742ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
4743 UnresolvedUsingValueDecl *D) {
4744 DeclContext *DC, *LexicalDC;
4745 DeclarationName Name;
4746 SourceLocation Loc;
4747 NamedDecl *ToD = nullptr;
4748 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4749 return std::move(Err);
4750 if (ToD)
4751 return ToD;
4752
4753 Error Err = Error::success();
4754 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4755 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4756 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4757 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4758 if (Err)
4759 return std::move(Err);
4760
4761 DeclarationNameInfo NameInfo(Name, ToLoc);
4762 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4763 return std::move(Err);
4764
4765 UnresolvedUsingValueDecl *ToUsingValue;
4766 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4767 ToUsingLoc, ToQualifierLoc, NameInfo,
4768 ToEllipsisLoc))
4769 return ToUsingValue;
4770
4771 ToUsingValue->setAccess(D->getAccess());
4772 ToUsingValue->setLexicalDeclContext(LexicalDC);
4773 LexicalDC->addDeclInternal(ToUsingValue);
4774
4775 return ToUsingValue;
4776}
4777
4778ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
4779 UnresolvedUsingTypenameDecl *D) {
4780 DeclContext *DC, *LexicalDC;
4781 DeclarationName Name;
4782 SourceLocation Loc;
4783 NamedDecl *ToD = nullptr;
4784 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4785 return std::move(Err);
4786 if (ToD)
4787 return ToD;
4788
4789 Error Err = Error::success();
4790 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4791 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
4792 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4793 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4794 if (Err)
4795 return std::move(Err);
4796
4797 UnresolvedUsingTypenameDecl *ToUsing;
4798 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4799 ToUsingLoc, ToTypenameLoc,
4800 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4801 return ToUsing;
4802
4803 ToUsing->setAccess(D->getAccess());
4804 ToUsing->setLexicalDeclContext(LexicalDC);
4805 LexicalDC->addDeclInternal(ToUsing);
4806
4807 return ToUsing;
4808}
4809
4810ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
4811 Decl* ToD = nullptr;
4812 switch (D->getBuiltinTemplateKind()) {
4813 case BuiltinTemplateKind::BTK__make_integer_seq:
4814 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
4815 break;
4816 case BuiltinTemplateKind::BTK__type_pack_element:
4817 ToD = Importer.getToContext().getTypePackElementDecl();
4818 break;
4819 }
4820 assert(ToD && "BuiltinTemplateDecl of unsupported kind!")(static_cast <bool> (ToD && "BuiltinTemplateDecl of unsupported kind!"
) ? void (0) : __assert_fail ("ToD && \"BuiltinTemplateDecl of unsupported kind!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 4820, __extension__ __PRETTY_FUNCTION__))
;
4821 Importer.MapImported(D, ToD);
4822 return ToD;
4823}
4824
4825Error ASTNodeImporter::ImportDefinition(
4826 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
4827 if (To->getDefinition()) {
4828 // Check consistency of superclass.
4829 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4830 if (FromSuper) {
4831 if (auto FromSuperOrErr = import(FromSuper))
4832 FromSuper = *FromSuperOrErr;
4833 else
4834 return FromSuperOrErr.takeError();
4835 }
4836
4837 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4838 if ((bool)FromSuper != (bool)ToSuper ||
4839 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4840 Importer.ToDiag(To->getLocation(),
4841 diag::warn_odr_objc_superclass_inconsistent)
4842 << To->getDeclName();
4843 if (ToSuper)
4844 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4845 << To->getSuperClass()->getDeclName();
4846 else
4847 Importer.ToDiag(To->getLocation(),
4848 diag::note_odr_objc_missing_superclass);
4849 if (From->getSuperClass())
4850 Importer.FromDiag(From->getSuperClassLoc(),
4851 diag::note_odr_objc_superclass)
4852 << From->getSuperClass()->getDeclName();
4853 else
4854 Importer.FromDiag(From->getLocation(),
4855 diag::note_odr_objc_missing_superclass);
4856 }
4857
4858 if (shouldForceImportDeclContext(Kind))
4859 if (Error Err = ImportDeclContext(From))
4860 return Err;
4861 return Error::success();
4862 }
4863
4864 // Start the definition.
4865 To->startDefinition();
4866
4867 // If this class has a superclass, import it.
4868 if (From->getSuperClass()) {
4869 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4870 To->setSuperClass(*SuperTInfoOrErr);
4871 else
4872 return SuperTInfoOrErr.takeError();
4873 }
4874
4875 // Import protocols
4876 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4877 SmallVector<SourceLocation, 4> ProtocolLocs;
4878 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
4879 From->protocol_loc_begin();
4880
4881 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4882 FromProtoEnd = From->protocol_end();
4883 FromProto != FromProtoEnd;
4884 ++FromProto, ++FromProtoLoc) {
4885 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4886 Protocols.push_back(*ToProtoOrErr);
4887 else
4888 return ToProtoOrErr.takeError();
4889
4890 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4891 ProtocolLocs.push_back(*ToProtoLocOrErr);
4892 else
4893 return ToProtoLocOrErr.takeError();
4894
4895 }
4896
4897 // FIXME: If we're merging, make sure that the protocol list is the same.
4898 To->setProtocolList(Protocols.data(), Protocols.size(),
4899 ProtocolLocs.data(), Importer.getToContext());
4900
4901 // Import categories. When the categories themselves are imported, they'll
4902 // hook themselves into this interface.
4903 for (auto *Cat : From->known_categories()) {
4904 auto ToCatOrErr = import(Cat);
4905 if (!ToCatOrErr)
4906 return ToCatOrErr.takeError();
4907 }
4908
4909 // If we have an @implementation, import it as well.
4910 if (From->getImplementation()) {
4911 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4912 import(From->getImplementation()))
4913 To->setImplementation(*ToImplOrErr);
4914 else
4915 return ToImplOrErr.takeError();
4916 }
4917
4918 // Import all of the members of this class.
4919 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4920 return Err;
4921
4922 return Error::success();
4923}
4924
4925Expected<ObjCTypeParamList *>
4926ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4927 if (!list)
4928 return nullptr;
4929
4930 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4931 for (auto *fromTypeParam : *list) {
4932 if (auto toTypeParamOrErr = import(fromTypeParam))
4933 toTypeParams.push_back(*toTypeParamOrErr);
4934 else
4935 return toTypeParamOrErr.takeError();
4936 }
4937
4938 auto LAngleLocOrErr = import(list->getLAngleLoc());
4939 if (!LAngleLocOrErr)
4940 return LAngleLocOrErr.takeError();
4941
4942 auto RAngleLocOrErr = import(list->getRAngleLoc());
4943 if (!RAngleLocOrErr)
4944 return RAngleLocOrErr.takeError();
4945
4946 return ObjCTypeParamList::create(Importer.getToContext(),
4947 *LAngleLocOrErr,
4948 toTypeParams,
4949 *RAngleLocOrErr);
4950}
4951
4952ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
4953 // If this class has a definition in the translation unit we're coming from,
4954 // but this particular declaration is not that definition, import the
4955 // definition and map to that.
4956 ObjCInterfaceDecl *Definition = D->getDefinition();
4957 if (Definition && Definition != D) {
4958 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4959 return Importer.MapImported(D, *ImportedDefOrErr);
4960 else
4961 return ImportedDefOrErr.takeError();
4962 }
4963
4964 // Import the major distinguishing characteristics of an @interface.
4965 DeclContext *DC, *LexicalDC;
4966 DeclarationName Name;
4967 SourceLocation Loc;
4968 NamedDecl *ToD;
4969 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4970 return std::move(Err);
4971 if (ToD)
4972 return ToD;
4973
4974 // Look for an existing interface with the same name.
4975 ObjCInterfaceDecl *MergeWithIface = nullptr;
4976 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4977 for (auto *FoundDecl : FoundDecls) {
4978 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4979 continue;
4980
4981 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4982 break;
4983 }
4984
4985 // Create an interface declaration, if one does not already exist.
4986 ObjCInterfaceDecl *ToIface = MergeWithIface;
4987 if (!ToIface) {
4988 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4989 if (!AtBeginLocOrErr)
4990 return AtBeginLocOrErr.takeError();
4991
4992 if (GetImportedOrCreateDecl(
4993 ToIface, D, Importer.getToContext(), DC,
4994 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4995 /*TypeParamList=*/nullptr,
4996 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4997 return ToIface;
4998 ToIface->setLexicalDeclContext(LexicalDC);
4999 LexicalDC->addDeclInternal(ToIface);
5000 }
5001 Importer.MapImported(D, ToIface);
5002 // Import the type parameter list after MapImported, to avoid
5003 // loops when bringing in their DeclContext.
5004 if (auto ToPListOrErr =
5005 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
5006 ToIface->setTypeParamList(*ToPListOrErr);
5007 else
5008 return ToPListOrErr.takeError();
5009
5010 if (D->isThisDeclarationADefinition())
5011 if (Error Err = ImportDefinition(D, ToIface))
5012 return std::move(Err);
5013
5014 return ToIface;
5015}
5016
5017ExpectedDecl
5018ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
5019 ObjCCategoryDecl *Category;
5020 if (Error Err = importInto(Category, D->getCategoryDecl()))
5021 return std::move(Err);
5022
5023 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5024 if (!ToImpl) {
5025 DeclContext *DC, *LexicalDC;
5026 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5027 return std::move(Err);
5028
5029 Error Err = Error::success();
5030 auto ToLocation = importChecked(Err, D->getLocation());
5031 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5032 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
5033 if (Err)
5034 return std::move(Err);
5035
5036 if (GetImportedOrCreateDecl(
5037 ToImpl, D, Importer.getToContext(), DC,
5038 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5039 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5040 return ToImpl;
5041
5042 ToImpl->setLexicalDeclContext(LexicalDC);
5043 LexicalDC->addDeclInternal(ToImpl);
5044 Category->setImplementation(ToImpl);
5045 }
5046
5047 Importer.MapImported(D, ToImpl);
5048 if (Error Err = ImportDeclContext(D))
5049 return std::move(Err);
5050
5051 return ToImpl;
5052}
5053
5054ExpectedDecl
5055ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
5056 // Find the corresponding interface.
5057 ObjCInterfaceDecl *Iface;
5058 if (Error Err = importInto(Iface, D->getClassInterface()))
5059 return std::move(Err);
5060
5061 // Import the superclass, if any.
5062 ObjCInterfaceDecl *Super;
5063 if (Error Err = importInto(Super, D->getSuperClass()))
5064 return std::move(Err);
5065
5066 ObjCImplementationDecl *Impl = Iface->getImplementation();
5067 if (!Impl) {
5068 // We haven't imported an implementation yet. Create a new @implementation
5069 // now.
5070 DeclContext *DC, *LexicalDC;
5071 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5072 return std::move(Err);
5073
5074 Error Err = Error::success();
5075 auto ToLocation = importChecked(Err, D->getLocation());
5076 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5077 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
5078 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
5079 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
5080 if (Err)
5081 return std::move(Err);
5082
5083 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5084 DC, Iface, Super,
5085 ToLocation,
5086 ToAtStartLoc,
5087 ToSuperClassLoc,
5088 ToIvarLBraceLoc,
5089 ToIvarRBraceLoc))
5090 return Impl;
5091
5092 Impl->setLexicalDeclContext(LexicalDC);
5093
5094 // Associate the implementation with the class it implements.
5095 Iface->setImplementation(Impl);
5096 Importer.MapImported(D, Iface->getImplementation());
5097 } else {
5098 Importer.MapImported(D, Iface->getImplementation());
5099
5100 // Verify that the existing @implementation has the same superclass.
5101 if ((Super && !Impl->getSuperClass()) ||
5102 (!Super && Impl->getSuperClass()) ||
5103 (Super && Impl->getSuperClass() &&
5104 !declaresSameEntity(Super->getCanonicalDecl(),
5105 Impl->getSuperClass()))) {
5106 Importer.ToDiag(Impl->getLocation(),
5107 diag::warn_odr_objc_superclass_inconsistent)
5108 << Iface->getDeclName();
5109 // FIXME: It would be nice to have the location of the superclass
5110 // below.
5111 if (Impl->getSuperClass())
5112 Importer.ToDiag(Impl->getLocation(),
5113 diag::note_odr_objc_superclass)
5114 << Impl->getSuperClass()->getDeclName();
5115 else
5116 Importer.ToDiag(Impl->getLocation(),
5117 diag::note_odr_objc_missing_superclass);
5118 if (D->getSuperClass())
5119 Importer.FromDiag(D->getLocation(),
5120 diag::note_odr_objc_superclass)
5121 << D->getSuperClass()->getDeclName();
5122 else
5123 Importer.FromDiag(D->getLocation(),
5124 diag::note_odr_objc_missing_superclass);
5125
5126 return make_error<ImportError>(ImportError::NameConflict);
5127 }
5128 }
5129
5130 // Import all of the members of this @implementation.
5131 if (Error Err = ImportDeclContext(D))
5132 return std::move(Err);
5133
5134 return Impl;
5135}
5136
5137ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
5138 // Import the major distinguishing characteristics of an @property.
5139 DeclContext *DC, *LexicalDC;
5140 DeclarationName Name;
5141 SourceLocation Loc;
5142 NamedDecl *ToD;
5143 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5144 return std::move(Err);
5145 if (ToD)
5146 return ToD;
5147
5148 // Check whether we have already imported this property.
5149 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5150 for (auto *FoundDecl : FoundDecls) {
5151 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
5152 // Instance and class properties can share the same name but are different
5153 // declarations.
5154 if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5155 continue;
5156
5157 // Check property types.
5158 if (!Importer.IsStructurallyEquivalent(D->getType(),
5159 FoundProp->getType())) {
5160 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5161 << Name << D->getType() << FoundProp->getType();
5162 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5163 << FoundProp->getType();
5164
5165 return make_error<ImportError>(ImportError::NameConflict);
5166 }
5167
5168 // FIXME: Check property attributes, getters, setters, etc.?
5169
5170 // Consider these properties to be equivalent.
5171 Importer.MapImported(D, FoundProp);
5172 return FoundProp;
5173 }
5174 }
5175
5176 Error Err = Error::success();
5177 auto ToType = importChecked(Err, D->getType());
5178 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5179 auto ToAtLoc = importChecked(Err, D->getAtLoc());
5180 auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
5181 if (Err)
5182 return std::move(Err);
5183
5184 // Create the new property.
5185 ObjCPropertyDecl *ToProperty;
5186 if (GetImportedOrCreateDecl(
5187 ToProperty, D, Importer.getToContext(), DC, Loc,
5188 Name.getAsIdentifierInfo(), ToAtLoc,
5189 ToLParenLoc, ToType,
5190 ToTypeSourceInfo, D->getPropertyImplementation()))
5191 return ToProperty;
5192
5193 auto ToGetterName = importChecked(Err, D->getGetterName());
5194 auto ToSetterName = importChecked(Err, D->getSetterName());
5195 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
5196 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
5197 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
5198 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
5199 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
5200 if (Err)
5201 return std::move(Err);
5202
5203 ToProperty->setLexicalDeclContext(LexicalDC);
5204 LexicalDC->addDeclInternal(ToProperty);
5205
5206 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5207 ToProperty->setPropertyAttributesAsWritten(
5208 D->getPropertyAttributesAsWritten());
5209 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
5210 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
5211 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5212 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5213 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5214 return ToProperty;
5215}
5216
5217ExpectedDecl
5218ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
5219 ObjCPropertyDecl *Property;
5220 if (Error Err = importInto(Property, D->getPropertyDecl()))
5221 return std::move(Err);
5222
5223 DeclContext *DC, *LexicalDC;
5224 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5225 return std::move(Err);
5226
5227 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
5228
5229 // Import the ivar (for an @synthesize).
5230 ObjCIvarDecl *Ivar = nullptr;
5231 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
5232 return std::move(Err);
5233
5234 ObjCPropertyImplDecl *ToImpl
5235 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
5236 Property->getQueryKind());
5237 if (!ToImpl) {
5238
5239 Error Err = Error::success();
5240 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
5241 auto ToLocation = importChecked(Err, D->getLocation());
5242 auto ToPropertyIvarDeclLoc =
5243 importChecked(Err, D->getPropertyIvarDeclLoc());
5244 if (Err)
5245 return std::move(Err);
5246
5247 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
5248 ToBeginLoc,
5249 ToLocation, Property,
5250 D->getPropertyImplementation(), Ivar,
5251 ToPropertyIvarDeclLoc))
5252 return ToImpl;
5253
5254 ToImpl->setLexicalDeclContext(LexicalDC);
5255 LexicalDC->addDeclInternal(ToImpl);
5256 } else {
5257 // Check that we have the same kind of property implementation (@synthesize
5258 // vs. @dynamic).
5259 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5260 Importer.ToDiag(ToImpl->getLocation(),
5261 diag::warn_odr_objc_property_impl_kind_inconsistent)
5262 << Property->getDeclName()
5263 << (ToImpl->getPropertyImplementation()
5264 == ObjCPropertyImplDecl::Dynamic);
5265 Importer.FromDiag(D->getLocation(),
5266 diag::note_odr_objc_property_impl_kind)
5267 << D->getPropertyDecl()->getDeclName()
5268 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5269
5270 return make_error<ImportError>(ImportError::NameConflict);
5271 }
5272
5273 // For @synthesize, check that we have the same
5274 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5275 Ivar != ToImpl->getPropertyIvarDecl()) {
5276 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
5277 diag::warn_odr_objc_synthesize_ivar_inconsistent)
5278 << Property->getDeclName()
5279 << ToImpl->getPropertyIvarDecl()->getDeclName()
5280 << Ivar->getDeclName();
5281 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
5282 diag::note_odr_objc_synthesize_ivar_here)
5283 << D->getPropertyIvarDecl()->getDeclName();
5284
5285 return make_error<ImportError>(ImportError::NameConflict);
5286 }
5287
5288 // Merge the existing implementation with the new implementation.
5289 Importer.MapImported(D, ToImpl);
5290 }
5291
5292 return ToImpl;
5293}
5294
5295ExpectedDecl
5296ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
5297 // For template arguments, we adopt the translation unit as our declaration
5298 // context. This context will be fixed when the actual template declaration
5299 // is created.
5300
5301 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5302 if (!BeginLocOrErr)
5303 return BeginLocOrErr.takeError();
5304
5305 ExpectedSLoc LocationOrErr = import(D->getLocation());
5306 if (!LocationOrErr)
5307 return LocationOrErr.takeError();
5308
5309 TemplateTypeParmDecl *ToD = nullptr;
5310 if (GetImportedOrCreateDecl(
5311 ToD, D, Importer.getToContext(),
5312 Importer.getToContext().getTranslationUnitDecl(),
5313 *BeginLocOrErr, *LocationOrErr,
5314 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5315 D->wasDeclaredWithTypename(), D->isParameterPack(),
5316 D->hasTypeConstraint()))
5317 return ToD;
5318
5319 // Import the type-constraint
5320 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5321
5322 Error Err = Error::success();
5323 auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc());
5324 auto ToName = importChecked(Err, TC->getConceptNameInfo().getName());
5325 auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc());
5326 auto ToFoundDecl = importChecked(Err, TC->getFoundDecl());
5327 auto ToNamedConcept = importChecked(Err, TC->getNamedConcept());
5328 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
5329 if (Err)
5330 return std::move(Err);
5331
5332 TemplateArgumentListInfo ToTAInfo;
5333 const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten();
5334 if (ASTTemplateArgs)
5335 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs,
5336 ToTAInfo))
5337 return std::move(Err);
5338
5339 ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc),
5340 ToFoundDecl, ToNamedConcept,
5341 ASTTemplateArgs ?
5342 ASTTemplateArgumentListInfo::Create(Importer.getToContext(),
5343 ToTAInfo) : nullptr,
5344 ToIDC);
5345 }
5346
5347 if (D->hasDefaultArgument()) {
5348 Expected<TypeSourceInfo *> ToDefaultArgOrErr =
5349 import(D->getDefaultArgumentInfo());
5350 if (!ToDefaultArgOrErr)
5351 return ToDefaultArgOrErr.takeError();
5352 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5353 }
5354
5355 return ToD;
5356}
5357
5358ExpectedDecl
5359ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
5360
5361 Error Err = Error::success();
5362 auto ToDeclName = importChecked(Err, D->getDeclName());
5363 auto ToLocation = importChecked(Err, D->getLocation());
5364 auto ToType = importChecked(Err, D->getType());
5365 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5366 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
5367 if (Err)
5368 return std::move(Err);
5369
5370 NonTypeTemplateParmDecl *ToD = nullptr;
5371 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
5372 Importer.getToContext().getTranslationUnitDecl(),
5373 ToInnerLocStart, ToLocation, D->getDepth(),
5374 D->getPosition(),
5375 ToDeclName.getAsIdentifierInfo(), ToType,
5376 D->isParameterPack(), ToTypeSourceInfo))
5377 return ToD;
5378
5379 if (D->hasDefaultArgument()) {
5380 ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument());
5381 if (!ToDefaultArgOrErr)
5382 return ToDefaultArgOrErr.takeError();
5383 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5384 }
5385
5386 return ToD;
5387}
5388
5389ExpectedDecl
5390ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
5391 // Import the name of this declaration.
5392 auto NameOrErr = import(D->getDeclName());
5393 if (!NameOrErr)
5394 return NameOrErr.takeError();
5395
5396 // Import the location of this declaration.
5397 ExpectedSLoc LocationOrErr = import(D->getLocation());
5398 if (!LocationOrErr)
5399 return LocationOrErr.takeError();
5400
5401 // Import template parameters.
5402 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5403 if (!TemplateParamsOrErr)
5404 return TemplateParamsOrErr.takeError();
5405
5406 TemplateTemplateParmDecl *ToD = nullptr;
5407 if (GetImportedOrCreateDecl(
5408 ToD, D, Importer.getToContext(),
5409 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5410 D->getDepth(), D->getPosition(), D->isParameterPack(),
5411 (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr))
5412 return ToD;
5413
5414 if (D->hasDefaultArgument()) {
5415 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5416 import(D->getDefaultArgument());
5417 if (!ToDefaultArgOrErr)
5418 return ToDefaultArgOrErr.takeError();
5419 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
5420 }
5421
5422 return ToD;
5423}
5424
5425// Returns the definition for a (forward) declaration of a TemplateDecl, if
5426// it has any definition in the redecl chain.
5427template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5428 assert(D->getTemplatedDecl() && "Should be called on templates only")(static_cast <bool> (D->getTemplatedDecl() &&
"Should be called on templates only") ? void (0) : __assert_fail
("D->getTemplatedDecl() && \"Should be called on templates only\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 5428, __extension__ __PRETTY_FUNCTION__))
;
5429 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
5430 if (!ToTemplatedDef)
5431 return nullptr;
5432 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
5433 return cast_or_null<T>(TemplateWithDef);
5434}
5435
5436ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
5437
5438 // Import the major distinguishing characteristics of this class template.
5439 DeclContext *DC, *LexicalDC;
5440 DeclarationName Name;
5441 SourceLocation Loc;
5442 NamedDecl *ToD;
5443 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5444 return std::move(Err);
5445 if (ToD)
5446 return ToD;
5447
5448 ClassTemplateDecl *FoundByLookup = nullptr;
5449
5450 // We may already have a template of the same name; try to find and match it.
5451 if (!DC->isFunctionOrMethod()) {
5452 SmallVector<NamedDecl *, 4> ConflictingDecls;
5453 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5454 for (auto *FoundDecl : FoundDecls) {
5455 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
5456 Decl::IDNS_TagFriend))
5457 continue;
5458
5459 Decl *Found = FoundDecl;
5460 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5461 if (FoundTemplate) {
5462 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
5463 continue;
5464
5465 if (IsStructuralMatch(D, FoundTemplate)) {
5466 ClassTemplateDecl *TemplateWithDef =
5467 getTemplateDefinition(FoundTemplate);
5468 if (D->isThisDeclarationADefinition() && TemplateWithDef)
5469 return Importer.MapImported(D, TemplateWithDef);
5470 if (!FoundByLookup)
5471 FoundByLookup = FoundTemplate;
5472 // Search in all matches because there may be multiple decl chains,
5473 // see ASTTests test ImportExistingFriendClassTemplateDef.
5474 continue;
5475 }
5476 ConflictingDecls.push_back(FoundDecl);
5477 }
5478 }
5479
5480 if (!ConflictingDecls.empty()) {
5481 ExpectedName NameOrErr = Importer.HandleNameConflict(
5482 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5483 ConflictingDecls.size());
5484 if (NameOrErr)
5485 Name = NameOrErr.get();
5486 else
5487 return NameOrErr.takeError();
5488 }
5489 }
5490
5491 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5492
5493 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5494 if (!TemplateParamsOrErr)
5495 return TemplateParamsOrErr.takeError();
5496
5497 // Create the declaration that is being templated.
5498 CXXRecordDecl *ToTemplated;
5499 if (Error Err = importInto(ToTemplated, FromTemplated))
5500 return std::move(Err);
5501
5502 // Create the class template declaration itself.
5503 ClassTemplateDecl *D2;
5504 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5505 *TemplateParamsOrErr, ToTemplated))
5506 return D2;
5507
5508 ToTemplated->setDescribedClassTemplate(D2);
5509
5510 D2->setAccess(D->getAccess());
5511 D2->setLexicalDeclContext(LexicalDC);
5512
5513 addDeclToContexts(D, D2);
5514
5515 if (FoundByLookup) {
5516 auto *Recent =
5517 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5518
5519 // It is possible that during the import of the class template definition
5520 // we start the import of a fwd friend decl of the very same class template
5521 // and we add the fwd friend decl to the lookup table. But the ToTemplated
5522 // had been created earlier and by that time the lookup could not find
5523 // anything existing, so it has no previous decl. Later, (still during the
5524 // import of the fwd friend decl) we start to import the definition again
5525 // and this time the lookup finds the previous fwd friend class template.
5526 // In this case we must set up the previous decl for the templated decl.
5527 if (!ToTemplated->getPreviousDecl()) {
5528 assert(FoundByLookup->getTemplatedDecl() &&(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 5529, __extension__ __PRETTY_FUNCTION__))
5529 "Found decl must have its templated decl set")(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 5529, __extension__ __PRETTY_FUNCTION__))
;
5530 CXXRecordDecl *PrevTemplated =
5531 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5532 if (ToTemplated != PrevTemplated)
5533 ToTemplated->setPreviousDecl(PrevTemplated);
5534 }
5535
5536 D2->setPreviousDecl(Recent);
5537 }
5538
5539 if (FromTemplated->isCompleteDefinition() &&
5540 !ToTemplated->isCompleteDefinition()) {
5541 // FIXME: Import definition!
5542 }
5543
5544 return D2;
5545}
5546
5547ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
5548 ClassTemplateSpecializationDecl *D) {
5549 ClassTemplateDecl *ClassTemplate;
5550 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5551 return std::move(Err);
5552
5553 // Import the context of this declaration.
5554 DeclContext *DC, *LexicalDC;
5555 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5556 return std::move(Err);
5557
5558 // Import template arguments.
5559 SmallVector<TemplateArgument, 2> TemplateArgs;
5560 if (Error Err = ImportTemplateArguments(
5561 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5562 return std::move(Err);
5563 // Try to find an existing specialization with these template arguments and
5564 // template parameter list.
5565 void *InsertPos = nullptr;
5566 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5567 ClassTemplatePartialSpecializationDecl *PartialSpec =
5568 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
5569
5570 // Import template parameters.
5571 TemplateParameterList *ToTPList = nullptr;
5572
5573 if (PartialSpec) {
5574 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5575 if (!ToTPListOrErr)
5576 return ToTPListOrErr.takeError();
5577 ToTPList = *ToTPListOrErr;
5578 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
5579 *ToTPListOrErr,
5580 InsertPos);
5581 } else
5582 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5583
5584 if (PrevDecl) {
5585 if (IsStructuralMatch(D, PrevDecl)) {
5586 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
5587 if (D->isThisDeclarationADefinition() && PrevDefinition) {
5588 Importer.MapImported(D, PrevDefinition);
5589 // Import those default field initializers which have been
5590 // instantiated in the "From" context, but not in the "To" context.
5591 for (auto *FromField : D->fields()) {
5592 auto ToOrErr = import(FromField);
5593 if (!ToOrErr)
5594 return ToOrErr.takeError();
5595 }
5596
5597 // Import those methods which have been instantiated in the
5598 // "From" context, but not in the "To" context.
5599 for (CXXMethodDecl *FromM : D->methods()) {
5600 auto ToOrErr = import(FromM);
5601 if (!ToOrErr)
5602 return ToOrErr.takeError();
5603 }
5604
5605 // TODO Import instantiated default arguments.
5606 // TODO Import instantiated exception specifications.
5607 //
5608 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5609 // what else could be fused during an AST merge.
5610 return PrevDefinition;
5611 }
5612 } else { // ODR violation.
5613 // FIXME HandleNameConflict
5614 return make_error<ImportError>(ImportError::NameConflict);
5615 }
5616 }
5617
5618 // Import the location of this declaration.
5619 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5620 if (!BeginLocOrErr)
5621 return BeginLocOrErr.takeError();
5622 ExpectedSLoc IdLocOrErr = import(D->getLocation());
5623 if (!IdLocOrErr)
5624 return IdLocOrErr.takeError();
5625
5626 // Create the specialization.
5627 ClassTemplateSpecializationDecl *D2 = nullptr;
5628 if (PartialSpec) {
5629 // Import TemplateArgumentListInfo.
5630 TemplateArgumentListInfo ToTAInfo;
5631 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5632 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5633 return std::move(Err);
5634
5635 QualType CanonInjType;
5636 if (Error Err = importInto(
5637 CanonInjType, PartialSpec->getInjectedSpecializationType()))
5638 return std::move(Err);
5639 CanonInjType = CanonInjType.getCanonicalType();
5640
5641 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5642 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5643 *BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate,
5644 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5645 ToTAInfo, CanonInjType,
5646 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5647 return D2;
5648
5649 // Update InsertPos, because preceding import calls may have invalidated
5650 // it by adding new specializations.
5651 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
5652 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
5653 InsertPos))
5654 // Add this partial specialization to the class template.
5655 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
5656
5657 } else { // Not a partial specialization.
5658 if (GetImportedOrCreateDecl(
5659 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5660 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5661 PrevDecl))
5662 return D2;
5663
5664 // Update InsertPos, because preceding import calls may have invalidated
5665 // it by adding new specializations.
5666 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5667 // Add this specialization to the class template.
5668 ClassTemplate->AddSpecialization(D2, InsertPos);
5669 }
5670
5671 D2->setSpecializationKind(D->getSpecializationKind());
5672
5673 // Set the context of this specialization/instantiation.
5674 D2->setLexicalDeclContext(LexicalDC);
5675
5676 // Add to the DC only if it was an explicit specialization/instantiation.
5677 if (D2->isExplicitInstantiationOrSpecialization()) {
5678 LexicalDC->addDeclInternal(D2);
5679 }
5680
5681 if (auto BraceRangeOrErr = import(D->getBraceRange()))
5682 D2->setBraceRange(*BraceRangeOrErr);
5683 else
5684 return BraceRangeOrErr.takeError();
5685
5686 // Import the qualifier, if any.
5687 if (auto LocOrErr = import(D->getQualifierLoc()))
5688 D2->setQualifierInfo(*LocOrErr);
5689 else
5690 return LocOrErr.takeError();
5691
5692 if (auto *TSI = D->getTypeAsWritten()) {
5693 if (auto TInfoOrErr = import(TSI))
5694 D2->setTypeAsWritten(*TInfoOrErr);
5695 else
5696 return TInfoOrErr.takeError();
5697
5698 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5699 D2->setTemplateKeywordLoc(*LocOrErr);
5700 else
5701 return LocOrErr.takeError();
5702
5703 if (auto LocOrErr = import(D->getExternLoc()))
5704 D2->setExternLoc(*LocOrErr);
5705 else
5706 return LocOrErr.takeError();
5707 }
5708
5709 if (D->getPointOfInstantiation().isValid()) {
5710 if (auto POIOrErr = import(D->getPointOfInstantiation()))
5711 D2->setPointOfInstantiation(*POIOrErr);
5712 else
5713 return POIOrErr.takeError();
5714 }
5715
5716 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
5717
5718 if (D->isCompleteDefinition())
5719 if (Error Err = ImportDefinition(D, D2))
5720 return std::move(Err);
5721
5722 return D2;
5723}
5724
5725ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
5726 // Import the major distinguishing characteristics of this variable template.
5727 DeclContext *DC, *LexicalDC;
5728 DeclarationName Name;
5729 SourceLocation Loc;
5730 NamedDecl *ToD;
5731 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5732 return std::move(Err);
5733 if (ToD)
5734 return ToD;
5735
5736 // We may already have a template of the same name; try to find and match it.
5737 assert(!DC->isFunctionOrMethod() &&(static_cast <bool> (!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope") ?
void (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 5738, __extension__ __PRETTY_FUNCTION__))
5738 "Variable templates cannot be declared at function scope")(static_cast <bool> (!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope") ?
void (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 5738, __extension__ __PRETTY_FUNCTION__))
;
5739
5740 SmallVector<NamedDecl *, 4> ConflictingDecls;
5741 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5742 VarTemplateDecl *FoundByLookup = nullptr;
5743 for (auto *FoundDecl : FoundDecls) {
5744 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5745 continue;
5746
5747 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
5748 // Use the templated decl, some linkage flags are set only there.
5749 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
5750 D->getTemplatedDecl()))
5751 continue;
5752 if (IsStructuralMatch(D, FoundTemplate)) {
5753 // The Decl in the "From" context has a definition, but in the
5754 // "To" context we already have a definition.
5755 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
5756 if (D->isThisDeclarationADefinition() && FoundDef)
5757 // FIXME Check for ODR error if the two definitions have
5758 // different initializers?
5759 return Importer.MapImported(D, FoundDef);
5760
5761 FoundByLookup = FoundTemplate;
5762 break;
5763 }
5764 ConflictingDecls.push_back(FoundDecl);
5765 }
5766 }
5767
5768 if (!ConflictingDecls.empty()) {
5769 ExpectedName NameOrErr = Importer.HandleNameConflict(
5770 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5771 ConflictingDecls.size());
5772 if (NameOrErr)
5773 Name = NameOrErr.get();
5774 else
5775 return NameOrErr.takeError();
5776 }
5777
5778 VarDecl *DTemplated = D->getTemplatedDecl();
5779
5780 // Import the type.
5781 // FIXME: Value not used?
5782 ExpectedType TypeOrErr = import(DTemplated->getType());
5783 if (!TypeOrErr)
5784 return TypeOrErr.takeError();
5785
5786 // Create the declaration that is being templated.
5787 VarDecl *ToTemplated;
5788 if (Error Err = importInto(ToTemplated, DTemplated))
5789 return std::move(Err);
5790
5791 // Create the variable template declaration itself.
5792 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5793 if (!TemplateParamsOrErr)
5794 return TemplateParamsOrErr.takeError();
5795
5796 VarTemplateDecl *ToVarTD;
5797 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5798 Name, *TemplateParamsOrErr, ToTemplated))
5799 return ToVarTD;
5800
5801 ToTemplated->setDescribedVarTemplate(ToVarTD);
5802
5803 ToVarTD->setAccess(D->getAccess());
5804 ToVarTD->setLexicalDeclContext(LexicalDC);
5805 LexicalDC->addDeclInternal(ToVarTD);
5806
5807 if (FoundByLookup) {
5808 auto *Recent =
5809 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5810 if (!ToTemplated->getPreviousDecl()) {
5811 auto *PrevTemplated =
5812 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5813 if (ToTemplated != PrevTemplated)
5814 ToTemplated->setPreviousDecl(PrevTemplated);
5815 }
5816 ToVarTD->setPreviousDecl(Recent);
5817 }
5818
5819 if (DTemplated->isThisDeclarationADefinition() &&
5820 !ToTemplated->isThisDeclarationADefinition()) {
5821 // FIXME: Import definition!
5822 }
5823
5824 return ToVarTD;
5825}
5826
5827ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
5828 VarTemplateSpecializationDecl *D) {
5829 // If this record has a definition in the translation unit we're coming from,
5830 // but this particular declaration is not that definition, import the
5831 // definition and map to that.
5832 VarDecl *Definition = D->getDefinition();
5833 if (Definition && Definition != D) {
5834 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5835 return Importer.MapImported(D, *ImportedDefOrErr);
5836 else
5837 return ImportedDefOrErr.takeError();
5838 }
5839
5840 VarTemplateDecl *VarTemplate = nullptr;
5841 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5842 return std::move(Err);
5843
5844 // Import the context of this declaration.
5845 DeclContext *DC, *LexicalDC;
5846 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5847 return std::move(Err);
5848
5849 // Import the location of this declaration.
5850 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5851 if (!BeginLocOrErr)
5852 return BeginLocOrErr.takeError();
5853
5854 auto IdLocOrErr = import(D->getLocation());
5855 if (!IdLocOrErr)
5856 return IdLocOrErr.takeError();
5857
5858 // Import template arguments.
5859 SmallVector<TemplateArgument, 2> TemplateArgs;
5860 if (Error Err = ImportTemplateArguments(
5861 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5862 return std::move(Err);
5863
5864 // Try to find an existing specialization with these template arguments.
5865 void *InsertPos = nullptr;
5866 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
5867 TemplateArgs, InsertPos);
5868 if (D2) {
5869 // We already have a variable template specialization with these template
5870 // arguments.
5871
5872 // FIXME: Check for specialization vs. instantiation errors.
5873
5874 if (VarDecl *FoundDef = D2->getDefinition()) {
5875 if (!D->isThisDeclarationADefinition() ||
5876 IsStructuralMatch(D, FoundDef)) {
5877 // The record types structurally match, or the "from" translation
5878 // unit only had a forward declaration anyway; call it the same
5879 // variable.
5880 return Importer.MapImported(D, FoundDef);
5881 }
5882 }
5883 } else {
5884 // Import the type.
5885 QualType T;
5886 if (Error Err = importInto(T, D->getType()))
5887 return std::move(Err);
5888
5889 auto TInfoOrErr = import(D->getTypeSourceInfo());
5890 if (!TInfoOrErr)
5891 return TInfoOrErr.takeError();
5892
5893 TemplateArgumentListInfo ToTAInfo;
5894 if (Error Err = ImportTemplateArgumentListInfo(
5895 D->getTemplateArgsInfo(), ToTAInfo))
5896 return std::move(Err);
5897
5898 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5899 // Create a new specialization.
5900 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5901 // Import TemplateArgumentListInfo
5902 TemplateArgumentListInfo ArgInfos;
5903 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5904 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5905 if (Error Err = ImportTemplateArgumentListInfo(
5906 *FromTAArgsAsWritten, ArgInfos))
5907 return std::move(Err);
5908
5909 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5910 if (!ToTPListOrErr)
5911 return ToTPListOrErr.takeError();
5912
5913 PartVarSpecDecl *ToPartial;
5914 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5915 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5916 VarTemplate, T, *TInfoOrErr,
5917 D->getStorageClass(), TemplateArgs, ArgInfos))
5918 return ToPartial;
5919
5920 if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5921 FromPartial->getInstantiatedFromMember()))
5922 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5923 else
5924 return ToInstOrErr.takeError();
5925
5926 if (FromPartial->isMemberSpecialization())
5927 ToPartial->setMemberSpecialization();
5928
5929 D2 = ToPartial;
5930
5931 } else { // Full specialization
5932 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5933 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5934 T, *TInfoOrErr,
5935 D->getStorageClass(), TemplateArgs))
5936 return D2;
5937 }
5938
5939 if (D->getPointOfInstantiation().isValid()) {
5940 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5941 D2->setPointOfInstantiation(*POIOrErr);
5942 else
5943 return POIOrErr.takeError();
5944 }
5945
5946 D2->setSpecializationKind(D->getSpecializationKind());
5947 D2->setTemplateArgsInfo(ToTAInfo);
5948
5949 // Add this specialization to the class template.
5950 VarTemplate->AddSpecialization(D2, InsertPos);
5951
5952 // Import the qualifier, if any.
5953 if (auto LocOrErr = import(D->getQualifierLoc()))
5954 D2->setQualifierInfo(*LocOrErr);
5955 else
5956 return LocOrErr.takeError();
5957
5958 if (D->isConstexpr())
5959 D2->setConstexpr(true);
5960
5961 // Add the specialization to this context.
5962 D2->setLexicalDeclContext(LexicalDC);
5963 LexicalDC->addDeclInternal(D2);
5964
5965 D2->setAccess(D->getAccess());
5966 }
5967
5968 if (Error Err = ImportInitializer(D, D2))
5969 return std::move(Err);
5970
5971 return D2;
5972}
5973
5974ExpectedDecl
5975ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
5976 DeclContext *DC, *LexicalDC;
5977 DeclarationName Name;
5978 SourceLocation Loc;
5979 NamedDecl *ToD;
5980
5981 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5982 return std::move(Err);
5983
5984 if (ToD)
5985 return ToD;
5986
5987 const FunctionTemplateDecl *FoundByLookup = nullptr;
5988
5989 // Try to find a function in our own ("to") context with the same name, same
5990 // type, and in the same context as the function we're importing.
5991 // FIXME Split this into a separate function.
5992 if (!LexicalDC->isFunctionOrMethod()) {
5993 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
5994 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5995 for (auto *FoundDecl : FoundDecls) {
5996 if (!FoundDecl->isInIdentifierNamespace(IDNS))
5997 continue;
5998
5999 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
6000 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
6001 continue;
6002 if (IsStructuralMatch(D, FoundTemplate)) {
6003 FunctionTemplateDecl *TemplateWithDef =
6004 getTemplateDefinition(FoundTemplate);
6005 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6006 return Importer.MapImported(D, TemplateWithDef);
6007
6008 FoundByLookup = FoundTemplate;
6009 break;
6010 // TODO: handle conflicting names
6011 }
6012 }
6013 }
6014 }
6015
6016 auto ParamsOrErr = import(D->getTemplateParameters());
6017 if (!ParamsOrErr)
6018 return ParamsOrErr.takeError();
6019
6020 FunctionDecl *TemplatedFD;
6021 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
6022 return std::move(Err);
6023
6024 FunctionTemplateDecl *ToFunc;
6025 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
6026 *ParamsOrErr, TemplatedFD))
6027 return ToFunc;
6028
6029 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
6030
6031 ToFunc->setAccess(D->getAccess());
6032 ToFunc->setLexicalDeclContext(LexicalDC);
6033 LexicalDC->addDeclInternal(ToFunc);
6034
6035 if (FoundByLookup) {
6036 auto *Recent =
6037 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6038 if (!TemplatedFD->getPreviousDecl()) {
6039 assert(FoundByLookup->getTemplatedDecl() &&(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 6040, __extension__ __PRETTY_FUNCTION__))
6040 "Found decl must have its templated decl set")(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/ASTImporter.cpp"
, 6040, __extension__ __PRETTY_FUNCTION__))
;
6041 auto *PrevTemplated =
6042 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6043 if (TemplatedFD != PrevTemplated)
6044 TemplatedFD->setPreviousDecl(PrevTemplated);
6045 }
6046 ToFunc->setPreviousDecl(Recent);
6047 }
6048
6049 return ToFunc;
6050}
6051
6052//----------------------------------------------------------------------------
6053// Import Statements
6054//----------------------------------------------------------------------------
6055
6056ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
6057 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
6058 << S->getStmtClassName();
6059 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6060}
6061
6062
6063ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
6064 if (Importer.returnWithErrorInTest())
6065 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6066 SmallVector<IdentifierInfo *, 4> Names;
6067 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6068 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
6069 // ToII is nullptr when no symbolic name is given for output operand
6070 // see ParseStmtAsm::ParseAsmOperandsOpt
6071 Names.push_back(ToII);
6072 }
6073
6074 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6075 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
6076 // ToII is nullptr when no symbolic name is given for input operand
6077 // see ParseStmtAsm::ParseAsmOperandsOpt
6078 Names.push_back(ToII);
6079 }
6080
6081 SmallVector<StringLiteral *, 4> Clobbers;
6082 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
6083 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
6084 Clobbers.push_back(*ClobberOrErr);
6085 else
6086 return ClobberOrErr.takeError();
6087
6088 }
6089
6090 SmallVector<StringLiteral *, 4> Constraints;
6091 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6092 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
6093 Constraints.push_back(*OutputOrErr);
6094 else
6095 return OutputOrErr.takeError();
6096 }
6097
6098 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6099 if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
6100 Constraints.push_back(*InputOrErr);
6101 else
6102 return InputOrErr.takeError();
6103 }
6104
6105 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
6106 S->getNumLabels());
6107 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
6108 return std::move(Err);
6109
6110 if (Error Err =
6111 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
6112 return std::move(Err);
6113
6114 if (Error Err = ImportArrayChecked(
6115 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
6116 return std::move(Err);
6117
6118 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
6119 if (!AsmLocOrErr)
6120 return AsmLocOrErr.takeError();
6121 auto AsmStrOrErr = import(S->getAsmString());
6122 if (!AsmStrOrErr)
6123 return AsmStrOrErr.takeError();
6124 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
6125 if (!RParenLocOrErr)
6126 return RParenLocOrErr.takeError();
6127
6128 return new (Importer.getToContext()) GCCAsmStmt(
6129 Importer.getToContext(),
6130 *AsmLocOrErr,
6131 S->isSimple(),
6132 S->isVolatile(),
6133 S->getNumOutputs(),
6134 S->getNumInputs(),
6135 Names.data(),
6136 Constraints.data(),
6137 Exprs.data(),
6138 *AsmStrOrErr,
6139 S->getNumClobbers(),
6140 Clobbers.data(),
6141 S->getNumLabels(),
6142 *RParenLocOrErr);
6143}
6144
6145ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
6146
6147 Error Err = Error::success();
6148 auto ToDG = importChecked(Err, S->getDeclGroup());
6149 auto ToBeginLoc = importChecked(Err, S->getBeginLoc());