Bug Summary

File:build/source/clang/lib/AST/ASTImporter.cpp
Warning:line 9346, column 47
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/source/clang/lib/AST -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1680300532 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-04-01-083001-16331-1 -x c++ /build/source/clang/lib/AST/ASTImporter.cpp

/build/source/clang/lib/AST/ASTImporter.cpp

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