Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 2614, 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 -clear-ast-before-backend -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 -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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 tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/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-14/lib/clang/14.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-command-line-argument -Wno-unknown-warning-option -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-14~++20211016100712+8e1d532707fd/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-10-17-004846-21170-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/clang/lib/AST/ASTImporter.cpp

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