1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the ASTImporter class which imports AST nodes from one
10 // context into another context.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15 #include "clang/AST/ASTImporterSharedState.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTDiagnostic.h"
18 #include "clang/AST/ASTStructuralEquivalence.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclAccessPair.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclVisitor.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExprObjC.h"
33 #include "clang/AST/ExternalASTSource.h"
34 #include "clang/AST/LambdaCapture.h"
35 #include "clang/AST/NestedNameSpecifier.h"
36 #include "clang/AST/OperationKinds.h"
37 #include "clang/AST/Stmt.h"
38 #include "clang/AST/StmtCXX.h"
39 #include "clang/AST/StmtObjC.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TemplateBase.h"
42 #include "clang/AST/TemplateName.h"
43 #include "clang/AST/Type.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/AST/TypeVisitor.h"
46 #include "clang/AST/UnresolvedSet.h"
47 #include "clang/Basic/ExceptionSpecificationType.h"
48 #include "clang/Basic/FileManager.h"
49 #include "clang/Basic/IdentifierTable.h"
50 #include "clang/Basic/LLVM.h"
51 #include "clang/Basic/LangOptions.h"
52 #include "clang/Basic/SourceLocation.h"
53 #include "clang/Basic/SourceManager.h"
54 #include "clang/Basic/Specifiers.h"
55 #include "llvm/ADT/APSInt.h"
56 #include "llvm/ADT/ArrayRef.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/None.h"
59 #include "llvm/ADT/Optional.h"
60 #include "llvm/ADT/ScopeExit.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/MemoryBuffer.h"
70 #include <type_traits>
75 using llvm::make_error;
78 using ExpectedType = llvm::Expected<QualType>;
79 using ExpectedStmt = llvm::Expected<Stmt *>;
80 using ExpectedExpr = llvm::Expected<Expr *>;
81 using ExpectedDecl = llvm::Expected<Decl *>;
82 using ExpectedSLoc = llvm::Expected<SourceLocation>;
84 std::string ImportError::toString() const {
85 // FIXME: Improve error texts.
88 return "NameConflict";
89 case UnsupportedConstruct:
90 return "UnsupportedConstruct";
92 return "Unknown error";
94 llvm_unreachable("Invalid error code.");
95 return "Invalid error code.";
98 void ImportError::log(raw_ostream &OS) const {
102 std::error_code ImportError::convertToErrorCode() const {
103 llvm_unreachable("Function not implemented.");
106 char ImportError::ID;
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);
116 Redecls.push_back(D->getFirstDecl());
117 std::reverse(Redecls.begin(), Redecls.end());
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");
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))
138 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
139 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
140 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
141 ASTImporter &Importer;
143 // Use this instead of Importer.importInto .
144 template <typename ImportT>
145 LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) {
146 return Importer.importInto(To, From);
149 // Use this to import pointers of specific type.
150 template <typename ImportT>
151 LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) {
152 auto ToOrErr = Importer.Import(From);
154 To = cast_or_null<ImportT>(*ToOrErr);
155 return ToOrErr.takeError();
158 // Call the import function of ASTImporter for a baseclass of type `T` and
159 // cast the return value to `T`.
160 template <typename T>
161 Expected<T *> import(T *From) {
162 auto ToOrErr = Importer.Import(From);
164 return ToOrErr.takeError();
165 return cast_or_null<T>(*ToOrErr);
168 template <typename T>
169 Expected<T *> import(const T *From) {
170 return import(const_cast<T *>(From));
173 // Call the import function of ASTImporter for type `T`.
174 template <typename T>
175 Expected<T> import(const T &From) {
176 return Importer.Import(From);
179 // Import an Optional<T> by importing the contained T, if any.
181 Expected<Optional<T>> import(Optional<T> From) {
183 return Optional<T>();
184 return import(*From);
188 Expected<std::tuple<T>>
189 importSeq(const T &From) {
190 Expected<T> ToOrErr = import(From);
192 return ToOrErr.takeError();
193 return std::make_tuple<T>(std::move(*ToOrErr));
196 // Import multiple objects with a single function call.
197 // This should work for every type for which a variant of `import` exists.
198 // The arguments are processed from left to right and import is stopped on
200 template <class THead, class... TTail>
201 Expected<std::tuple<THead, TTail...>>
202 importSeq(const THead &FromHead, const TTail &...FromTail) {
203 Expected<std::tuple<THead>> ToHeadOrErr = importSeq(FromHead);
205 return ToHeadOrErr.takeError();
206 Expected<std::tuple<TTail...>> ToTailOrErr = importSeq(FromTail...);
208 return ToTailOrErr.takeError();
209 return std::tuple_cat(*ToHeadOrErr, *ToTailOrErr);
212 // Wrapper for an overload set.
213 template <typename ToDeclT> struct CallOverloadedCreateFun {
214 template <typename... Args>
215 auto operator()(Args &&... args)
216 -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) {
217 return ToDeclT::Create(std::forward<Args>(args)...);
221 // Always use these functions to create a Decl during import. There are
222 // certain tasks which must be done after the Decl was created, e.g. we
223 // must immediately register that as an imported Decl. The parameter `ToD`
224 // will be set to the newly created Decl or if had been imported before
225 // then to the already imported Decl. Returns a bool value set to true if
226 // the `FromD` had been imported before.
227 template <typename ToDeclT, typename FromDeclT, typename... Args>
228 LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
230 // There may be several overloads of ToDeclT::Create. We must make sure
231 // to call the one which would be chosen by the arguments, thus we use a
232 // wrapper for the overload set.
233 CallOverloadedCreateFun<ToDeclT> OC;
234 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
235 std::forward<Args>(args)...);
237 // Use this overload if a special Type is needed to be created. E.g if we
238 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
240 // TypedefNameDecl *ToTypedef;
241 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
242 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
244 LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
246 CallOverloadedCreateFun<NewDeclT> OC;
247 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
248 std::forward<Args>(args)...);
250 // Use this version if a special create function must be
251 // used, e.g. CXXRecordDecl::CreateLambda .
252 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
255 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
256 FromDeclT *FromD, Args &&... args) {
257 if (Importer.getImportDeclErrorIfAny(FromD)) {
259 return true; // Already imported but with error.
261 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
263 return true; // Already imported.
264 ToD = CreateFun(std::forward<Args>(args)...);
265 // Keep track of imported Decls.
266 Importer.RegisterImportedDecl(FromD, ToD);
267 InitializeImportedDecl(FromD, ToD);
268 return false; // A new Decl is created.
271 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
272 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
273 if (FromD->hasAttrs())
274 for (const Attr *FromAttr : FromD->getAttrs()) {
275 // FIXME: Return of the error here is not possible until store of
276 // import errors is implemented.
277 auto ToAttrOrErr = import(FromAttr);
279 ToD->addAttr(*ToAttrOrErr);
281 llvm::consumeError(ToAttrOrErr.takeError());
285 if (FromD->isImplicit())
289 // Check if we have found an existing definition. Returns with that
290 // definition if yes, otherwise returns null.
291 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
292 const FunctionDecl *Definition = nullptr;
293 if (D->doesThisDeclarationHaveABody() &&
294 FoundFunction->hasBody(Definition))
295 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
300 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
302 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
303 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
304 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
307 ExpectedType VisitType(const Type *T);
308 ExpectedType VisitAtomicType(const AtomicType *T);
309 ExpectedType VisitBuiltinType(const BuiltinType *T);
310 ExpectedType VisitDecayedType(const DecayedType *T);
311 ExpectedType VisitComplexType(const ComplexType *T);
312 ExpectedType VisitPointerType(const PointerType *T);
313 ExpectedType VisitBlockPointerType(const BlockPointerType *T);
314 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
315 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
316 ExpectedType VisitMemberPointerType(const MemberPointerType *T);
317 ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
318 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
319 ExpectedType VisitVariableArrayType(const VariableArrayType *T);
320 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
321 // FIXME: DependentSizedExtVectorType
322 ExpectedType VisitVectorType(const VectorType *T);
323 ExpectedType VisitExtVectorType(const ExtVectorType *T);
324 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
325 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
326 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
327 ExpectedType VisitParenType(const ParenType *T);
328 ExpectedType VisitTypedefType(const TypedefType *T);
329 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
330 // FIXME: DependentTypeOfExprType
331 ExpectedType VisitTypeOfType(const TypeOfType *T);
332 ExpectedType VisitDecltypeType(const DecltypeType *T);
333 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
334 ExpectedType VisitAutoType(const AutoType *T);
335 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
336 // FIXME: DependentDecltypeType
337 ExpectedType VisitRecordType(const RecordType *T);
338 ExpectedType VisitEnumType(const EnumType *T);
339 ExpectedType VisitAttributedType(const AttributedType *T);
340 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
341 ExpectedType VisitSubstTemplateTypeParmType(
342 const SubstTemplateTypeParmType *T);
343 ExpectedType VisitTemplateSpecializationType(
344 const TemplateSpecializationType *T);
345 ExpectedType VisitElaboratedType(const ElaboratedType *T);
346 ExpectedType VisitDependentNameType(const DependentNameType *T);
347 ExpectedType VisitPackExpansionType(const PackExpansionType *T);
348 ExpectedType VisitDependentTemplateSpecializationType(
349 const DependentTemplateSpecializationType *T);
350 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
351 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
352 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
354 // Importing declarations
355 Error ImportDeclParts(
356 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
357 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
358 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
359 Error ImportDeclarationNameLoc(
360 const DeclarationNameInfo &From, DeclarationNameInfo &To);
361 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
362 Error ImportDeclContext(
363 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
364 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
366 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
368 using Designator = DesignatedInitExpr::Designator;
370 /// What we should import from the definition.
371 enum ImportDefinitionKind {
372 /// Import the default subset of the definition, which might be
373 /// nothing (if minimal import is set) or might be everything (if minimal
374 /// import is not set).
376 /// Import everything.
378 /// Import only the bare bones needed to establish a valid
383 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
384 return IDK == IDK_Everything ||
385 (IDK == IDK_Default && !Importer.isMinimalImport());
388 Error ImportInitializer(VarDecl *From, VarDecl *To);
389 Error ImportDefinition(
390 RecordDecl *From, RecordDecl *To,
391 ImportDefinitionKind Kind = IDK_Default);
392 Error ImportDefinition(
393 EnumDecl *From, EnumDecl *To,
394 ImportDefinitionKind Kind = IDK_Default);
395 Error ImportDefinition(
396 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
397 ImportDefinitionKind Kind = IDK_Default);
398 Error ImportDefinition(
399 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
400 ImportDefinitionKind Kind = IDK_Default);
401 Error ImportTemplateArguments(
402 const TemplateArgument *FromArgs, unsigned NumFromArgs,
403 SmallVectorImpl<TemplateArgument> &ToArgs);
404 Expected<TemplateArgument>
405 ImportTemplateArgument(const TemplateArgument &From);
407 template <typename InContainerTy>
408 Error ImportTemplateArgumentListInfo(
409 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
411 template<typename InContainerTy>
412 Error ImportTemplateArgumentListInfo(
413 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
414 const InContainerTy &Container, TemplateArgumentListInfo &Result);
416 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
417 using FunctionTemplateAndArgsTy =
418 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
419 Expected<FunctionTemplateAndArgsTy>
420 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
421 FunctionDecl *FromFD);
422 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
423 DeclaratorDecl *ToD);
425 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
427 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
429 template <typename T>
430 bool hasSameVisibilityContext(T *Found, T *From);
432 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
433 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
434 bool Complain = true);
435 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
436 bool Complain = true);
437 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
438 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
439 bool IsStructuralMatch(FunctionTemplateDecl *From,
440 FunctionTemplateDecl *To);
441 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
442 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
443 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
444 ExpectedDecl VisitDecl(Decl *D);
445 ExpectedDecl VisitImportDecl(ImportDecl *D);
446 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
447 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
448 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
449 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
450 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
451 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
452 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
453 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
454 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
455 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
456 ExpectedDecl VisitLabelDecl(LabelDecl *D);
457 ExpectedDecl VisitEnumDecl(EnumDecl *D);
458 ExpectedDecl VisitRecordDecl(RecordDecl *D);
459 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
460 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
461 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
462 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
463 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
464 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
465 ExpectedDecl VisitFieldDecl(FieldDecl *D);
466 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
467 ExpectedDecl VisitFriendDecl(FriendDecl *D);
468 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
469 ExpectedDecl VisitVarDecl(VarDecl *D);
470 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
471 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
472 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
473 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
474 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
475 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
476 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
477 ExpectedDecl VisitUsingDecl(UsingDecl *D);
478 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
479 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
480 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
481 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
483 Expected<ObjCTypeParamList *>
484 ImportObjCTypeParamList(ObjCTypeParamList *list);
486 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
487 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
488 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
489 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
490 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
491 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
492 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
493 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
494 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
495 ExpectedDecl VisitClassTemplateSpecializationDecl(
496 ClassTemplateSpecializationDecl *D);
497 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
498 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
499 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
501 // Importing statements
502 ExpectedStmt VisitStmt(Stmt *S);
503 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
504 ExpectedStmt VisitDeclStmt(DeclStmt *S);
505 ExpectedStmt VisitNullStmt(NullStmt *S);
506 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
507 ExpectedStmt VisitCaseStmt(CaseStmt *S);
508 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
509 ExpectedStmt VisitLabelStmt(LabelStmt *S);
510 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
511 ExpectedStmt VisitIfStmt(IfStmt *S);
512 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
513 ExpectedStmt VisitWhileStmt(WhileStmt *S);
514 ExpectedStmt VisitDoStmt(DoStmt *S);
515 ExpectedStmt VisitForStmt(ForStmt *S);
516 ExpectedStmt VisitGotoStmt(GotoStmt *S);
517 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
518 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
519 ExpectedStmt VisitBreakStmt(BreakStmt *S);
520 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
522 // FIXME: SEHExceptStmt
523 // FIXME: SEHFinallyStmt
525 // FIXME: SEHLeaveStmt
526 // FIXME: CapturedStmt
527 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
528 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
529 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
530 // FIXME: MSDependentExistsStmt
531 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
532 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
533 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
534 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
535 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
536 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
537 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
539 // Importing expressions
540 ExpectedStmt VisitExpr(Expr *E);
541 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
542 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
543 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
544 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
545 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
546 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
547 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
548 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
549 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
550 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
551 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
552 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
553 ExpectedStmt VisitStringLiteral(StringLiteral *E);
554 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
555 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
556 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
557 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
558 ExpectedStmt VisitParenExpr(ParenExpr *E);
559 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
560 ExpectedStmt VisitStmtExpr(StmtExpr *E);
561 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
562 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
563 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
564 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
565 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
566 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
567 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
568 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
569 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
570 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
571 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
572 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
573 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
574 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
575 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
576 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
577 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
578 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
579 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
580 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
581 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
582 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
583 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
584 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
585 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
586 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
587 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
588 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
589 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
590 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
591 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
592 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
593 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
594 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
595 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
596 ExpectedStmt VisitMemberExpr(MemberExpr *E);
597 ExpectedStmt VisitCallExpr(CallExpr *E);
598 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
599 ExpectedStmt VisitInitListExpr(InitListExpr *E);
600 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
601 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
602 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
603 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
604 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
605 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
606 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
607 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
608 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
610 template<typename IIter, typename OIter>
611 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
612 using ItemT = typename std::remove_reference<decltype(*Obegin)>::type;
613 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
614 Expected<ItemT> ToOrErr = import(*Ibegin);
616 return ToOrErr.takeError();
619 return Error::success();
622 // Import every item from a container structure into an output container.
623 // If error occurs, stops at first error and returns the error.
624 // The output container should have space for all needed elements (it is not
625 // expanded, new items are put into from the beginning).
626 template<typename InContainerTy, typename OutContainerTy>
627 Error ImportContainerChecked(
628 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
629 return ImportArrayChecked(
630 InContainer.begin(), InContainer.end(), OutContainer.begin());
633 template<typename InContainerTy, typename OIter>
634 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
635 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
638 void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod);
640 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
641 FunctionDecl *FromFD);
644 template <typename InContainerTy>
645 Error ASTNodeImporter::ImportTemplateArgumentListInfo(
646 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
647 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
648 auto ToLAngleLocOrErr = import(FromLAngleLoc);
649 if (!ToLAngleLocOrErr)
650 return ToLAngleLocOrErr.takeError();
651 auto ToRAngleLocOrErr = import(FromRAngleLoc);
652 if (!ToRAngleLocOrErr)
653 return ToRAngleLocOrErr.takeError();
655 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
656 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
659 return Error::success();
663 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
664 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
665 return ImportTemplateArgumentListInfo(
666 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
670 Error ASTNodeImporter::ImportTemplateArgumentListInfo<
671 ASTTemplateArgumentListInfo>(
672 const ASTTemplateArgumentListInfo &From,
673 TemplateArgumentListInfo &Result) {
674 return ImportTemplateArgumentListInfo(
675 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
678 Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
679 ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
680 FunctionDecl *FromFD) {
681 assert(FromFD->getTemplatedKind() ==
682 FunctionDecl::TK_FunctionTemplateSpecialization);
684 FunctionTemplateAndArgsTy Result;
686 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
687 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
688 return std::move(Err);
690 // Import template arguments.
691 auto TemplArgs = FTSInfo->TemplateArguments->asArray();
692 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
693 std::get<1>(Result)))
694 return std::move(Err);
700 Expected<TemplateParameterList *>
701 ASTNodeImporter::import(TemplateParameterList *From) {
702 SmallVector<NamedDecl *, 4> To(From->size());
703 if (Error Err = ImportContainerChecked(*From, To))
704 return std::move(Err);
706 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
707 if (!ToRequiresClause)
708 return ToRequiresClause.takeError();
710 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
711 if (!ToTemplateLocOrErr)
712 return ToTemplateLocOrErr.takeError();
713 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
714 if (!ToLAngleLocOrErr)
715 return ToLAngleLocOrErr.takeError();
716 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
717 if (!ToRAngleLocOrErr)
718 return ToRAngleLocOrErr.takeError();
720 return TemplateParameterList::Create(
721 Importer.getToContext(),
730 Expected<TemplateArgument>
731 ASTNodeImporter::import(const TemplateArgument &From) {
732 switch (From.getKind()) {
733 case TemplateArgument::Null:
734 return TemplateArgument();
736 case TemplateArgument::Type: {
737 ExpectedType ToTypeOrErr = import(From.getAsType());
739 return ToTypeOrErr.takeError();
740 return TemplateArgument(*ToTypeOrErr);
743 case TemplateArgument::Integral: {
744 ExpectedType ToTypeOrErr = import(From.getIntegralType());
746 return ToTypeOrErr.takeError();
747 return TemplateArgument(From, *ToTypeOrErr);
750 case TemplateArgument::Declaration: {
751 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
753 return ToOrErr.takeError();
754 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
756 return ToTypeOrErr.takeError();
757 return TemplateArgument(*ToOrErr, *ToTypeOrErr);
760 case TemplateArgument::NullPtr: {
761 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
763 return ToTypeOrErr.takeError();
764 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
767 case TemplateArgument::Template: {
768 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
769 if (!ToTemplateOrErr)
770 return ToTemplateOrErr.takeError();
772 return TemplateArgument(*ToTemplateOrErr);
775 case TemplateArgument::TemplateExpansion: {
776 Expected<TemplateName> ToTemplateOrErr =
777 import(From.getAsTemplateOrTemplatePattern());
778 if (!ToTemplateOrErr)
779 return ToTemplateOrErr.takeError();
781 return TemplateArgument(
782 *ToTemplateOrErr, From.getNumTemplateExpansions());
785 case TemplateArgument::Expression:
786 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
787 return TemplateArgument(*ToExpr);
789 return ToExpr.takeError();
791 case TemplateArgument::Pack: {
792 SmallVector<TemplateArgument, 2> ToPack;
793 ToPack.reserve(From.pack_size());
794 if (Error Err = ImportTemplateArguments(
795 From.pack_begin(), From.pack_size(), ToPack))
796 return std::move(Err);
798 return TemplateArgument(
799 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
803 llvm_unreachable("Invalid template argument kind");
807 Expected<TemplateArgumentLoc>
808 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
809 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
811 return ArgOrErr.takeError();
812 TemplateArgument Arg = *ArgOrErr;
814 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
816 TemplateArgumentLocInfo ToInfo;
817 if (Arg.getKind() == TemplateArgument::Expression) {
818 ExpectedExpr E = import(FromInfo.getAsExpr());
820 return E.takeError();
821 ToInfo = TemplateArgumentLocInfo(*E);
822 } else if (Arg.getKind() == TemplateArgument::Type) {
823 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
824 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
826 return TSIOrErr.takeError();
828 auto ToTemplateQualifierLocOrErr =
829 import(FromInfo.getTemplateQualifierLoc());
830 if (!ToTemplateQualifierLocOrErr)
831 return ToTemplateQualifierLocOrErr.takeError();
832 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
833 if (!ToTemplateNameLocOrErr)
834 return ToTemplateNameLocOrErr.takeError();
835 auto ToTemplateEllipsisLocOrErr =
836 import(FromInfo.getTemplateEllipsisLoc());
837 if (!ToTemplateEllipsisLocOrErr)
838 return ToTemplateEllipsisLocOrErr.takeError();
840 ToInfo = TemplateArgumentLocInfo(
841 *ToTemplateQualifierLocOrErr,
842 *ToTemplateNameLocOrErr,
843 *ToTemplateEllipsisLocOrErr);
846 return TemplateArgumentLoc(Arg, ToInfo);
850 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
852 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
853 size_t NumDecls = DG.end() - DG.begin();
854 SmallVector<Decl *, 1> ToDecls;
855 ToDecls.reserve(NumDecls);
856 for (Decl *FromD : DG) {
857 if (auto ToDOrErr = import(FromD))
858 ToDecls.push_back(*ToDOrErr);
860 return ToDOrErr.takeError();
862 return DeclGroupRef::Create(Importer.getToContext(),
868 Expected<ASTNodeImporter::Designator>
869 ASTNodeImporter::import(const Designator &D) {
870 if (D.isFieldDesignator()) {
871 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
873 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
875 return ToDotLocOrErr.takeError();
877 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
878 if (!ToFieldLocOrErr)
879 return ToFieldLocOrErr.takeError();
881 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
884 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
885 if (!ToLBracketLocOrErr)
886 return ToLBracketLocOrErr.takeError();
888 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
889 if (!ToRBracketLocOrErr)
890 return ToRBracketLocOrErr.takeError();
892 if (D.isArrayDesignator())
893 return Designator(D.getFirstExprIndex(),
894 *ToLBracketLocOrErr, *ToRBracketLocOrErr);
896 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
897 if (!ToEllipsisLocOrErr)
898 return ToEllipsisLocOrErr.takeError();
900 assert(D.isArrayRangeDesignator());
902 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
903 *ToRBracketLocOrErr);
907 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
908 VarDecl *Var = nullptr;
909 if (From.capturesVariable()) {
910 if (auto VarOrErr = import(From.getCapturedVar()))
913 return VarOrErr.takeError();
916 auto LocationOrErr = import(From.getLocation());
918 return LocationOrErr.takeError();
920 SourceLocation EllipsisLoc;
921 if (From.isPackExpansion())
922 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
923 return std::move(Err);
925 return LambdaCapture(
926 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
932 //----------------------------------------------------------------------------
934 //----------------------------------------------------------------------------
936 using namespace clang;
938 ExpectedType ASTNodeImporter::VisitType(const Type *T) {
939 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
940 << T->getTypeClassName();
941 return make_error<ImportError>(ImportError::UnsupportedConstruct);
944 ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
945 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
946 if (!UnderlyingTypeOrErr)
947 return UnderlyingTypeOrErr.takeError();
949 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
952 ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
953 switch (T->getKind()) {
954 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
955 case BuiltinType::Id: \
956 return Importer.getToContext().SingletonId;
957 #include "clang/Basic/OpenCLImageTypes.def"
958 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
959 case BuiltinType::Id: \
960 return Importer.getToContext().Id##Ty;
961 #include "clang/Basic/OpenCLExtensionTypes.def"
962 #define SHARED_SINGLETON_TYPE(Expansion)
963 #define BUILTIN_TYPE(Id, SingletonId) \
964 case BuiltinType::Id: return Importer.getToContext().SingletonId;
965 #include "clang/AST/BuiltinTypes.def"
967 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
968 // context supports C++.
970 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
971 // context supports ObjC.
973 case BuiltinType::Char_U:
974 // The context we're importing from has an unsigned 'char'. If we're
975 // importing into a context with a signed 'char', translate to
976 // 'unsigned char' instead.
977 if (Importer.getToContext().getLangOpts().CharIsSigned)
978 return Importer.getToContext().UnsignedCharTy;
980 return Importer.getToContext().CharTy;
982 case BuiltinType::Char_S:
983 // The context we're importing from has an unsigned 'char'. If we're
984 // importing into a context with a signed 'char', translate to
985 // 'unsigned char' instead.
986 if (!Importer.getToContext().getLangOpts().CharIsSigned)
987 return Importer.getToContext().SignedCharTy;
989 return Importer.getToContext().CharTy;
991 case BuiltinType::WChar_S:
992 case BuiltinType::WChar_U:
993 // FIXME: If not in C++, shall we translate to the C equivalent of
995 return Importer.getToContext().WCharTy;
998 llvm_unreachable("Invalid BuiltinType Kind!");
1001 ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1002 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1003 if (!ToOriginalTypeOrErr)
1004 return ToOriginalTypeOrErr.takeError();
1006 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1009 ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1010 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1011 if (!ToElementTypeOrErr)
1012 return ToElementTypeOrErr.takeError();
1014 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1017 ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1018 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1019 if (!ToPointeeTypeOrErr)
1020 return ToPointeeTypeOrErr.takeError();
1022 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1025 ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1026 // FIXME: Check for blocks support in "to" context.
1027 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1028 if (!ToPointeeTypeOrErr)
1029 return ToPointeeTypeOrErr.takeError();
1031 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1035 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1036 // FIXME: Check for C++ support in "to" context.
1037 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1038 if (!ToPointeeTypeOrErr)
1039 return ToPointeeTypeOrErr.takeError();
1041 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1045 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1046 // FIXME: Check for C++0x support in "to" context.
1047 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1048 if (!ToPointeeTypeOrErr)
1049 return ToPointeeTypeOrErr.takeError();
1051 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1055 ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1056 // FIXME: Check for C++ support in "to" context.
1057 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1058 if (!ToPointeeTypeOrErr)
1059 return ToPointeeTypeOrErr.takeError();
1061 ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1062 if (!ClassTypeOrErr)
1063 return ClassTypeOrErr.takeError();
1065 return Importer.getToContext().getMemberPointerType(
1066 *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1070 ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1071 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1072 if (!ToElementTypeOrErr)
1073 return ToElementTypeOrErr.takeError();
1075 return Importer.getToContext().getConstantArrayType(*ToElementTypeOrErr,
1077 T->getSizeModifier(),
1078 T->getIndexTypeCVRQualifiers());
1082 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1083 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1084 if (!ToElementTypeOrErr)
1085 return ToElementTypeOrErr.takeError();
1087 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1088 T->getSizeModifier(),
1089 T->getIndexTypeCVRQualifiers());
1093 ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1094 QualType ToElementType;
1096 SourceRange ToBracketsRange;
1097 if (auto Imp = importSeq(
1098 T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1099 std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1101 return Imp.takeError();
1103 return Importer.getToContext().getVariableArrayType(
1104 ToElementType, ToSizeExpr, T->getSizeModifier(),
1105 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1108 ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1109 const DependentSizedArrayType *T) {
1110 QualType ToElementType;
1112 SourceRange ToBracketsRange;
1113 if (auto Imp = importSeq(
1114 T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1115 std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1117 return Imp.takeError();
1118 // SizeExpr may be null if size is not specified directly.
1119 // For example, 'int a[]'.
1121 return Importer.getToContext().getDependentSizedArrayType(
1122 ToElementType, ToSizeExpr, T->getSizeModifier(),
1123 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1126 ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1127 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1128 if (!ToElementTypeOrErr)
1129 return ToElementTypeOrErr.takeError();
1131 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1132 T->getNumElements(),
1133 T->getVectorKind());
1136 ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1137 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1138 if (!ToElementTypeOrErr)
1139 return ToElementTypeOrErr.takeError();
1141 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1142 T->getNumElements());
1146 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1147 // FIXME: What happens if we're importing a function without a prototype
1148 // into C++? Should we make it variadic?
1149 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1150 if (!ToReturnTypeOrErr)
1151 return ToReturnTypeOrErr.takeError();
1153 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1158 ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1159 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1160 if (!ToReturnTypeOrErr)
1161 return ToReturnTypeOrErr.takeError();
1163 // Import argument types
1164 SmallVector<QualType, 4> ArgTypes;
1165 for (const auto &A : T->param_types()) {
1166 ExpectedType TyOrErr = import(A);
1168 return TyOrErr.takeError();
1169 ArgTypes.push_back(*TyOrErr);
1172 // Import exception types
1173 SmallVector<QualType, 4> ExceptionTypes;
1174 for (const auto &E : T->exceptions()) {
1175 ExpectedType TyOrErr = import(E);
1177 return TyOrErr.takeError();
1178 ExceptionTypes.push_back(*TyOrErr);
1181 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1182 FunctionProtoType::ExtProtoInfo ToEPI;
1184 auto Imp = importSeq(
1185 FromEPI.ExceptionSpec.NoexceptExpr,
1186 FromEPI.ExceptionSpec.SourceDecl,
1187 FromEPI.ExceptionSpec.SourceTemplate);
1189 return Imp.takeError();
1191 ToEPI.ExtInfo = FromEPI.ExtInfo;
1192 ToEPI.Variadic = FromEPI.Variadic;
1193 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1194 ToEPI.TypeQuals = FromEPI.TypeQuals;
1195 ToEPI.RefQualifier = FromEPI.RefQualifier;
1196 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1197 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1199 ToEPI.ExceptionSpec.NoexceptExpr,
1200 ToEPI.ExceptionSpec.SourceDecl,
1201 ToEPI.ExceptionSpec.SourceTemplate) = *Imp;
1203 return Importer.getToContext().getFunctionType(
1204 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1207 ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1208 const UnresolvedUsingType *T) {
1209 UnresolvedUsingTypenameDecl *ToD;
1211 if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl()))
1212 std::tie(ToD, ToPrevD) = *Imp;
1214 return Imp.takeError();
1216 return Importer.getToContext().getTypeDeclType(
1217 ToD, cast_or_null<TypeDecl>(ToPrevD));
1220 ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1221 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1222 if (!ToInnerTypeOrErr)
1223 return ToInnerTypeOrErr.takeError();
1225 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1228 ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1229 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1231 return ToDeclOrErr.takeError();
1233 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1236 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1237 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1239 return ToExprOrErr.takeError();
1241 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1244 ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1245 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1246 if (!ToUnderlyingTypeOrErr)
1247 return ToUnderlyingTypeOrErr.takeError();
1249 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1252 ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1253 // FIXME: Make sure that the "to" context supports C++0x!
1254 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1256 return ToExprOrErr.takeError();
1258 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1259 if (!ToUnderlyingTypeOrErr)
1260 return ToUnderlyingTypeOrErr.takeError();
1262 return Importer.getToContext().getDecltypeType(
1263 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1267 ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1268 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1269 if (!ToBaseTypeOrErr)
1270 return ToBaseTypeOrErr.takeError();
1272 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1273 if (!ToUnderlyingTypeOrErr)
1274 return ToUnderlyingTypeOrErr.takeError();
1276 return Importer.getToContext().getUnaryTransformType(
1277 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1280 ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1281 // FIXME: Make sure that the "to" context supports C++11!
1282 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1283 if (!ToDeducedTypeOrErr)
1284 return ToDeducedTypeOrErr.takeError();
1286 return Importer.getToContext().getAutoType(*ToDeducedTypeOrErr,
1288 /*IsDependent*/false);
1291 ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1292 const InjectedClassNameType *T) {
1293 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1295 return ToDeclOrErr.takeError();
1297 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1298 if (!ToInjTypeOrErr)
1299 return ToInjTypeOrErr.takeError();
1301 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1302 // See comments in InjectedClassNameType definition for details
1303 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1305 TypeAlignmentInBits = 4,
1306 TypeAlignment = 1 << TypeAlignmentInBits
1309 return QualType(new (Importer.getToContext(), TypeAlignment)
1310 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1313 ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1314 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1316 return ToDeclOrErr.takeError();
1318 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1321 ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1322 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1324 return ToDeclOrErr.takeError();
1326 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1329 ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1330 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1331 if (!ToModifiedTypeOrErr)
1332 return ToModifiedTypeOrErr.takeError();
1333 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1334 if (!ToEquivalentTypeOrErr)
1335 return ToEquivalentTypeOrErr.takeError();
1337 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1338 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1341 ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1342 const TemplateTypeParmType *T) {
1343 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1345 return ToDeclOrErr.takeError();
1347 return Importer.getToContext().getTemplateTypeParmType(
1348 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1351 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1352 const SubstTemplateTypeParmType *T) {
1353 ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1355 return ReplacedOrErr.takeError();
1356 const TemplateTypeParmType *Replaced =
1357 cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1359 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1360 if (!ToReplacementTypeOrErr)
1361 return ToReplacementTypeOrErr.takeError();
1363 return Importer.getToContext().getSubstTemplateTypeParmType(
1364 Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1367 ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1368 const TemplateSpecializationType *T) {
1369 auto ToTemplateOrErr = import(T->getTemplateName());
1370 if (!ToTemplateOrErr)
1371 return ToTemplateOrErr.takeError();
1373 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1374 if (Error Err = ImportTemplateArguments(
1375 T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1376 return std::move(Err);
1378 QualType ToCanonType;
1379 if (!QualType(T, 0).isCanonical()) {
1380 QualType FromCanonType
1381 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1382 if (ExpectedType TyOrErr = import(FromCanonType))
1383 ToCanonType = *TyOrErr;
1385 return TyOrErr.takeError();
1387 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1392 ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1393 // Note: the qualifier in an ElaboratedType is optional.
1394 auto ToQualifierOrErr = import(T->getQualifier());
1395 if (!ToQualifierOrErr)
1396 return ToQualifierOrErr.takeError();
1398 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1399 if (!ToNamedTypeOrErr)
1400 return ToNamedTypeOrErr.takeError();
1402 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1403 if (!ToOwnedTagDeclOrErr)
1404 return ToOwnedTagDeclOrErr.takeError();
1406 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1409 *ToOwnedTagDeclOrErr);
1413 ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1414 ExpectedType ToPatternOrErr = import(T->getPattern());
1415 if (!ToPatternOrErr)
1416 return ToPatternOrErr.takeError();
1418 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1419 T->getNumExpansions());
1422 ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1423 const DependentTemplateSpecializationType *T) {
1424 auto ToQualifierOrErr = import(T->getQualifier());
1425 if (!ToQualifierOrErr)
1426 return ToQualifierOrErr.takeError();
1428 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1430 SmallVector<TemplateArgument, 2> ToPack;
1431 ToPack.reserve(T->getNumArgs());
1432 if (Error Err = ImportTemplateArguments(
1433 T->getArgs(), T->getNumArgs(), ToPack))
1434 return std::move(Err);
1436 return Importer.getToContext().getDependentTemplateSpecializationType(
1437 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1441 ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1442 auto ToQualifierOrErr = import(T->getQualifier());
1443 if (!ToQualifierOrErr)
1444 return ToQualifierOrErr.takeError();
1446 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1449 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1450 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1451 Canon = (*TyOrErr).getCanonicalType();
1453 return TyOrErr.takeError();
1456 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1462 ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1463 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1465 return ToDeclOrErr.takeError();
1467 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1470 ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1471 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1472 if (!ToBaseTypeOrErr)
1473 return ToBaseTypeOrErr.takeError();
1475 SmallVector<QualType, 4> TypeArgs;
1476 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1477 if (ExpectedType TyOrErr = import(TypeArg))
1478 TypeArgs.push_back(*TyOrErr);
1480 return TyOrErr.takeError();
1483 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1484 for (auto *P : T->quals()) {
1485 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1486 Protocols.push_back(*ProtocolOrErr);
1488 return ProtocolOrErr.takeError();
1492 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1494 T->isKindOfTypeAsWritten());
1498 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1499 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1500 if (!ToPointeeTypeOrErr)
1501 return ToPointeeTypeOrErr.takeError();
1503 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1506 //----------------------------------------------------------------------------
1507 // Import Declarations
1508 //----------------------------------------------------------------------------
1509 Error ASTNodeImporter::ImportDeclParts(
1510 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1511 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1512 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1513 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1514 DeclContext *OrigDC = D->getDeclContext();
1515 FunctionDecl *FunDecl;
1516 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1517 FunDecl->hasBody()) {
1518 auto getLeafPointeeType = [](const Type *T) {
1519 while (T->isPointerType() || T->isArrayType()) {
1520 T = T->getPointeeOrArrayElementType();
1524 for (const ParmVarDecl *P : FunDecl->parameters()) {
1526 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1527 auto *RT = dyn_cast<RecordType>(LeafT);
1528 if (RT && RT->getDecl() == D) {
1529 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1530 << D->getDeclKindName();
1531 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1536 // Import the context of this declaration.
1537 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1540 // Import the name of this declaration.
1541 if (Error Err = importInto(Name, D->getDeclName()))
1544 // Import the location of this declaration.
1545 if (Error Err = importInto(Loc, D->getLocation()))
1548 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1550 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1553 return Error::success();
1556 Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1558 return Error::success();
1561 if (Error Err = importInto(ToD, FromD))
1564 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1565 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1566 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1567 !ToRecord->getDefinition()) {
1568 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1572 return Error::success();
1575 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1576 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1577 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1578 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1582 return Error::success();
1585 return Error::success();
1589 ASTNodeImporter::ImportDeclarationNameLoc(
1590 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1591 // NOTE: To.Name and To.Loc are already imported.
1592 // We only have to import To.LocInfo.
1593 switch (To.getName().getNameKind()) {
1594 case DeclarationName::Identifier:
1595 case DeclarationName::ObjCZeroArgSelector:
1596 case DeclarationName::ObjCOneArgSelector:
1597 case DeclarationName::ObjCMultiArgSelector:
1598 case DeclarationName::CXXUsingDirective:
1599 case DeclarationName::CXXDeductionGuideName:
1600 return Error::success();
1602 case DeclarationName::CXXOperatorName: {
1603 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1604 To.setCXXOperatorNameRange(*ToRangeOrErr);
1606 return ToRangeOrErr.takeError();
1607 return Error::success();
1609 case DeclarationName::CXXLiteralOperatorName: {
1610 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1611 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1613 return LocOrErr.takeError();
1614 return Error::success();
1616 case DeclarationName::CXXConstructorName:
1617 case DeclarationName::CXXDestructorName:
1618 case DeclarationName::CXXConversionFunctionName: {
1619 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1620 To.setNamedTypeInfo(*ToTInfoOrErr);
1622 return ToTInfoOrErr.takeError();
1623 return Error::success();
1626 llvm_unreachable("Unknown name kind.");
1630 ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1631 if (Importer.isMinimalImport() && !ForceImport) {
1632 auto ToDCOrErr = Importer.ImportContext(FromDC);
1633 return ToDCOrErr.takeError();
1636 // We use strict error handling in case of records and enums, but not
1637 // with e.g. namespaces.
1639 // FIXME Clients of the ASTImporter should be able to choose an
1640 // appropriate error handling strategy for their needs. For instance,
1641 // they may not want to mark an entire namespace as erroneous merely
1642 // because there is an ODR error with two typedefs. As another example,
1643 // the client may allow EnumConstantDecls with same names but with
1644 // different values in two distinct translation units.
1645 bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1647 Error ChildErrors = Error::success();
1648 llvm::SmallVector<Decl *, 8> ImportedDecls;
1649 for (auto *From : FromDC->decls()) {
1650 ExpectedDecl ImportedOrErr = import(From);
1651 if (!ImportedOrErr) {
1652 if (AccumulateChildErrors)
1654 joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1656 consumeError(ImportedOrErr.takeError());
1663 Error ASTNodeImporter::ImportDeclContext(
1664 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1665 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1667 return ToDCOrErr.takeError();
1670 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1671 auto ToLexicalDCOrErr = Importer.ImportContext(
1672 FromD->getLexicalDeclContext());
1673 if (!ToLexicalDCOrErr)
1674 return ToLexicalDCOrErr.takeError();
1675 ToLexicalDC = *ToLexicalDCOrErr;
1679 return Error::success();
1682 Error ASTNodeImporter::ImportImplicitMethods(
1683 const CXXRecordDecl *From, CXXRecordDecl *To) {
1684 assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1685 "Import implicit methods to or from non-definition");
1687 for (CXXMethodDecl *FromM : From->methods())
1688 if (FromM->isImplicit()) {
1689 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1691 return ToMOrErr.takeError();
1694 return Error::success();
1697 static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
1698 ASTImporter &Importer) {
1699 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1700 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1701 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1703 return ToTypedefOrErr.takeError();
1705 return Error::success();
1708 Error ASTNodeImporter::ImportDefinition(
1709 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
1710 auto DefinitionCompleter = [To]() {
1711 // There are cases in LLDB when we first import a class without its
1712 // members. The class will have DefinitionData, but no members. Then,
1713 // importDefinition is called from LLDB, which tries to get the members, so
1714 // when we get here, the class already has the DefinitionData set, so we
1715 // must unset the CompleteDefinition here to be able to complete again the
1717 To->setCompleteDefinition(false);
1718 To->completeDefinition();
1721 if (To->getDefinition() || To->isBeingDefined()) {
1722 if (Kind == IDK_Everything ||
1723 // In case of lambdas, the class already has a definition ptr set, but
1724 // the contained decls are not imported yet. Also, isBeingDefined was
1725 // set in CXXRecordDecl::CreateLambda. We must import the contained
1726 // decls here and finish the definition.
1727 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
1728 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
1729 // Finish the definition of the lambda, set isBeingDefined to false.
1731 DefinitionCompleter();
1735 return Error::success();
1738 To->startDefinition();
1739 // Complete the definition even if error is returned.
1740 // The RecordDecl may be already part of the AST so it is better to
1741 // have it in complete state even if something is wrong with it.
1742 auto DefinitionCompleterScopeExit =
1743 llvm::make_scope_exit(DefinitionCompleter);
1745 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1748 // Add base classes.
1749 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1750 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1751 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1753 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1754 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1755 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1756 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1757 ToData.Aggregate = FromData.Aggregate;
1758 ToData.PlainOldData = FromData.PlainOldData;
1759 ToData.Empty = FromData.Empty;
1760 ToData.Polymorphic = FromData.Polymorphic;
1761 ToData.Abstract = FromData.Abstract;
1762 ToData.IsStandardLayout = FromData.IsStandardLayout;
1763 ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout;
1764 ToData.HasBasesWithFields = FromData.HasBasesWithFields;
1765 ToData.HasBasesWithNonStaticDataMembers =
1766 FromData.HasBasesWithNonStaticDataMembers;
1767 ToData.HasPrivateFields = FromData.HasPrivateFields;
1768 ToData.HasProtectedFields = FromData.HasProtectedFields;
1769 ToData.HasPublicFields = FromData.HasPublicFields;
1770 ToData.HasMutableFields = FromData.HasMutableFields;
1771 ToData.HasVariantMembers = FromData.HasVariantMembers;
1772 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1773 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1774 ToData.HasUninitializedReferenceMember
1775 = FromData.HasUninitializedReferenceMember;
1776 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1777 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1778 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1779 ToData.NeedOverloadResolutionForCopyConstructor
1780 = FromData.NeedOverloadResolutionForCopyConstructor;
1781 ToData.NeedOverloadResolutionForMoveConstructor
1782 = FromData.NeedOverloadResolutionForMoveConstructor;
1783 ToData.NeedOverloadResolutionForMoveAssignment
1784 = FromData.NeedOverloadResolutionForMoveAssignment;
1785 ToData.NeedOverloadResolutionForDestructor
1786 = FromData.NeedOverloadResolutionForDestructor;
1787 ToData.DefaultedCopyConstructorIsDeleted
1788 = FromData.DefaultedCopyConstructorIsDeleted;
1789 ToData.DefaultedMoveConstructorIsDeleted
1790 = FromData.DefaultedMoveConstructorIsDeleted;
1791 ToData.DefaultedMoveAssignmentIsDeleted
1792 = FromData.DefaultedMoveAssignmentIsDeleted;
1793 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1794 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1795 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1796 ToData.HasConstexprNonCopyMoveConstructor
1797 = FromData.HasConstexprNonCopyMoveConstructor;
1798 ToData.HasDefaultedDefaultConstructor
1799 = FromData.HasDefaultedDefaultConstructor;
1800 ToData.DefaultedDefaultConstructorIsConstexpr
1801 = FromData.DefaultedDefaultConstructorIsConstexpr;
1802 ToData.HasConstexprDefaultConstructor
1803 = FromData.HasConstexprDefaultConstructor;
1804 ToData.HasNonLiteralTypeFieldsOrBases
1805 = FromData.HasNonLiteralTypeFieldsOrBases;
1806 // ComputedVisibleConversions not imported.
1807 ToData.UserProvidedDefaultConstructor
1808 = FromData.UserProvidedDefaultConstructor;
1809 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1810 ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1811 = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1812 ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1813 = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1814 ToData.ImplicitCopyAssignmentHasConstParam
1815 = FromData.ImplicitCopyAssignmentHasConstParam;
1816 ToData.HasDeclaredCopyConstructorWithConstParam
1817 = FromData.HasDeclaredCopyConstructorWithConstParam;
1818 ToData.HasDeclaredCopyAssignmentWithConstParam
1819 = FromData.HasDeclaredCopyAssignmentWithConstParam;
1821 // Copy over the data stored in RecordDeclBits
1822 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
1824 SmallVector<CXXBaseSpecifier *, 4> Bases;
1825 for (const auto &Base1 : FromCXX->bases()) {
1826 ExpectedType TyOrErr = import(Base1.getType());
1828 return TyOrErr.takeError();
1830 SourceLocation EllipsisLoc;
1831 if (Base1.isPackExpansion()) {
1832 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
1833 EllipsisLoc = *LocOrErr;
1835 return LocOrErr.takeError();
1838 // Ensure that we have a definition for the base.
1840 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
1843 auto RangeOrErr = import(Base1.getSourceRange());
1845 return RangeOrErr.takeError();
1847 auto TSIOrErr = import(Base1.getTypeSourceInfo());
1849 return TSIOrErr.takeError();
1852 new (Importer.getToContext()) CXXBaseSpecifier(
1855 Base1.isBaseOfClass(),
1856 Base1.getAccessSpecifierAsWritten(),
1861 ToCXX->setBases(Bases.data(), Bases.size());
1864 if (shouldForceImportDeclContext(Kind))
1865 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1868 return Error::success();
1871 Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
1872 if (To->getAnyInitializer())
1873 return Error::success();
1875 Expr *FromInit = From->getInit();
1877 return Error::success();
1879 ExpectedExpr ToInitOrErr = import(FromInit);
1881 return ToInitOrErr.takeError();
1883 To->setInit(*ToInitOrErr);
1884 if (From->isInitKnownICE()) {
1885 EvaluatedStmt *Eval = To->ensureEvaluatedStmt();
1886 Eval->CheckedICE = true;
1887 Eval->IsICE = From->isInitICE();
1890 // FIXME: Other bits to merge?
1891 return Error::success();
1894 Error ASTNodeImporter::ImportDefinition(
1895 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
1896 if (To->getDefinition() || To->isBeingDefined()) {
1897 if (Kind == IDK_Everything)
1898 return ImportDeclContext(From, /*ForceImport=*/true);
1899 return Error::success();
1902 To->startDefinition();
1904 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1907 ExpectedType ToTypeOrErr =
1908 import(Importer.getFromContext().getTypeDeclType(From));
1910 return ToTypeOrErr.takeError();
1912 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
1913 if (!ToPromotionTypeOrErr)
1914 return ToPromotionTypeOrErr.takeError();
1916 if (shouldForceImportDeclContext(Kind))
1917 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1920 // FIXME: we might need to merge the number of positive or negative bits
1921 // if the enumerator lists don't match.
1922 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
1923 From->getNumPositiveBits(),
1924 From->getNumNegativeBits());
1925 return Error::success();
1928 Error ASTNodeImporter::ImportTemplateArguments(
1929 const TemplateArgument *FromArgs, unsigned NumFromArgs,
1930 SmallVectorImpl<TemplateArgument> &ToArgs) {
1931 for (unsigned I = 0; I != NumFromArgs; ++I) {
1932 if (auto ToOrErr = import(FromArgs[I]))
1933 ToArgs.push_back(*ToOrErr);
1935 return ToOrErr.takeError();
1938 return Error::success();
1941 // FIXME: Do not forget to remove this and use only 'import'.
1942 Expected<TemplateArgument>
1943 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1944 return import(From);
1947 template <typename InContainerTy>
1948 Error ASTNodeImporter::ImportTemplateArgumentListInfo(
1949 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1950 for (const auto &FromLoc : Container) {
1951 if (auto ToLocOrErr = import(FromLoc))
1952 ToTAInfo.addArgument(*ToLocOrErr);
1954 return ToLocOrErr.takeError();
1956 return Error::success();
1959 static StructuralEquivalenceKind
1960 getStructuralEquivalenceKind(const ASTImporter &Importer) {
1961 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
1962 : StructuralEquivalenceKind::Default;
1965 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
1966 StructuralEquivalenceContext Ctx(
1967 Importer.getFromContext(), Importer.getToContext(),
1968 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1970 return Ctx.IsEquivalent(From, To);
1973 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1974 RecordDecl *ToRecord, bool Complain) {
1975 // Eliminate a potential failure point where we attempt to re-import
1976 // something we're trying to import while completing ToRecord.
1977 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1979 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1981 ToRecord = ToOriginRecord;
1984 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1985 ToRecord->getASTContext(),
1986 Importer.getNonEquivalentDecls(),
1987 getStructuralEquivalenceKind(Importer),
1989 return Ctx.IsEquivalent(FromRecord, ToRecord);
1992 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
1994 StructuralEquivalenceContext Ctx(
1995 Importer.getFromContext(), Importer.getToContext(),
1996 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1998 return Ctx.IsEquivalent(FromVar, ToVar);
2001 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2002 // Eliminate a potential failure point where we attempt to re-import
2003 // something we're trying to import while completing ToEnum.
2004 if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2005 if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2006 ToEnum = ToOriginEnum;
2008 StructuralEquivalenceContext Ctx(
2009 Importer.getFromContext(), Importer.getToContext(),
2010 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2011 return Ctx.IsEquivalent(FromEnum, ToEnum);
2014 bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
2015 FunctionTemplateDecl *To) {
2016 StructuralEquivalenceContext Ctx(
2017 Importer.getFromContext(), Importer.getToContext(),
2018 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2020 return Ctx.IsEquivalent(From, To);
2023 bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
2024 StructuralEquivalenceContext Ctx(
2025 Importer.getFromContext(), Importer.getToContext(),
2026 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2028 return Ctx.IsEquivalent(From, To);
2031 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2032 EnumConstantDecl *ToEC) {
2033 const llvm::APSInt &FromVal = FromEC->getInitVal();
2034 const llvm::APSInt &ToVal = ToEC->getInitVal();
2036 return FromVal.isSigned() == ToVal.isSigned() &&
2037 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2041 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2042 ClassTemplateDecl *To) {
2043 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2044 Importer.getToContext(),
2045 Importer.getNonEquivalentDecls(),
2046 getStructuralEquivalenceKind(Importer));
2047 return Ctx.IsEquivalent(From, To);
2050 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2051 VarTemplateDecl *To) {
2052 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2053 Importer.getToContext(),
2054 Importer.getNonEquivalentDecls(),
2055 getStructuralEquivalenceKind(Importer));
2056 return Ctx.IsEquivalent(From, To);
2059 ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2060 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2061 << D->getDeclKindName();
2062 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2065 ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2066 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2067 << D->getDeclKindName();
2068 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2071 ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2072 // Import the context of this declaration.
2073 DeclContext *DC, *LexicalDC;
2074 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2075 return std::move(Err);
2077 // Import the location of this declaration.
2078 ExpectedSLoc LocOrErr = import(D->getLocation());
2080 return LocOrErr.takeError();
2083 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2086 ToD->setLexicalDeclContext(LexicalDC);
2087 LexicalDC->addDeclInternal(ToD);
2091 ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2092 TranslationUnitDecl *ToD =
2093 Importer.getToContext().getTranslationUnitDecl();
2095 Importer.MapImported(D, ToD);
2100 ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2101 ExpectedSLoc LocOrErr = import(D->getLocation());
2103 return LocOrErr.takeError();
2104 auto ColonLocOrErr = import(D->getColonLoc());
2106 return ColonLocOrErr.takeError();
2108 // Import the context of this declaration.
2109 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2111 return DCOrErr.takeError();
2112 DeclContext *DC = *DCOrErr;
2114 AccessSpecDecl *ToD;
2115 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2116 DC, *LocOrErr, *ColonLocOrErr))
2119 // Lexical DeclContext and Semantic DeclContext
2120 // is always the same for the accessSpec.
2121 ToD->setLexicalDeclContext(DC);
2122 DC->addDeclInternal(ToD);
2127 ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2128 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2130 return DCOrErr.takeError();
2131 DeclContext *DC = *DCOrErr;
2132 DeclContext *LexicalDC = DC;
2134 SourceLocation ToLocation, ToRParenLoc;
2136 StringLiteral *ToMessage;
2137 if (auto Imp = importSeq(
2138 D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc()))
2139 std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp;
2141 return Imp.takeError();
2143 StaticAssertDecl *ToD;
2144 if (GetImportedOrCreateDecl(
2145 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2146 ToRParenLoc, D->isFailed()))
2149 ToD->setLexicalDeclContext(LexicalDC);
2150 LexicalDC->addDeclInternal(ToD);
2154 ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2155 // Import the major distinguishing characteristics of this namespace.
2156 DeclContext *DC, *LexicalDC;
2157 DeclarationName Name;
2160 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2161 return std::move(Err);
2165 NamespaceDecl *MergeWithNamespace = nullptr;
2167 // This is an anonymous namespace. Adopt an existing anonymous
2168 // namespace if we can.
2169 // FIXME: Not testable.
2170 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2171 MergeWithNamespace = TU->getAnonymousNamespace();
2173 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2175 SmallVector<NamedDecl *, 4> ConflictingDecls;
2176 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2177 for (auto *FoundDecl : FoundDecls) {
2178 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2181 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2182 MergeWithNamespace = FoundNS;
2183 ConflictingDecls.clear();
2187 ConflictingDecls.push_back(FoundDecl);
2190 if (!ConflictingDecls.empty()) {
2191 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2192 ConflictingDecls.data(),
2193 ConflictingDecls.size());
2195 return make_error<ImportError>(ImportError::NameConflict);
2199 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2201 return BeginLocOrErr.takeError();
2203 // Create the "to" namespace, if needed.
2204 NamespaceDecl *ToNamespace = MergeWithNamespace;
2206 if (GetImportedOrCreateDecl(
2207 ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2208 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2209 /*PrevDecl=*/nullptr))
2211 ToNamespace->setLexicalDeclContext(LexicalDC);
2212 LexicalDC->addDeclInternal(ToNamespace);
2214 // If this is an anonymous namespace, register it as the anonymous
2215 // namespace within its context.
2217 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2218 TU->setAnonymousNamespace(ToNamespace);
2220 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2223 Importer.MapImported(D, ToNamespace);
2225 if (Error Err = ImportDeclContext(D))
2226 return std::move(Err);
2231 ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2232 // Import the major distinguishing characteristics of this namespace.
2233 DeclContext *DC, *LexicalDC;
2234 DeclarationName Name;
2237 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2238 return std::move(Err);
2242 // NOTE: No conflict resolution is done for namespace aliases now.
2244 SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc;
2245 NestedNameSpecifierLoc ToQualifierLoc;
2246 NamespaceDecl *ToNamespace;
2247 if (auto Imp = importSeq(
2248 D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(),
2249 D->getTargetNameLoc(), D->getNamespace()))
2251 ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc,
2252 ToNamespace) = *Imp;
2254 return Imp.takeError();
2255 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2257 NamespaceAliasDecl *ToD;
2258 if (GetImportedOrCreateDecl(
2259 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2260 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2263 ToD->setLexicalDeclContext(LexicalDC);
2264 LexicalDC->addDeclInternal(ToD);
2270 ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2271 // Import the major distinguishing characteristics of this typedef.
2272 DeclContext *DC, *LexicalDC;
2273 DeclarationName Name;
2276 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2277 return std::move(Err);
2281 // If this typedef is not in block scope, determine whether we've
2282 // seen a typedef with the same name (that we can merge with) or any
2283 // other entity by that name (which name lookup could conflict with).
2284 if (!DC->isFunctionOrMethod()) {
2285 SmallVector<NamedDecl *, 4> ConflictingDecls;
2286 unsigned IDNS = Decl::IDNS_Ordinary;
2287 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2288 for (auto *FoundDecl : FoundDecls) {
2289 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2291 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2292 QualType FromUT = D->getUnderlyingType();
2293 QualType FoundUT = FoundTypedef->getUnderlyingType();
2294 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2295 // If the "From" context has a complete underlying type but we
2296 // already have a complete underlying type then return with that.
2297 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2298 return Importer.MapImported(D, FoundTypedef);
2300 // FIXME Handle redecl chain. When you do that make consistent changes
2301 // in ASTImporterLookupTable too.
2305 ConflictingDecls.push_back(FoundDecl);
2308 if (!ConflictingDecls.empty()) {
2309 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2310 ConflictingDecls.data(),
2311 ConflictingDecls.size());
2313 return make_error<ImportError>(ImportError::NameConflict);
2317 QualType ToUnderlyingType;
2318 TypeSourceInfo *ToTypeSourceInfo;
2319 SourceLocation ToBeginLoc;
2320 if (auto Imp = importSeq(
2321 D->getUnderlyingType(), D->getTypeSourceInfo(), D->getBeginLoc()))
2322 std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp;
2324 return Imp.takeError();
2326 // Create the new typedef node.
2327 // FIXME: ToUnderlyingType is not used.
2328 TypedefNameDecl *ToTypedef;
2330 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2331 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2332 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2334 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2335 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2336 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2339 ToTypedef->setAccess(D->getAccess());
2340 ToTypedef->setLexicalDeclContext(LexicalDC);
2342 // Templated declarations should not appear in DeclContext.
2343 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2344 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2345 LexicalDC->addDeclInternal(ToTypedef);
2350 ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2351 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2354 ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2355 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2359 ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2360 // Import the major distinguishing characteristics of this typedef.
2361 DeclContext *DC, *LexicalDC;
2362 DeclarationName Name;
2365 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2366 return std::move(Err);
2370 // If this typedef is not in block scope, determine whether we've
2371 // seen a typedef with the same name (that we can merge with) or any
2372 // other entity by that name (which name lookup could conflict with).
2373 if (!DC->isFunctionOrMethod()) {
2374 SmallVector<NamedDecl *, 4> ConflictingDecls;
2375 unsigned IDNS = Decl::IDNS_Ordinary;
2376 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2377 for (auto *FoundDecl : FoundDecls) {
2378 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2380 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2381 return Importer.MapImported(D, FoundAlias);
2382 ConflictingDecls.push_back(FoundDecl);
2385 if (!ConflictingDecls.empty()) {
2386 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2387 ConflictingDecls.data(),
2388 ConflictingDecls.size());
2390 return make_error<ImportError>(ImportError::NameConflict);
2394 TemplateParameterList *ToTemplateParameters;
2395 TypeAliasDecl *ToTemplatedDecl;
2396 if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl()))
2397 std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp;
2399 return Imp.takeError();
2401 TypeAliasTemplateDecl *ToAlias;
2402 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2403 Name, ToTemplateParameters, ToTemplatedDecl))
2406 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2408 ToAlias->setAccess(D->getAccess());
2409 ToAlias->setLexicalDeclContext(LexicalDC);
2410 LexicalDC->addDeclInternal(ToAlias);
2414 ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2415 // Import the major distinguishing characteristics of this label.
2416 DeclContext *DC, *LexicalDC;
2417 DeclarationName Name;
2420 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2421 return std::move(Err);
2425 assert(LexicalDC->isFunctionOrMethod());
2428 if (D->isGnuLocal()) {
2429 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2431 return BeginLocOrErr.takeError();
2432 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2433 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2437 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2438 Name.getAsIdentifierInfo()))
2443 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2445 return ToStmtOrErr.takeError();
2447 ToLabel->setStmt(*ToStmtOrErr);
2448 ToLabel->setLexicalDeclContext(LexicalDC);
2449 LexicalDC->addDeclInternal(ToLabel);
2453 ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2454 // Import the major distinguishing characteristics of this enum.
2455 DeclContext *DC, *LexicalDC;
2456 DeclarationName Name;
2459 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2460 return std::move(Err);
2464 // Figure out what enum name we're looking for.
2465 unsigned IDNS = Decl::IDNS_Tag;
2466 DeclarationName SearchName = Name;
2467 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2468 if (Error Err = importInto(
2469 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2470 return std::move(Err);
2471 IDNS = Decl::IDNS_Ordinary;
2472 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2473 IDNS |= Decl::IDNS_Ordinary;
2475 // We may already have an enum of the same name; try to find and match it.
2476 if (!DC->isFunctionOrMethod() && SearchName) {
2477 SmallVector<NamedDecl *, 4> ConflictingDecls;
2479 Importer.findDeclsInToCtx(DC, SearchName);
2480 for (auto *FoundDecl : FoundDecls) {
2481 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2484 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2485 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2486 FoundDecl = Tag->getDecl();
2489 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2490 if (!hasSameVisibilityContext(FoundEnum, D))
2492 if (IsStructuralMatch(D, FoundEnum))
2493 return Importer.MapImported(D, FoundEnum);
2496 ConflictingDecls.push_back(FoundDecl);
2499 if (!ConflictingDecls.empty()) {
2500 Name = Importer.HandleNameConflict(SearchName, DC, IDNS,
2501 ConflictingDecls.data(),
2502 ConflictingDecls.size());
2504 return make_error<ImportError>(ImportError::NameConflict);
2508 SourceLocation ToBeginLoc;
2509 NestedNameSpecifierLoc ToQualifierLoc;
2510 QualType ToIntegerType;
2511 if (auto Imp = importSeq(
2512 D->getBeginLoc(), D->getQualifierLoc(), D->getIntegerType()))
2513 std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType) = *Imp;
2515 return Imp.takeError();
2517 // Create the enum declaration.
2519 if (GetImportedOrCreateDecl(
2520 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2521 Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2522 D->isScopedUsingClassTag(), D->isFixed()))
2525 D2->setQualifierInfo(ToQualifierLoc);
2526 D2->setIntegerType(ToIntegerType);
2527 D2->setAccess(D->getAccess());
2528 D2->setLexicalDeclContext(LexicalDC);
2529 LexicalDC->addDeclInternal(D2);
2531 // Import the definition
2532 if (D->isCompleteDefinition())
2533 if (Error Err = ImportDefinition(D, D2))
2534 return std::move(Err);
2539 ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2540 bool IsFriendTemplate = false;
2541 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2543 DCXX->getDescribedClassTemplate() &&
2544 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2548 // Import the major distinguishing characteristics of this record.
2549 DeclContext *DC, *LexicalDC;
2550 DeclarationName Name;
2553 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2554 return std::move(Err);
2558 // Figure out what structure name we're looking for.
2559 unsigned IDNS = Decl::IDNS_Tag;
2560 DeclarationName SearchName = Name;
2561 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2562 if (Error Err = importInto(
2563 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2564 return std::move(Err);
2565 IDNS = Decl::IDNS_Ordinary;
2566 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2567 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
2569 // We may already have a record of the same name; try to find and match it.
2570 RecordDecl *PrevDecl = nullptr;
2571 if (!DC->isFunctionOrMethod()) {
2572 SmallVector<NamedDecl *, 4> ConflictingDecls;
2574 Importer.findDeclsInToCtx(DC, SearchName);
2575 if (!FoundDecls.empty()) {
2576 // We're going to have to compare D against potentially conflicting Decls,
2578 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2579 D->getASTContext().getExternalSource()->CompleteType(D);
2582 for (auto *FoundDecl : FoundDecls) {
2583 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2586 Decl *Found = FoundDecl;
2587 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2588 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2589 Found = Tag->getDecl();
2592 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2593 // Do not emit false positive diagnostic in case of unnamed
2594 // struct/union and in case of anonymous structs. Would be false
2595 // because there may be several anonymous/unnamed structs in a class.
2596 // E.g. these are both valid:
2597 // struct A { // unnamed structs
2598 // struct { struct A *next; } entry0;
2599 // struct { struct A *next; } entry1;
2601 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2603 if (!IsStructuralMatch(D, FoundRecord, false))
2606 if (!hasSameVisibilityContext(FoundRecord, D))
2609 if (IsStructuralMatch(D, FoundRecord)) {
2610 RecordDecl *FoundDef = FoundRecord->getDefinition();
2611 if (D->isThisDeclarationADefinition() && FoundDef) {
2612 // FIXME: Structural equivalence check should check for same
2613 // user-defined methods.
2614 Importer.MapImported(D, FoundDef);
2615 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2616 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2617 assert(FoundCXX && "Record type mismatch");
2619 if (!Importer.isMinimalImport())
2620 // FoundDef may not have every implicit method that D has
2621 // because implicit methods are created only if they are used.
2622 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2623 return std::move(Err);
2626 PrevDecl = FoundRecord->getMostRecentDecl();
2631 ConflictingDecls.push_back(FoundDecl);
2634 if (!ConflictingDecls.empty() && SearchName) {
2635 Name = Importer.HandleNameConflict(SearchName, DC, IDNS,
2636 ConflictingDecls.data(),
2637 ConflictingDecls.size());
2639 return make_error<ImportError>(ImportError::NameConflict);
2643 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2645 return BeginLocOrErr.takeError();
2647 // Create the record declaration.
2648 RecordDecl *D2 = nullptr;
2649 CXXRecordDecl *D2CXX = nullptr;
2650 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2651 if (DCXX->isLambda()) {
2652 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2654 return TInfoOrErr.takeError();
2655 if (GetImportedOrCreateSpecialDecl(
2656 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2657 DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2658 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2660 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2662 return CDeclOrErr.takeError();
2663 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr);
2664 } else if (DCXX->isInjectedClassName()) {
2665 // We have to be careful to do a similar dance to the one in
2666 // Sema::ActOnStartCXXMemberDeclarations
2667 const bool DelayTypeCreation = true;
2668 if (GetImportedOrCreateDecl(
2669 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2670 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2671 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2673 Importer.getToContext().getTypeDeclType(
2674 D2CXX, dyn_cast<CXXRecordDecl>(DC));
2676 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2677 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2678 Name.getAsIdentifierInfo(),
2679 cast_or_null<CXXRecordDecl>(PrevDecl)))
2684 D2->setAccess(D->getAccess());
2685 D2->setLexicalDeclContext(LexicalDC);
2686 if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2687 LexicalDC->addDeclInternal(D2);
2689 if (LexicalDC != DC && D->isInIdentifierNamespace(Decl::IDNS_TagFriend))
2690 DC->makeDeclVisibleInContext(D2);
2692 if (ClassTemplateDecl *FromDescribed =
2693 DCXX->getDescribedClassTemplate()) {
2694 ClassTemplateDecl *ToDescribed;
2695 if (Error Err = importInto(ToDescribed, FromDescribed))
2696 return std::move(Err);
2697 D2CXX->setDescribedClassTemplate(ToDescribed);
2698 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2699 // In a record describing a template the type should be an
2700 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2701 // previously set type to the correct value here (ToDescribed is not
2702 // available at record create).
2703 // FIXME: The previous type is cleared but not removed from
2704 // ASTContext's internal storage.
2705 CXXRecordDecl *Injected = nullptr;
2706 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2707 auto *Record = dyn_cast<CXXRecordDecl>(Found);
2708 if (Record && Record->isInjectedClassName()) {
2713 // Create an injected type for the whole redecl chain.
2714 SmallVector<Decl *, 2> Redecls =
2715 getCanonicalForwardRedeclChain(D2CXX);
2716 for (auto *R : Redecls) {
2717 auto *RI = cast<CXXRecordDecl>(R);
2718 RI->setTypeForDecl(nullptr);
2719 // Below we create a new injected type and assign that to the
2720 // canonical decl, subsequent declarations in the chain will reuse
2722 Importer.getToContext().getInjectedClassNameType(
2723 RI, ToDescribed->getInjectedClassNameSpecialization());
2725 // Set the new type for the previous injected decl too.
2727 Injected->setTypeForDecl(nullptr);
2728 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2731 } else if (MemberSpecializationInfo *MemberInfo =
2732 DCXX->getMemberSpecializationInfo()) {
2733 TemplateSpecializationKind SK =
2734 MemberInfo->getTemplateSpecializationKind();
2735 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2737 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2738 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2740 return ToInstOrErr.takeError();
2742 if (ExpectedSLoc POIOrErr =
2743 import(MemberInfo->getPointOfInstantiation()))
2744 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
2747 return POIOrErr.takeError();
2751 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2752 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2753 Name.getAsIdentifierInfo(), PrevDecl))
2755 D2->setLexicalDeclContext(LexicalDC);
2756 LexicalDC->addDeclInternal(D2);
2759 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2760 D2->setQualifierInfo(*QualifierLocOrErr);
2762 return QualifierLocOrErr.takeError();
2764 if (D->isAnonymousStructOrUnion())
2765 D2->setAnonymousStructOrUnion(true);
2767 if (D->isCompleteDefinition())
2768 if (Error Err = ImportDefinition(D, D2, IDK_Default))
2769 return std::move(Err);
2774 ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2775 // Import the major distinguishing characteristics of this enumerator.
2776 DeclContext *DC, *LexicalDC;
2777 DeclarationName Name;
2780 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2781 return std::move(Err);
2785 // Determine whether there are any other declarations with the same name and
2786 // in the same context.
2787 if (!LexicalDC->isFunctionOrMethod()) {
2788 SmallVector<NamedDecl *, 4> ConflictingDecls;
2789 unsigned IDNS = Decl::IDNS_Ordinary;
2790 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2791 for (auto *FoundDecl : FoundDecls) {
2792 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2795 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2796 if (IsStructuralMatch(D, FoundEnumConstant))
2797 return Importer.MapImported(D, FoundEnumConstant);
2800 ConflictingDecls.push_back(FoundDecl);
2803 if (!ConflictingDecls.empty()) {
2804 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2805 ConflictingDecls.data(),
2806 ConflictingDecls.size());
2808 return make_error<ImportError>(ImportError::NameConflict);
2812 ExpectedType TypeOrErr = import(D->getType());
2814 return TypeOrErr.takeError();
2816 ExpectedExpr InitOrErr = import(D->getInitExpr());
2818 return InitOrErr.takeError();
2820 EnumConstantDecl *ToEnumerator;
2821 if (GetImportedOrCreateDecl(
2822 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2823 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
2824 return ToEnumerator;
2826 ToEnumerator->setAccess(D->getAccess());
2827 ToEnumerator->setLexicalDeclContext(LexicalDC);
2828 LexicalDC->addDeclInternal(ToEnumerator);
2829 return ToEnumerator;
2832 Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
2833 DeclaratorDecl *ToD) {
2834 unsigned int Num = FromD->getNumTemplateParameterLists();
2836 return Error::success();
2837 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
2838 for (unsigned int I = 0; I < Num; ++I)
2839 if (Expected<TemplateParameterList *> ToTPListOrErr =
2840 import(FromD->getTemplateParameterList(I)))
2841 ToTPLists[I] = *ToTPListOrErr;
2843 return ToTPListOrErr.takeError();
2844 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
2845 return Error::success();
2848 Error ASTNodeImporter::ImportTemplateInformation(
2849 FunctionDecl *FromFD, FunctionDecl *ToFD) {
2850 switch (FromFD->getTemplatedKind()) {
2851 case FunctionDecl::TK_NonTemplate:
2852 case FunctionDecl::TK_FunctionTemplate:
2853 return Error::success();
2855 case FunctionDecl::TK_MemberSpecialization: {
2856 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
2858 if (Expected<FunctionDecl *> InstFDOrErr =
2859 import(FromFD->getInstantiatedFromMemberFunction()))
2860 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
2862 return InstFDOrErr.takeError();
2864 if (ExpectedSLoc POIOrErr = import(
2865 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
2866 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
2868 return POIOrErr.takeError();
2870 return Error::success();
2873 case FunctionDecl::TK_FunctionTemplateSpecialization: {
2874 auto FunctionAndArgsOrErr =
2875 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2876 if (!FunctionAndArgsOrErr)
2877 return FunctionAndArgsOrErr.takeError();
2879 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
2880 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
2882 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2883 TemplateArgumentListInfo ToTAInfo;
2884 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2885 if (FromTAArgsAsWritten)
2886 if (Error Err = ImportTemplateArgumentListInfo(
2887 *FromTAArgsAsWritten, ToTAInfo))
2890 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
2892 return POIOrErr.takeError();
2894 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
2897 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2898 ToFD->setFunctionTemplateSpecialization(
2899 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
2900 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
2901 return Error::success();
2904 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
2905 auto *FromInfo = FromFD->getDependentSpecializationInfo();
2906 UnresolvedSet<8> TemplDecls;
2907 unsigned NumTemplates = FromInfo->getNumTemplates();
2908 for (unsigned I = 0; I < NumTemplates; I++) {
2909 if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
2910 import(FromInfo->getTemplate(I)))
2911 TemplDecls.addDecl(*ToFTDOrErr);
2913 return ToFTDOrErr.takeError();
2916 // Import TemplateArgumentListInfo.
2917 TemplateArgumentListInfo ToTAInfo;
2918 if (Error Err = ImportTemplateArgumentListInfo(
2919 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2921 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
2925 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2926 TemplDecls, ToTAInfo);
2927 return Error::success();
2930 llvm_unreachable("All cases should be covered!");
2933 Expected<FunctionDecl *>
2934 ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
2935 auto FunctionAndArgsOrErr =
2936 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2937 if (!FunctionAndArgsOrErr)
2938 return FunctionAndArgsOrErr.takeError();
2940 FunctionTemplateDecl *Template;
2941 TemplateArgsTy ToTemplArgs;
2942 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
2943 void *InsertPos = nullptr;
2944 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
2948 Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
2949 FunctionDecl *ToFD) {
2950 if (Stmt *FromBody = FromFD->getBody()) {
2951 if (ExpectedStmt ToBodyOrErr = import(FromBody))
2952 ToFD->setBody(*ToBodyOrErr);
2954 return ToBodyOrErr.takeError();
2956 return Error::success();
2959 template <typename T>
2960 bool ASTNodeImporter::hasSameVisibilityContext(T *Found, T *From) {
2961 if (From->hasExternalFormalLinkage())
2962 return Found->hasExternalFormalLinkage();
2963 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
2965 if (From->isInAnonymousNamespace())
2966 return Found->isInAnonymousNamespace();
2968 return !Found->isInAnonymousNamespace() &&
2969 !Found->hasExternalFormalLinkage();
2972 ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2974 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
2975 auto RedeclIt = Redecls.begin();
2976 // Import the first part of the decl chain. I.e. import all previous
2977 // declarations starting from the canonical decl.
2978 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
2979 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
2981 return ToRedeclOrErr.takeError();
2983 assert(*RedeclIt == D);
2985 // Import the major distinguishing characteristics of this function.
2986 DeclContext *DC, *LexicalDC;
2987 DeclarationName Name;
2990 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2991 return std::move(Err);
2995 FunctionDecl *FoundByLookup = nullptr;
2996 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
2998 // If this is a function template specialization, then try to find the same
2999 // existing specialization in the "to" context. The lookup below will not
3000 // find any specialization, but would find the primary template; thus, we
3001 // have to skip normal lookup in case of specializations.
3002 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3003 if (D->getTemplatedKind() ==
3004 FunctionDecl::TK_FunctionTemplateSpecialization) {
3005 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3006 if (!FoundFunctionOrErr)
3007 return FoundFunctionOrErr.takeError();
3008 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3009 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3011 FoundByLookup = FoundFunction;
3014 // Try to find a function in our own ("to") context with the same name, same
3015 // type, and in the same context as the function we're importing.
3016 else if (!LexicalDC->isFunctionOrMethod()) {
3017 SmallVector<NamedDecl *, 4> ConflictingDecls;
3018 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3019 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3020 for (auto *FoundDecl : FoundDecls) {
3021 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3024 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3025 if (!hasSameVisibilityContext(FoundFunction, D))
3028 if (IsStructuralMatch(D, FoundFunction)) {
3029 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3031 FoundByLookup = FoundFunction;
3034 // FIXME: Check for overloading more carefully, e.g., by boosting
3035 // Sema::IsOverload out to the AST library.
3037 // Function overloading is okay in C++.
3038 if (Importer.getToContext().getLangOpts().CPlusPlus)
3041 // Complain about inconsistent function types.
3042 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3043 << Name << D->getType() << FoundFunction->getType();
3044 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3045 << FoundFunction->getType();
3048 ConflictingDecls.push_back(FoundDecl);
3051 if (!ConflictingDecls.empty()) {
3052 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3053 ConflictingDecls.data(),
3054 ConflictingDecls.size());
3056 return make_error<ImportError>(ImportError::NameConflict);
3060 // We do not allow more than one in-class declaration of a function. This is
3061 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3062 // assumes there is only one in-class declaration. Building a redecl
3063 // chain would result in more than one in-class declaration for
3064 // overrides (even if they are part of the same redecl chain inside the
3066 if (FoundByLookup) {
3067 if (isa<CXXMethodDecl>(FoundByLookup)) {
3068 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3069 if (!D->doesThisDeclarationHaveABody())
3070 return Importer.MapImported(D, FoundByLookup);
3072 // Let's continue and build up the redecl chain in this case.
3073 // FIXME Merge the functions into one decl.
3079 DeclarationNameInfo NameInfo(Name, Loc);
3080 // Import additional name location/type info.
3081 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3082 return std::move(Err);
3084 QualType FromTy = D->getType();
3085 bool usedDifferentExceptionSpec = false;
3087 if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3088 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3089 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3090 // FunctionDecl that we are importing the FunctionProtoType for.
3091 // To avoid an infinite recursion when importing, create the FunctionDecl
3092 // with a simplified function type and update it afterwards.
3093 if (FromEPI.ExceptionSpec.SourceDecl ||
3094 FromEPI.ExceptionSpec.SourceTemplate ||
3095 FromEPI.ExceptionSpec.NoexceptExpr) {
3096 FunctionProtoType::ExtProtoInfo DefaultEPI;
3097 FromTy = Importer.getFromContext().getFunctionType(
3098 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3099 usedDifferentExceptionSpec = true;
3104 TypeSourceInfo *TInfo;
3105 SourceLocation ToInnerLocStart, ToEndLoc;
3106 NestedNameSpecifierLoc ToQualifierLoc;
3107 if (auto Imp = importSeq(
3108 FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(),
3109 D->getQualifierLoc(), D->getEndLoc()))
3110 std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc) = *Imp;
3112 return Imp.takeError();
3114 // Import the function parameters.
3115 SmallVector<ParmVarDecl *, 8> Parameters;
3116 for (auto P : D->parameters()) {
3117 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3118 Parameters.push_back(*ToPOrErr);
3120 return ToPOrErr.takeError();
3123 // Create the imported function.
3124 FunctionDecl *ToFunction = nullptr;
3125 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3126 Expr *ExplicitExpr = nullptr;
3127 if (FromConstructor->getExplicitSpecifier().getExpr()) {
3128 auto Imp = importSeq(FromConstructor->getExplicitSpecifier().getExpr());
3130 return Imp.takeError();
3131 std::tie(ExplicitExpr) = *Imp;
3133 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3134 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3135 ToInnerLocStart, NameInfo, T, TInfo,
3138 FromConstructor->getExplicitSpecifier().getKind()),
3139 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind()))
3141 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3144 importSeq(const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()),
3145 FromDtor->getOperatorDeleteThisArg());
3148 return Imp.takeError();
3150 FunctionDecl *ToOperatorDelete;
3152 std::tie(ToOperatorDelete, ToThisArg) = *Imp;
3154 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3155 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3156 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3160 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3162 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3163 } else if (CXXConversionDecl *FromConversion =
3164 dyn_cast<CXXConversionDecl>(D)) {
3165 Expr *ExplicitExpr = nullptr;
3166 if (FromConversion->getExplicitSpecifier().getExpr()) {
3167 auto Imp = importSeq(FromConversion->getExplicitSpecifier().getExpr());
3169 return Imp.takeError();
3170 std::tie(ExplicitExpr) = *Imp;
3172 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3173 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3174 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3175 ExplicitSpecifier(ExplicitExpr,
3176 FromConversion->getExplicitSpecifier().getKind()),
3177 D->getConstexprKind(), SourceLocation()))
3179 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3180 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3181 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3182 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3183 Method->isInlineSpecified(), D->getConstexprKind(),
3187 if (GetImportedOrCreateDecl(
3188 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3189 NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(),
3190 D->hasWrittenPrototype(), D->getConstexprKind()))
3194 // Connect the redecl chain.
3195 if (FoundByLookup) {
3196 auto *Recent = const_cast<FunctionDecl *>(
3197 FoundByLookup->getMostRecentDecl());
3198 ToFunction->setPreviousDecl(Recent);
3199 // FIXME Probably we should merge exception specifications. E.g. In the
3200 // "To" context the existing function may have exception specification with
3201 // noexcept-unevaluated, while the newly imported function may have an
3202 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3203 // decl and its redeclarations may be required.
3206 // Import Ctor initializers.
3207 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3208 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3209 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3210 // Import first, then allocate memory and copy if there was no error.
3211 if (Error Err = ImportContainerChecked(
3212 FromConstructor->inits(), CtorInitializers))
3213 return std::move(Err);
3215 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3216 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3217 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3218 ToCtor->setCtorInitializers(Memory);
3219 ToCtor->setNumCtorInitializers(NumInitializers);
3223 ToFunction->setQualifierInfo(ToQualifierLoc);
3224 ToFunction->setAccess(D->getAccess());
3225 ToFunction->setLexicalDeclContext(LexicalDC);
3226 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3227 ToFunction->setTrivial(D->isTrivial());
3228 ToFunction->setPure(D->isPure());
3229 ToFunction->setRangeEnd(ToEndLoc);
3231 // Set the parameters.
3232 for (auto *Param : Parameters) {
3233 Param->setOwningFunction(ToFunction);
3234 ToFunction->addDeclInternal(Param);
3236 ToFunction->setParams(Parameters);
3238 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3239 // params it refers to.
3242 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3243 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3244 ProtoLoc.setParam(I, Parameters[I]);
3248 if (usedDifferentExceptionSpec) {
3249 // Update FunctionProtoType::ExtProtoInfo.
3250 if (ExpectedType TyOrErr = import(D->getType()))
3251 ToFunction->setType(*TyOrErr);
3253 return TyOrErr.takeError();
3256 // Import the describing template function, if any.
3258 auto ToFTOrErr = import(FromFT);
3260 return ToFTOrErr.takeError();
3263 if (D->doesThisDeclarationHaveABody()) {
3264 Error Err = ImportFunctionDeclBody(D, ToFunction);
3267 return std::move(Err);
3270 // FIXME: Other bits to merge?
3272 // If it is a template, import all related things.
3273 if (Error Err = ImportTemplateInformation(D, ToFunction))
3274 return std::move(Err);
3276 bool IsFriend = D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend);
3278 // TODO Can we generalize this approach to other AST nodes as well?
3279 if (D->getDeclContext()->containsDeclAndLoad(D))
3280 DC->addDeclInternal(ToFunction);
3281 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3282 LexicalDC->addDeclInternal(ToFunction);
3284 // Friend declaration's lexical context is the befriending class, but the
3285 // semantic context is the enclosing scope of the befriending class.
3286 // We want the friend functions to be found in the semantic context by lookup.
3287 // FIXME should we handle this generically in VisitFriendDecl?
3288 // In Other cases when LexicalDC != DC we don't want it to be added,
3289 // e.g out-of-class definitions like void B::f() {} .
3290 if (LexicalDC != DC && IsFriend) {
3291 DC->makeDeclVisibleInContext(ToFunction);
3294 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3295 ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod);
3297 // Import the rest of the chain. I.e. import all subsequent declarations.
3298 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3299 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3301 return ToRedeclOrErr.takeError();
3307 ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3308 return VisitFunctionDecl(D);
3311 ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3312 return VisitCXXMethodDecl(D);
3315 ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3316 return VisitCXXMethodDecl(D);
3319 ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3320 return VisitCXXMethodDecl(D);
3323 ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3324 // Import the major distinguishing characteristics of a variable.
3325 DeclContext *DC, *LexicalDC;
3326 DeclarationName Name;
3329 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3330 return std::move(Err);
3334 // Determine whether we've already imported this field.
3335 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3336 for (auto *FoundDecl : FoundDecls) {
3337 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3338 // For anonymous fields, match up by index.
3340 ASTImporter::getFieldIndex(D) !=
3341 ASTImporter::getFieldIndex(FoundField))
3344 if (Importer.IsStructurallyEquivalent(D->getType(),
3345 FoundField->getType())) {
3346 Importer.MapImported(D, FoundField);
3347 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3348 // initializer of a FieldDecl might not had been instantiated in the
3349 // "To" context. However, the "From" context might instantiated that,
3350 // thus we have to merge that.
3351 if (Expr *FromInitializer = D->getInClassInitializer()) {
3352 // We don't have yet the initializer set.
3353 if (FoundField->hasInClassInitializer() &&
3354 !FoundField->getInClassInitializer()) {
3355 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3356 FoundField->setInClassInitializer(*ToInitializerOrErr);
3358 // We can't return error here,
3359 // since we already mapped D as imported.
3360 // FIXME: warning message?
3361 consumeError(ToInitializerOrErr.takeError());
3369 // FIXME: Why is this case not handled with calling HandleNameConflict?
3370 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3371 << Name << D->getType() << FoundField->getType();
3372 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3373 << FoundField->getType();
3375 return make_error<ImportError>(ImportError::NameConflict);
3380 TypeSourceInfo *ToTInfo;
3382 SourceLocation ToInnerLocStart;
3383 Expr *ToInitializer;
3384 if (auto Imp = importSeq(
3385 D->getType(), D->getTypeSourceInfo(), D->getBitWidth(),
3386 D->getInnerLocStart(), D->getInClassInitializer()))
3388 ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp;
3390 return Imp.takeError();
3393 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3394 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3395 ToType, ToTInfo, ToBitWidth, D->isMutable(),
3396 D->getInClassInitStyle()))
3399 ToField->setAccess(D->getAccess());
3400 ToField->setLexicalDeclContext(LexicalDC);
3402 ToField->setInClassInitializer(ToInitializer);
3403 ToField->setImplicit(D->isImplicit());
3404 LexicalDC->addDeclInternal(ToField);
3408 ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3409 // Import the major distinguishing characteristics of a variable.
3410 DeclContext *DC, *LexicalDC;
3411 DeclarationName Name;
3414 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3415 return std::move(Err);
3419 // Determine whether we've already imported this field.
3420 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3421 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3422 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3423 // For anonymous indirect fields, match up by index.
3425 ASTImporter::getFieldIndex(D) !=
3426 ASTImporter::getFieldIndex(FoundField))
3429 if (Importer.IsStructurallyEquivalent(D->getType(),
3430 FoundField->getType(),
3432 Importer.MapImported(D, FoundField);
3436 // If there are more anonymous fields to check, continue.
3437 if (!Name && I < N-1)
3440 // FIXME: Why is this case not handled with calling HandleNameConflict?
3441 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3442 << Name << D->getType() << FoundField->getType();
3443 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3444 << FoundField->getType();
3446 return make_error<ImportError>(ImportError::NameConflict);
3451 auto TypeOrErr = import(D->getType());
3453 return TypeOrErr.takeError();
3456 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3459 for (auto *PI : D->chain())
3460 if (Expected<NamedDecl *> ToD = import(PI))
3461 NamedChain[i++] = *ToD;
3463 return ToD.takeError();
3465 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3466 IndirectFieldDecl *ToIndirectField;
3467 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3468 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3469 // FIXME here we leak `NamedChain` which is allocated before
3470 return ToIndirectField;
3472 ToIndirectField->setAccess(D->getAccess());
3473 ToIndirectField->setLexicalDeclContext(LexicalDC);
3474 LexicalDC->addDeclInternal(ToIndirectField);
3475 return ToIndirectField;
3478 ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
3479 // Import the major distinguishing characteristics of a declaration.
3480 DeclContext *DC, *LexicalDC;
3481 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3482 return std::move(Err);
3484 // Determine whether we've already imported this decl.
3485 // FriendDecl is not a NamedDecl so we cannot use lookup.
3486 auto *RD = cast<CXXRecordDecl>(DC);
3487 FriendDecl *ImportedFriend = RD->getFirstFriend();
3489 while (ImportedFriend) {
3490 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3491 if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3492 /*Complain=*/false))
3493 return Importer.MapImported(D, ImportedFriend);
3495 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3496 if (Importer.IsStructurallyEquivalent(
3497 D->getFriendType()->getType(),
3498 ImportedFriend->getFriendType()->getType(), true))
3499 return Importer.MapImported(D, ImportedFriend);
3501 ImportedFriend = ImportedFriend->getNextFriend();
3504 // Not found. Create it.
3505 FriendDecl::FriendUnion ToFU;
3506 if (NamedDecl *FriendD = D->getFriendDecl()) {
3507 NamedDecl *ToFriendD;
3508 if (Error Err = importInto(ToFriendD, FriendD))
3509 return std::move(Err);
3511 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3512 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3513 ToFriendD->setObjectOfFriendDecl(false);
3516 } else { // The friend is a type, not a decl.
3517 if (auto TSIOrErr = import(D->getFriendType()))
3520 return TSIOrErr.takeError();
3523 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3524 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3525 for (unsigned I = 0; I < D->NumTPLists; I++) {
3526 if (auto ListOrErr = import(FromTPLists[I]))
3527 ToTPLists[I] = *ListOrErr;
3529 return ListOrErr.takeError();
3532 auto LocationOrErr = import(D->getLocation());
3534 return LocationOrErr.takeError();
3535 auto FriendLocOrErr = import(D->getFriendLoc());
3536 if (!FriendLocOrErr)
3537 return FriendLocOrErr.takeError();
3540 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3541 *LocationOrErr, ToFU,
3542 *FriendLocOrErr, ToTPLists))
3545 FrD->setAccess(D->getAccess());
3546 FrD->setLexicalDeclContext(LexicalDC);
3547 LexicalDC->addDeclInternal(FrD);
3551 ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3552 // Import the major distinguishing characteristics of an ivar.
3553 DeclContext *DC, *LexicalDC;
3554 DeclarationName Name;
3557 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3558 return std::move(Err);
3562 // Determine whether we've already imported this ivar
3563 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3564 for (auto *FoundDecl : FoundDecls) {
3565 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3566 if (Importer.IsStructurallyEquivalent(D->getType(),
3567 FoundIvar->getType())) {
3568 Importer.MapImported(D, FoundIvar);
3572 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3573 << Name << D->getType() << FoundIvar->getType();
3574 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3575 << FoundIvar->getType();
3577 return make_error<ImportError>(ImportError::NameConflict);
3582 TypeSourceInfo *ToTypeSourceInfo;
3584 SourceLocation ToInnerLocStart;
3585 if (auto Imp = importSeq(
3586 D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart()))
3587 std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp;
3589 return Imp.takeError();
3591 ObjCIvarDecl *ToIvar;
3592 if (GetImportedOrCreateDecl(
3593 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3594 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3595 ToType, ToTypeSourceInfo,
3596 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3599 ToIvar->setLexicalDeclContext(LexicalDC);
3600 LexicalDC->addDeclInternal(ToIvar);
3604 ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3606 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
3607 auto RedeclIt = Redecls.begin();
3608 // Import the first part of the decl chain. I.e. import all previous
3609 // declarations starting from the canonical decl.
3610 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3611 ExpectedDecl RedeclOrErr = import(*RedeclIt);
3613 return RedeclOrErr.takeError();
3615 assert(*RedeclIt == D);
3617 // Import the major distinguishing characteristics of a variable.
3618 DeclContext *DC, *LexicalDC;
3619 DeclarationName Name;
3622 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3623 return std::move(Err);
3627 // Try to find a variable in our own ("to") context with the same name and
3628 // in the same context as the variable we're importing.
3629 VarDecl *FoundByLookup = nullptr;
3630 if (D->isFileVarDecl()) {
3631 SmallVector<NamedDecl *, 4> ConflictingDecls;
3632 unsigned IDNS = Decl::IDNS_Ordinary;
3633 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3634 for (auto *FoundDecl : FoundDecls) {
3635 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3638 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3639 if (!hasSameVisibilityContext(FoundVar, D))
3641 if (Importer.IsStructurallyEquivalent(D->getType(),
3642 FoundVar->getType())) {
3644 // The VarDecl in the "From" context has a definition, but in the
3645 // "To" context we already have a definition.
3646 VarDecl *FoundDef = FoundVar->getDefinition();
3647 if (D->isThisDeclarationADefinition() && FoundDef)
3648 // FIXME Check for ODR error if the two definitions have
3649 // different initializers?
3650 return Importer.MapImported(D, FoundDef);
3652 // The VarDecl in the "From" context has an initializer, but in the
3653 // "To" context we already have an initializer.
3654 const VarDecl *FoundDInit = nullptr;
3655 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3656 // FIXME Diagnose ODR error if the two initializers are different?
3657 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3659 FoundByLookup = FoundVar;
3663 const ArrayType *FoundArray
3664 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3665 const ArrayType *TArray
3666 = Importer.getToContext().getAsArrayType(D->getType());
3667 if (FoundArray && TArray) {
3668 if (isa<IncompleteArrayType>(FoundArray) &&
3669 isa<ConstantArrayType>(TArray)) {
3671 if (auto TyOrErr = import(D->getType()))
3672 FoundVar->setType(*TyOrErr);
3674 return TyOrErr.takeError();
3676 FoundByLookup = FoundVar;
3678 } else if (isa<IncompleteArrayType>(TArray) &&
3679 isa<ConstantArrayType>(FoundArray)) {
3680 FoundByLookup = FoundVar;
3685 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
3686 << Name << D->getType() << FoundVar->getType();
3687 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3688 << FoundVar->getType();
3691 ConflictingDecls.push_back(FoundDecl);
3694 if (!ConflictingDecls.empty()) {
3695 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3696 ConflictingDecls.data(),
3697 ConflictingDecls.size());
3699 return make_error<ImportError>(ImportError::NameConflict);
3704 TypeSourceInfo *ToTypeSourceInfo;
3705 SourceLocation ToInnerLocStart;
3706 NestedNameSpecifierLoc ToQualifierLoc;
3707 if (auto Imp = importSeq(
3708 D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(),
3709 D->getQualifierLoc()))
3710 std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp;
3712 return Imp.takeError();
3714 // Create the imported variable.
3716 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3717 ToInnerLocStart, Loc,
3718 Name.getAsIdentifierInfo(),
3719 ToType, ToTypeSourceInfo,
3720 D->getStorageClass()))
3723 ToVar->setQualifierInfo(ToQualifierLoc);
3724 ToVar->setAccess(D->getAccess());
3725 ToVar->setLexicalDeclContext(LexicalDC);
3727 if (FoundByLookup) {
3728 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
3729 ToVar->setPreviousDecl(Recent);
3732 if (Error Err = ImportInitializer(D, ToVar))
3733 return std::move(Err);
3735 if (D->isConstexpr())
3736 ToVar->setConstexpr(true);
3738 if (D->getDeclContext()->containsDeclAndLoad(D))
3739 DC->addDeclInternal(ToVar);
3740 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3741 LexicalDC->addDeclInternal(ToVar);
3743 // Import the rest of the chain. I.e. import all subsequent declarations.
3744 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3745 ExpectedDecl RedeclOrErr = import(*RedeclIt);
3747 return RedeclOrErr.takeError();
3753 ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3754 // Parameters are created in the translation unit's context, then moved
3755 // into the function declaration's context afterward.
3756 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3758 DeclarationName ToDeclName;
3759 SourceLocation ToLocation;
3761 if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType()))
3762 std::tie(ToDeclName, ToLocation, ToType) = *Imp;
3764 return Imp.takeError();
3766 // Create the imported parameter.
3767 ImplicitParamDecl *ToParm = nullptr;
3768 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3769 ToLocation, ToDeclName.getAsIdentifierInfo(),
3770 ToType, D->getParameterKind()))
3775 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3776 // Parameters are created in the translation unit's context, then moved
3777 // into the function declaration's context afterward.
3778 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3780 DeclarationName ToDeclName;
3781 SourceLocation ToLocation, ToInnerLocStart;
3783 TypeSourceInfo *ToTypeSourceInfo;
3784 if (auto Imp = importSeq(
3785 D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(),
3786 D->getTypeSourceInfo()))
3788 ToDeclName, ToLocation, ToType, ToInnerLocStart,
3789 ToTypeSourceInfo) = *Imp;
3791 return Imp.takeError();
3793 ParmVarDecl *ToParm;
3794 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3795 ToInnerLocStart, ToLocation,
3796 ToDeclName.getAsIdentifierInfo(), ToType,
3797 ToTypeSourceInfo, D->getStorageClass(),
3798 /*DefaultArg*/ nullptr))
3801 // Set the default argument.
3802 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3803 ToParm->setKNRPromoted(D->isKNRPromoted());
3805 if (D->hasUninstantiatedDefaultArg()) {
3806 if (auto ToDefArgOrErr = import(D->getUninstantiatedDefaultArg()))
3807 ToParm->setUninstantiatedDefaultArg(*ToDefArgOrErr);
3809 return ToDefArgOrErr.takeError();
3810 } else if (D->hasUnparsedDefaultArg()) {
3811 ToParm->setUnparsedDefaultArg();
3812 } else if (D->hasDefaultArg()) {
3813 if (auto ToDefArgOrErr = import(D->getDefaultArg()))
3814 ToParm->setDefaultArg(*ToDefArgOrErr);
3816 return ToDefArgOrErr.takeError();
3819 if (D->isObjCMethodParameter()) {
3820 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
3821 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
3823 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3824 D->getFunctionScopeIndex());
3830 ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3831 // Import the major distinguishing characteristics of a method.
3832 DeclContext *DC, *LexicalDC;
3833 DeclarationName Name;
3836 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3837 return std::move(Err);
3841 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3842 for (auto *FoundDecl : FoundDecls) {
3843 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3844 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3847 // Check return types.
3848 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3849 FoundMethod->getReturnType())) {
3850 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
3851 << D->isInstanceMethod() << Name << D->getReturnType()
3852 << FoundMethod->getReturnType();
3853 Importer.ToDiag(FoundMethod->getLocation(),
3854 diag::note_odr_objc_method_here)
3855 << D->isInstanceMethod() << Name;
3857 return make_error<ImportError>(ImportError::NameConflict);
3860 // Check the number of parameters.
3861 if (D->param_size() != FoundMethod->param_size()) {
3862 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
3863 << D->isInstanceMethod() << Name
3864 << D->param_size() << FoundMethod->param_size();
3865 Importer.ToDiag(FoundMethod->getLocation(),
3866 diag::note_odr_objc_method_here)
3867 << D->isInstanceMethod() << Name;
3869 return make_error<ImportError>(ImportError::NameConflict);
3872 // Check parameter types.
3873 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3874 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3875 P != PEnd; ++P, ++FoundP) {
3876 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3877 (*FoundP)->getType())) {
3878 Importer.FromDiag((*P)->getLocation(),
3879 diag::warn_odr_objc_method_param_type_inconsistent)
3880 << D->isInstanceMethod() << Name
3881 << (*P)->getType() << (*FoundP)->getType();
3882 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3883 << (*FoundP)->getType();
3885 return make_error<ImportError>(ImportError::NameConflict);
3889 // Check variadic/non-variadic.
3890 // Check the number of parameters.
3891 if (D->isVariadic() != FoundMethod->isVariadic()) {
3892 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
3893 << D->isInstanceMethod() << Name;
3894 Importer.ToDiag(FoundMethod->getLocation(),
3895 diag::note_odr_objc_method_here)
3896 << D->isInstanceMethod() << Name;
3898 return make_error<ImportError>(ImportError::NameConflict);
3901 // FIXME: Any other bits we need to merge?
3902 return Importer.MapImported(D, FoundMethod);
3906 SourceLocation ToEndLoc;
3907 QualType ToReturnType;
3908 TypeSourceInfo *ToReturnTypeSourceInfo;
3909 if (auto Imp = importSeq(
3910 D->getEndLoc(), D->getReturnType(), D->getReturnTypeSourceInfo()))
3911 std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp;
3913 return Imp.takeError();
3915 ObjCMethodDecl *ToMethod;
3916 if (GetImportedOrCreateDecl(
3917 ToMethod, D, Importer.getToContext(), Loc,
3918 ToEndLoc, Name.getObjCSelector(), ToReturnType,
3919 ToReturnTypeSourceInfo, DC, D->isInstanceMethod(), D->isVariadic(),
3920 D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3921 D->getImplementationControl(), D->hasRelatedResultType()))
3924 // FIXME: When we decide to merge method definitions, we'll need to
3925 // deal with implicit parameters.
3927 // Import the parameters
3928 SmallVector<ParmVarDecl *, 5> ToParams;
3929 for (auto *FromP : D->parameters()) {
3930 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
3931 ToParams.push_back(*ToPOrErr);
3933 return ToPOrErr.takeError();
3936 // Set the parameters.
3937 for (auto *ToParam : ToParams) {
3938 ToParam->setOwningFunction(ToMethod);
3939 ToMethod->addDeclInternal(ToParam);
3942 SmallVector<SourceLocation, 12> FromSelLocs;
3943 D->getSelectorLocs(FromSelLocs);
3944 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
3945 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
3946 return std::move(Err);
3948 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
3950 ToMethod->setLexicalDeclContext(LexicalDC);
3951 LexicalDC->addDeclInternal(ToMethod);
3955 ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3956 // Import the major distinguishing characteristics of a category.
3957 DeclContext *DC, *LexicalDC;
3958 DeclarationName Name;
3961 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3962 return std::move(Err);
3966 SourceLocation ToVarianceLoc, ToLocation, ToColonLoc;
3967 TypeSourceInfo *ToTypeSourceInfo;
3968 if (auto Imp = importSeq(
3969 D->getVarianceLoc(), D->getLocation(), D->getColonLoc(),
3970 D->getTypeSourceInfo()))
3971 std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp;
3973 return Imp.takeError();
3975 ObjCTypeParamDecl *Result;
3976 if (GetImportedOrCreateDecl(
3977 Result, D, Importer.getToContext(), DC, D->getVariance(),
3978 ToVarianceLoc, D->getIndex(),
3979 ToLocation, Name.getAsIdentifierInfo(),
3980 ToColonLoc, ToTypeSourceInfo))
3983 Result->setLexicalDeclContext(LexicalDC);
3987 ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3988 // Import the major distinguishing characteristics of a category.
3989 DeclContext *DC, *LexicalDC;
3990 DeclarationName Name;
3993 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3994 return std::move(Err);
3998 ObjCInterfaceDecl *ToInterface;
3999 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4000 return std::move(Err);
4002 // Determine if we've already encountered this category.
4003 ObjCCategoryDecl *MergeWithCategory
4004 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4005 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4007 SourceLocation ToAtStartLoc, ToCategoryNameLoc;
4008 SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4009 if (auto Imp = importSeq(
4010 D->getAtStartLoc(), D->getCategoryNameLoc(),
4011 D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4013 ToAtStartLoc, ToCategoryNameLoc,
4014 ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4016 return Imp.takeError();
4018 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4021 Name.getAsIdentifierInfo(), ToInterface,
4022 /*TypeParamList=*/nullptr,
4027 ToCategory->setLexicalDeclContext(LexicalDC);
4028 LexicalDC->addDeclInternal(ToCategory);
4029 // Import the type parameter list after MapImported, to avoid
4030 // loops when bringing in their DeclContext.
4031 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4032 ToCategory->setTypeParamList(*PListOrErr);
4034 return PListOrErr.takeError();
4037 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4038 SmallVector<SourceLocation, 4> ProtocolLocs;
4039 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4040 = D->protocol_loc_begin();
4041 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4042 FromProtoEnd = D->protocol_end();
4043 FromProto != FromProtoEnd;
4044 ++FromProto, ++FromProtoLoc) {
4045 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4046 Protocols.push_back(*ToProtoOrErr);
4048 return ToProtoOrErr.takeError();
4050 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4051 ProtocolLocs.push_back(*ToProtoLocOrErr);
4053 return ToProtoLocOrErr.takeError();
4056 // FIXME: If we're merging, make sure that the protocol list is the same.
4057 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4058 ProtocolLocs.data(), Importer.getToContext());
4061 Importer.MapImported(D, ToCategory);
4064 // Import all of the members of this category.
4065 if (Error Err = ImportDeclContext(D))
4066 return std::move(Err);
4068 // If we have an implementation, import it as well.
4069 if (D->getImplementation()) {
4070 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4071 import(D->getImplementation()))
4072 ToCategory->setImplementation(*ToImplOrErr);
4074 return ToImplOrErr.takeError();
4080 Error ASTNodeImporter::ImportDefinition(
4081 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4082 if (To->getDefinition()) {
4083 if (shouldForceImportDeclContext(Kind))
4084 if (Error Err = ImportDeclContext(From))
4086 return Error::success();
4089 // Start the protocol definition
4090 To->startDefinition();
4093 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4094 SmallVector<SourceLocation, 4> ProtocolLocs;
4095 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4096 From->protocol_loc_begin();
4097 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4098 FromProtoEnd = From->protocol_end();
4099 FromProto != FromProtoEnd;
4100 ++FromProto, ++FromProtoLoc) {
4101 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4102 Protocols.push_back(*ToProtoOrErr);
4104 return ToProtoOrErr.takeError();
4106 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4107 ProtocolLocs.push_back(*ToProtoLocOrErr);
4109 return ToProtoLocOrErr.takeError();
4113 // FIXME: If we're merging, make sure that the protocol list is the same.
4114 To->setProtocolList(Protocols.data(), Protocols.size(),
4115 ProtocolLocs.data(), Importer.getToContext());
4117 if (shouldForceImportDeclContext(Kind)) {
4118 // Import all of the members of this protocol.
4119 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4122 return Error::success();
4125 ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4126 // If this protocol has a definition in the translation unit we're coming
4127 // from, but this particular declaration is not that definition, import the
4128 // definition and map to that.
4129 ObjCProtocolDecl *Definition = D->getDefinition();
4130 if (Definition && Definition != D) {
4131 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4132 return Importer.MapImported(D, *ImportedDefOrErr);
4134 return ImportedDefOrErr.takeError();
4137 // Import the major distinguishing characteristics of a protocol.
4138 DeclContext *DC, *LexicalDC;
4139 DeclarationName Name;
4142 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4143 return std::move(Err);
4147 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4148 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4149 for (auto *FoundDecl : FoundDecls) {
4150 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4153 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4157 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4159 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4160 if (!ToAtBeginLocOrErr)
4161 return ToAtBeginLocOrErr.takeError();
4163 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4164 Name.getAsIdentifierInfo(), Loc,
4166 /*PrevDecl=*/nullptr))
4168 ToProto->setLexicalDeclContext(LexicalDC);
4169 LexicalDC->addDeclInternal(ToProto);
4172 Importer.MapImported(D, ToProto);
4174 if (D->isThisDeclarationADefinition())
4175 if (Error Err = ImportDefinition(D, ToProto))
4176 return std::move(Err);
4181 ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4182 DeclContext *DC, *LexicalDC;
4183 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4184 return std::move(Err);
4186 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4187 if (!ExternLocOrErr)
4188 return ExternLocOrErr.takeError();
4190 ExpectedSLoc LangLocOrErr = import(D->getLocation());
4192 return LangLocOrErr.takeError();
4194 bool HasBraces = D->hasBraces();
4196 LinkageSpecDecl *ToLinkageSpec;
4197 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4198 *ExternLocOrErr, *LangLocOrErr,
4199 D->getLanguage(), HasBraces))
4200 return ToLinkageSpec;
4203 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4204 if (!RBraceLocOrErr)
4205 return RBraceLocOrErr.takeError();
4206 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4209 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4210 LexicalDC->addDeclInternal(ToLinkageSpec);
4212 return ToLinkageSpec;
4215 ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
4216 DeclContext *DC, *LexicalDC;
4217 DeclarationName Name;
4219 NamedDecl *ToD = nullptr;
4220 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4221 return std::move(Err);
4225 SourceLocation ToLoc, ToUsingLoc;
4226 NestedNameSpecifierLoc ToQualifierLoc;
4227 if (auto Imp = importSeq(
4228 D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc()))
4229 std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp;
4231 return Imp.takeError();
4233 DeclarationNameInfo NameInfo(Name, ToLoc);
4234 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4235 return std::move(Err);
4238 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4239 ToUsingLoc, ToQualifierLoc, NameInfo,
4243 ToUsing->setLexicalDeclContext(LexicalDC);
4244 LexicalDC->addDeclInternal(ToUsing);
4246 if (NamedDecl *FromPattern =
4247 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4248 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4249 Importer.getToContext().setInstantiatedFromUsingDecl(
4250 ToUsing, *ToPatternOrErr);
4252 return ToPatternOrErr.takeError();
4255 for (UsingShadowDecl *FromShadow : D->shadows()) {
4256 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4257 ToUsing->addShadowDecl(*ToShadowOrErr);
4259 // FIXME: We return error here but the definition is already created
4260 // and available with lookups. How to fix this?..
4261 return ToShadowOrErr.takeError();
4266 ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
4267 DeclContext *DC, *LexicalDC;
4268 DeclarationName Name;
4270 NamedDecl *ToD = nullptr;
4271 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4272 return std::move(Err);
4276 Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
4278 return ToUsingOrErr.takeError();
4280 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4282 return ToTargetOrErr.takeError();
4284 UsingShadowDecl *ToShadow;
4285 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4286 *ToUsingOrErr, *ToTargetOrErr))
4289 ToShadow->setLexicalDeclContext(LexicalDC);
4290 ToShadow->setAccess(D->getAccess());
4292 if (UsingShadowDecl *FromPattern =
4293 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4294 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4295 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4296 ToShadow, *ToPatternOrErr);
4298 // FIXME: We return error here but the definition is already created
4299 // and available with lookups. How to fix this?..
4300 return ToPatternOrErr.takeError();
4303 LexicalDC->addDeclInternal(ToShadow);
4308 ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4309 DeclContext *DC, *LexicalDC;
4310 DeclarationName Name;
4312 NamedDecl *ToD = nullptr;
4313 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4314 return std::move(Err);
4318 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4319 if (!ToComAncestorOrErr)
4320 return ToComAncestorOrErr.takeError();
4322 NamespaceDecl *ToNominatedNamespace;
4323 SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation;
4324 NestedNameSpecifierLoc ToQualifierLoc;
4325 if (auto Imp = importSeq(
4326 D->getNominatedNamespace(), D->getUsingLoc(),
4327 D->getNamespaceKeyLocation(), D->getQualifierLoc(),
4328 D->getIdentLocation()))
4330 ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation,
4331 ToQualifierLoc, ToIdentLocation) = *Imp;
4333 return Imp.takeError();
4335 UsingDirectiveDecl *ToUsingDir;
4336 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4338 ToNamespaceKeyLocation,
4341 ToNominatedNamespace, *ToComAncestorOrErr))
4344 ToUsingDir->setLexicalDeclContext(LexicalDC);
4345 LexicalDC->addDeclInternal(ToUsingDir);
4350 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
4351 UnresolvedUsingValueDecl *D) {
4352 DeclContext *DC, *LexicalDC;
4353 DeclarationName Name;
4355 NamedDecl *ToD = nullptr;
4356 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4357 return std::move(Err);
4361 SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc;
4362 NestedNameSpecifierLoc ToQualifierLoc;
4363 if (auto Imp = importSeq(
4364 D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(),
4365 D->getEllipsisLoc()))
4366 std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4368 return Imp.takeError();
4370 DeclarationNameInfo NameInfo(Name, ToLoc);
4371 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4372 return std::move(Err);
4374 UnresolvedUsingValueDecl *ToUsingValue;
4375 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4376 ToUsingLoc, ToQualifierLoc, NameInfo,
4378 return ToUsingValue;
4380 ToUsingValue->setAccess(D->getAccess());
4381 ToUsingValue->setLexicalDeclContext(LexicalDC);
4382 LexicalDC->addDeclInternal(ToUsingValue);
4384 return ToUsingValue;
4387 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
4388 UnresolvedUsingTypenameDecl *D) {
4389 DeclContext *DC, *LexicalDC;
4390 DeclarationName Name;
4392 NamedDecl *ToD = nullptr;
4393 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4394 return std::move(Err);
4398 SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc;
4399 NestedNameSpecifierLoc ToQualifierLoc;
4400 if (auto Imp = importSeq(
4401 D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(),
4402 D->getEllipsisLoc()))
4403 std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4405 return Imp.takeError();
4407 UnresolvedUsingTypenameDecl *ToUsing;
4408 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4409 ToUsingLoc, ToTypenameLoc,
4410 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4413 ToUsing->setAccess(D->getAccess());
4414 ToUsing->setLexicalDeclContext(LexicalDC);
4415 LexicalDC->addDeclInternal(ToUsing);
4421 Error ASTNodeImporter::ImportDefinition(
4422 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
4423 if (To->getDefinition()) {
4424 // Check consistency of superclass.
4425 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4427 if (auto FromSuperOrErr = import(FromSuper))
4428 FromSuper = *FromSuperOrErr;
4430 return FromSuperOrErr.takeError();
4433 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4434 if ((bool)FromSuper != (bool)ToSuper ||
4435 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4436 Importer.ToDiag(To->getLocation(),
4437 diag::warn_odr_objc_superclass_inconsistent)
4438 << To->getDeclName();
4440 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4441 << To->getSuperClass()->getDeclName();
4443 Importer.ToDiag(To->getLocation(),
4444 diag::note_odr_objc_missing_superclass);
4445 if (From->getSuperClass())
4446 Importer.FromDiag(From->getSuperClassLoc(),
4447 diag::note_odr_objc_superclass)
4448 << From->getSuperClass()->getDeclName();
4450 Importer.FromDiag(From->getLocation(),
4451 diag::note_odr_objc_missing_superclass);
4454 if (shouldForceImportDeclContext(Kind))
4455 if (Error Err = ImportDeclContext(From))
4457 return Error::success();
4460 // Start the definition.
4461 To->startDefinition();
4463 // If this class has a superclass, import it.
4464 if (From->getSuperClass()) {
4465 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4466 To->setSuperClass(*SuperTInfoOrErr);
4468 return SuperTInfoOrErr.takeError();
4472 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4473 SmallVector<SourceLocation, 4> ProtocolLocs;
4474 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
4475 From->protocol_loc_begin();
4477 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4478 FromProtoEnd = From->protocol_end();
4479 FromProto != FromProtoEnd;
4480 ++FromProto, ++FromProtoLoc) {
4481 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4482 Protocols.push_back(*ToProtoOrErr);
4484 return ToProtoOrErr.takeError();
4486 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4487 ProtocolLocs.push_back(*ToProtoLocOrErr);
4489 return ToProtoLocOrErr.takeError();
4493 // FIXME: If we're merging, make sure that the protocol list is the same.
4494 To->setProtocolList(Protocols.data(), Protocols.size(),
4495 ProtocolLocs.data(), Importer.getToContext());
4497 // Import categories. When the categories themselves are imported, they'll
4498 // hook themselves into this interface.
4499 for (auto *Cat : From->known_categories()) {
4500 auto ToCatOrErr = import(Cat);
4502 return ToCatOrErr.takeError();
4505 // If we have an @implementation, import it as well.
4506 if (From->getImplementation()) {
4507 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4508 import(From->getImplementation()))
4509 To->setImplementation(*ToImplOrErr);
4511 return ToImplOrErr.takeError();
4514 if (shouldForceImportDeclContext(Kind)) {
4515 // Import all of the members of this class.
4516 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4519 return Error::success();
4522 Expected<ObjCTypeParamList *>
4523 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4527 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4528 for (auto *fromTypeParam : *list) {
4529 if (auto toTypeParamOrErr = import(fromTypeParam))
4530 toTypeParams.push_back(*toTypeParamOrErr);
4532 return toTypeParamOrErr.takeError();
4535 auto LAngleLocOrErr = import(list->getLAngleLoc());
4536 if (!LAngleLocOrErr)
4537 return LAngleLocOrErr.takeError();
4539 auto RAngleLocOrErr = import(list->getRAngleLoc());
4540 if (!RAngleLocOrErr)
4541 return RAngleLocOrErr.takeError();
4543 return ObjCTypeParamList::create(Importer.getToContext(),
4549 ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
4550 // If this class has a definition in the translation unit we're coming from,
4551 // but this particular declaration is not that definition, import the
4552 // definition and map to that.
4553 ObjCInterfaceDecl *Definition = D->getDefinition();
4554 if (Definition && Definition != D) {
4555 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4556 return Importer.MapImported(D, *ImportedDefOrErr);
4558 return ImportedDefOrErr.takeError();
4561 // Import the major distinguishing characteristics of an @interface.
4562 DeclContext *DC, *LexicalDC;
4563 DeclarationName Name;
4566 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4567 return std::move(Err);
4571 // Look for an existing interface with the same name.
4572 ObjCInterfaceDecl *MergeWithIface = nullptr;
4573 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4574 for (auto *FoundDecl : FoundDecls) {
4575 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4578 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4582 // Create an interface declaration, if one does not already exist.
4583 ObjCInterfaceDecl *ToIface = MergeWithIface;
4585 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4586 if (!AtBeginLocOrErr)
4587 return AtBeginLocOrErr.takeError();
4589 if (GetImportedOrCreateDecl(
4590 ToIface, D, Importer.getToContext(), DC,
4591 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4592 /*TypeParamList=*/nullptr,
4593 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4595 ToIface->setLexicalDeclContext(LexicalDC);
4596 LexicalDC->addDeclInternal(ToIface);
4598 Importer.MapImported(D, ToIface);
4599 // Import the type parameter list after MapImported, to avoid
4600 // loops when bringing in their DeclContext.
4601 if (auto ToPListOrErr =
4602 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
4603 ToIface->setTypeParamList(*ToPListOrErr);
4605 return ToPListOrErr.takeError();
4607 if (D->isThisDeclarationADefinition())
4608 if (Error Err = ImportDefinition(D, ToIface))
4609 return std::move(Err);
4615 ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4616 ObjCCategoryDecl *Category;
4617 if (Error Err = importInto(Category, D->getCategoryDecl()))
4618 return std::move(Err);
4620 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4622 DeclContext *DC, *LexicalDC;
4623 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4624 return std::move(Err);
4626 SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc;
4627 if (auto Imp = importSeq(
4628 D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc()))
4629 std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp;
4631 return Imp.takeError();
4633 if (GetImportedOrCreateDecl(
4634 ToImpl, D, Importer.getToContext(), DC,
4635 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4636 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
4639 ToImpl->setLexicalDeclContext(LexicalDC);
4640 LexicalDC->addDeclInternal(ToImpl);
4641 Category->setImplementation(ToImpl);
4644 Importer.MapImported(D, ToImpl);
4645 if (Error Err = ImportDeclContext(D))
4646 return std::move(Err);
4652 ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4653 // Find the corresponding interface.
4654 ObjCInterfaceDecl *Iface;
4655 if (Error Err = importInto(Iface, D->getClassInterface()))
4656 return std::move(Err);
4658 // Import the superclass, if any.
4659 ObjCInterfaceDecl *Super;
4660 if (Error Err = importInto(Super, D->getSuperClass()))
4661 return std::move(Err);
4663 ObjCImplementationDecl *Impl = Iface->getImplementation();
4665 // We haven't imported an implementation yet. Create a new @implementation
4667 DeclContext *DC, *LexicalDC;
4668 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4669 return std::move(Err);
4671 SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc;
4672 SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4673 if (auto Imp = importSeq(
4674 D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(),
4675 D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4677 ToLocation, ToAtStartLoc, ToSuperClassLoc,
4678 ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4680 return Imp.takeError();
4682 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4691 Impl->setLexicalDeclContext(LexicalDC);
4693 // Associate the implementation with the class it implements.
4694 Iface->setImplementation(Impl);
4695 Importer.MapImported(D, Iface->getImplementation());
4697 Importer.MapImported(D, Iface->getImplementation());
4699 // Verify that the existing @implementation has the same superclass.
4700 if ((Super && !Impl->getSuperClass()) ||
4701 (!Super && Impl->getSuperClass()) ||
4702 (Super && Impl->getSuperClass() &&
4703 !declaresSameEntity(Super->getCanonicalDecl(),
4704 Impl->getSuperClass()))) {
4705 Importer.ToDiag(Impl->getLocation(),
4706 diag::warn_odr_objc_superclass_inconsistent)
4707 << Iface->getDeclName();
4708 // FIXME: It would be nice to have the location of the superclass
4710 if (Impl->getSuperClass())
4711 Importer.ToDiag(Impl->getLocation(),
4712 diag::note_odr_objc_superclass)
4713 << Impl->getSuperClass()->getDeclName();
4715 Importer.ToDiag(Impl->getLocation(),
4716 diag::note_odr_objc_missing_superclass);
4717 if (D->getSuperClass())
4718 Importer.FromDiag(D->getLocation(),
4719 diag::note_odr_objc_superclass)
4720 << D->getSuperClass()->getDeclName();
4722 Importer.FromDiag(D->getLocation(),
4723 diag::note_odr_objc_missing_superclass);
4725 return make_error<ImportError>(ImportError::NameConflict);
4729 // Import all of the members of this @implementation.
4730 if (Error Err = ImportDeclContext(D))
4731 return std::move(Err);
4736 ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
4737 // Import the major distinguishing characteristics of an @property.
4738 DeclContext *DC, *LexicalDC;
4739 DeclarationName Name;
4742 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4743 return std::move(Err);
4747 // Check whether we have already imported this property.
4748 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4749 for (auto *FoundDecl : FoundDecls) {
4750 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4751 // Check property types.
4752 if (!Importer.IsStructurallyEquivalent(D->getType(),
4753 FoundProp->getType())) {
4754 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
4755 << Name << D->getType() << FoundProp->getType();
4756 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4757 << FoundProp->getType();
4759 return make_error<ImportError>(ImportError::NameConflict);
4762 // FIXME: Check property attributes, getters, setters, etc.?
4764 // Consider these properties to be equivalent.
4765 Importer.MapImported(D, FoundProp);
4771 TypeSourceInfo *ToTypeSourceInfo;
4772 SourceLocation ToAtLoc, ToLParenLoc;
4773 if (auto Imp = importSeq(
4774 D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc()))
4775 std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp;
4777 return Imp.takeError();
4779 // Create the new property.
4780 ObjCPropertyDecl *ToProperty;
4781 if (GetImportedOrCreateDecl(
4782 ToProperty, D, Importer.getToContext(), DC, Loc,
4783 Name.getAsIdentifierInfo(), ToAtLoc,
4784 ToLParenLoc, ToType,
4785 ToTypeSourceInfo, D->getPropertyImplementation()))
4788 Selector ToGetterName, ToSetterName;
4789 SourceLocation ToGetterNameLoc, ToSetterNameLoc;
4790 ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl;
4791 ObjCIvarDecl *ToPropertyIvarDecl;
4792 if (auto Imp = importSeq(
4793 D->getGetterName(), D->getSetterName(),
4794 D->getGetterNameLoc(), D->getSetterNameLoc(),
4795 D->getGetterMethodDecl(), D->getSetterMethodDecl(),
4796 D->getPropertyIvarDecl()))
4798 ToGetterName, ToSetterName,
4799 ToGetterNameLoc, ToSetterNameLoc,
4800 ToGetterMethodDecl, ToSetterMethodDecl,
4801 ToPropertyIvarDecl) = *Imp;
4803 return Imp.takeError();
4805 ToProperty->setLexicalDeclContext(LexicalDC);
4806 LexicalDC->addDeclInternal(ToProperty);
4808 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4809 ToProperty->setPropertyAttributesAsWritten(
4810 D->getPropertyAttributesAsWritten());
4811 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
4812 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
4813 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
4814 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
4815 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
4820 ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4821 ObjCPropertyDecl *Property;
4822 if (Error Err = importInto(Property, D->getPropertyDecl()))
4823 return std::move(Err);
4825 DeclContext *DC, *LexicalDC;
4826 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4827 return std::move(Err);
4829 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
4831 // Import the ivar (for an @synthesize).
4832 ObjCIvarDecl *Ivar = nullptr;
4833 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
4834 return std::move(Err);
4836 ObjCPropertyImplDecl *ToImpl
4837 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4838 Property->getQueryKind());
4840 SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc;
4841 if (auto Imp = importSeq(
4842 D->getBeginLoc(), D->getLocation(), D->getPropertyIvarDeclLoc()))
4843 std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp;
4845 return Imp.takeError();
4847 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4849 ToLocation, Property,
4850 D->getPropertyImplementation(), Ivar,
4851 ToPropertyIvarDeclLoc))
4854 ToImpl->setLexicalDeclContext(LexicalDC);
4855 LexicalDC->addDeclInternal(ToImpl);
4857 // Check that we have the same kind of property implementation (@synthesize
4859 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4860 Importer.ToDiag(ToImpl->getLocation(),
4861 diag::warn_odr_objc_property_impl_kind_inconsistent)
4862 << Property->getDeclName()
4863 << (ToImpl->getPropertyImplementation()
4864 == ObjCPropertyImplDecl::Dynamic);
4865 Importer.FromDiag(D->getLocation(),
4866 diag::note_odr_objc_property_impl_kind)
4867 << D->getPropertyDecl()->getDeclName()
4868 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4870 return make_error<ImportError>(ImportError::NameConflict);
4873 // For @synthesize, check that we have the same
4874 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4875 Ivar != ToImpl->getPropertyIvarDecl()) {
4876 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4877 diag::warn_odr_objc_synthesize_ivar_inconsistent)
4878 << Property->getDeclName()
4879 << ToImpl->getPropertyIvarDecl()->getDeclName()
4880 << Ivar->getDeclName();
4881 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4882 diag::note_odr_objc_synthesize_ivar_here)
4883 << D->getPropertyIvarDecl()->getDeclName();
4885 return make_error<ImportError>(ImportError::NameConflict);
4888 // Merge the existing implementation with the new implementation.
4889 Importer.MapImported(D, ToImpl);
4896 ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4897 // For template arguments, we adopt the translation unit as our declaration
4898 // context. This context will be fixed when the actual template declaration
4901 // FIXME: Import default argument.
4903 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
4905 return BeginLocOrErr.takeError();
4907 ExpectedSLoc LocationOrErr = import(D->getLocation());
4909 return LocationOrErr.takeError();
4911 TemplateTypeParmDecl *ToD = nullptr;
4912 (void)GetImportedOrCreateDecl(
4913 ToD, D, Importer.getToContext(),
4914 Importer.getToContext().getTranslationUnitDecl(),
4915 *BeginLocOrErr, *LocationOrErr,
4916 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
4917 D->wasDeclaredWithTypename(), D->isParameterPack());
4922 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4923 DeclarationName ToDeclName;
4924 SourceLocation ToLocation, ToInnerLocStart;
4926 TypeSourceInfo *ToTypeSourceInfo;
4927 if (auto Imp = importSeq(
4928 D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(),
4929 D->getInnerLocStart()))
4931 ToDeclName, ToLocation, ToType, ToTypeSourceInfo,
4932 ToInnerLocStart) = *Imp;
4934 return Imp.takeError();
4936 // FIXME: Import default argument.
4938 NonTypeTemplateParmDecl *ToD = nullptr;
4939 (void)GetImportedOrCreateDecl(
4940 ToD, D, Importer.getToContext(),
4941 Importer.getToContext().getTranslationUnitDecl(),
4942 ToInnerLocStart, ToLocation, D->getDepth(),
4943 D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType,
4944 D->isParameterPack(), ToTypeSourceInfo);
4949 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4950 // Import the name of this declaration.
4951 auto NameOrErr = import(D->getDeclName());
4953 return NameOrErr.takeError();
4955 // Import the location of this declaration.
4956 ExpectedSLoc LocationOrErr = import(D->getLocation());
4958 return LocationOrErr.takeError();
4960 // Import template parameters.
4961 auto TemplateParamsOrErr = import(D->getTemplateParameters());
4962 if (!TemplateParamsOrErr)
4963 return TemplateParamsOrErr.takeError();
4965 // FIXME: Import default argument.
4967 TemplateTemplateParmDecl *ToD = nullptr;
4968 (void)GetImportedOrCreateDecl(
4969 ToD, D, Importer.getToContext(),
4970 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
4971 D->getDepth(), D->getPosition(), D->isParameterPack(),
4972 (*NameOrErr).getAsIdentifierInfo(),
4973 *TemplateParamsOrErr);
4977 // Returns the definition for a (forward) declaration of a TemplateDecl, if
4978 // it has any definition in the redecl chain.
4979 template <typename T> static auto getTemplateDefinition(T *D) -> T * {
4980 assert(D->getTemplatedDecl() && "Should be called on templates only");
4981 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
4982 if (!ToTemplatedDef)
4984 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
4985 return cast_or_null<T>(TemplateWithDef);
4988 ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4989 bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None;
4991 // Import the major distinguishing characteristics of this class template.
4992 DeclContext *DC, *LexicalDC;
4993 DeclarationName Name;
4996 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4997 return std::move(Err);
5001 ClassTemplateDecl *FoundByLookup = nullptr;
5003 // We may already have a template of the same name; try to find and match it.
5004 if (!DC->isFunctionOrMethod()) {
5005 SmallVector<NamedDecl *, 4> ConflictingDecls;
5006 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5007 for (auto *FoundDecl : FoundDecls) {
5008 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
5009 Decl::IDNS_TagFriend))
5012 Decl *Found = FoundDecl;
5013 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5014 if (FoundTemplate) {
5016 if (IsStructuralMatch(D, FoundTemplate)) {
5017 ClassTemplateDecl *TemplateWithDef =
5018 getTemplateDefinition(FoundTemplate);
5019 if (D->isThisDeclarationADefinition() && TemplateWithDef) {
5020 return Importer.MapImported(D, TemplateWithDef);
5022 FoundByLookup = FoundTemplate;
5027 ConflictingDecls.push_back(FoundDecl);
5030 if (!ConflictingDecls.empty()) {
5031 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
5032 ConflictingDecls.data(),
5033 ConflictingDecls.size());
5037 return make_error<ImportError>(ImportError::NameConflict);
5040 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5042 // Create the declaration that is being templated.
5043 CXXRecordDecl *ToTemplated;
5044 if (Error Err = importInto(ToTemplated, FromTemplated))
5045 return std::move(Err);
5047 // Create the class template declaration itself.
5048 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5049 if (!TemplateParamsOrErr)
5050 return TemplateParamsOrErr.takeError();
5052 ClassTemplateDecl *D2;
5053 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5054 *TemplateParamsOrErr, ToTemplated))
5057 ToTemplated->setDescribedClassTemplate(D2);
5059 D2->setAccess(D->getAccess());
5060 D2->setLexicalDeclContext(LexicalDC);
5062 if (D->getDeclContext()->containsDeclAndLoad(D))
5063 DC->addDeclInternal(D2);
5064 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
5065 LexicalDC->addDeclInternal(D2);
5067 if (FoundByLookup) {
5069 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5071 // It is possible that during the import of the class template definition
5072 // we start the import of a fwd friend decl of the very same class template
5073 // and we add the fwd friend decl to the lookup table. But the ToTemplated
5074 // had been created earlier and by that time the lookup could not find
5075 // anything existing, so it has no previous decl. Later, (still during the
5076 // import of the fwd friend decl) we start to import the definition again
5077 // and this time the lookup finds the previous fwd friend class template.
5078 // In this case we must set up the previous decl for the templated decl.
5079 if (!ToTemplated->getPreviousDecl()) {
5080 assert(FoundByLookup->getTemplatedDecl() &&
5081 "Found decl must have its templated decl set");
5082 CXXRecordDecl *PrevTemplated =
5083 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5084 if (ToTemplated != PrevTemplated)
5085 ToTemplated->setPreviousDecl(PrevTemplated);
5088 D2->setPreviousDecl(Recent);
5091 if (LexicalDC != DC && IsFriend)
5092 DC->makeDeclVisibleInContext(D2);
5094 if (FromTemplated->isCompleteDefinition() &&
5095 !ToTemplated->isCompleteDefinition()) {
5096 // FIXME: Import definition!
5102 ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
5103 ClassTemplateSpecializationDecl *D) {
5104 ClassTemplateDecl *ClassTemplate;
5105 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5106 return std::move(Err);
5108 // Import the context of this declaration.
5109 DeclContext *DC, *LexicalDC;
5110 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5111 return std::move(Err);
5113 // Import template arguments.
5114 SmallVector<TemplateArgument, 2> TemplateArgs;
5115 if (Error Err = ImportTemplateArguments(
5116 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5117 return std::move(Err);
5119 // Try to find an existing specialization with these template arguments.
5120 void *InsertPos = nullptr;
5121 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5122 ClassTemplatePartialSpecializationDecl *PartialSpec =
5123 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
5126 ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
5128 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5131 if (IsStructuralMatch(D, PrevDecl)) {
5132 if (D->isThisDeclarationADefinition() && PrevDecl->getDefinition()) {
5133 Importer.MapImported(D, PrevDecl->getDefinition());
5134 // Import those default field initializers which have been
5135 // instantiated in the "From" context, but not in the "To" context.
5136 for (auto *FromField : D->fields()) {
5137 auto ToOrErr = import(FromField);
5139 return ToOrErr.takeError();
5142 // Import those methods which have been instantiated in the
5143 // "From" context, but not in the "To" context.
5144 for (CXXMethodDecl *FromM : D->methods()) {
5145 auto ToOrErr = import(FromM);
5147 return ToOrErr.takeError();
5150 // TODO Import instantiated default arguments.
5151 // TODO Import instantiated exception specifications.
5153 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5154 // what else could be fused during an AST merge.
5157 } else { // ODR violation.
5158 // FIXME HandleNameConflict
5159 return make_error<ImportError>(ImportError::NameConflict);
5163 // Import the location of this declaration.
5164 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5166 return BeginLocOrErr.takeError();
5167 ExpectedSLoc IdLocOrErr = import(D->getLocation());
5169 return IdLocOrErr.takeError();
5171 // Create the specialization.
5172 ClassTemplateSpecializationDecl *D2 = nullptr;
5174 // Import TemplateArgumentListInfo.
5175 TemplateArgumentListInfo ToTAInfo;
5176 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5177 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5178 return std::move(Err);
5180 QualType CanonInjType;
5181 if (Error Err = importInto(
5182 CanonInjType, PartialSpec->getInjectedSpecializationType()))
5183 return std::move(Err);
5184 CanonInjType = CanonInjType.getCanonicalType();
5186 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5188 return ToTPListOrErr.takeError();
5190 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5191 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5192 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, ClassTemplate,
5193 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5194 ToTAInfo, CanonInjType,
5195 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5198 // Update InsertPos, because preceding import calls may have invalidated
5199 // it by adding new specializations.
5200 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos))
5201 // Add this partial specialization to the class template.
5202 ClassTemplate->AddPartialSpecialization(
5203 cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos);
5205 } else { // Not a partial specialization.
5206 if (GetImportedOrCreateDecl(
5207 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5208 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5212 // Update InsertPos, because preceding import calls may have invalidated
5213 // it by adding new specializations.
5214 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5215 // Add this specialization to the class template.
5216 ClassTemplate->AddSpecialization(D2, InsertPos);
5219 D2->setSpecializationKind(D->getSpecializationKind());
5221 // Set the context of this specialization/instantiation.
5222 D2->setLexicalDeclContext(LexicalDC);
5224 // Add to the DC only if it was an explicit specialization/instantiation.
5225 if (D2->isExplicitInstantiationOrSpecialization()) {
5226 LexicalDC->addDeclInternal(D2);
5229 // Import the qualifier, if any.
5230 if (auto LocOrErr = import(D->getQualifierLoc()))
5231 D2->setQualifierInfo(*LocOrErr);
5233 return LocOrErr.takeError();
5235 if (auto *TSI = D->getTypeAsWritten()) {
5236 if (auto TInfoOrErr = import(TSI))
5237 D2->setTypeAsWritten(*TInfoOrErr);
5239 return TInfoOrErr.takeError();
5241 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5242 D2->setTemplateKeywordLoc(*LocOrErr);
5244 return LocOrErr.takeError();
5246 if (auto LocOrErr = import(D->getExternLoc()))
5247 D2->setExternLoc(*LocOrErr);
5249 return LocOrErr.takeError();
5252 if (D->getPointOfInstantiation().isValid()) {
5253 if (auto POIOrErr = import(D->getPointOfInstantiation()))
5254 D2->setPointOfInstantiation(*POIOrErr);
5256 return POIOrErr.takeError();
5259 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
5261 if (D->isCompleteDefinition())
5262 if (Error Err = ImportDefinition(D, D2))
5263 return std::move(Err);
5268 ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
5269 // If this variable has a definition in the translation unit we're coming
5271 // but this particular declaration is not that definition, import the
5272 // definition and map to that.
5274 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
5275 if (Definition && Definition != D->getTemplatedDecl()) {
5276 if (ExpectedDecl ImportedDefOrErr = import(
5277 Definition->getDescribedVarTemplate()))
5278 return Importer.MapImported(D, *ImportedDefOrErr);
5280 return ImportedDefOrErr.takeError();
5283 // Import the major distinguishing characteristics of this variable template.
5284 DeclContext *DC, *LexicalDC;
5285 DeclarationName Name;
5288 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5289 return std::move(Err);
5293 // We may already have a template of the same name; try to find and match it.
5294 assert(!DC->isFunctionOrMethod() &&
5295 "Variable templates cannot be declared at function scope");
5296 SmallVector<NamedDecl *, 4> ConflictingDecls;
5297 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5298 for (auto *FoundDecl : FoundDecls) {
5299 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5302 Decl *Found = FoundDecl;
5303 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
5304 if (IsStructuralMatch(D, FoundTemplate)) {
5305 // The variable templates structurally match; call it the same template.
5306 Importer.MapImported(D->getTemplatedDecl(),
5307 FoundTemplate->getTemplatedDecl());
5308 return Importer.MapImported(D, FoundTemplate);
5312 ConflictingDecls.push_back(FoundDecl);
5315 if (!ConflictingDecls.empty()) {
5316 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
5317 ConflictingDecls.data(),
5318 ConflictingDecls.size());
5322 // FIXME: Is it possible to get other error than name conflict?
5323 // (Put this `if` into the previous `if`?)
5324 return make_error<ImportError>(ImportError::NameConflict);
5326 VarDecl *DTemplated = D->getTemplatedDecl();
5329 // FIXME: Value not used?
5330 ExpectedType TypeOrErr = import(DTemplated->getType());
5332 return TypeOrErr.takeError();
5334 // Create the declaration that is being templated.
5335 VarDecl *ToTemplated;
5336 if (Error Err = importInto(ToTemplated, DTemplated))
5337 return std::move(Err);
5339 // Create the variable template declaration itself.
5340 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5341 if (!TemplateParamsOrErr)
5342 return TemplateParamsOrErr.takeError();
5344 VarTemplateDecl *ToVarTD;
5345 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5346 Name, *TemplateParamsOrErr, ToTemplated))
5349 ToTemplated->setDescribedVarTemplate(ToVarTD);
5351 ToVarTD->setAccess(D->getAccess());
5352 ToVarTD->setLexicalDeclContext(LexicalDC);
5353 LexicalDC->addDeclInternal(ToVarTD);
5355 if (DTemplated->isThisDeclarationADefinition() &&
5356 !ToTemplated->isThisDeclarationADefinition()) {
5357 // FIXME: Import definition!
5363 ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
5364 VarTemplateSpecializationDecl *D) {
5365 // If this record has a definition in the translation unit we're coming from,
5366 // but this particular declaration is not that definition, import the
5367 // definition and map to that.
5368 VarDecl *Definition = D->getDefinition();
5369 if (Definition && Definition != D) {
5370 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5371 return Importer.MapImported(D, *ImportedDefOrErr);
5373 return ImportedDefOrErr.takeError();
5376 VarTemplateDecl *VarTemplate = nullptr;
5377 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5378 return std::move(Err);
5380 // Import the context of this declaration.
5381 DeclContext *DC, *LexicalDC;
5382 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5383 return std::move(Err);
5385 // Import the location of this declaration.
5386 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5388 return BeginLocOrErr.takeError();
5390 auto IdLocOrErr = import(D->getLocation());
5392 return IdLocOrErr.takeError();
5394 // Import template arguments.
5395 SmallVector<TemplateArgument, 2> TemplateArgs;
5396 if (Error Err = ImportTemplateArguments(
5397 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5398 return std::move(Err);
5400 // Try to find an existing specialization with these template arguments.
5401 void *InsertPos = nullptr;
5402 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
5403 TemplateArgs, InsertPos);
5405 // We already have a variable template specialization with these template
5408 // FIXME: Check for specialization vs. instantiation errors.
5410 if (VarDecl *FoundDef = D2->getDefinition()) {
5411 if (!D->isThisDeclarationADefinition() ||
5412 IsStructuralMatch(D, FoundDef)) {
5413 // The record types structurally match, or the "from" translation
5414 // unit only had a forward declaration anyway; call it the same
5416 return Importer.MapImported(D, FoundDef);
5422 if (Error Err = importInto(T, D->getType()))
5423 return std::move(Err);
5425 auto TInfoOrErr = import(D->getTypeSourceInfo());
5427 return TInfoOrErr.takeError();
5429 TemplateArgumentListInfo ToTAInfo;
5430 if (Error Err = ImportTemplateArgumentListInfo(
5431 D->getTemplateArgsInfo(), ToTAInfo))
5432 return std::move(Err);
5434 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5435 // Create a new specialization.
5436 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5437 // Import TemplateArgumentListInfo
5438 TemplateArgumentListInfo ArgInfos;
5439 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5440 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5441 if (Error Err = ImportTemplateArgumentListInfo(
5442 *FromTAArgsAsWritten, ArgInfos))
5443 return std::move(Err);
5445 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5447 return ToTPListOrErr.takeError();
5449 PartVarSpecDecl *ToPartial;
5450 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5451 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5452 VarTemplate, T, *TInfoOrErr,
5453 D->getStorageClass(), TemplateArgs, ArgInfos))
5456 if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5457 FromPartial->getInstantiatedFromMember()))
5458 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5460 return ToInstOrErr.takeError();
5462 if (FromPartial->isMemberSpecialization())
5463 ToPartial->setMemberSpecialization();
5467 } else { // Full specialization
5468 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5469 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5471 D->getStorageClass(), TemplateArgs))
5475 if (D->getPointOfInstantiation().isValid()) {
5476 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5477 D2->setPointOfInstantiation(*POIOrErr);
5479 return POIOrErr.takeError();
5482 D2->setSpecializationKind(D->getSpecializationKind());
5483 D2->setTemplateArgsInfo(ToTAInfo);
5485 // Add this specialization to the class template.
5486 VarTemplate->AddSpecialization(D2, InsertPos);
5488 // Import the qualifier, if any.
5489 if (auto LocOrErr = import(D->getQualifierLoc()))
5490 D2->setQualifierInfo(*LocOrErr);
5492 return LocOrErr.takeError();
5494 if (D->isConstexpr())
5495 D2->setConstexpr(true);
5497 // Add the specialization to this context.
5498 D2->setLexicalDeclContext(LexicalDC);
5499 LexicalDC->addDeclInternal(D2);
5501 D2->setAccess(D->getAccess());
5504 if (Error Err = ImportInitializer(D, D2))
5505 return std::move(Err);
5511 ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
5512 DeclContext *DC, *LexicalDC;
5513 DeclarationName Name;
5517 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5518 return std::move(Err);
5523 const FunctionTemplateDecl *FoundByLookup = nullptr;
5525 // Try to find a function in our own ("to") context with the same name, same
5526 // type, and in the same context as the function we're importing.
5527 // FIXME Split this into a separate function.
5528 if (!LexicalDC->isFunctionOrMethod()) {
5529 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
5530 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5531 for (auto *FoundDecl : FoundDecls) {
5532 if (!FoundDecl->isInIdentifierNamespace(IDNS))
5535 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
5536 if (FoundTemplate->hasExternalFormalLinkage() &&
5537 D->hasExternalFormalLinkage()) {
5538 if (IsStructuralMatch(D, FoundTemplate)) {
5539 FunctionTemplateDecl *TemplateWithDef =
5540 getTemplateDefinition(FoundTemplate);
5541 if (D->isThisDeclarationADefinition() && TemplateWithDef) {
5542 return Importer.MapImported(D, TemplateWithDef);
5544 FoundByLookup = FoundTemplate;
5547 // TODO: handle conflicting names
5553 auto ParamsOrErr = import(D->getTemplateParameters());
5555 return ParamsOrErr.takeError();
5557 FunctionDecl *TemplatedFD;
5558 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
5559 return std::move(Err);
5561 FunctionTemplateDecl *ToFunc;
5562 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
5563 *ParamsOrErr, TemplatedFD))
5566 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
5568 ToFunc->setAccess(D->getAccess());
5569 ToFunc->setLexicalDeclContext(LexicalDC);
5570 LexicalDC->addDeclInternal(ToFunc);
5572 if (FoundByLookup) {
5574 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5575 if (!TemplatedFD->getPreviousDecl()) {
5576 assert(FoundByLookup->getTemplatedDecl() &&
5577 "Found decl must have its templated decl set");
5578 auto *PrevTemplated =
5579 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5580 if (TemplatedFD != PrevTemplated)
5581 TemplatedFD->setPreviousDecl(PrevTemplated);
5583 ToFunc->setPreviousDecl(Recent);
5589 //----------------------------------------------------------------------------
5590 // Import Statements
5591 //----------------------------------------------------------------------------
5593 ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
5594 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5595 << S->getStmtClassName();
5596 return make_error<ImportError>(ImportError::UnsupportedConstruct);
5600 ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
5601 if (Importer.returnWithErrorInTest())
5602 return make_error<ImportError>(ImportError::UnsupportedConstruct);
5603 SmallVector<IdentifierInfo *, 4> Names;
5604 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5605 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5606 // ToII is nullptr when no symbolic name is given for output operand
5607 // see ParseStmtAsm::ParseAsmOperandsOpt
5608 Names.push_back(ToII);
5611 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5612 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5613 // ToII is nullptr when no symbolic name is given for input operand
5614 // see ParseStmtAsm::ParseAsmOperandsOpt
5615 Names.push_back(ToII);
5618 SmallVector<StringLiteral *, 4> Clobbers;
5619 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5620 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
5621 Clobbers.push_back(*ClobberOrErr);
5623 return ClobberOrErr.takeError();
5627 SmallVector<StringLiteral *, 4> Constraints;
5628 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5629 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
5630 Constraints.push_back(*OutputOrErr);
5632 return OutputOrErr.takeError();
5635 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5636 if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
5637 Constraints.push_back(*InputOrErr);
5639 return InputOrErr.takeError();
5642 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
5644 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
5645 return std::move(Err);
5648 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
5649 return std::move(Err);
5651 if (Error Err = ImportArrayChecked(
5652 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
5653 return std::move(Err);
5655 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
5657 return AsmLocOrErr.takeError();
5658 auto AsmStrOrErr = import(S->getAsmString());
5660 return AsmStrOrErr.takeError();
5661 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
5662 if (!RParenLocOrErr)
5663 return RParenLocOrErr.takeError();
5665 return new (Importer.getToContext()) GCCAsmStmt(
5666 Importer.getToContext(),
5676 S->getNumClobbers(),
5682 ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
5683 auto Imp = importSeq(S->getDeclGroup(), S->getBeginLoc(), S->getEndLoc());
5685 return Imp.takeError();
5688 SourceLocation ToBeginLoc, ToEndLoc;
5689 std::tie(ToDG, ToBeginLoc, ToEndLoc) = *Imp;
5691 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
5694 ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
5695 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
5696 if (!ToSemiLocOrErr)
5697 return ToSemiLocOrErr.takeError();
5698 return new (Importer.getToContext()) NullStmt(
5699 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
5702 ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
5703 SmallVector<Stmt *, 8> ToStmts(S->size());
5705 if (Error Err = ImportContainerChecked(S->body(), ToStmts))
5706 return std::move(Err);
5708 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
5709 if (!ToLBracLocOrErr)
5710 return ToLBracLocOrErr.takeError();
5712 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
5713 if (!ToRBracLocOrErr)
5714 return ToRBracLocOrErr.takeError();
5716 return CompoundStmt::Create(
5717 Importer.getToContext(), ToStmts,
5718 *ToLBracLocOrErr, *ToRBracLocOrErr);
5721 ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
5722 auto Imp = importSeq(
5723 S->getLHS(), S->getRHS(), S->getSubStmt(), S->getCaseLoc(),
5724 S->getEllipsisLoc(), S->getColonLoc());
5726 return Imp.takeError();
5728 Expr *ToLHS, *ToRHS;
5730 SourceLocation ToCaseLoc, ToEllipsisLoc, ToColonLoc;
5731 std::tie(ToLHS, ToRHS, ToSubStmt, ToCaseLoc, ToEllipsisLoc, ToColonLoc) =
5734 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
5735 ToCaseLoc, ToEllipsisLoc, ToColonLoc);
5736 ToStmt->setSubStmt(ToSubStmt);
5741 ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
5742 auto Imp = importSeq(S->getDefaultLoc(), S->getColonLoc(), S->getSubStmt());
5744 return Imp.takeError();
5746 SourceLocation ToDefaultLoc, ToColonLoc;
5748 std::tie(ToDefaultLoc, ToColonLoc, ToSubStmt) = *Imp;
5750 return new (Importer.getToContext()) DefaultStmt(
5751 ToDefaultLoc, ToColonLoc, ToSubStmt);
5754 ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
5755 auto Imp = importSeq(S->getIdentLoc(), S->getDecl(), S->getSubStmt());
5757 return Imp.takeError();
5759 SourceLocation ToIdentLoc;
5760 LabelDecl *ToLabelDecl;
5762 std::tie(ToIdentLoc, ToLabelDecl, ToSubStmt) = *Imp;
5764 return new (Importer.getToContext()) LabelStmt(
5765 ToIdentLoc, ToLabelDecl, ToSubStmt);
5768 ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
5769 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
5770 if (!ToAttrLocOrErr)
5771 return ToAttrLocOrErr.takeError();
5772 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
5773 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
5774 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
5775 return std::move(Err);
5776 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
5777 if (!ToSubStmtOrErr)
5778 return ToSubStmtOrErr.takeError();
5780 return AttributedStmt::Create(
5781 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
5784 ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
5785 auto Imp = importSeq(
5786 S->getIfLoc(), S->getInit(), S->getConditionVariable(), S->getCond(),
5787 S->getThen(), S->getElseLoc(), S->getElse());
5789 return Imp.takeError();
5791 SourceLocation ToIfLoc, ToElseLoc;
5792 Stmt *ToInit, *ToThen, *ToElse;
5793 VarDecl *ToConditionVariable;
5796 ToIfLoc, ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, ToElse) =
5799 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->isConstexpr(),
5800 ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc,
5804 ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
5805 auto Imp = importSeq(
5806 S->getInit(), S->getConditionVariable(), S->getCond(),
5807 S->getBody(), S->getSwitchLoc());
5809 return Imp.takeError();
5811 Stmt *ToInit, *ToBody;
5812 VarDecl *ToConditionVariable;
5814 SourceLocation ToSwitchLoc;
5815 std::tie(ToInit, ToConditionVariable, ToCond, ToBody, ToSwitchLoc) = *Imp;
5817 auto *ToStmt = SwitchStmt::Create(Importer.getToContext(), ToInit,
5818 ToConditionVariable, ToCond);
5819 ToStmt->setBody(ToBody);
5820 ToStmt->setSwitchLoc(ToSwitchLoc);
5822 // Now we have to re-chain the cases.
5823 SwitchCase *LastChainedSwitchCase = nullptr;
5824 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5825 SC = SC->getNextSwitchCase()) {
5826 Expected<SwitchCase *> ToSCOrErr = import(SC);
5828 return ToSCOrErr.takeError();
5829 if (LastChainedSwitchCase)
5830 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
5832 ToStmt->setSwitchCaseList(*ToSCOrErr);
5833 LastChainedSwitchCase = *ToSCOrErr;
5839 ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
5840 auto Imp = importSeq(
5841 S->getConditionVariable(), S->getCond(), S->getBody(), S->getWhileLoc());
5843 return Imp.takeError();
5845 VarDecl *ToConditionVariable;
5848 SourceLocation ToWhileLoc;
5849 std::tie(ToConditionVariable, ToCond, ToBody, ToWhileLoc) = *Imp;
5851 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond,
5852 ToBody, ToWhileLoc);
5855 ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
5856 auto Imp = importSeq(
5857 S->getBody(), S->getCond(), S->getDoLoc(), S->getWhileLoc(),
5860 return Imp.takeError();
5864 SourceLocation ToDoLoc, ToWhileLoc, ToRParenLoc;
5865 std::tie(ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc) = *Imp;
5867 return new (Importer.getToContext()) DoStmt(
5868 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
5871 ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
5872 auto Imp = importSeq(
5873 S->getInit(), S->getCond(), S->getConditionVariable(), S->getInc(),
5874 S->getBody(), S->getForLoc(), S->getLParenLoc(), S->getRParenLoc());
5876 return Imp.takeError();
5879 Expr *ToCond, *ToInc;
5880 VarDecl *ToConditionVariable;
5882 SourceLocation ToForLoc, ToLParenLoc, ToRParenLoc;
5884 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc,
5885 ToLParenLoc, ToRParenLoc) = *Imp;
5887 return new (Importer.getToContext()) ForStmt(
5888 Importer.getToContext(),
5889 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
5893 ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
5894 auto Imp = importSeq(S->getLabel(), S->getGotoLoc(), S->getLabelLoc());
5896 return Imp.takeError();
5899 SourceLocation ToGotoLoc, ToLabelLoc;
5900 std::tie(ToLabel, ToGotoLoc, ToLabelLoc) = *Imp;
5902 return new (Importer.getToContext()) GotoStmt(
5903 ToLabel, ToGotoLoc, ToLabelLoc);
5906 ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
5907 auto Imp = importSeq(S->getGotoLoc(), S->getStarLoc(), S->getTarget());
5909 return Imp.takeError();
5911 SourceLocation ToGotoLoc, ToStarLoc;
5913 std::tie(ToGotoLoc, ToStarLoc, ToTarget) = *Imp;
5915 return new (Importer.getToContext()) IndirectGotoStmt(
5916 ToGotoLoc, ToStarLoc, ToTarget);
5919 ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
5920 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc());
5921 if (!ToContinueLocOrErr)
5922 return ToContinueLocOrErr.takeError();
5923 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
5926 ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
5927 auto ToBreakLocOrErr = import(S->getBreakLoc());
5928 if (!ToBreakLocOrErr)
5929 return ToBreakLocOrErr.takeError();
5930 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
5933 ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
5934 auto Imp = importSeq(
5935 S->getReturnLoc(), S->getRetValue(), S->getNRVOCandidate());
5937 return Imp.takeError();
5939 SourceLocation ToReturnLoc;
5941 const VarDecl *ToNRVOCandidate;
5942 std::tie(ToReturnLoc, ToRetValue, ToNRVOCandidate) = *Imp;
5944 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue,
5948 ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
5949 auto Imp = importSeq(
5950 S->getCatchLoc(), S->getExceptionDecl(), S->getHandlerBlock());
5952 return Imp.takeError();
5954 SourceLocation ToCatchLoc;
5955 VarDecl *ToExceptionDecl;
5956 Stmt *ToHandlerBlock;
5957 std::tie(ToCatchLoc, ToExceptionDecl, ToHandlerBlock) = *Imp;
5959 return new (Importer.getToContext()) CXXCatchStmt (
5960 ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
5963 ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
5964 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc());
5966 return ToTryLocOrErr.takeError();
5968 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock());
5969 if (!ToTryBlockOrErr)
5970 return ToTryBlockOrErr.takeError();
5972 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5973 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5974 CXXCatchStmt *FromHandler = S->getHandler(HI);
5975 if (auto ToHandlerOrErr = import(FromHandler))
5976 ToHandlers[HI] = *ToHandlerOrErr;
5978 return ToHandlerOrErr.takeError();
5981 return CXXTryStmt::Create(
5982 Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers);
5985 ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
5986 auto Imp1 = importSeq(
5987 S->getInit(), S->getRangeStmt(), S->getBeginStmt(), S->getEndStmt(),
5988 S->getCond(), S->getInc(), S->getLoopVarStmt(), S->getBody());
5990 return Imp1.takeError();
5991 auto Imp2 = importSeq(
5992 S->getForLoc(), S->getCoawaitLoc(), S->getColonLoc(), S->getRParenLoc());
5994 return Imp2.takeError();
5996 DeclStmt *ToRangeStmt, *ToBeginStmt, *ToEndStmt, *ToLoopVarStmt;
5997 Expr *ToCond, *ToInc;
5998 Stmt *ToInit, *ToBody;
6000 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
6002 SourceLocation ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc;
6003 std::tie(ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc) = *Imp2;
6005 return new (Importer.getToContext()) CXXForRangeStmt(
6006 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
6007 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
6011 ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
6012 auto Imp = importSeq(
6013 S->getElement(), S->getCollection(), S->getBody(),
6014 S->getForLoc(), S->getRParenLoc());
6016 return Imp.takeError();
6018 Stmt *ToElement, *ToBody;
6020 SourceLocation ToForLoc, ToRParenLoc;
6021 std::tie(ToElement, ToCollection, ToBody, ToForLoc, ToRParenLoc) = *Imp;
6023 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
6030 ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
6031 auto Imp = importSeq(
6032 S->getAtCatchLoc(), S->getRParenLoc(), S->getCatchParamDecl(),
6035 return Imp.takeError();
6037 SourceLocation ToAtCatchLoc, ToRParenLoc;
6038 VarDecl *ToCatchParamDecl;
6040 std::tie(ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody) = *Imp;
6042 return new (Importer.getToContext()) ObjCAtCatchStmt (
6043 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
6046 ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
6047 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc());
6048 if (!ToAtFinallyLocOrErr)
6049 return ToAtFinallyLocOrErr.takeError();
6050 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody());
6051 if (!ToAtFinallyStmtOrErr)
6052 return ToAtFinallyStmtOrErr.takeError();
6053 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
6054 *ToAtFinallyStmtOrErr);
6057 ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
6058 auto Imp = importSeq(
6059 S->getAtTryLoc(), S->getTryBody(), S->getFinallyStmt());
6061 return Imp.takeError();
6063 SourceLocation ToAtTryLoc;
6064 Stmt *ToTryBody, *ToFinallyStmt;
6065 std::tie(ToAtTryLoc, ToTryBody, ToFinallyStmt) = *Imp;
6067 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
6068 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
6069 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
6070 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt))
6071 ToCatchStmts[CI] = *ToCatchStmtOrErr;
6073 return ToCatchStmtOrErr.takeError();
6076 return ObjCAtTryStmt::Create(Importer.getToContext(),
6077 ToAtTryLoc, ToTryBody,
6078 ToCatchStmts.begin(), ToCatchStmts.size(),
6082 ExpectedStmt ASTNodeImporter::VisitObjCAtSynchronizedStmt
6083 (ObjCAtSynchronizedStmt *S) {
6084 auto Imp = importSeq(
6085 S->getAtSynchronizedLoc(), S->getSynchExpr(), S->getSynchBody());
6087 return Imp.takeError();
6089 SourceLocation ToAtSynchronizedLoc;
6092 std::tie(ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody) = *Imp;
6094 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
6095 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
6098 ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
6099 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc());
6100 if (!ToThrowLocOrErr)
6101 return ToThrowLocOrErr.takeError();
6102 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr());
6103 if (!ToThrowExprOrErr)
6104 return ToThrowExprOrErr.takeError();
6105 return new (Importer.getToContext()) ObjCAtThrowStmt(
6106 *ToThrowLocOrErr, *ToThrowExprOrErr);
6109 ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
6110 ObjCAutoreleasePoolStmt *S) {
6111 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc());
6113 return ToAtLocOrErr.takeError();
6114 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
6115 if (!ToSubStmtOrErr)
6116 return ToSubStmtOrErr.takeError();
6117 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
6121 //----------------------------------------------------------------------------
6122 // Import Expressions
6123 //----------------------------------------------------------------------------
6124 ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
6125 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
6126 << E->getStmtClassName();
6127 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6130 ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
6131 auto Imp = importSeq(
6132 E->getBuiltinLoc(), E->getSubExpr(), E->getWrittenTypeInfo(),
6133 E->getRParenLoc(), E->getType());
6135 return Imp.takeError();
6137 SourceLocation ToBuiltinLoc, ToRParenLoc;
6139 TypeSourceInfo *ToWrittenTypeInfo;
6141 std::tie(ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType) =
6144 return new (Importer.getToContext()) VAArgExpr(
6145 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
6146 E->isMicrosoftABI());
6149 ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
6150 auto Imp = importSeq(E->getCond(), E->getLHS(), E->getRHS(),
6151 E->getBuiltinLoc(), E->getRParenLoc(), E->getType());
6153 return Imp.takeError();
6158 SourceLocation ToBuiltinLoc, ToRParenLoc;
6160 std::tie(ToCond, ToLHS, ToRHS, ToBuiltinLoc, ToRParenLoc, ToType) = *Imp;
6162 ExprValueKind VK = E->getValueKind();
6163 ExprObjectKind OK = E->getObjectKind();
6165 bool TypeDependent = ToCond->isTypeDependent();
6166 bool ValueDependent = ToCond->isValueDependent();
6168 // The value of CondIsTrue only matters if the value is not
6169 // condition-dependent.
6170 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
6172 return new (Importer.getToContext())
6173 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
6174 ToRParenLoc, CondIsTrue, TypeDependent, ValueDependent);
6177 ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
6178 ExpectedType TypeOrErr = import(E->getType());
6180 return TypeOrErr.takeError();
6182 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc());
6184 return BeginLocOrErr.takeError();
6186 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
6189 ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
6190 auto Imp = importSeq(
6191 E->getBeginLoc(), E->getType(), E->getFunctionName());
6193 return Imp.takeError();
6195 SourceLocation ToBeginLoc;
6197 StringLiteral *ToFunctionName;
6198 std::tie(ToBeginLoc, ToType, ToFunctionName) = *Imp;
6200 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType,
6201 E->getIdentKind(), ToFunctionName);
6204 ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
6205 auto Imp = importSeq(
6206 E->getQualifierLoc(), E->getTemplateKeywordLoc(), E->getDecl(),
6207 E->getLocation(), E->getType());
6209 return Imp.takeError();
6211 NestedNameSpecifierLoc ToQualifierLoc;
6212 SourceLocation ToTemplateKeywordLoc, ToLocation;
6215 std::tie(ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, ToLocation, ToType) =
6218 NamedDecl *ToFoundD = nullptr;
6219 if (E->getDecl() != E->getFoundDecl()) {
6220 auto FoundDOrErr = import(E->getFoundDecl());
6222 return FoundDOrErr.takeError();
6223 ToFoundD = *FoundDOrErr;
6226 TemplateArgumentListInfo ToTAInfo;
6227 TemplateArgumentListInfo *ToResInfo = nullptr;
6228 if (E->hasExplicitTemplateArgs()) {
6230 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
6231 return std::move(Err);
6232 ToResInfo = &ToTAInfo;
6235 auto *ToE = DeclRefExpr::Create(
6236 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
6237 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
6238 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse());
6239 if (E->hadMultipleCandidates())
6240 ToE->setHadMultipleCandidates(true);
6244 ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
6245 ExpectedType TypeOrErr = import(E->getType());
6247 return TypeOrErr.takeError();
6249 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
6252 ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
6253 ExpectedExpr ToInitOrErr = import(E->getInit());
6255 return ToInitOrErr.takeError();
6257 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc());
6258 if (!ToEqualOrColonLocOrErr)
6259 return ToEqualOrColonLocOrErr.takeError();
6261 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
6262 // List elements from the second, the first is Init itself
6263 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
6264 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I)))
6265 ToIndexExprs[I - 1] = *ToArgOrErr;
6267 return ToArgOrErr.takeError();
6270 SmallVector<Designator, 4> ToDesignators(E->size());
6271 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators))
6272 return std::move(Err);
6274 return DesignatedInitExpr::Create(
6275 Importer.getToContext(), ToDesignators,
6276 ToIndexExprs, *ToEqualOrColonLocOrErr,
6277 E->usesGNUSyntax(), *ToInitOrErr);
6281 ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
6282 ExpectedType ToTypeOrErr = import(E->getType());
6284 return ToTypeOrErr.takeError();
6286 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6287 if (!ToLocationOrErr)
6288 return ToLocationOrErr.takeError();
6290 return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
6291 *ToTypeOrErr, *ToLocationOrErr);
6294 ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
6295 ExpectedType ToTypeOrErr = import(E->getType());
6297 return ToTypeOrErr.takeError();
6299 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6300 if (!ToLocationOrErr)
6301 return ToLocationOrErr.takeError();
6303 return IntegerLiteral::Create(
6304 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
6308 ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
6309 ExpectedType ToTypeOrErr = import(E->getType());
6311 return ToTypeOrErr.takeError();
6313 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6314 if (!ToLocationOrErr)
6315 return ToLocationOrErr.takeError();
6317 return FloatingLiteral::Create(
6318 Importer.getToContext(), E->getValue(), E->isExact(),
6319 *ToTypeOrErr, *ToLocationOrErr);
6322 ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
6323 auto ToTypeOrErr = import(E->getType());
6325 return ToTypeOrErr.takeError();
6327 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
6328 if (!ToSubExprOrErr)
6329 return ToSubExprOrErr.takeError();
6331 return new (Importer.getToContext()) ImaginaryLiteral(
6332 *ToSubExprOrErr, *ToTypeOrErr);
6335 ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
6336 ExpectedType ToTypeOrErr = import(E->getType());
6338 return ToTypeOrErr.takeError();
6340 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6341 if (!ToLocationOrErr)
6342 return ToLocationOrErr.takeError();
6344 return new (Importer.getToContext()) CharacterLiteral(
6345 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
6348 ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
6349 ExpectedType ToTypeOrErr = import(E->getType());
6351 return ToTypeOrErr.takeError();
6353 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
6354 if (Error Err = ImportArrayChecked(
6355 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin()))
6356 return std::move(Err);
6358 return StringLiteral::Create(
6359 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(),
6360 *ToTypeOrErr, ToLocations.data(), ToLocations.size());
6363 ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
6364 auto Imp = importSeq(
6365 E->getLParenLoc(), E->getTypeSourceInfo(), E->getType(),
6366 E->getInitializer());
6368 return Imp.takeError();
6370 SourceLocation ToLParenLoc;
6371 TypeSourceInfo *ToTypeSourceInfo;
6373 Expr *ToInitializer;
6374 std::tie(ToLParenLoc, ToTypeSourceInfo, ToType, ToInitializer) = *Imp;
6376 return new (Importer.getToContext()) CompoundLiteralExpr(
6377 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
6378 ToInitializer, E->isFileScope());
6381 ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
6382 auto Imp = importSeq(
6383 E->getBuiltinLoc(), E->getType(), E->getRParenLoc());
6385 return Imp.takeError();
6387 SourceLocation ToBuiltinLoc, ToRParenLoc;
6389 std::tie(ToBuiltinLoc, ToType, ToRParenLoc) = *Imp;
6391 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
6392 if (Error Err = ImportArrayChecked(
6393 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
6395 return std::move(Err);
6397 return new (Importer.getToContext()) AtomicExpr(
6398 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
6401 ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
6402 auto Imp = importSeq(
6403 E->getAmpAmpLoc(), E->getLabelLoc(), E->getLabel(), E->getType());
6405 return Imp.takeError();
6407 SourceLocation ToAmpAmpLoc, ToLabelLoc;
6410 std::tie(ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType) = *Imp;
6412 return new (Importer.getToContext()) AddrLabelExpr(
6413 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
6416 ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
6417 auto Imp = importSeq(E->getSubExpr());
6419 return Imp.takeError();
6422 std::tie(ToSubExpr) = *Imp;
6424 // TODO : Handle APValue::ValueKind that require importing.
6425 APValue::ValueKind Kind = E->getResultAPValueKind();
6426 if (Kind == APValue::Int || Kind == APValue::Float ||
6427 Kind == APValue::FixedPoint || Kind == APValue::ComplexFloat ||
6428 Kind == APValue::ComplexInt)
6429 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr,
6430 E->getAPValueResult());
6431 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr);
6434 ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
6435 auto Imp = importSeq(E->getLParen(), E->getRParen(), E->getSubExpr());
6437 return Imp.takeError();
6439 SourceLocation ToLParen, ToRParen;
6441 std::tie(ToLParen, ToRParen, ToSubExpr) = *Imp;
6443 return new (Importer.getToContext())
6444 ParenExpr(ToLParen, ToRParen, ToSubExpr);
6447 ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
6448 SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
6449 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs))
6450 return std::move(Err);
6452 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc());
6453 if (!ToLParenLocOrErr)
6454 return ToLParenLocOrErr.takeError();
6456 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc());
6457 if (!ToRParenLocOrErr)
6458 return ToRParenLocOrErr.takeError();
6460 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr,
6461 ToExprs, *ToRParenLocOrErr);
6464 ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
6465 auto Imp = importSeq(
6466 E->getSubStmt(), E->getType(), E->getLParenLoc(), E->getRParenLoc());
6468 return Imp.takeError();
6470 CompoundStmt *ToSubStmt;
6472 SourceLocation ToLParenLoc, ToRParenLoc;
6473 std::tie(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc) = *Imp;
6475 return new (Importer.getToContext()) StmtExpr(
6476 ToSubStmt, ToType, ToLParenLoc, ToRParenLoc);
6479 ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
6480 auto Imp = importSeq(
6481 E->getSubExpr(), E->getType(), E->getOperatorLoc());
6483 return Imp.takeError();
6487 SourceLocation ToOperatorLoc;
6488 std::tie(ToSubExpr, ToType, ToOperatorLoc) = *Imp;
6490 return new (Importer.getToContext()) UnaryOperator(
6491 ToSubExpr, E->getOpcode(), ToType, E->getValueKind(), E->getObjectKind(),
6492 ToOperatorLoc, E->canOverflow());
6496 ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
6497 auto Imp = importSeq(E->getType(), E->getOperatorLoc(), E->getRParenLoc());
6499 return Imp.takeError();
6502 SourceLocation ToOperatorLoc, ToRParenLoc;
6503 std::tie(ToType, ToOperatorLoc, ToRParenLoc) = *Imp;
6505 if (E->isArgumentType()) {
6506 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
6507 import(E->getArgumentTypeInfo());
6508 if (!ToArgumentTypeInfoOrErr)
6509 return ToArgumentTypeInfoOrErr.takeError();
6511 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
6512 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
6516 ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr());
6517 if (!ToArgumentExprOrErr)
6518 return ToArgumentExprOrErr.takeError();
6520 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
6521 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
6524 ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
6525 auto Imp = importSeq(
6526 E->getLHS(), E->getRHS(), E->getType(), E->getOperatorLoc());
6528 return Imp.takeError();
6530 Expr *ToLHS, *ToRHS;
6532 SourceLocation ToOperatorLoc;
6533 std::tie(ToLHS, ToRHS, ToType, ToOperatorLoc) = *Imp;
6535 return new (Importer.getToContext()) BinaryOperator(
6536 ToLHS, ToRHS, E->getOpcode(), ToType, E->getValueKind(),
6537 E->getObjectKind(), ToOperatorLoc, E->getFPFeatures());
6540 ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
6541 auto Imp = importSeq(
6542 E->getCond(), E->getQuestionLoc(), E->getLHS(), E->getColonLoc(),
6543 E->getRHS(), E->getType());
6545 return Imp.takeError();
6547 Expr *ToCond, *ToLHS, *ToRHS;
6548 SourceLocation ToQuestionLoc, ToColonLoc;
6550 std::tie(ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType) = *Imp;
6552 return new (Importer.getToContext()) ConditionalOperator(
6553 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
6554 E->getValueKind(), E->getObjectKind());
6557 ExpectedStmt ASTNodeImporter::VisitBinaryConditionalOperator(
6558 BinaryConditionalOperator *E) {
6559 auto Imp = importSeq(
6560 E->getCommon(), E->getOpaqueValue(), E->getCond(), E->getTrueExpr(),
6561 E->getFalseExpr(), E->getQuestionLoc(), E->getColonLoc(), E->getType());
6563 return Imp.takeError();
6565 Expr *ToCommon, *ToCond, *ToTrueExpr, *ToFalseExpr;
6566 OpaqueValueExpr *ToOpaqueValue;
6567 SourceLocation ToQuestionLoc, ToColonLoc;
6570 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, ToQuestionLoc,
6571 ToColonLoc, ToType) = *Imp;
6573 return new (Importer.getToContext()) BinaryConditionalOperator(
6574 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
6575 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
6576 E->getObjectKind());
6579 ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
6580 auto Imp = importSeq(
6581 E->getBeginLoc(), E->getQueriedTypeSourceInfo(),
6582 E->getDimensionExpression(), E->getEndLoc(), E->getType());
6584 return Imp.takeError();
6586 SourceLocation ToBeginLoc, ToEndLoc;
6587 TypeSourceInfo *ToQueriedTypeSourceInfo;
6588 Expr *ToDimensionExpression;
6591 ToBeginLoc, ToQueriedTypeSourceInfo, ToDimensionExpression, ToEndLoc,
6594 return new (Importer.getToContext()) ArrayTypeTraitExpr(
6595 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
6596 ToDimensionExpression, ToEndLoc, ToType);
6599 ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
6600 auto Imp = importSeq(
6601 E->getBeginLoc(), E->getQueriedExpression(), E->getEndLoc(), E->getType());
6603 return Imp.takeError();
6605 SourceLocation ToBeginLoc, ToEndLoc;
6606 Expr *ToQueriedExpression;
6608 std::tie(ToBeginLoc, ToQueriedExpression, ToEndLoc, ToType) = *Imp;
6610 return new (Importer.getToContext()) ExpressionTraitExpr(
6611 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
6615 ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
6616 auto Imp = importSeq(
6617 E->getLocation(), E->getType(), E->getSourceExpr());
6619 return Imp.takeError();
6621 SourceLocation ToLocation;
6624 std::tie(ToLocation, ToType, ToSourceExpr) = *Imp;
6626 return new (Importer.getToContext()) OpaqueValueExpr(
6627 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
6630 ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
6631 auto Imp = importSeq(
6632 E->getLHS(), E->getRHS(), E->getType(), E->getRBracketLoc());
6634 return Imp.takeError();
6636 Expr *ToLHS, *ToRHS;
6637 SourceLocation ToRBracketLoc;
6639 std::tie(ToLHS, ToRHS, ToType, ToRBracketLoc) = *Imp;
6641 return new (Importer.getToContext()) ArraySubscriptExpr(
6642 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
6647 ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
6648 auto Imp = importSeq(
6649 E->getLHS(), E->getRHS(), E->getType(), E->getComputationLHSType(),
6650 E->getComputationResultType(), E->getOperatorLoc());
6652 return Imp.takeError();
6654 Expr *ToLHS, *ToRHS;
6655 QualType ToType, ToComputationLHSType, ToComputationResultType;
6656 SourceLocation ToOperatorLoc;
6657 std::tie(ToLHS, ToRHS, ToType, ToComputationLHSType, ToComputationResultType,
6658 ToOperatorLoc) = *Imp;
6660 return new (Importer.getToContext()) CompoundAssignOperator(
6661 ToLHS, ToRHS, E->getOpcode(), ToType, E->getValueKind(),
6662 E->getObjectKind(), ToComputationLHSType, ToComputationResultType,
6663 ToOperatorLoc, E->getFPFeatures());
6666 Expected<CXXCastPath>
6667 ASTNodeImporter::ImportCastPath(CastExpr *CE) {
6669 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
6670 if (auto SpecOrErr = import(*I))
6671 Path.push_back(*SpecOrErr);
6673 return SpecOrErr.takeError();
6678 ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
6679 ExpectedType ToTypeOrErr = import(E->getType());
6681 return ToTypeOrErr.takeError();
6683 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
6684 if (!ToSubExprOrErr)
6685 return ToSubExprOrErr.takeError();
6687 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
6688 if (!ToBasePathOrErr)
6689 return ToBasePathOrErr.takeError();
6691 return ImplicitCastExpr::Create(
6692 Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr,
6693 &(*ToBasePathOrErr), E->getValueKind());
6696 ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
6697 auto Imp1 = importSeq(
6698 E->getType(), E->getSubExpr(), E->getTypeInfoAsWritten());
6700 return Imp1.takeError();
6704 TypeSourceInfo *ToTypeInfoAsWritten;
6705 std::tie(ToType, ToSubExpr, ToTypeInfoAsWritten) = *Imp1;
6707 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
6708 if (!ToBasePathOrErr)
6709 return ToBasePathOrErr.takeError();
6710 CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
6712 switch (E->getStmtClass()) {
6713 case Stmt::CStyleCastExprClass: {
6714 auto *CCE = cast<CStyleCastExpr>(E);
6715 ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc());
6716 if (!ToLParenLocOrErr)
6717 return ToLParenLocOrErr.takeError();
6718 ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc());
6719 if (!ToRParenLocOrErr)
6720 return ToRParenLocOrErr.takeError();
6721 return CStyleCastExpr::Create(
6722 Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(),
6723 ToSubExpr, ToBasePath, ToTypeInfoAsWritten, *ToLParenLocOrErr,
6727 case Stmt::CXXFunctionalCastExprClass: {
6728 auto *FCE = cast<CXXFunctionalCastExpr>(E);
6729 ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc());
6730 if (!ToLParenLocOrErr)
6731 return ToLParenLocOrErr.takeError();
6732 ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc());
6733 if (!ToRParenLocOrErr)
6734 return ToRParenLocOrErr.takeError();
6735 return CXXFunctionalCastExpr::Create(
6736 Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten,
6737 E->getCastKind(), ToSubExpr, ToBasePath, *ToLParenLocOrErr,
6741 case Stmt::ObjCBridgedCastExprClass: {
6742 auto *OCE = cast<ObjCBridgedCastExpr>(E);
6743 ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc());
6744 if (!ToLParenLocOrErr)
6745 return ToLParenLocOrErr.takeError();
6746 ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc());
6747 if (!ToBridgeKeywordLocOrErr)
6748 return ToBridgeKeywordLocOrErr.takeError();
6749 return new (Importer.getToContext()) ObjCBridgedCastExpr(
6750 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
6751 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
6754 llvm_unreachable("Cast expression of unsupported type!");
6755 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6759 ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) {
6760 SmallVector<OffsetOfNode, 4> ToNodes;
6761 for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
6762 const OffsetOfNode &FromNode = E->getComponent(I);
6764 SourceLocation ToBeginLoc, ToEndLoc;
6765 if (FromNode.getKind() != OffsetOfNode::Base) {
6766 auto Imp = importSeq(FromNode.getBeginLoc(), FromNode.getEndLoc());
6768 return Imp.takeError();
6769 std::tie(ToBeginLoc, ToEndLoc) = *Imp;
6772 switch (FromNode.getKind()) {
6773 case OffsetOfNode::Array:
6775 OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
6777 case OffsetOfNode::Base: {
6778 auto ToBSOrErr = import(FromNode.getBase());
6780 return ToBSOrErr.takeError();
6781 ToNodes.push_back(OffsetOfNode(*ToBSOrErr));
6784 case OffsetOfNode::Field: {
6785 auto ToFieldOrErr = import(FromNode.getField());
6787 return ToFieldOrErr.takeError();
6788 ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
6791 case OffsetOfNode::Identifier: {
6792 IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName());
6793 ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
6799 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
6800 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
6801 ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I));
6802 if (!ToIndexExprOrErr)
6803 return ToIndexExprOrErr.takeError();
6804 ToExprs[I] = *ToIndexExprOrErr;
6807 auto Imp = importSeq(
6808 E->getType(), E->getTypeSourceInfo(), E->getOperatorLoc(),
6811 return Imp.takeError();
6814 TypeSourceInfo *ToTypeSourceInfo;
6815 SourceLocation ToOperatorLoc, ToRParenLoc;
6816 std::tie(ToType, ToTypeSourceInfo, ToOperatorLoc, ToRParenLoc) = *Imp;
6818 return OffsetOfExpr::Create(
6819 Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes,
6820 ToExprs, ToRParenLoc);
6823 ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
6824 auto Imp = importSeq(
6825 E->getType(), E->getOperand(), E->getBeginLoc(), E->getEndLoc());
6827 return Imp.takeError();
6831 SourceLocation ToBeginLoc, ToEndLoc;
6832 std::tie(ToType, ToOperand, ToBeginLoc, ToEndLoc) = *Imp;
6834 CanThrowResult ToCanThrow;
6835 if (E->isValueDependent())
6836 ToCanThrow = CT_Dependent;
6838 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
6840 return new (Importer.getToContext()) CXXNoexceptExpr(
6841 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
6844 ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
6845 auto Imp = importSeq(E->getSubExpr(), E->getType(), E->getThrowLoc());
6847 return Imp.takeError();
6851 SourceLocation ToThrowLoc;
6852 std::tie(ToSubExpr, ToType, ToThrowLoc) = *Imp;
6854 return new (Importer.getToContext()) CXXThrowExpr(
6855 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
6858 ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6859 ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation());
6860 if (!ToUsedLocOrErr)
6861 return ToUsedLocOrErr.takeError();
6863 auto ToParamOrErr = import(E->getParam());
6865 return ToParamOrErr.takeError();
6867 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
6868 if (!UsedContextOrErr)
6869 return UsedContextOrErr.takeError();
6871 return CXXDefaultArgExpr::Create(
6872 Importer.getToContext(), *ToUsedLocOrErr, *ToParamOrErr, *UsedContextOrErr);
6876 ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
6877 auto Imp = importSeq(
6878 E->getType(), E->getTypeSourceInfo(), E->getRParenLoc());
6880 return Imp.takeError();
6883 TypeSourceInfo *ToTypeSourceInfo;
6884 SourceLocation ToRParenLoc;
6885 std::tie(ToType, ToTypeSourceInfo, ToRParenLoc) = *Imp;
6887 return new (Importer.getToContext()) CXXScalarValueInitExpr(
6888 ToType, ToTypeSourceInfo, ToRParenLoc);
6892 ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
6893 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
6894 if (!ToSubExprOrErr)
6895 return ToSubExprOrErr.takeError();
6897 auto ToDtorOrErr = import(E->getTemporary()->getDestructor());
6899 return ToDtorOrErr.takeError();
6901 ASTContext &ToCtx = Importer.getToContext();
6902 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr);
6903 return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr);
6907 ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
6908 auto Imp = importSeq(
6909 E->getConstructor(), E->getType(), E->getTypeSourceInfo(),
6910 E->getParenOrBraceRange());
6912 return Imp.takeError();
6914 CXXConstructorDecl *ToConstructor;
6916 TypeSourceInfo *ToTypeSourceInfo;
6917 SourceRange ToParenOrBraceRange;
6918 std::tie(ToConstructor, ToType, ToTypeSourceInfo, ToParenOrBraceRange) = *Imp;
6920 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
6921 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
6922 return std::move(Err);
6924 return CXXTemporaryObjectExpr::Create(
6925 Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs,
6926 ToParenOrBraceRange, E->hadMultipleCandidates(),
6927 E->isListInitialization(), E->isStdInitListInitialization(),
6928 E->requiresZeroInitialization());
6932 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
6933 auto Imp = importSeq(
6934 E->getType(), E->GetTemporaryExpr(), E->getExtendingDecl());
6936 return Imp.takeError();
6939 Expr *ToTemporaryExpr;
6940 const ValueDecl *ToExtendingDecl;
6941 std::tie(ToType, ToTemporaryExpr, ToExtendingDecl) = *Imp;
6943 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
6944 ToType, ToTemporaryExpr, E->isBoundToLvalueReference());
6946 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
6947 ToMTE->setExtendingDecl(ToExtendingDecl, E->getManglingNumber());
6951 ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
6952 auto Imp = importSeq(
6953 E->getType(), E->getPattern(), E->getEllipsisLoc());
6955 return Imp.takeError();
6959 SourceLocation ToEllipsisLoc;
6960 std::tie(ToType, ToPattern, ToEllipsisLoc) = *Imp;
6962 return new (Importer.getToContext()) PackExpansionExpr(
6963 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
6966 ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
6967 auto Imp = importSeq(
6968 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc());
6970 return Imp.takeError();
6972 SourceLocation ToOperatorLoc, ToPackLoc, ToRParenLoc;
6974 std::tie(ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc) = *Imp;
6976 Optional<unsigned> Length;
6977 if (!E->isValueDependent())
6978 Length = E->getPackLength();
6980 SmallVector<TemplateArgument, 8> ToPartialArguments;
6981 if (E->isPartiallySubstituted()) {
6982 if (Error Err = ImportTemplateArguments(
6983 E->getPartialArguments().data(),
6984 E->getPartialArguments().size(),
6985 ToPartialArguments))
6986 return std::move(Err);
6989 return SizeOfPackExpr::Create(
6990 Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc,
6991 Length, ToPartialArguments);
6995 ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) {
6996 auto Imp = importSeq(
6997 E->getOperatorNew(), E->getOperatorDelete(), E->getTypeIdParens(),
6998 E->getArraySize(), E->getInitializer(), E->getType(),
6999 E->getAllocatedTypeSourceInfo(), E->getSourceRange(),
7000 E->getDirectInitRange());
7002 return Imp.takeError();
7004 FunctionDecl *ToOperatorNew, *ToOperatorDelete;
7005 SourceRange ToTypeIdParens, ToSourceRange, ToDirectInitRange;
7006 Optional<Expr *> ToArraySize;
7007 Expr *ToInitializer;
7009 TypeSourceInfo *ToAllocatedTypeSourceInfo;
7011 ToOperatorNew, ToOperatorDelete, ToTypeIdParens, ToArraySize, ToInitializer,
7012 ToType, ToAllocatedTypeSourceInfo, ToSourceRange, ToDirectInitRange) = *Imp;
7014 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
7016 ImportContainerChecked(E->placement_arguments(), ToPlacementArgs))
7017 return std::move(Err);
7019 return CXXNewExpr::Create(
7020 Importer.getToContext(), E->isGlobalNew(), ToOperatorNew,
7021 ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(),
7022 ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(),
7023 ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange,
7027 ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
7028 auto Imp = importSeq(
7029 E->getType(), E->getOperatorDelete(), E->getArgument(), E->getBeginLoc());
7031 return Imp.takeError();
7034 FunctionDecl *ToOperatorDelete;
7036 SourceLocation ToBeginLoc;
7037 std::tie(ToType, ToOperatorDelete, ToArgument, ToBeginLoc) = *Imp;
7039 return new (Importer.getToContext()) CXXDeleteExpr(
7040 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
7041 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
7045 ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
7046 auto Imp = importSeq(
7047 E->getType(), E->getLocation(), E->getConstructor(),
7048 E->getParenOrBraceRange());
7050 return Imp.takeError();
7053 SourceLocation ToLocation;
7054 CXXConstructorDecl *ToConstructor;
7055 SourceRange ToParenOrBraceRange;
7056 std::tie(ToType, ToLocation, ToConstructor, ToParenOrBraceRange) = *Imp;
7058 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
7059 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
7060 return std::move(Err);
7062 return CXXConstructExpr::Create(
7063 Importer.getToContext(), ToType, ToLocation, ToConstructor,
7064 E->isElidable(), ToArgs, E->hadMultipleCandidates(),
7065 E->isListInitialization(), E->isStdInitListInitialization(),
7066 E->requiresZeroInitialization(), E->getConstructionKind(),
7067 ToParenOrBraceRange);
7070 ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) {
7071 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7072 if (!ToSubExprOrErr)
7073 return ToSubExprOrErr.takeError();
7075 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
7076 if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects))
7077 return std::move(Err);
7079 return ExprWithCleanups::Create(
7080 Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(),
7084 ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
7085 auto Imp = importSeq(
7086 E->getCallee(), E->getType(), E->getRParenLoc());
7088 return Imp.takeError();
7092 SourceLocation ToRParenLoc;
7093 std::tie(ToCallee, ToType, ToRParenLoc) = *Imp;
7095 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
7096 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
7097 return std::move(Err);
7099 return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs,
7100 ToType, E->getValueKind(), ToRParenLoc);
7103 ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
7104 ExpectedType ToTypeOrErr = import(E->getType());
7106 return ToTypeOrErr.takeError();
7108 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7109 if (!ToLocationOrErr)
7110 return ToLocationOrErr.takeError();
7112 return new (Importer.getToContext()) CXXThisExpr(
7113 *ToLocationOrErr, *ToTypeOrErr, E->isImplicit());
7116 ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
7117 ExpectedType ToTypeOrErr = import(E->getType());
7119 return ToTypeOrErr.takeError();
7121 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7122 if (!ToLocationOrErr)
7123 return ToLocationOrErr.takeError();
7125 return new (Importer.getToContext()) CXXBoolLiteralExpr(
7126 E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
7129 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
7130 auto Imp1 = importSeq(
7131 E->getBase(), E->getOperatorLoc(), E->getQualifierLoc(),
7132 E->getTemplateKeywordLoc(), E->getMemberDecl(), E->getType());
7134 return Imp1.takeError();
7137 SourceLocation ToOperatorLoc, ToTemplateKeywordLoc;
7138 NestedNameSpecifierLoc ToQualifierLoc;
7139 ValueDecl *ToMemberDecl;
7142 ToBase, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, ToMemberDecl,
7145 auto Imp2 = importSeq(
7146 E->getFoundDecl().getDecl(), E->getMemberNameInfo().getName(),
7147 E->getMemberNameInfo().getLoc(), E->getLAngleLoc(), E->getRAngleLoc());
7149 return Imp2.takeError();
7151 DeclarationName ToName;
7152 SourceLocation ToLoc, ToLAngleLoc, ToRAngleLoc;
7153 std::tie(ToDecl, ToName, ToLoc, ToLAngleLoc, ToRAngleLoc) = *Imp2;
7155 DeclAccessPair ToFoundDecl =
7156 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess());
7158 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
7160 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
7161 if (E->hasExplicitTemplateArgs()) {
7163 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
7164 E->template_arguments(), ToTAInfo))
7165 return std::move(Err);
7166 ResInfo = &ToTAInfo;
7169 return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(),
7170 ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
7171 ToMemberDecl, ToFoundDecl, ToMemberNameInfo,
7172 ResInfo, ToType, E->getValueKind(),
7173 E->getObjectKind(), E->isNonOdrUse());
7177 ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
7178 auto Imp = importSeq(
7179 E->getBase(), E->getOperatorLoc(), E->getQualifierLoc(),
7180 E->getScopeTypeInfo(), E->getColonColonLoc(), E->getTildeLoc());
7182 return Imp.takeError();
7185 SourceLocation ToOperatorLoc, ToColonColonLoc, ToTildeLoc;
7186 NestedNameSpecifierLoc ToQualifierLoc;
7187 TypeSourceInfo *ToScopeTypeInfo;
7189 ToBase, ToOperatorLoc, ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc,
7192 PseudoDestructorTypeStorage Storage;
7193 if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
7194 IdentifierInfo *ToII = Importer.Import(FromII);
7195 ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc());
7196 if (!ToDestroyedTypeLocOrErr)
7197 return ToDestroyedTypeLocOrErr.takeError();
7198 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
7200 if (auto ToTIOrErr = import(E->getDestroyedTypeInfo()))
7201 Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
7203 return ToTIOrErr.takeError();
7206 return new (Importer.getToContext()) CXXPseudoDestructorExpr(
7207 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
7208 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
7211 ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
7212 CXXDependentScopeMemberExpr *E) {
7213 auto Imp = importSeq(
7214 E->getType(), E->getOperatorLoc(), E->getQualifierLoc(),
7215 E->getTemplateKeywordLoc(), E->getFirstQualifierFoundInScope());
7217 return Imp.takeError();
7220 SourceLocation ToOperatorLoc, ToTemplateKeywordLoc;
7221 NestedNameSpecifierLoc ToQualifierLoc;
7222 NamedDecl *ToFirstQualifierFoundInScope;
7224 ToType, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
7225 ToFirstQualifierFoundInScope) = *Imp;
7227 Expr *ToBase = nullptr;
7228 if (!E->isImplicitAccess()) {
7229 if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
7230 ToBase = *ToBaseOrErr;
7232 return ToBaseOrErr.takeError();
7235 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
7236 if (E->hasExplicitTemplateArgs()) {
7237 if (Error Err = ImportTemplateArgumentListInfo(
7238 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
7240 return std::move(Err);
7241 ResInfo = &ToTAInfo;
7244 auto ToMemberNameInfoOrErr = importSeq(E->getMember(), E->getMemberLoc());
7245 if (!ToMemberNameInfoOrErr)
7246 return ToMemberNameInfoOrErr.takeError();
7247 DeclarationNameInfo ToMemberNameInfo(
7248 std::get<0>(*ToMemberNameInfoOrErr), std::get<1>(*ToMemberNameInfoOrErr));
7249 // Import additional name location/type info.
7250 if (Error Err = ImportDeclarationNameLoc(
7251 E->getMemberNameInfo(), ToMemberNameInfo))
7252 return std::move(Err);
7254 return CXXDependentScopeMemberExpr::Create(
7255 Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc,
7256 ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope,
7257 ToMemberNameInfo, ResInfo);
7261 ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
7262 auto Imp = importSeq(
7263 E->getQualifierLoc(), E->getTemplateKeywordLoc(), E->getDeclName(),
7264 E->getExprLoc(), E->getLAngleLoc(), E->getRAngleLoc());
7266 return Imp.takeError();
7268 NestedNameSpecifierLoc ToQualifierLoc;
7269 SourceLocation ToTemplateKeywordLoc, ToExprLoc, ToLAngleLoc, ToRAngleLoc;
7270 DeclarationName ToDeclName;
7272 ToQualifierLoc, ToTemplateKeywordLoc, ToDeclName, ToExprLoc,
7273 ToLAngleLoc, ToRAngleLoc) = *Imp;
7275 DeclarationNameInfo ToNameInfo(ToDeclName, ToExprLoc);
7276 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
7277 return std::move(Err);
7279 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
7280 TemplateArgumentListInfo *ResInfo = nullptr;
7281 if (E->hasExplicitTemplateArgs()) {
7283 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
7284 return std::move(Err);
7285 ResInfo = &ToTAInfo;
7288 return DependentScopeDeclRefExpr::Create(
7289 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc,
7290 ToNameInfo, ResInfo);
7293 ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
7294 CXXUnresolvedConstructExpr *E) {
7295 auto Imp = importSeq(
7296 E->getLParenLoc(), E->getRParenLoc(), E->getTypeSourceInfo());
7298 return Imp.takeError();
7300 SourceLocation ToLParenLoc, ToRParenLoc;
7301 TypeSourceInfo *ToTypeSourceInfo;
7302 std::tie(ToLParenLoc, ToRParenLoc, ToTypeSourceInfo) = *Imp;
7304 SmallVector<Expr *, 8> ToArgs(E->arg_size());
7306 ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
7307 return std::move(Err);
7309 return CXXUnresolvedConstructExpr::Create(
7310 Importer.getToContext(), ToTypeSourceInfo, ToLParenLoc,
7311 llvm::makeArrayRef(ToArgs), ToRParenLoc);
7315 ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
7316 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass());
7317 if (!ToNamingClassOrErr)
7318 return ToNamingClassOrErr.takeError();
7320 auto ToQualifierLocOrErr = import(E->getQualifierLoc());
7321 if (!ToQualifierLocOrErr)
7322 return ToQualifierLocOrErr.takeError();
7324 auto ToNameInfoOrErr = importSeq(E->getName(), E->getNameLoc());
7325 if (!ToNameInfoOrErr)
7326 return ToNameInfoOrErr.takeError();
7327 DeclarationNameInfo ToNameInfo(
7328 std::get<0>(*ToNameInfoOrErr), std::get<1>(*ToNameInfoOrErr));
7329 // Import additional name location/type info.
7330 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
7331 return std::move(Err);
7333 UnresolvedSet<8> ToDecls;
7334 for (auto *D : E->decls())
7335 if (auto ToDOrErr = import(D))
7336 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
7338 return ToDOrErr.takeError();
7340 if (E->hasExplicitTemplateArgs() && E->getTemplateKeywordLoc().isValid()) {
7341 TemplateArgumentListInfo ToTAInfo;
7342 if (Error Err = ImportTemplateArgumentListInfo(
7343 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
7345 return std::move(Err);
7347 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc());
7348 if (!ToTemplateKeywordLocOrErr)
7349 return ToTemplateKeywordLocOrErr.takeError();
7351 return UnresolvedLookupExpr::Create(
7352 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
7353 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
7354 ToDecls.begin(), ToDecls.end());
7357 return UnresolvedLookupExpr::Create(
7358 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
7359 ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(),
7364 ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
7365 auto Imp1 = importSeq(
7366 E->getType(), E->getOperatorLoc(), E->getQualifierLoc(),
7367 E->getTemplateKeywordLoc());
7369 return Imp1.takeError();
7372 SourceLocation ToOperatorLoc, ToTemplateKeywordLoc;
7373 NestedNameSpecifierLoc ToQualifierLoc;
7374 std::tie(ToType, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc) = *Imp1;
7376 auto Imp2 = importSeq(E->getName(), E->getNameLoc());
7378 return Imp2.takeError();
7379 DeclarationNameInfo ToNameInfo(std::get<0>(*Imp2), std::get<1>(*Imp2));
7380 // Import additional name location/type info.
7381 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
7382 return std::move(Err);
7384 UnresolvedSet<8> ToDecls;
7385 for (Decl *D : E->decls())
7386 if (auto ToDOrErr = import(D))
7387 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
7389 return ToDOrErr.takeError();
7391 TemplateArgumentListInfo ToTAInfo;
7392 TemplateArgumentListInfo *ResInfo = nullptr;
7393 if (E->hasExplicitTemplateArgs()) {
7395 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
7396 return std::move(Err);
7397 ResInfo = &ToTAInfo;
7400 Expr *ToBase = nullptr;
7401 if (!E->isImplicitAccess()) {
7402 if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
7403 ToBase = *ToBaseOrErr;
7405 return ToBaseOrErr.takeError();
7408 return UnresolvedMemberExpr::Create(
7409 Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType,
7410 E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
7411 ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end());
7414 ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) {
7415 auto Imp = importSeq(E->getCallee(), E->getType(), E->getRParenLoc());
7417 return Imp.takeError();
7421 SourceLocation ToRParenLoc;
7422 std::tie(ToCallee, ToType, ToRParenLoc) = *Imp;
7424 unsigned NumArgs = E->getNumArgs();
7425 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
7426 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
7427 return std::move(Err);
7429 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7430 return CXXOperatorCallExpr::Create(
7431 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType,
7432 OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(),
7433 OCE->getADLCallKind());
7436 return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType,
7437 E->getValueKind(), ToRParenLoc, /*MinNumArgs=*/0,
7438 E->getADLCallKind());
7441 ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) {
7442 CXXRecordDecl *FromClass = E->getLambdaClass();
7443 auto ToClassOrErr = import(FromClass);
7445 return ToClassOrErr.takeError();
7446 CXXRecordDecl *ToClass = *ToClassOrErr;
7448 auto ToCallOpOrErr = import(E->getCallOperator());
7450 return ToCallOpOrErr.takeError();
7452 SmallVector<LambdaCapture, 8> ToCaptures;
7453 ToCaptures.reserve(E->capture_size());
7454 for (const auto &FromCapture : E->captures()) {
7455 if (auto ToCaptureOrErr = import(FromCapture))
7456 ToCaptures.push_back(*ToCaptureOrErr);
7458 return ToCaptureOrErr.takeError();
7461 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
7462 if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits))
7463 return std::move(Err);
7465 auto Imp = importSeq(
7466 E->getIntroducerRange(), E->getCaptureDefaultLoc(), E->getEndLoc());
7468 return Imp.takeError();
7470 SourceRange ToIntroducerRange;
7471 SourceLocation ToCaptureDefaultLoc, ToEndLoc;
7472 std::tie(ToIntroducerRange, ToCaptureDefaultLoc, ToEndLoc) = *Imp;
7474 return LambdaExpr::Create(
7475 Importer.getToContext(), ToClass, ToIntroducerRange,
7476 E->getCaptureDefault(), ToCaptureDefaultLoc, ToCaptures,
7477 E->hasExplicitParameters(), E->hasExplicitResultType(), ToCaptureInits,
7478 ToEndLoc, E->containsUnexpandedParameterPack());
7482 ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) {
7483 auto Imp = importSeq(E->getLBraceLoc(), E->getRBraceLoc(), E->getType());
7485 return Imp.takeError();
7487 SourceLocation ToLBraceLoc, ToRBraceLoc;
7489 std::tie(ToLBraceLoc, ToRBraceLoc, ToType) = *Imp;
7491 SmallVector<Expr *, 4> ToExprs(E->getNumInits());
7492 if (Error Err = ImportContainerChecked(E->inits(), ToExprs))
7493 return std::move(Err);
7495 ASTContext &ToCtx = Importer.getToContext();
7496 InitListExpr *To = new (ToCtx) InitListExpr(
7497 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
7498 To->setType(ToType);
7500 if (E->hasArrayFiller()) {
7501 if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller()))
7502 To->setArrayFiller(*ToFillerOrErr);
7504 return ToFillerOrErr.takeError();
7507 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
7508 if (auto ToFDOrErr = import(FromFD))
7509 To->setInitializedFieldInUnion(*ToFDOrErr);
7511 return ToFDOrErr.takeError();
7514 if (InitListExpr *SyntForm = E->getSyntacticForm()) {
7515 if (auto ToSyntFormOrErr = import(SyntForm))
7516 To->setSyntacticForm(*ToSyntFormOrErr);
7518 return ToSyntFormOrErr.takeError();
7521 // Copy InitListExprBitfields, which are not handled in the ctor of
7523 To->sawArrayRangeDesignator(E->hadArrayRangeDesignator());
7528 ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr(
7529 CXXStdInitializerListExpr *E) {
7530 ExpectedType ToTypeOrErr = import(E->getType());
7532 return ToTypeOrErr.takeError();
7534 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7535 if (!ToSubExprOrErr)
7536 return ToSubExprOrErr.takeError();
7538 return new (Importer.getToContext()) CXXStdInitializerListExpr(
7539 *ToTypeOrErr, *ToSubExprOrErr);
7542 ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
7543 CXXInheritedCtorInitExpr *E) {
7544 auto Imp = importSeq(E->getLocation(), E->getType(), E->getConstructor());
7546 return Imp.takeError();
7548 SourceLocation ToLocation;
7550 CXXConstructorDecl *ToConstructor;
7551 std::tie(ToLocation, ToType, ToConstructor) = *Imp;
7553 return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
7554 ToLocation, ToType, ToConstructor, E->constructsVBase(),
7555 E->inheritedFromVBase());
7558 ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
7559 auto Imp = importSeq(E->getType(), E->getCommonExpr(), E->getSubExpr());
7561 return Imp.takeError();
7564 Expr *ToCommonExpr, *ToSubExpr;
7565 std::tie(ToType, ToCommonExpr, ToSubExpr) = *Imp;
7567 return new (Importer.getToContext()) ArrayInitLoopExpr(
7568 ToType, ToCommonExpr, ToSubExpr);
7571 ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
7572 ExpectedType ToTypeOrErr = import(E->getType());
7574 return ToTypeOrErr.takeError();
7575 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
7578 ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
7579 ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc());
7580 if (!ToBeginLocOrErr)
7581 return ToBeginLocOrErr.takeError();
7583 auto ToFieldOrErr = import(E->getField());
7585 return ToFieldOrErr.takeError();
7587 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
7588 if (!UsedContextOrErr)
7589 return UsedContextOrErr.takeError();
7591 return CXXDefaultInitExpr::Create(
7592 Importer.getToContext(), *ToBeginLocOrErr, *ToFieldOrErr, *UsedContextOrErr);
7595 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
7596 auto Imp = importSeq(
7597 E->getType(), E->getSubExpr(), E->getTypeInfoAsWritten(),
7598 E->getOperatorLoc(), E->getRParenLoc(), E->getAngleBrackets());
7600 return Imp.takeError();
7604 TypeSourceInfo *ToTypeInfoAsWritten;
7605 SourceLocation ToOperatorLoc, ToRParenLoc;
7606 SourceRange ToAngleBrackets;
7608 ToType, ToSubExpr, ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc,
7609 ToAngleBrackets) = *Imp;
7611 ExprValueKind VK = E->getValueKind();
7612 CastKind CK = E->getCastKind();
7613 auto ToBasePathOrErr = ImportCastPath(E);
7614 if (!ToBasePathOrErr)
7615 return ToBasePathOrErr.takeError();
7617 if (isa<CXXStaticCastExpr>(E)) {
7618 return CXXStaticCastExpr::Create(
7619 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
7620 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
7621 } else if (isa<CXXDynamicCastExpr>(E)) {
7622 return CXXDynamicCastExpr::Create(
7623 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
7624 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
7625 } else if (isa<CXXReinterpretCastExpr>(E)) {
7626 return CXXReinterpretCastExpr::Create(
7627 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
7628 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
7629 } else if (isa<CXXConstCastExpr>(E)) {
7630 return CXXConstCastExpr::Create(
7631 Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten,
7632 ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
7634 llvm_unreachable("Unknown cast type");
7635 return make_error<ImportError>();
7639 ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
7640 SubstNonTypeTemplateParmExpr *E) {
7641 auto Imp = importSeq(
7642 E->getType(), E->getExprLoc(), E->getParameter(), E->getReplacement());
7644 return Imp.takeError();
7647 SourceLocation ToExprLoc;
7648 NonTypeTemplateParmDecl *ToParameter;
7649 Expr *ToReplacement;
7650 std::tie(ToType, ToExprLoc, ToParameter, ToReplacement) = *Imp;
7652 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
7653 ToType, E->getValueKind(), ToExprLoc, ToParameter, ToReplacement);
7656 ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
7657 auto Imp = importSeq(
7658 E->getType(), E->getBeginLoc(), E->getEndLoc());
7660 return Imp.takeError();
7663 SourceLocation ToBeginLoc, ToEndLoc;
7664 std::tie(ToType, ToBeginLoc, ToEndLoc) = *Imp;
7666 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
7667 if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs))
7668 return std::move(Err);
7670 // According to Sema::BuildTypeTrait(), if E is value-dependent,
7671 // Value is always false.
7672 bool ToValue = (E->isValueDependent() ? false : E->getValue());
7674 return TypeTraitExpr::Create(
7675 Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs,
7679 ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
7680 ExpectedType ToTypeOrErr = import(E->getType());
7682 return ToTypeOrErr.takeError();
7684 auto ToSourceRangeOrErr = import(E->getSourceRange());
7685 if (!ToSourceRangeOrErr)
7686 return ToSourceRangeOrErr.takeError();
7688 if (E->isTypeOperand()) {
7689 if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo()))
7690 return new (Importer.getToContext()) CXXTypeidExpr(
7691 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
7693 return ToTSIOrErr.takeError();
7696 ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand());
7697 if (!ToExprOperandOrErr)
7698 return ToExprOperandOrErr.takeError();
7700 return new (Importer.getToContext()) CXXTypeidExpr(
7701 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
7704 void ASTNodeImporter::ImportOverrides(CXXMethodDecl *ToMethod,
7705 CXXMethodDecl *FromMethod) {
7706 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
7707 if (auto ImportedOrErr = import(FromOverriddenMethod))
7708 ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>(
7709 (*ImportedOrErr)->getCanonicalDecl()));
7711 consumeError(ImportedOrErr.takeError());
7715 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
7716 ASTContext &FromContext, FileManager &FromFileManager,
7718 std::shared_ptr<ASTImporterSharedState> SharedState)
7719 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
7720 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
7721 Minimal(MinimalImport) {
7723 // Create a default state without the lookup table: LLDB case.
7725 this->SharedState = std::make_shared<ASTImporterSharedState>();
7728 ImportedDecls[FromContext.getTranslationUnitDecl()] =
7729 ToContext.getTranslationUnitDecl();
7732 ASTImporter::~ASTImporter() = default;
7734 Optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
7735 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
7736 "Try to get field index for non-field.");
7738 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
7743 for (const auto *D : Owner->decls()) {
7747 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
7751 llvm_unreachable("Field was not found in its parent context.");
7756 ASTImporter::FoundDeclsTy
7757 ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
7758 // We search in the redecl context because of transparent contexts.
7759 // E.g. a simple C language enum is a transparent context:
7761 // Now if we had a global variable in the TU
7763 // then the enum constant 'A' and the variable 'A' violates ODR.
7764 // We can diagnose this only if we search in the redecl context.
7765 DeclContext *ReDC = DC->getRedeclContext();
7766 if (SharedState->getLookupTable()) {
7767 ASTImporterLookupTable::LookupResult LookupResult =
7768 SharedState->getLookupTable()->lookup(ReDC, Name);
7769 return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
7771 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
7772 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
7773 // We must search by the slow case of localUncachedLookup because that is
7774 // working even if there is no LookupPtr for the DC. We could use
7775 // DC::buildLookup() to create the LookupPtr, but that would load external
7776 // decls again, we must avoid that case.
7777 // Also, even if we had the LookupPtr, we must find Decls which are not
7778 // in the LookupPtr, so we need the slow case.
7779 // These cases are handled in ASTImporterLookupTable, but we cannot use
7780 // that with LLDB since that traverses through the AST which initiates the
7781 // load of external decls again via DC::decls(). And again, we must avoid
7782 // loading external decls during the import.
7784 ReDC->localUncachedLookup(Name, Result);
7789 void ASTImporter::AddToLookupTable(Decl *ToD) {
7790 SharedState->addDeclToLookup(ToD);
7793 Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) {
7794 // Import the decl using ASTNodeImporter.
7795 ASTNodeImporter Importer(*this);
7796 return Importer.Visit(FromD);
7799 void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) {
7800 MapImported(FromD, ToD);
7803 Expected<QualType> ASTImporter::Import(QualType FromT) {
7807 const Type *FromTy = FromT.getTypePtr();
7809 // Check whether we've already imported this type.
7810 llvm::DenseMap<const Type *, const Type *>::iterator Pos
7811 = ImportedTypes.find(FromTy);
7812 if (Pos != ImportedTypes.end())
7813 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
7816 ASTNodeImporter Importer(*this);
7817 ExpectedType ToTOrErr = Importer.Visit(FromTy);
7819 return ToTOrErr.takeError();
7821 // Record the imported type.
7822 ImportedTypes[FromTy] = (*ToTOrErr).getTypePtr();
7824 return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers());
7827 Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) {
7831 // FIXME: For now we just create a "trivial" type source info based
7832 // on the type and a single location. Implement a real version of this.
7833 ExpectedType TOrErr = Import(FromTSI->getType());
7835 return TOrErr.takeError();
7836 ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc());
7838 return BeginLocOrErr.takeError();
7840 return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
7843 Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) {
7844 Attr *ToAttr = FromAttr->clone(ToContext);
7845 if (auto ToRangeOrErr = Import(FromAttr->getRange()))
7846 ToAttr->setRange(*ToRangeOrErr);
7848 return ToRangeOrErr.takeError();
7853 Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const {
7854 auto Pos = ImportedDecls.find(FromD);
7855 if (Pos != ImportedDecls.end())
7861 TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) {
7862 auto FromDPos = ImportedFromDecls.find(ToD);
7863 if (FromDPos == ImportedFromDecls.end())
7865 return FromDPos->second->getTranslationUnitDecl();
7868 Expected<Decl *> ASTImporter::Import(Decl *FromD) {
7872 // Push FromD to the stack, and remove that when we return.
7873 ImportPath.push(FromD);
7874 auto ImportPathBuilder =
7875 llvm::make_scope_exit([this]() { ImportPath.pop(); });
7877 // Check whether there was a previous failed import.
7878 // If yes return the existing error.
7879 if (auto Error = getImportDeclErrorIfAny(FromD))
7880 return make_error<ImportError>(*Error);
7882 // Check whether we've already imported this declaration.
7883 Decl *ToD = GetAlreadyImportedOrNull(FromD);
7885 // Already imported (possibly from another TU) and with an error.
7886 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
7887 setImportDeclError(FromD, *Error);
7888 return make_error<ImportError>(*Error);
7891 // If FromD has some updated flags after last import, apply it
7892 updateFlags(FromD, ToD);
7893 // If we encounter a cycle during an import then we save the relevant part
7894 // of the import path associated to the Decl.
7895 if (ImportPath.hasCycleAtBack())
7896 SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack());
7900 // Import the declaration.
7901 ExpectedDecl ToDOrErr = ImportImpl(FromD);
7903 // Failed to import.
7905 auto Pos = ImportedDecls.find(FromD);
7906 if (Pos != ImportedDecls.end()) {
7907 // Import failed after the object was created.
7908 // Remove all references to it.
7909 auto *ToD = Pos->second;
7910 ImportedDecls.erase(Pos);
7912 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen
7913 // (e.g. with namespaces) that several decls from the 'from' context are
7914 // mapped to the same decl in the 'to' context. If we removed entries
7915 // from the LookupTable here then we may end up removing them multiple
7918 // The Lookuptable contains decls only which are in the 'to' context.
7919 // Remove from the Lookuptable only if it is *imported* into the 'to'
7920 // context (and do not remove it if it was added during the initial
7921 // traverse of the 'to' context).
7922 auto PosF = ImportedFromDecls.find(ToD);
7923 if (PosF != ImportedFromDecls.end()) {
7924 SharedState->removeDeclFromLookup(ToD);
7925 ImportedFromDecls.erase(PosF);
7928 // FIXME: AST may contain remaining references to the failed object.
7929 // However, the ImportDeclErrors in the shared state contains all the
7930 // failed objects together with their error.
7933 // Error encountered for the first time.
7934 // After takeError the error is not usable any more in ToDOrErr.
7935 // Get a copy of the error object (any more simple solution for this?).
7937 handleAllErrors(ToDOrErr.takeError(),
7938 [&ErrOut](const ImportError &E) { ErrOut = E; });
7939 setImportDeclError(FromD, ErrOut);
7940 // Set the error for the mapped to Decl, which is in the "to" context.
7941 if (Pos != ImportedDecls.end())
7942 SharedState->setImportDeclError(Pos->second, ErrOut);
7944 // Set the error for all nodes which have been created before we
7945 // recognized the error.
7946 for (const auto &Path : SavedImportPaths[FromD])
7947 for (Decl *FromDi : Path) {
7948 setImportDeclError(FromDi, ErrOut);
7949 //FIXME Should we remove these Decls from ImportedDecls?
7950 // Set the error for the mapped to Decl, which is in the "to" context.
7951 auto Ii = ImportedDecls.find(FromDi);
7952 if (Ii != ImportedDecls.end())
7953 SharedState->setImportDeclError(Ii->second, ErrOut);
7954 // FIXME Should we remove these Decls from the LookupTable,
7955 // and from ImportedFromDecls?
7957 SavedImportPaths[FromD].clear();
7959 // Do not return ToDOrErr, error was taken out of it.
7960 return make_error<ImportError>(ErrOut);
7965 // FIXME: Handle the "already imported with error" case. We can get here
7966 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a
7967 // previously failed create was requested).
7968 // Later GetImportedOrCreateDecl can be updated to return the error.
7970 auto Err = getImportDeclErrorIfAny(FromD);
7972 return make_error<ImportError>(*Err);
7975 // We could import from the current TU without error. But previously we
7976 // already had imported a Decl as `ToD` from another TU (with another
7977 // ASTImporter object) and with an error.
7978 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
7979 setImportDeclError(FromD, *Error);
7980 return make_error<ImportError>(*Error);
7983 // Make sure that ImportImpl registered the imported decl.
7984 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
7986 // Notify subclasses.
7987 Imported(FromD, ToD);
7989 updateFlags(FromD, ToD);
7990 SavedImportPaths[FromD].clear();
7994 Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) {
7998 ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC));
8000 return ToDCOrErr.takeError();
8001 auto *ToDC = cast<DeclContext>(*ToDCOrErr);
8003 // When we're using a record/enum/Objective-C class/protocol as a context, we
8004 // need it to have a definition.
8005 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
8006 auto *FromRecord = cast<RecordDecl>(FromDC);
8007 if (ToRecord->isCompleteDefinition()) {
8009 } else if (FromRecord->isCompleteDefinition()) {
8010 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
8011 FromRecord, ToRecord, ASTNodeImporter::IDK_Basic))
8012 return std::move(Err);
8014 CompleteDecl(ToRecord);
8016 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
8017 auto *FromEnum = cast<EnumDecl>(FromDC);
8018 if (ToEnum->isCompleteDefinition()) {
8020 } else if (FromEnum->isCompleteDefinition()) {
8021 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
8022 FromEnum, ToEnum, ASTNodeImporter::IDK_Basic))
8023 return std::move(Err);
8025 CompleteDecl(ToEnum);
8027 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
8028 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC);
8029 if (ToClass->getDefinition()) {
8031 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
8032 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
8033 FromDef, ToClass, ASTNodeImporter::IDK_Basic))
8034 return std::move(Err);
8036 CompleteDecl(ToClass);
8038 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
8039 auto *FromProto = cast<ObjCProtocolDecl>(FromDC);
8040 if (ToProto->getDefinition()) {
8042 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
8043 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
8044 FromDef, ToProto, ASTNodeImporter::IDK_Basic))
8045 return std::move(Err);
8047 CompleteDecl(ToProto);
8054 Expected<Expr *> ASTImporter::Import(Expr *FromE) {
8055 if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE)))
8056 return cast_or_null<Expr>(*ToSOrErr);
8058 return ToSOrErr.takeError();
8061 Expected<Stmt *> ASTImporter::Import(Stmt *FromS) {
8065 // Check whether we've already imported this statement.
8066 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
8067 if (Pos != ImportedStmts.end())
8070 // Import the statement.
8071 ASTNodeImporter Importer(*this);
8072 ExpectedStmt ToSOrErr = Importer.Visit(FromS);
8076 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) {
8077 auto *FromE = cast<Expr>(FromS);
8078 // Copy ExprBitfields, which may not be handled in Expr subclasses
8080 ToE->setValueKind(FromE->getValueKind());
8081 ToE->setObjectKind(FromE->getObjectKind());
8082 ToE->setTypeDependent(FromE->isTypeDependent());
8083 ToE->setValueDependent(FromE->isValueDependent());
8084 ToE->setInstantiationDependent(FromE->isInstantiationDependent());
8085 ToE->setContainsUnexpandedParameterPack(
8086 FromE->containsUnexpandedParameterPack());
8089 // Record the imported statement object.
8090 ImportedStmts[FromS] = *ToSOrErr;
8094 Expected<NestedNameSpecifier *>
8095 ASTImporter::Import(NestedNameSpecifier *FromNNS) {
8099 NestedNameSpecifier *Prefix = nullptr;
8100 if (Error Err = importInto(Prefix, FromNNS->getPrefix()))
8101 return std::move(Err);
8103 switch (FromNNS->getKind()) {
8104 case NestedNameSpecifier::Identifier:
8105 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
8106 return NestedNameSpecifier::Create(ToContext, Prefix,
8107 Import(FromNNS->getAsIdentifier()));
8109 case NestedNameSpecifier::Namespace:
8110 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) {
8111 return NestedNameSpecifier::Create(ToContext, Prefix,
8112 cast<NamespaceDecl>(*NSOrErr));
8114 return NSOrErr.takeError();
8116 case NestedNameSpecifier::NamespaceAlias:
8117 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias()))
8118 return NestedNameSpecifier::Create(ToContext, Prefix,
8119 cast<NamespaceAliasDecl>(*NSADOrErr));
8121 return NSADOrErr.takeError();
8123 case NestedNameSpecifier::Global:
8124 return NestedNameSpecifier::GlobalSpecifier(ToContext);
8126 case NestedNameSpecifier::Super:
8127 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl()))
8128 return NestedNameSpecifier::SuperSpecifier(ToContext,
8129 cast<CXXRecordDecl>(*RDOrErr));
8131 return RDOrErr.takeError();
8133 case NestedNameSpecifier::TypeSpec:
8134 case NestedNameSpecifier::TypeSpecWithTemplate:
8135 if (Expected<QualType> TyOrErr =
8136 Import(QualType(FromNNS->getAsType(), 0u))) {
8138 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate;
8139 return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate,
8140 TyOrErr->getTypePtr());
8142 return TyOrErr.takeError();
8146 llvm_unreachable("Invalid nested name specifier kind");
8149 Expected<NestedNameSpecifierLoc>
8150 ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
8151 // Copied from NestedNameSpecifier mostly.
8152 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
8153 NestedNameSpecifierLoc NNS = FromNNS;
8155 // Push each of the nested-name-specifiers's onto a stack for
8156 // serialization in reverse order.
8158 NestedNames.push_back(NNS);
8159 NNS = NNS.getPrefix();
8162 NestedNameSpecifierLocBuilder Builder;
8164 while (!NestedNames.empty()) {
8165 NNS = NestedNames.pop_back_val();
8166 NestedNameSpecifier *Spec = nullptr;
8167 if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier()))
8168 return std::move(Err);
8170 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
8172 SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
8173 if (Kind != NestedNameSpecifier::Super) {
8174 if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc()))
8175 return std::move(Err);
8177 if (Kind != NestedNameSpecifier::Global)
8178 if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc()))
8179 return std::move(Err);
8183 case NestedNameSpecifier::Identifier:
8184 Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc,
8188 case NestedNameSpecifier::Namespace:
8189 Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc,
8193 case NestedNameSpecifier::NamespaceAlias:
8194 Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(),
8195 ToLocalBeginLoc, ToLocalEndLoc);
8198 case NestedNameSpecifier::TypeSpec:
8199 case NestedNameSpecifier::TypeSpecWithTemplate: {
8200 SourceLocation ToTLoc;
8201 if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc()))
8202 return std::move(Err);
8203 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
8204 QualType(Spec->getAsType(), 0), ToTLoc);
8205 Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(),
8210 case NestedNameSpecifier::Global:
8211 Builder.MakeGlobal(getToContext(), ToLocalBeginLoc);
8214 case NestedNameSpecifier::Super: {
8215 auto ToSourceRangeOrErr = Import(NNS.getSourceRange());
8216 if (!ToSourceRangeOrErr)
8217 return ToSourceRangeOrErr.takeError();
8219 Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(),
8220 ToSourceRangeOrErr->getBegin(),
8221 ToSourceRangeOrErr->getEnd());
8226 return Builder.getWithLocInContext(getToContext());
8229 Expected<TemplateName> ASTImporter::Import(TemplateName From) {
8230 switch (From.getKind()) {
8231 case TemplateName::Template:
8232 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
8233 return TemplateName(cast<TemplateDecl>(*ToTemplateOrErr));
8235 return ToTemplateOrErr.takeError();
8237 case TemplateName::OverloadedTemplate: {
8238 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
8239 UnresolvedSet<2> ToTemplates;
8240 for (auto *I : *FromStorage) {
8241 if (auto ToOrErr = Import(I))
8242 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr));
8244 return ToOrErr.takeError();
8246 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
8250 case TemplateName::AssumedTemplate: {
8251 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName();
8252 auto DeclNameOrErr = Import(FromStorage->getDeclName());
8254 return DeclNameOrErr.takeError();
8255 return ToContext.getAssumedTemplateName(*DeclNameOrErr);
8258 case TemplateName::QualifiedTemplate: {
8259 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
8260 auto QualifierOrErr = Import(QTN->getQualifier());
8261 if (!QualifierOrErr)
8262 return QualifierOrErr.takeError();
8264 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
8265 return ToContext.getQualifiedTemplateName(
8266 *QualifierOrErr, QTN->hasTemplateKeyword(),
8267 cast<TemplateDecl>(*ToTemplateOrErr));
8269 return ToTemplateOrErr.takeError();
8272 case TemplateName::DependentTemplate: {
8273 DependentTemplateName *DTN = From.getAsDependentTemplateName();
8274 auto QualifierOrErr = Import(DTN->getQualifier());
8275 if (!QualifierOrErr)
8276 return QualifierOrErr.takeError();
8278 if (DTN->isIdentifier()) {
8279 return ToContext.getDependentTemplateName(*QualifierOrErr,
8280 Import(DTN->getIdentifier()));
8283 return ToContext.getDependentTemplateName(*QualifierOrErr,
8284 DTN->getOperator());
8287 case TemplateName::SubstTemplateTemplateParm: {
8288 SubstTemplateTemplateParmStorage *Subst =
8289 From.getAsSubstTemplateTemplateParm();
8290 ExpectedDecl ParamOrErr = Import(Subst->getParameter());
8292 return ParamOrErr.takeError();
8294 auto ReplacementOrErr = Import(Subst->getReplacement());
8295 if (!ReplacementOrErr)
8296 return ReplacementOrErr.takeError();
8298 return ToContext.getSubstTemplateTemplateParm(
8299 cast<TemplateTemplateParmDecl>(*ParamOrErr), *ReplacementOrErr);
8302 case TemplateName::SubstTemplateTemplateParmPack: {
8303 SubstTemplateTemplateParmPackStorage *SubstPack
8304 = From.getAsSubstTemplateTemplateParmPack();
8305 ExpectedDecl ParamOrErr = Import(SubstPack->getParameterPack());
8307 return ParamOrErr.takeError();
8309 ASTNodeImporter Importer(*this);
8311 Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
8313 return ArgPackOrErr.takeError();
8315 return ToContext.getSubstTemplateTemplateParmPack(
8316 cast<TemplateTemplateParmDecl>(*ParamOrErr), *ArgPackOrErr);
8320 llvm_unreachable("Invalid template name kind");
8323 Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) {
8324 if (FromLoc.isInvalid())
8325 return SourceLocation{};
8327 SourceManager &FromSM = FromContext.getSourceManager();
8328 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc);
8330 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
8331 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
8333 return ToFileIDOrErr.takeError();
8334 SourceManager &ToSM = ToContext.getSourceManager();
8335 return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second);
8338 Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) {
8339 SourceLocation ToBegin, ToEnd;
8340 if (Error Err = importInto(ToBegin, FromRange.getBegin()))
8341 return std::move(Err);
8342 if (Error Err = importInto(ToEnd, FromRange.getEnd()))
8343 return std::move(Err);
8345 return SourceRange(ToBegin, ToEnd);
8348 Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
8349 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID);
8350 if (Pos != ImportedFileIDs.end())
8353 SourceManager &FromSM = FromContext.getSourceManager();
8354 SourceManager &ToSM = ToContext.getSourceManager();
8355 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
8357 // Map the FromID to the "to" source manager.
8359 if (FromSLoc.isExpansion()) {
8360 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
8361 ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc());
8363 return ToSpLoc.takeError();
8364 ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart());
8366 return ToExLocS.takeError();
8367 unsigned TokenLen = FromSM.getFileIDSize(FromID);
8368 SourceLocation MLoc;
8369 if (FromEx.isMacroArgExpansion()) {
8370 MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, TokenLen);
8372 if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd()))
8373 MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, TokenLen,
8374 FromEx.isExpansionTokenRange());
8376 return ToExLocE.takeError();
8378 ToID = ToSM.getFileID(MLoc);
8380 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
8383 // Include location of this file.
8384 ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
8386 return ToIncludeLoc.takeError();
8388 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
8389 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
8391 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
8392 // than mmap the files several times.
8393 const FileEntry *Entry =
8394 ToFileManager.getFile(Cache->OrigEntry->getName());
8395 // FIXME: The filename may be a virtual name that does probably not
8396 // point to a valid file and we get no Entry here. In this case try with
8397 // the memory buffer below.
8399 ToID = ToSM.createFileID(Entry, *ToIncludeLoc,
8400 FromSLoc.getFile().getFileCharacteristic());
8404 if (ToID.isInvalid() || IsBuiltin) {
8405 // FIXME: We want to re-use the existing MemoryBuffer!
8406 bool Invalid = true;
8407 const llvm::MemoryBuffer *FromBuf = Cache->getBuffer(
8408 FromContext.getDiagnostics(), FromSM, SourceLocation{}, &Invalid);
8409 if (!FromBuf || Invalid)
8410 // FIXME: Use a new error kind?
8411 return llvm::make_error<ImportError>(ImportError::Unknown);
8413 std::unique_ptr<llvm::MemoryBuffer> ToBuf =
8414 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
8415 FromBuf->getBufferIdentifier());
8416 ToID = ToSM.createFileID(std::move(ToBuf),
8417 FromSLoc.getFile().getFileCharacteristic());
8421 assert(ToID.isValid() && "Unexpected invalid fileID was created.");
8423 ImportedFileIDs[FromID] = ToID;
8427 Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) {
8428 ExpectedExpr ToExprOrErr = Import(From->getInit());
8430 return ToExprOrErr.takeError();
8432 auto LParenLocOrErr = Import(From->getLParenLoc());
8433 if (!LParenLocOrErr)
8434 return LParenLocOrErr.takeError();
8436 auto RParenLocOrErr = Import(From->getRParenLoc());
8437 if (!RParenLocOrErr)
8438 return RParenLocOrErr.takeError();
8440 if (From->isBaseInitializer()) {
8441 auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
8443 return ToTInfoOrErr.takeError();
8445 SourceLocation EllipsisLoc;
8446 if (From->isPackExpansion())
8447 if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc()))
8448 return std::move(Err);
8450 return new (ToContext) CXXCtorInitializer(
8451 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
8452 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
8453 } else if (From->isMemberInitializer()) {
8454 ExpectedDecl ToFieldOrErr = Import(From->getMember());
8456 return ToFieldOrErr.takeError();
8458 auto MemberLocOrErr = Import(From->getMemberLocation());
8459 if (!MemberLocOrErr)
8460 return MemberLocOrErr.takeError();
8462 return new (ToContext) CXXCtorInitializer(
8463 ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr,
8464 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
8465 } else if (From->isIndirectMemberInitializer()) {
8466 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember());
8468 return ToIFieldOrErr.takeError();
8470 auto MemberLocOrErr = Import(From->getMemberLocation());
8471 if (!MemberLocOrErr)
8472 return MemberLocOrErr.takeError();
8474 return new (ToContext) CXXCtorInitializer(
8475 ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr),
8476 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
8477 } else if (From->isDelegatingInitializer()) {
8478 auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
8480 return ToTInfoOrErr.takeError();
8482 return new (ToContext)
8483 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
8484 *ToExprOrErr, *RParenLocOrErr);
8487 return make_error<ImportError>();
8491 Expected<CXXBaseSpecifier *>
8492 ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
8493 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
8494 if (Pos != ImportedCXXBaseSpecifiers.end())
8497 Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange());
8499 return ToSourceRange.takeError();
8500 Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo());
8502 return ToTSI.takeError();
8503 ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc());
8505 return ToEllipsisLoc.takeError();
8506 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
8507 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
8508 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
8509 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
8513 Error ASTImporter::ImportDefinition(Decl *From) {
8514 ExpectedDecl ToOrErr = Import(From);
8516 return ToOrErr.takeError();
8517 Decl *To = *ToOrErr;
8519 auto *FromDC = cast<DeclContext>(From);
8520 ASTNodeImporter Importer(*this);
8522 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) {
8523 if (!ToRecord->getDefinition()) {
8524 return Importer.ImportDefinition(
8525 cast<RecordDecl>(FromDC), ToRecord,
8526 ASTNodeImporter::IDK_Everything);
8530 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) {
8531 if (!ToEnum->getDefinition()) {
8532 return Importer.ImportDefinition(
8533 cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything);
8537 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
8538 if (!ToIFace->getDefinition()) {
8539 return Importer.ImportDefinition(
8540 cast<ObjCInterfaceDecl>(FromDC), ToIFace,
8541 ASTNodeImporter::IDK_Everything);
8545 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
8546 if (!ToProto->getDefinition()) {
8547 return Importer.ImportDefinition(
8548 cast<ObjCProtocolDecl>(FromDC), ToProto,
8549 ASTNodeImporter::IDK_Everything);
8553 return Importer.ImportDeclContext(FromDC, true);
8556 Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) {
8558 return DeclarationName{};
8560 switch (FromName.getNameKind()) {
8561 case DeclarationName::Identifier:
8562 return DeclarationName(Import(FromName.getAsIdentifierInfo()));
8564 case DeclarationName::ObjCZeroArgSelector:
8565 case DeclarationName::ObjCOneArgSelector:
8566 case DeclarationName::ObjCMultiArgSelector:
8567 if (auto ToSelOrErr = Import(FromName.getObjCSelector()))
8568 return DeclarationName(*ToSelOrErr);
8570 return ToSelOrErr.takeError();
8572 case DeclarationName::CXXConstructorName: {
8573 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
8574 return ToContext.DeclarationNames.getCXXConstructorName(
8575 ToContext.getCanonicalType(*ToTyOrErr));
8577 return ToTyOrErr.takeError();
8580 case DeclarationName::CXXDestructorName: {
8581 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
8582 return ToContext.DeclarationNames.getCXXDestructorName(
8583 ToContext.getCanonicalType(*ToTyOrErr));
8585 return ToTyOrErr.takeError();
8588 case DeclarationName::CXXDeductionGuideName: {
8589 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate()))
8590 return ToContext.DeclarationNames.getCXXDeductionGuideName(
8591 cast<TemplateDecl>(*ToTemplateOrErr));
8593 return ToTemplateOrErr.takeError();
8596 case DeclarationName::CXXConversionFunctionName: {
8597 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
8598 return ToContext.DeclarationNames.getCXXConversionFunctionName(
8599 ToContext.getCanonicalType(*ToTyOrErr));
8601 return ToTyOrErr.takeError();
8604 case DeclarationName::CXXOperatorName:
8605 return ToContext.DeclarationNames.getCXXOperatorName(
8606 FromName.getCXXOverloadedOperator());
8608 case DeclarationName::CXXLiteralOperatorName:
8609 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
8610 Import(FromName.getCXXLiteralIdentifier()));
8612 case DeclarationName::CXXUsingDirective:
8614 return DeclarationName::getUsingDirectiveName();
8617 llvm_unreachable("Invalid DeclarationName Kind!");
8620 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
8624 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
8626 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
8627 ToId->setBuiltinID(FromId->getBuiltinID());
8632 Expected<Selector> ASTImporter::Import(Selector FromSel) {
8633 if (FromSel.isNull())
8636 SmallVector<IdentifierInfo *, 4> Idents;
8637 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
8638 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
8639 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
8640 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
8643 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
8647 unsigned NumDecls) {
8651 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
8652 if (LastDiagFromFrom)
8653 ToContext.getDiagnostics().notePriorDiagnosticFrom(
8654 FromContext.getDiagnostics());
8655 LastDiagFromFrom = false;
8656 return ToContext.getDiagnostics().Report(Loc, DiagID);
8659 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
8660 if (!LastDiagFromFrom)
8661 FromContext.getDiagnostics().notePriorDiagnosticFrom(
8662 ToContext.getDiagnostics());
8663 LastDiagFromFrom = true;
8664 return FromContext.getDiagnostics().Report(Loc, DiagID);
8667 void ASTImporter::CompleteDecl (Decl *D) {
8668 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8669 if (!ID->getDefinition())
8670 ID->startDefinition();
8672 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) {
8673 if (!PD->getDefinition())
8674 PD->startDefinition();
8676 else if (auto *TD = dyn_cast<TagDecl>(D)) {
8677 if (!TD->getDefinition() && !TD->isBeingDefined()) {
8678 TD->startDefinition();
8679 TD->setCompleteDefinition(true);
8683 assert(0 && "CompleteDecl called on a Decl that can't be completed");
8687 Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
8688 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From);
8689 assert((Pos == ImportedDecls.end() || Pos->second == To) &&
8690 "Try to import an already imported Decl");
8691 if (Pos != ImportedDecls.end())
8693 ImportedDecls[From] = To;
8694 // This mapping should be maintained only in this function. Therefore do not
8695 // check for additional consistency.
8696 ImportedFromDecls[To] = From;
8697 AddToLookupTable(To);
8701 llvm::Optional<ImportError>
8702 ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const {
8703 auto Pos = ImportDeclErrors.find(FromD);
8704 if (Pos != ImportDeclErrors.end())
8707 return Optional<ImportError>();
8710 void ASTImporter::setImportDeclError(Decl *From, ImportError Error) {
8711 auto InsertRes = ImportDeclErrors.insert({From, Error});
8713 // Either we set the error for the first time, or we already had set one and
8714 // now we want to set the same error.
8715 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
8718 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
8720 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
8721 ImportedTypes.find(From.getTypePtr());
8722 if (Pos != ImportedTypes.end()) {
8723 if (ExpectedType ToFromOrErr = Import(From)) {
8724 if (ToContext.hasSameType(*ToFromOrErr, To))
8727 llvm::consumeError(ToFromOrErr.takeError());
8731 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
8732 getStructuralEquivalenceKind(*this), false,
8734 return Ctx.IsEquivalent(From, To);