Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 198, column 16
6th function call argument is an uninitialized value

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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -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~++20220126101029+f487a76430a0/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/AST/ASTImporter.cpp

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