Bug Summary

File:build/source/clang/include/clang/AST/Expr.h
Warning:line 4238, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-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/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/source/clang/lib/AST -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/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-17/lib/clang/17/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/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1680002200 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -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-2023-03-28-162341-16322-1 -x c++ /build/source/clang/lib/AST/ASTImporter.cpp

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