Bug Summary

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