//===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTImporter class which imports AST nodes from one // context into another context. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTImporter.h" #include "clang/AST/Attr.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/TypeVisitor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Sema/Sema.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/FileSystem.h" #include namespace clang { class ASTNodeImporter : public TypeVisitor, public DeclVisitor, public StmtVisitor { ASTImporter &Importer; public: explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { } using TypeVisitor::Visit; using DeclVisitor::Visit; using StmtVisitor::Visit; // Importing types QualType VisitType(const Type *T); QualType VisitAttributedType(const AttributedType *T); QualType VisitBuiltinType(const BuiltinType *T); QualType VisitDecayedType(const DecayedType *T); QualType VisitComplexType(const ComplexType *T); QualType VisitPointerType(const PointerType *T); QualType VisitBlockPointerType(const BlockPointerType *T); QualType VisitLValueReferenceType(const LValueReferenceType *T); QualType VisitRValueReferenceType(const RValueReferenceType *T); QualType VisitMemberPointerType(const MemberPointerType *T); QualType VisitConstantArrayType(const ConstantArrayType *T); QualType VisitIncompleteArrayType(const IncompleteArrayType *T); QualType VisitVariableArrayType(const VariableArrayType *T); QualType VisitDependentSizedArrayType(const DependentSizedArrayType *T); // FIXME: DependentSizedExtVectorType QualType VisitVectorType(const VectorType *T); QualType VisitExtVectorType(const ExtVectorType *T); QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T); QualType VisitFunctionProtoType(const FunctionProtoType *T); QualType VisitUnresolvedUsingType(const UnresolvedUsingType *T); QualType VisitParenType(const ParenType *T); QualType VisitTypedefType(const TypedefType *T); QualType VisitTypeOfExprType(const TypeOfExprType *T); // FIXME: DependentTypeOfExprType QualType VisitTypeOfType(const TypeOfType *T); QualType VisitDecltypeType(const DecltypeType *T); QualType VisitUnaryTransformType(const UnaryTransformType *T); QualType VisitAutoType(const AutoType *T); QualType VisitInjectedClassNameType(const InjectedClassNameType *T); // FIXME: DependentDecltypeType QualType VisitRecordType(const RecordType *T); QualType VisitEnumType(const EnumType *T); QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T); QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T); QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T); QualType VisitElaboratedType(const ElaboratedType *T); QualType VisitDependentNameType(const DependentNameType *T); QualType VisitPackExpansionType(const PackExpansionType *T); QualType VisitDependentTemplateSpecializationType( const DependentTemplateSpecializationType *T); QualType VisitObjCInterfaceType(const ObjCInterfaceType *T); QualType VisitObjCObjectType(const ObjCObjectType *T); QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); // Importing declarations bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, DeclarationName &Name, SourceLocation &Loc); void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = 0); void ImportDeclarationNameLoc(const DeclarationNameInfo &From, DeclarationNameInfo& To); void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); bool ImportCastPath(CastExpr *E, CXXCastPath &Path); bool ImportVarDeclInfo(VarDecl *From, VarDecl *To); typedef DesignatedInitExpr::Designator Designator; Designator ImportDesignator(const Designator &D); /// \brief What we should import from the definition. enum ImportDefinitionKind { /// \brief Import the default subset of the definition, which might be /// nothing (if minimal import is set) or might be everything (if minimal /// import is not set). IDK_Default, /// \brief Import everything. IDK_Everything, /// \brief Import only the bare bones needed to establish a valid /// DeclContext. IDK_Basic }; bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { return IDK == IDK_Everything || (IDK == IDK_Default && !Importer.isMinimalImport()); } bool ImportDefinition(FunctionDecl *From, FunctionDecl *To); bool ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind = IDK_Default); bool ImportDefinition(VarDecl *From, VarDecl *To, ImportDefinitionKind Kind = IDK_Default); bool ImportDefinition(EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind = IDK_Default); bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind = IDK_Default); bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind = IDK_Default); void ImportAttributes(Decl *From, Decl *To); TemplateParameterList *ImportTemplateParameterList( TemplateParameterList *Params); TemplateArgument ImportTemplateArgument(const TemplateArgument &From); TemplateArgumentLoc ImportTemplateArgumentLoc( const TemplateArgumentLoc &TALoc); bool ImportTemplateArguments(const TemplateArgument *FromArgs, unsigned NumFromArgs, SmallVectorImpl &ToArgs); bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, bool Complain = true); bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, bool Complain = true); bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord); bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC); bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To, bool Complain = true); bool IsStructuralMatch(FunctionTemplateDecl *From, FunctionTemplateDecl *To); bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To); Decl *VisitDecl(Decl *D); Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); Decl *VisitEmptyDecl(EmptyDecl *D); Decl *VisitNamespaceDecl(NamespaceDecl *D); Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D); Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D); Decl *VisitUsingDecl(UsingDecl *D); Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); Decl *VisitUsingShadowDecl(UsingShadowDecl *D); Decl *VisitStaticAssertDecl(StaticAssertDecl *D); Decl *VisitAccessSpecDecl(AccessSpecDecl *D); Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); Decl *VisitTypedefDecl(TypedefDecl *D); Decl *VisitTypeAliasDecl(TypeAliasDecl *D); Decl *VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); Decl *VisitLabelDecl(LabelDecl *D); Decl *VisitEnumDecl(EnumDecl *D); Decl *VisitRecordDecl(RecordDecl *D); Decl *VisitEnumConstantDecl(EnumConstantDecl *D); Decl *VisitFunctionDecl(FunctionDecl *D); Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); Decl *VisitCXXMethodDecl(CXXMethodDecl *D); Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); Decl *VisitCXXConversionDecl(CXXConversionDecl *D); Decl *VisitFieldDecl(FieldDecl *D); Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D); Decl *VisitFriendDecl(FriendDecl *D); Decl *VisitObjCIvarDecl(ObjCIvarDecl *D); Decl *VisitVarDecl(VarDecl *D); Decl *VisitImplicitParamDecl(ImplicitParamDecl *D); Decl *VisitParmVarDecl(ParmVarDecl *D); Decl *VisitObjCMethodDecl(ObjCMethodDecl *D); Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D); Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D); Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D); Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D); Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); Decl *VisitClassTemplateSpecializationDecl( ClassTemplateSpecializationDecl *D); Decl *VisitVarTemplateDecl(VarTemplateDecl *D); Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); // Importing statements Stmt *VisitStmt(Stmt *S); Stmt *VisitGCCAsmStmt(GCCAsmStmt *S); Stmt *VisitGotoStmt(GotoStmt *S); Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S); Stmt *VisitLabelStmt(LabelStmt *S); Stmt *VisitAttributedStmt(AttributedStmt *S); Stmt *VisitCompoundStmt(CompoundStmt *S); Stmt *VisitDeclStmt(DeclStmt *S); Stmt *VisitIfStmt(IfStmt *S); Stmt *VisitForStmt(ForStmt *S); Stmt *VisitDoStmt(DoStmt *S); Stmt *VisitWhileStmt(WhileStmt *S); Stmt *VisitSwitchStmt(SwitchStmt *S); Stmt *VisitCaseStmt(CaseStmt *S); Stmt *VisitDefaultStmt(DefaultStmt *S); Stmt *VisitBreakStmt(BreakStmt *S); Stmt *VisitContinueStmt(ContinueStmt *S); Stmt *VisitNullStmt(NullStmt *S); Stmt *VisitReturnStmt(ReturnStmt *S); Stmt *VisitCXXTryStmt(CXXTryStmt *S); Stmt *VisitCXXCatchStmt(CXXCatchStmt *S); // Importing expressions Expr *VisitExpr(Expr *E); Expr *VisitVAArgExpr(VAArgExpr *E); Expr *VisitGNUNullExpr(GNUNullExpr *E); Expr *VisitPredefinedExpr(PredefinedExpr *E); Expr *VisitDeclRefExpr(DeclRefExpr *E); Expr *VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); Expr *VisitInitListExpr(InitListExpr *ILE); Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E); Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); Expr *VisitIntegerLiteral(IntegerLiteral *E); Expr *VisitFloatingLiteral(FloatingLiteral *E); Expr *VisitCharacterLiteral(CharacterLiteral *E); Expr *VisitStringLiteral(StringLiteral *E); Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E); Expr *VisitAtomicExpr(AtomicExpr *E); Expr *VisitAddrLabelExpr(AddrLabelExpr *E); Expr *VisitParenExpr(ParenExpr *E); Expr *VisitParenListExpr(ParenListExpr *E); Expr *VisitStmtExpr(StmtExpr *E); Expr *VisitUnaryOperator(UnaryOperator *E); Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); Expr *VisitBinaryOperator(BinaryOperator *E); Expr *VisitConditionalOperator(ConditionalOperator *E); Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E); Expr *VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E); Expr *VisitExpressionTraitExpr(ExpressionTraitExpr *E); Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E); Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E); Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E); Expr *VisitImplicitCastExpr(ImplicitCastExpr *E); Expr *VisitExplicitCastExpr(ExplicitCastExpr *E); Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); Expr *VisitOffsetOfExpr(OffsetOfExpr *E); Expr *VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E); Expr *VisitMemberExpr(MemberExpr *E); Expr *VisitCXXThisExpr(CXXThisExpr *E); Expr *VisitCXXThrowExpr(CXXThrowExpr *E); Expr *VisitCXXNoexceptExpr(CXXNoexceptExpr *E); Expr *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); Expr *VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE); Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); Expr *VisitOverloadExpr(OverloadExpr *E); Expr *VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); Expr *VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *CE); Expr *VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); Expr *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); Expr *VisitSizeOfPackExpr(SizeOfPackExpr *E); Expr *VisitPackExpansionExpr(PackExpansionExpr *E); Expr *VisitCXXNewExpr(CXXNewExpr *CE); Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E); Expr *VisitCXXConstructExpr(CXXConstructExpr *CE); Expr *VisitExprWithCleanups(ExprWithCleanups *E); Expr *VisitCallExpr(CallExpr *CE); }; } using namespace clang; //---------------------------------------------------------------------------- // Structural Equivalence //---------------------------------------------------------------------------- namespace { struct StructuralEquivalenceContext { /// \brief AST contexts for which we are checking structural equivalence. ASTContext &C1, &C2; /// \brief The set of "tentative" equivalences between two canonical /// declarations, mapping from a declaration in the first context to the /// declaration in the second context that we believe to be equivalent. llvm::DenseMap TentativeEquivalences; /// \brief Queue of declarations in the first context whose equivalence /// with a declaration in the second context still needs to be verified. std::deque DeclsToCheck; /// \brief Declaration (from, to) pairs that are known not to be equivalent /// (which we have already complained about). llvm::DenseSet > &NonEquivalentDecls; /// \brief Whether we're being strict about the spelling of types when /// unifying two types. bool StrictTypeSpelling; /// \brief Whether to complain about failures. bool Complain; /// \brief \c true if the last diagnostic came from C2. bool LastDiagFromC2; StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2, llvm::DenseSet > &NonEquivalentDecls, bool StrictTypeSpelling = false, bool Complain = true) : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls), StrictTypeSpelling(StrictTypeSpelling), Complain(Complain), LastDiagFromC2(false) {} /// \brief Determine whether the two declarations are structurally /// equivalent. bool IsStructurallyEquivalent(Decl *D1, Decl *D2); /// \brief Determine whether the two types are structurally equivalent. bool IsStructurallyEquivalent(QualType T1, QualType T2, bool CheckQualifiers = true); private: /// \brief Finish checking all of the structural equivalences. /// /// \returns true if an error occurred, false otherwise. bool Finish(); public: DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) { assert(Complain && "Not allowed to complain"); if (LastDiagFromC2) C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics()); LastDiagFromC2 = false; return C1.getDiagnostics().Report(Loc, DiagID); } DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) { assert(Complain && "Not allowed to complain"); if (!LastDiagFromC2) C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics()); LastDiagFromC2 = true; return C2.getDiagnostics().Report(Loc, DiagID); } }; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, QualType T1, QualType T2, bool CheckQualifiers = true); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1, Decl *D2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const TemplateArgument &Arg1, const TemplateArgument &Arg2); /// \brief Determine structural equivalence of two expressions. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Expr *E1, Expr *E2) { if (!E1 || !E2) return E1 == E2; // FIXME: Actually perform a structural comparison! return true; } /// \brief Determine whether two identifiers are equivalent. static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, const IdentifierInfo *Name2) { if (!Name1 || !Name2) return Name1 == Name2; return Name1->getName() == Name2->getName(); } /// \brief Determine whether two nested-name-specifiers are equivalent. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, NestedNameSpecifier *NNS1, NestedNameSpecifier *NNS2) { if (NNS1->getKind() != NNS2->getKind()) return false; NestedNameSpecifier *Prefix1 = NNS1->getPrefix(), *Prefix2 = NNS2->getPrefix(); if ((bool)Prefix1 ^ (bool)Prefix2) return false; if (Prefix1) if (!IsStructurallyEquivalent(Context, Prefix1, Prefix2)) return false; switch (NNS1->getKind()) { case NestedNameSpecifier::Identifier: return IsStructurallyEquivalent(NNS1->getAsIdentifier(), NNS2->getAsIdentifier()); case NestedNameSpecifier::Namespace: return IsStructurallyEquivalent(Context, NNS1->getAsNamespace(), NNS2->getAsNamespace()); case NestedNameSpecifier::NamespaceAlias: return IsStructurallyEquivalent(Context, NNS1->getAsNamespaceAlias(), NNS2->getAsNamespaceAlias()); case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: return IsStructurallyEquivalent(Context, QualType(NNS1->getAsType(), 0), QualType(NNS2->getAsType(), 0)); case NestedNameSpecifier::Global: return true; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const TemplateName &N1, const TemplateName &N2) { if (N1.getKind() != N2.getKind()) return false; switch (N1.getKind()) { case TemplateName::Template: return IsStructurallyEquivalent(Context, N1.getAsTemplateDecl(), N2.getAsTemplateDecl()); case TemplateName::OverloadedTemplate: { OverloadedTemplateStorage *OS1 = N1.getAsOverloadedTemplate(), *OS2 = N2.getAsOverloadedTemplate(); OverloadedTemplateStorage::iterator I1 = OS1->begin(), I2 = OS2->begin(), E1 = OS1->end(), E2 = OS2->end(); for (; I1 != E1 && I2 != E2; ++I1, ++I2) if (!IsStructurallyEquivalent(Context, *I1, *I2)) return false; return I1 == E1 && I2 == E2; } case TemplateName::QualifiedTemplate: { QualifiedTemplateName *QN1 = N1.getAsQualifiedTemplateName(), *QN2 = N2.getAsQualifiedTemplateName(); return IsStructurallyEquivalent(Context, QN1->getDecl(), QN2->getDecl()) && IsStructurallyEquivalent(Context, QN1->getQualifier(), QN2->getQualifier()); } case TemplateName::DependentTemplate: { DependentTemplateName *DN1 = N1.getAsDependentTemplateName(), *DN2 = N2.getAsDependentTemplateName(); if (!IsStructurallyEquivalent(Context, DN1->getQualifier(), DN2->getQualifier())) return false; if (DN1->isIdentifier()) return IsStructurallyEquivalent(DN1->getIdentifier(), DN2->getIdentifier()); return DN1->getOperator() == DN2->getOperator(); } case TemplateName::SubstTemplateTemplateParm: { SubstTemplateTemplateParmStorage *TS1 = N1.getAsSubstTemplateTemplateParm(), *TS2 = N2.getAsSubstTemplateTemplateParm(); return IsStructurallyEquivalent(Context, TS1->getParameter(), TS2->getParameter()) && IsStructurallyEquivalent(Context, TS1->getReplacement(), TS2->getReplacement()); } case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *P1 = N1.getAsSubstTemplateTemplateParmPack(), *P2 = N2.getAsSubstTemplateTemplateParmPack(); return IsStructurallyEquivalent(Context, P1->getArgumentPack(), P2->getArgumentPack()) && IsStructurallyEquivalent(Context, P1->getParameterPack(), P2->getParameterPack()); } } return true; } /// \brief Determine whether two template arguments are equivalent. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const TemplateArgument &Arg1, const TemplateArgument &Arg2) { if (Arg1.getKind() != Arg2.getKind()) return false; switch (Arg1.getKind()) { case TemplateArgument::Null: return true; case TemplateArgument::Type: return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType()); case TemplateArgument::Integral: if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(), Arg2.getIntegralType())) return false; return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral()); case TemplateArgument::Declaration: return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl()); case TemplateArgument::NullPtr: return true; // FIXME: Is this correct? case TemplateArgument::Template: return IsStructurallyEquivalent(Context, Arg1.getAsTemplate(), Arg2.getAsTemplate()); case TemplateArgument::TemplateExpansion: return IsStructurallyEquivalent(Context, Arg1.getAsTemplateOrTemplatePattern(), Arg2.getAsTemplateOrTemplatePattern()); case TemplateArgument::Expression: return IsStructurallyEquivalent(Context, Arg1.getAsExpr(), Arg2.getAsExpr()); case TemplateArgument::Pack: if (Arg1.pack_size() != Arg2.pack_size()) return false; for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I) if (!IsStructurallyEquivalent(Context, Arg1.pack_begin()[I], Arg2.pack_begin()[I])) return false; return true; } llvm_unreachable("Invalid template argument kind"); } /// \brief Determine structural equivalence for the common part of array /// types. static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context, const ArrayType *Array1, const ArrayType *Array2) { if (!IsStructurallyEquivalent(Context, Array1->getElementType(), Array2->getElementType())) return false; if (Array1->getSizeModifier() != Array2->getSizeModifier()) return false; if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers()) return false; return true; } /// \brief Determine structural equivalence of two types. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, QualType T1, QualType T2, bool CheckQualifiers) { if (T1.isNull() || T2.isNull()) return T1.isNull() && T2.isNull(); if (!Context.StrictTypeSpelling) { // We aren't being strict about token-to-token equivalence of types, // so map down to the canonical type. T1 = Context.C1.getCanonicalType(T1); T2 = Context.C2.getCanonicalType(T2); } if (CheckQualifiers && T1.getQualifiers() != T2.getQualifiers()) return false; Type::TypeClass TC = T1->getTypeClass(); if (T1->getTypeClass() != T2->getTypeClass()) { // Compare function types with prototypes vs. without prototypes as if // both did not have prototypes. if (T1->getTypeClass() == Type::FunctionProto && T2->getTypeClass() == Type::FunctionNoProto) TC = Type::FunctionNoProto; else if (T1->getTypeClass() == Type::FunctionNoProto && T2->getTypeClass() == Type::FunctionProto) TC = Type::FunctionNoProto; else return false; } switch (TC) { case Type::Builtin: // FIXME: Deal with Char_S/Char_U. if (cast(T1)->getKind() != cast(T2)->getKind()) return false; break; case Type::Complex: if (!IsStructurallyEquivalent(Context, cast(T1)->getElementType(), cast(T2)->getElementType())) return false; break; case Type::Decayed: if (!IsStructurallyEquivalent(Context, cast(T1)->getPointeeType(), cast(T2)->getPointeeType())) return false; break; case Type::Pointer: if (!IsStructurallyEquivalent(Context, cast(T1)->getPointeeType(), cast(T2)->getPointeeType())) return false; break; case Type::BlockPointer: if (!IsStructurallyEquivalent(Context, cast(T1)->getPointeeType(), cast(T2)->getPointeeType())) return false; break; case Type::LValueReference: case Type::RValueReference: { const ReferenceType *Ref1 = cast(T1); const ReferenceType *Ref2 = cast(T2); if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue()) return false; if (Ref1->isInnerRef() != Ref2->isInnerRef()) return false; if (!IsStructurallyEquivalent(Context, Ref1->getPointeeTypeAsWritten(), Ref2->getPointeeTypeAsWritten())) return false; break; } case Type::MemberPointer: { const MemberPointerType *MemPtr1 = cast(T1); const MemberPointerType *MemPtr2 = cast(T2); if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(), MemPtr2->getPointeeType())) return false; if (!IsStructurallyEquivalent(Context, QualType(MemPtr1->getClass(), 0), QualType(MemPtr2->getClass(), 0))) return false; break; } case Type::ConstantArray: { const ConstantArrayType *Array1 = cast(T1); const ConstantArrayType *Array2 = cast(T2); if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize())) return false; if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) return false; break; } case Type::IncompleteArray: if (!IsArrayStructurallyEquivalent(Context, cast(T1), cast(T2))) return false; break; case Type::VariableArray: { const VariableArrayType *Array1 = cast(T1); const VariableArrayType *Array2 = cast(T2); if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), Array2->getSizeExpr())) return false; if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) return false; break; } case Type::DependentSizedArray: { const DependentSizedArrayType *Array1 = cast(T1); const DependentSizedArrayType *Array2 = cast(T2); if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), Array2->getSizeExpr())) return false; if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) return false; break; } case Type::DependentSizedExtVector: { const DependentSizedExtVectorType *Vec1 = cast(T1); const DependentSizedExtVectorType *Vec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), Vec2->getSizeExpr())) return false; if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), Vec2->getElementType())) return false; break; } case Type::Vector: case Type::ExtVector: { const VectorType *Vec1 = cast(T1); const VectorType *Vec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), Vec2->getElementType())) return false; if (Vec1->getNumElements() != Vec2->getNumElements()) return false; if (Vec1->getVectorKind() != Vec2->getVectorKind()) return false; break; } case Type::FunctionProto: { const FunctionProtoType *Proto1 = cast(T1); const FunctionProtoType *Proto2 = cast(T2); if (Proto1->getNumArgs() != Proto2->getNumArgs()) return false; for (unsigned I = 0, N = Proto1->getNumArgs(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Proto1->getArgType(I), Proto2->getArgType(I))) return false; } if (Proto1->isVariadic() != Proto2->isVariadic()) return false; if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType()) return false; if (Proto1->getExceptionSpecType() == EST_Dynamic) { if (Proto1->getNumExceptions() != Proto2->getNumExceptions()) return false; for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Proto1->getExceptionType(I), Proto2->getExceptionType(I))) return false; } } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) { if (!IsStructurallyEquivalent(Context, Proto1->getNoexceptExpr(), Proto2->getNoexceptExpr())) return false; } if (Proto1->getTypeQuals() != Proto2->getTypeQuals()) return false; // Fall through to check the bits common with FunctionNoProtoType. } case Type::FunctionNoProto: { const FunctionType *Function1 = cast(T1); const FunctionType *Function2 = cast(T2); if (!IsStructurallyEquivalent(Context, Function1->getResultType(), Function2->getResultType())) return false; if (Function1->getExtInfo() != Function2->getExtInfo()) return false; break; } case Type::UnresolvedUsing: if (!IsStructurallyEquivalent(Context, cast(T1)->getDecl(), cast(T2)->getDecl())) return false; break; case Type::Attributed: if (!IsStructurallyEquivalent(Context, cast(T1)->getModifiedType(), cast(T2)->getModifiedType())) return false; if (!IsStructurallyEquivalent(Context, cast(T1)->getEquivalentType(), cast(T2)->getEquivalentType())) return false; break; case Type::Paren: if (!IsStructurallyEquivalent(Context, cast(T1)->getInnerType(), cast(T2)->getInnerType())) return false; break; case Type::Typedef: if (!IsStructurallyEquivalent(Context, cast(T1)->getDecl(), cast(T2)->getDecl())) return false; break; case Type::TypeOfExpr: if (!IsStructurallyEquivalent(Context, cast(T1)->getUnderlyingExpr(), cast(T2)->getUnderlyingExpr())) return false; break; case Type::TypeOf: if (!IsStructurallyEquivalent(Context, cast(T1)->getUnderlyingType(), cast(T2)->getUnderlyingType())) return false; break; case Type::UnaryTransform: if (!IsStructurallyEquivalent(Context, cast(T1)->getUnderlyingType(), cast(T1)->getUnderlyingType())) return false; break; case Type::Decltype: if (!IsStructurallyEquivalent(Context, cast(T1)->getUnderlyingExpr(), cast(T2)->getUnderlyingExpr())) return false; break; case Type::Auto: if (!IsStructurallyEquivalent(Context, cast(T1)->getDeducedType(), cast(T2)->getDeducedType())) return false; break; case Type::Record: case Type::Enum: if (!IsStructurallyEquivalent(Context, cast(T1)->getDecl(), cast(T2)->getDecl())) return false; break; case Type::TemplateTypeParm: { const TemplateTypeParmType *Parm1 = cast(T1); const TemplateTypeParmType *Parm2 = cast(T2); if (Parm1->getDepth() != Parm2->getDepth()) return false; if (Parm1->getIndex() != Parm2->getIndex()) return false; if (Parm1->isParameterPack() != Parm2->isParameterPack()) return false; // Names of template type parameters are never significant. break; } case Type::SubstTemplateTypeParm: { const SubstTemplateTypeParmType *Subst1 = cast(T1); const SubstTemplateTypeParmType *Subst2 = cast(T2); if (!IsStructurallyEquivalent(Context, QualType(Subst1->getReplacedParameter(), 0), QualType(Subst2->getReplacedParameter(), 0))) return false; if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(), Subst2->getReplacementType())) return false; break; } case Type::SubstTemplateTypeParmPack: { const SubstTemplateTypeParmPackType *Subst1 = cast(T1); const SubstTemplateTypeParmPackType *Subst2 = cast(T2); if (!IsStructurallyEquivalent(Context, QualType(Subst1->getReplacedParameter(), 0), QualType(Subst2->getReplacedParameter(), 0))) return false; if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(), Subst2->getArgumentPack())) return false; break; } case Type::TemplateSpecialization: { const TemplateSpecializationType *Spec1 = cast(T1); const TemplateSpecializationType *Spec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(), Spec2->getTemplateName())) return false; if (Spec1->getNumArgs() != Spec2->getNumArgs()) return false; for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Spec1->getArg(I), Spec2->getArg(I))) return false; } break; } case Type::Elaborated: { const ElaboratedType *Elab1 = cast(T1); const ElaboratedType *Elab2 = cast(T2); // CHECKME: what if a keyword is ETK_None or ETK_typename ? if (Elab1->getKeyword() != Elab2->getKeyword()) return false; if (!IsStructurallyEquivalent(Context, Elab1->getQualifier(), Elab2->getQualifier())) return false; if (!IsStructurallyEquivalent(Context, Elab1->getNamedType(), Elab2->getNamedType())) return false; break; } case Type::InjectedClassName: { const InjectedClassNameType *Inj1 = cast(T1); const InjectedClassNameType *Inj2 = cast(T2); if (!IsStructurallyEquivalent(Context, Inj1->getInjectedSpecializationType(), Inj2->getInjectedSpecializationType())) return false; break; } case Type::DependentName: { const DependentNameType *Typename1 = cast(T1); const DependentNameType *Typename2 = cast(T2); if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(), Typename2->getQualifier())) return false; if (!IsStructurallyEquivalent(Typename1->getIdentifier(), Typename2->getIdentifier())) return false; break; } case Type::DependentTemplateSpecialization: { const DependentTemplateSpecializationType *Spec1 = cast(T1); const DependentTemplateSpecializationType *Spec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(), Spec2->getQualifier())) return false; if (!IsStructurallyEquivalent(Spec1->getIdentifier(), Spec2->getIdentifier())) return false; if (Spec1->getNumArgs() != Spec2->getNumArgs()) return false; for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Spec1->getArg(I), Spec2->getArg(I))) return false; } break; } case Type::PackExpansion: if (!IsStructurallyEquivalent(Context, cast(T1)->getPattern(), cast(T2)->getPattern())) return false; break; case Type::ObjCInterface: { const ObjCInterfaceType *Iface1 = cast(T1); const ObjCInterfaceType *Iface2 = cast(T2); if (!IsStructurallyEquivalent(Context, Iface1->getDecl(), Iface2->getDecl())) return false; break; } case Type::ObjCObject: { const ObjCObjectType *Obj1 = cast(T1); const ObjCObjectType *Obj2 = cast(T2); if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(), Obj2->getBaseType())) return false; if (Obj1->getNumProtocols() != Obj2->getNumProtocols()) return false; for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I), Obj2->getProtocol(I))) return false; } break; } case Type::ObjCObjectPointer: { const ObjCObjectPointerType *Ptr1 = cast(T1); const ObjCObjectPointerType *Ptr2 = cast(T2); if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(), Ptr2->getPointeeType())) return false; break; } case Type::Atomic: { if (!IsStructurallyEquivalent(Context, cast(T1)->getValueType(), cast(T2)->getValueType())) return false; break; } } // end switch return true; } /// \brief Compare two source locations from different source managers. static bool SourceLocationEqual(SourceLocation SL1, SourceManager &SM1, SourceLocation SL2, SourceManager &SM2) { if (!SL1.isFileID() || !SL2.isFileID()) return false; PresumedLoc PLoc1 = SM1.getPresumedLoc(SL1), PLoc2 = SM2.getPresumedLoc(SL2); if (PLoc1.isInvalid() || PLoc2.isInvalid()) return false; if (PLoc1.getLine() != PLoc2.getLine() || PLoc1.getColumn() != PLoc2.getColumn()) return false; return llvm::sys::fs::equivalent(PLoc1.getFilename(), PLoc2.getFilename()); } static bool SourceRangeEqual(const SourceRange &SR1, SourceManager &SM1, const SourceRange &SR2, SourceManager &SM2) { return SourceLocationEqual(SR1.getBegin(), SM1, SR2.getBegin(), SM2) && SourceLocationEqual(SR1.getEnd(), SM1, SR2.getEnd(), SM2); } /// \brief Determine structural equivalence of two fields. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FieldDecl *Field1, FieldDecl *Field2) { RecordDecl *Owner2 = cast(Field2->getDeclContext()); // For anonymous structs/unions, match up the anonymous struct/union type // declarations directly, so that we don't go off searching for anonymous // types if (Field1->isAnonymousStructOrUnion() && Field2->isAnonymousStructOrUnion()) { RecordDecl *D1 = Field1->getType()->castAs()->getDecl(); RecordDecl *D2 = Field2->getType()->castAs()->getDecl(); return IsStructurallyEquivalent(Context, D1, D2); } // Check for equivalent field names. IdentifierInfo *Name1 = Field1->getIdentifier(); IdentifierInfo *Name2 = Field2->getIdentifier(); if (!::IsStructurallyEquivalent(Name1, Name2)) return false; if (!Field1->getLocStart().isInvalid()) if (SourceLocationEqual(Field1->getLocStart(), Field1->getASTContext().getSourceManager(), Field2->getLocStart(), Field2->getASTContext().getSourceManager())) return true; if (!IsStructurallyEquivalent(Context, Field1->getType(), Field2->getType())) { if (Context.Complain) { Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(Owner2); Context.Diag2(Field2->getLocation(), diag::note_odr_field) << Field2->getDeclName() << Field2->getType(); Context.Diag1(Field1->getLocation(), diag::note_odr_field) << Field1->getDeclName() << Field1->getType(); } return false; } if (Field1->isBitField() != Field2->isBitField()) { if (Context.Complain) { Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(Owner2); if (Field1->isBitField()) { Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field) << Field1->getDeclName() << Field1->getType() << Field1->getBitWidthValue(Context.C1); Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field) << Field2->getDeclName(); } else { Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field) << Field2->getDeclName() << Field2->getType() << Field2->getBitWidthValue(Context.C2); Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field) << Field1->getDeclName(); } } return false; } if (Field1->isBitField()) { // Make sure that the bit-fields are the same length. unsigned Bits1 = Field1->getBitWidthValue(Context.C1); unsigned Bits2 = Field2->getBitWidthValue(Context.C2); if (Bits1 != Bits2) { if (Context.Complain) { Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(Owner2); Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field) << Field2->getDeclName() << Field2->getType() << Bits2; Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field) << Field1->getDeclName() << Field1->getType() << Bits1; } return false; } } return true; } /// \brief Find the index of the given anonymous struct/union within its /// context. /// /// \returns Returns the index of this anonymous struct/union in its context, /// including the next assigned index (if none of them match). Returns an /// empty option if the context is not a record, i.e.. if the anonymous /// struct/union is at namespace or block scope. static Optional findAnonymousStructOrUnionIndex(RecordDecl *Anon) { ASTContext &Context = Anon->getASTContext(); QualType AnonTy = Context.getRecordType(Anon); RecordDecl *Owner = dyn_cast(Anon->getDeclContext()); if (!Owner) return None; unsigned Index = 0; for (DeclContext::decl_iterator D = Owner->decls_begin(), DEnd = Owner->decls_end(); D != DEnd; ++D) { FieldDecl *F = dyn_cast(*D); if (!F || !F->isAnonymousStructOrUnion()) continue; if (Context.hasSameType(F->getType(), AnonTy)) break; ++Index; } return Index; } /// \brief Determine structural equivalence of two records. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, RecordDecl *D1, RecordDecl *D2) { if (D1->isUnion() != D2->isUnion()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here) << D1->getDeclName() << (unsigned)D1->getTagKind(); } return false; } if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) { // If both anonymous structs/unions are in a record context, make sure // they occur in the same location in the context records. if (Optional Index1 = findAnonymousStructOrUnionIndex(D1)) { if (Optional Index2 = findAnonymousStructOrUnionIndex(D2)) { if (*Index1 != *Index2) return false; } } } // If both declarations are class template specializations, we know // the ODR applies, so check the template and template arguments. ClassTemplateSpecializationDecl *Spec1 = dyn_cast(D1); ClassTemplateSpecializationDecl *Spec2 = dyn_cast(D2); if (Spec1 && Spec2) { // Check that the specialized templates are the same. if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(), Spec2->getSpecializedTemplate())) return false; // Check that the template arguments are the same. if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size()) return false; for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I) if (!IsStructurallyEquivalent(Context, Spec1->getTemplateArgs().get(I), Spec2->getTemplateArgs().get(I))) return false; } // If one is a class template specialization and the other is not, these // structures are different. else if (Spec1 || Spec2) return false; // Compare the definitions of these two records. If either or both are // incomplete, we assume that they are equivalent. D1 = D1->getDefinition(); D2 = D2->getDefinition(); if (!D1 || !D2) return true; if (CXXRecordDecl *D1CXX = dyn_cast(D1)) { if (CXXRecordDecl *D2CXX = dyn_cast(D2)) { if (D1CXX->getNumBases() != D2CXX->getNumBases()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases) << D2CXX->getNumBases(); Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases) << D1CXX->getNumBases(); } return false; } // Check the base classes. for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), BaseEnd1 = D1CXX->bases_end(), Base2 = D2CXX->bases_begin(); Base1 != BaseEnd1; ++Base1, ++Base2) { if (!IsStructurallyEquivalent(Context, Base1->getType(), Base2->getType())) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag2(Base2->getLocStart(), diag::note_odr_base) << Base2->getType() << Base2->getSourceRange(); Context.Diag1(Base1->getLocStart(), diag::note_odr_base) << Base1->getType() << Base1->getSourceRange(); } return false; } // Check virtual vs. non-virtual inheritance mismatch. if (Base1->isVirtual() != Base2->isVirtual()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag2(Base2->getLocStart(), diag::note_odr_virtual_base) << Base2->isVirtual() << Base2->getSourceRange(); Context.Diag1(Base1->getLocStart(), diag::note_odr_base) << Base1->isVirtual() << Base1->getSourceRange(); } return false; } } } else if (D1CXX->getNumBases() > 0) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); const CXXBaseSpecifier *Base1 = D1CXX->bases_begin(); Context.Diag1(Base1->getLocStart(), diag::note_odr_base) << Base1->getType() << Base1->getSourceRange(); Context.Diag2(D2->getLocation(), diag::note_odr_missing_base); } return false; } } // Check the fields for consistency. RecordDecl::field_iterator Field2 = D2->field_begin(), Field2End = D2->field_end(); for (RecordDecl::field_iterator Field1 = D1->field_begin(), Field1End = D1->field_end(); Field1 != Field1End; ++Field1, ++Field2) { if (Field2 == Field2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag1(Field1->getLocation(), diag::note_odr_field) << Field1->getDeclName() << Field1->getType(); Context.Diag2(D2->getLocation(), diag::note_odr_missing_field); } return false; } if (!IsStructurallyEquivalent(Context, *Field1, *Field2)) return false; } if (Field2 != Field2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag2(Field2->getLocation(), diag::note_odr_field) << Field2->getDeclName() << Field2->getType(); Context.Diag1(D1->getLocation(), diag::note_odr_missing_field); } return false; } return true; } /// \brief Determine structural equivalence of two enums. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, EnumDecl *D1, EnumDecl *D2) { EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(), EC2End = D2->enumerator_end(); for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(), EC1End = D1->enumerator_end(); EC1 != EC1End; ++EC1, ++EC2) { if (EC2 == EC2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) << EC1->getDeclName() << EC1->getInitVal().toString(10); Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator); } return false; } llvm::APSInt Val1 = EC1->getInitVal(); llvm::APSInt Val2 = EC2->getInitVal(); if (!llvm::APSInt::isSameValue(Val1, Val2) || !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) << EC2->getDeclName() << EC2->getInitVal().toString(10); Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) << EC1->getDeclName() << EC1->getInitVal().toString(10); } return false; } } if (EC2 != EC2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) << Context.C2.getTypeDeclType(D2); Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) << EC2->getDeclName() << EC2->getInitVal().toString(10); Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TemplateParameterList *Params1, TemplateParameterList *Params2) { if (Params1->size() != Params2->size()) { if (Context.Complain) { Context.Diag2(Params2->getTemplateLoc(), diag::err_odr_different_num_template_parameters) << Params1->size() << Params2->size(); Context.Diag1(Params1->getTemplateLoc(), diag::note_odr_template_parameter_list); } return false; } for (unsigned I = 0, N = Params1->size(); I != N; ++I) { if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) { if (Context.Complain) { Context.Diag2(Params2->getParam(I)->getLocation(), diag::err_odr_different_template_parameter_kind); Context.Diag1(Params1->getParam(I)->getLocation(), diag::note_odr_template_parameter_here); } return false; } if (!Context.IsStructurallyEquivalent(Params1->getParam(I), Params2->getParam(I))) { return false; } } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TemplateTypeParmDecl *D1, TemplateTypeParmDecl *D2) { if (D1->isParameterPack() != D2->isParameterPack()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack) << D2->isParameterPack(); Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) << D1->isParameterPack(); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, NonTypeTemplateParmDecl *D1, NonTypeTemplateParmDecl *D2) { if (D1->isParameterPack() != D2->isParameterPack()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack) << D2->isParameterPack(); Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) << D1->isParameterPack(); } return false; } // Check types. if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::err_odr_non_type_parameter_type_inconsistent) << D2->getType() << D1->getType(); Context.Diag1(D1->getLocation(), diag::note_odr_value_here) << D1->getType(); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TemplateTemplateParmDecl *D1, TemplateTemplateParmDecl *D2) { if (D1->isParameterPack() != D2->isParameterPack()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack) << D2->isParameterPack(); Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) << D1->isParameterPack(); } return false; } // Check template parameter lists. return IsStructurallyEquivalent(Context, D1->getTemplateParameters(), D2->getTemplateParameters()); } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, ClassTemplateDecl *D1, ClassTemplateDecl *D2) { // Check template parameters. if (!IsStructurallyEquivalent(Context, D1->getTemplateParameters(), D2->getTemplateParameters())) return false; // Check the templated declaration. return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(), D2->getTemplatedDecl()); } /// \brief Determine structural equivalence of two declarations. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1, Decl *D2) { if (!D1 && !D2) return true; if (!D1 || !D2) return false; if (D1->getKind() != D1->getKind()) return false; if (!D1->getLocStart().isInvalid()) if (SourceLocationEqual(D1->getLocStart(), D1->getASTContext().getSourceManager(), D2->getLocStart(), D2->getASTContext().getSourceManager())) if (!isa(D1) && !isa(D1)) return true; if (NamedDecl *ND1 = dyn_cast(D1)) { NamedDecl *ND2 = dyn_cast(D2); if (ND1->getNameAsString() != ND2->getNameAsString()) return false; } // FIXME: Check for known structural equivalences via a callback of some sort. // Check whether we already know that these two declarations are not // structurally equivalent. if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(), D2->getCanonicalDecl()))) return false; // Determine whether we've already produced a tentative equivalence for D1. Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()]; if (EquivToD1) return EquivToD1 == D2->getCanonicalDecl(); // Produce a tentative equivalence D1 <-> D2, which will be checked later. EquivToD1 = D2->getCanonicalDecl(); Context.DeclsToCheck.push_back(D1->getCanonicalDecl()); return true; } bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1, Decl *D2) { if (!::IsStructurallyEquivalent(*this, D1, D2)) return false; return !Finish(); } bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1, QualType T2, bool CheckQualifiers) { if (!::IsStructurallyEquivalent(*this, T1, T2, CheckQualifiers)) return false; return !Finish(); } static bool IsTemplateDeclStructurallyEquivalent( StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) { if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) return false; if (!D1->getIdentifier()) // Special name if (D1->getNameAsString() != D2->getNameAsString()) return false; return IsStructurallyEquivalent(Ctx, D1->getTemplateParameters(), D2->getTemplateParameters()); } bool StructuralEquivalenceContext::Finish() { while (!DeclsToCheck.empty()) { // Check the next declaration. Decl *D1 = DeclsToCheck.front(); DeclsToCheck.pop_front(); Decl *D2 = TentativeEquivalences[D1]; assert(D2 && "Unrecorded tentative equivalence?"); bool Equivalent = true; // FIXME: Switch on all declaration kinds. For now, we're just going to // check the obvious ones. if (RecordDecl *Record1 = dyn_cast(D1)) { if (RecordDecl *Record2 = dyn_cast(D2)) { // Check for equivalent structure names. IdentifierInfo *Name1 = Record1->getIdentifier(); if (!Name1 && Record1->getTypedefNameForAnonDecl()) Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier(); IdentifierInfo *Name2 = Record2->getIdentifier(); if (!Name2 && Record2->getTypedefNameForAnonDecl()) Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier(); if (!::IsStructurallyEquivalent(Name1, Name2) || !::IsStructurallyEquivalent(*this, Record1, Record2)) Equivalent = false; } else { // Record/non-record mismatch. Equivalent = false; } } else if (EnumDecl *Enum1 = dyn_cast(D1)) { if (EnumDecl *Enum2 = dyn_cast(D2)) { // Check for equivalent enum names. IdentifierInfo *Name1 = Enum1->getIdentifier(); if (!Name1 && Enum1->getTypedefNameForAnonDecl()) Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier(); IdentifierInfo *Name2 = Enum2->getIdentifier(); if (!Name2 && Enum2->getTypedefNameForAnonDecl()) Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier(); if (!::IsStructurallyEquivalent(Name1, Name2) || !::IsStructurallyEquivalent(*this, Enum1, Enum2)) Equivalent = false; } else { // Enum/non-enum mismatch Equivalent = false; } } else if (TypedefNameDecl *Typedef1 = dyn_cast(D1)) { if (TypedefNameDecl *Typedef2 = dyn_cast(D2)) { if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(), Typedef2->getIdentifier()) || !::IsStructurallyEquivalent(*this, Typedef1->getUnderlyingType(), Typedef2->getUnderlyingType())) Equivalent = false; } else { // Typedef/non-typedef mismatch. Equivalent = false; } } else if (ClassTemplateDecl *ClassTemplate1 = dyn_cast(D1)) { if (ClassTemplateDecl *ClassTemplate2 = dyn_cast(D2)) { if (!::IsTemplateDeclStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2) || !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2) || !::IsStructurallyEquivalent( *this, ClassTemplate1->getTemplatedDecl(), ClassTemplate2->getTemplatedDecl())) Equivalent = false; } else { // Class template/non-class-template mismatch. Equivalent = false; } } else if (FunctionTemplateDecl *FunctionTemplate1 = dyn_cast(D1)) { if (FunctionTemplateDecl *FunctionTemplate2 = dyn_cast(D2)) { if (!::IsTemplateDeclStructurallyEquivalent(*this, FunctionTemplate1, FunctionTemplate2) || !::IsStructurallyEquivalent(*this, FunctionTemplate1, FunctionTemplate2) || !::IsStructurallyEquivalent( *this, FunctionTemplate1->getTemplatedDecl()->getType(), FunctionTemplate2->getTemplatedDecl()->getType())) Equivalent = false; } else { // Class template/non-class-template mismatch. Equivalent = false; } } else if (TemplateTypeParmDecl *TTP1= dyn_cast(D1)) { if (TemplateTypeParmDecl *TTP2 = dyn_cast(D2)) { if (!::IsStructurallyEquivalent(*this, TTP1, TTP2)) Equivalent = false; } else { // Kind mismatch. Equivalent = false; } } else if (NonTypeTemplateParmDecl *NTTP1 = dyn_cast(D1)) { if (NonTypeTemplateParmDecl *NTTP2 = dyn_cast(D2)) { if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2)) Equivalent = false; } else { // Kind mismatch. Equivalent = false; } } else if (TemplateTemplateParmDecl *TTP1 = dyn_cast(D1)) { if (TemplateTemplateParmDecl *TTP2 = dyn_cast(D2)) { if (!::IsStructurallyEquivalent(*this, TTP1, TTP2)) Equivalent = false; } else { // Kind mismatch. Equivalent = false; } } else if (FunctionDecl *FD1 = dyn_cast(D1)) { if (FunctionDecl *FD2 = dyn_cast(D2)) { if (!IsStructurallyEquivalent(FD1->getType(), FD2->getType())) { Equivalent = false; } } else { // Kind mismatch. Equivalent = false; } } if (!Equivalent) { // Note that these two declarations are not equivalent (and we already // know about it). NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(), D2->getCanonicalDecl())); return true; } // FIXME: Check other declaration kinds! } return false; } //---------------------------------------------------------------------------- // Import Types //---------------------------------------------------------------------------- QualType ASTNodeImporter::VisitType(const Type *T) { Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node) << T->getTypeClassName(); return QualType(); } QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) { QualType ToModType = Importer.Import(T->getModifiedType()); if (ToModType.isNull()) { assert(!ToModType.isNull()); return QualType(); } QualType ToEqType = Importer.Import(T->getEquivalentType()); if (ToEqType.isNull()) { assert(!ToEqType.isNull()); return QualType(); } return Importer.getToContext().getAttributedType(T->getAttrKind(), ToModType, ToEqType); } QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { switch (T->getKind()) { #define SHARED_SINGLETON_TYPE(Expansion) #define BUILTIN_TYPE(Id, SingletonId) \ case BuiltinType::Id: return Importer.getToContext().SingletonId; #include "clang/AST/BuiltinTypes.def" // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" // context supports C++. // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" // context supports ObjC. case BuiltinType::Char_U: // The context we're importing from has an unsigned 'char'. If we're // importing into a context with a signed 'char', translate to // 'unsigned char' instead. if (Importer.getToContext().getLangOpts().CharIsSigned) return Importer.getToContext().UnsignedCharTy; return Importer.getToContext().CharTy; case BuiltinType::Char_S: // The context we're importing from has an unsigned 'char'. If we're // importing into a context with a signed 'char', translate to // 'unsigned char' instead. if (!Importer.getToContext().getLangOpts().CharIsSigned) return Importer.getToContext().SignedCharTy; return Importer.getToContext().CharTy; case BuiltinType::WChar_S: case BuiltinType::WChar_U: // FIXME: If not in C++, shall we translate to the C equivalent of // wchar_t? return Importer.getToContext().WCharTy; } llvm_unreachable("Invalid BuiltinType Kind!"); } QualType ASTNodeImporter::VisitDecayedType(const DecayedType *T) { QualType OrigT = Importer.Import(T->getOriginalType()); if (OrigT.isNull()) return QualType(); return Importer.getToContext().getDecayedType(OrigT); } QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return QualType(); return Importer.getToContext().getComplexType(ToElementType); } QualType ASTNodeImporter::VisitPointerType(const PointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return QualType(); return Importer.getToContext().getPointerType(ToPointeeType); } QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { // FIXME: Check for blocks support in "to" context. QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return QualType(); return Importer.getToContext().getBlockPointerType(ToPointeeType); } QualType ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { // FIXME: Check for C++ support in "to" context. QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten()); if (ToPointeeType.isNull()) return QualType(); return Importer.getToContext().getLValueReferenceType(ToPointeeType); } QualType ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { // FIXME: Check for C++0x support in "to" context. QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten()); if (ToPointeeType.isNull()) return QualType(); return Importer.getToContext().getRValueReferenceType(ToPointeeType); } QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { // FIXME: Check for C++ support in "to" context. QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return QualType(); QualType ClassType = Importer.Import(QualType(T->getClass(), 0)); return Importer.getToContext().getMemberPointerType(ToPointeeType, ClassType.getTypePtr()); } QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return QualType(); return Importer.getToContext().getConstantArrayType(ToElementType, T->getSize(), T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); } QualType ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return QualType(); return Importer.getToContext().getIncompleteArrayType(ToElementType, T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); } QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return QualType(); Expr *Size = Importer.Import(T->getSizeExpr()); if (!Size) return QualType(); SourceRange Brackets = Importer.Import(T->getBracketsRange()); return Importer.getToContext().getVariableArrayType(ToElementType, Size, T->getSizeModifier(), T->getIndexTypeCVRQualifiers(), Brackets); } QualType ASTNodeImporter::VisitDependentSizedArrayType( const DependentSizedArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); assert(!ToElementType.isNull()); if (ToElementType.isNull()) return QualType(); // SizeExpr may be null if size is not specified directly // For example, 'int a[]' Expr *Size = Importer.Import(T->getSizeExpr()); assert(Size || !T->getSizeExpr()); if (!Size && T->getSizeExpr()) return QualType(); SourceRange Brackets = Importer.Import(T->getBracketsRange()); return Importer.getToContext().getDependentSizedArrayType( ToElementType, Size, T->getSizeModifier(), T->getIndexTypeCVRQualifiers(), Brackets); } QualType ASTNodeImporter::VisitVectorType(const VectorType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return QualType(); return Importer.getToContext().getVectorType(ToElementType, T->getNumElements(), T->getVectorKind()); } QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return QualType(); return Importer.getToContext().getExtVectorType(ToElementType, T->getNumElements()); } QualType ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { // FIXME: What happens if we're importing a function without a prototype // into C++? Should we make it variadic? QualType ToResultType = Importer.Import(T->getResultType()); if (ToResultType.isNull()) return QualType(); return Importer.getToContext().getFunctionNoProtoType(ToResultType, T->getExtInfo()); } QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { QualType ToResultType = Importer.Import(T->getResultType()); if (ToResultType.isNull()) return QualType(); // Import argument types SmallVector ArgTypes; for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(), AEnd = T->arg_type_end(); A != AEnd; ++A) { QualType ArgType = Importer.Import(*A); if (ArgType.isNull()) return QualType(); ArgTypes.push_back(ArgType); } // Import exception types SmallVector ExceptionTypes; for (FunctionProtoType::exception_iterator E = T->exception_begin(), EEnd = T->exception_end(); E != EEnd; ++E) { QualType ExceptionType = Importer.Import(*E); if (ExceptionType.isNull()) return QualType(); ExceptionTypes.push_back(ExceptionType); } FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo(); FunctionProtoType::ExtProtoInfo ToEPI; ToEPI.ExtInfo = FromEPI.ExtInfo; ToEPI.Variadic = FromEPI.Variadic; ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn; ToEPI.TypeQuals = FromEPI.TypeQuals; ToEPI.RefQualifier = FromEPI.RefQualifier; ToEPI.NumExceptions = ExceptionTypes.size(); ToEPI.Exceptions = ExceptionTypes.data(); ToEPI.ConsumedArguments = FromEPI.ConsumedArguments; ToEPI.ExceptionSpecType = FromEPI.ExceptionSpecType; ToEPI.NoexceptExpr = Importer.Import(FromEPI.NoexceptExpr); ToEPI.ExceptionSpecDecl = cast_or_null( Importer.Import(FromEPI.ExceptionSpecDecl)); ToEPI.ExceptionSpecTemplate = cast_or_null( Importer.Import(FromEPI.ExceptionSpecTemplate)); return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI); } QualType ASTNodeImporter::VisitUnresolvedUsingType( const UnresolvedUsingType *T) { UnresolvedUsingTypenameDecl *ToD = cast_or_null( Importer.Import(T->getDecl())); if (!ToD) { assert(ToD); return QualType(); } UnresolvedUsingTypenameDecl *ToPrevD = cast_or_null( Importer.Import(T->getDecl()->getPreviousDecl())); if (!ToPrevD && T->getDecl()->getPreviousDecl()) { assert(ToPrevD || !T->getDecl()->getPreviousDecl()); return QualType(); } return Importer.getToContext().getTypeDeclType(ToD, ToPrevD); } QualType ASTNodeImporter::VisitParenType(const ParenType *T) { QualType ToInnerType = Importer.Import(T->getInnerType()); if (ToInnerType.isNull()) return QualType(); return Importer.getToContext().getParenType(ToInnerType); } QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { TypedefNameDecl *ToDecl = dyn_cast_or_null(Importer.Import(T->getDecl())); if (!ToDecl) return QualType(); return Importer.getToContext().getTypeDeclType(ToDecl); } QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { Expr *ToExpr = Importer.Import(T->getUnderlyingExpr()); if (!ToExpr) return QualType(); return Importer.getToContext().getTypeOfExprType(ToExpr); } QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType()); if (ToUnderlyingType.isNull()) return QualType(); return Importer.getToContext().getTypeOfType(ToUnderlyingType); } QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { // FIXME: Make sure that the "to" context supports C++0x! Expr *ToExpr = Importer.Import(T->getUnderlyingExpr()); if (!ToExpr) return QualType(); QualType UnderlyingType = Importer.Import(T->getUnderlyingType()); if (UnderlyingType.isNull()) return QualType(); return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType); } QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) { QualType ToBaseType = Importer.Import(T->getBaseType()); QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType()); if (ToBaseType.isNull() || ToUnderlyingType.isNull()) return QualType(); return Importer.getToContext().getUnaryTransformType(ToBaseType, ToUnderlyingType, T->getUTTKind()); } QualType ASTNodeImporter::VisitAutoType(const AutoType *T) { // FIXME: Make sure that the "to" context supports C++11! QualType FromDeduced = T->getDeducedType(); QualType ToDeduced; if (!FromDeduced.isNull()) { ToDeduced = Importer.Import(FromDeduced); if (ToDeduced.isNull()) return QualType(); } return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto(), /*IsDependent*/false); } QualType ASTNodeImporter::VisitInjectedClassNameType( const InjectedClassNameType *T) { CXXRecordDecl *D = cast_or_null(Importer.Import(T->getDecl())); assert(D); if (!D) return QualType(); QualType InjType = Importer.Import(T->getInjectedSpecializationType()); if (InjType.isNull()) return QualType(); // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading // See Type.h:3855 for details // return Importer.getToContext().getInjectedClassNameType(D, InjType); enum { TypeAlignmentInBits = 4, TypeAlignment = 1 << TypeAlignmentInBits }; return QualType(new (Importer.getToContext(), TypeAlignment) InjectedClassNameType(D, InjType), 0); } QualType ASTNodeImporter::VisitRecordType(const RecordType *T) { RecordDecl *ToDecl = dyn_cast_or_null(Importer.Import(T->getDecl())); if (!ToDecl) return QualType(); return Importer.getToContext().getTagDeclType(ToDecl); } QualType ASTNodeImporter::VisitEnumType(const EnumType *T) { EnumDecl *ToDecl = dyn_cast_or_null(Importer.Import(T->getDecl())); if (!ToDecl) return QualType(); return Importer.getToContext().getTagDeclType(ToDecl); } QualType ASTNodeImporter::VisitTemplateTypeParmType( const TemplateTypeParmType *T) { return Importer.getToContext().getTemplateTypeParmType( T->getDepth(), T->getIndex(), T->isParameterPack(), cast_or_null(Importer.Import(T->getDecl()))); } QualType ASTNodeImporter::VisitSubstTemplateTypeParmType( const SubstTemplateTypeParmType *T) { const TemplateTypeParmType *Replaced = cast_or_null(Importer.Import( QualType(T->getReplacedParameter(), 0)).getTypePtr()); assert(Replaced); if (!Replaced) return QualType(); QualType Replacement = Importer.Import(T->getReplacementType()); assert(!Replacement.isNull()); if (Replacement.isNull()) return QualType(); Replacement = Replacement.getCanonicalType(); return Importer.getToContext().getSubstTemplateTypeParmType( Replaced, Replacement); } QualType ASTNodeImporter::VisitTemplateSpecializationType( const TemplateSpecializationType *T) { TemplateName ToTemplate = Importer.Import(T->getTemplateName()); if (ToTemplate.isNull()) return QualType(); SmallVector ToTemplateArgs; if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs)) return QualType(); QualType ToCanonType; if (!QualType(T, 0).isCanonical()) { QualType FromCanonType = Importer.getFromContext().getCanonicalType(QualType(T, 0)); ToCanonType =Importer.Import(FromCanonType); if (ToCanonType.isNull()) return QualType(); } return Importer.getToContext().getTemplateSpecializationType(ToTemplate, ToTemplateArgs.data(), ToTemplateArgs.size(), ToCanonType); } QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) { NestedNameSpecifier *ToQualifier = 0; // Note: the qualifier in an ElaboratedType is optional. if (T->getQualifier()) { ToQualifier = Importer.Import(T->getQualifier()); if (!ToQualifier) return QualType(); } QualType ToNamedType = Importer.Import(T->getNamedType()); if (ToNamedType.isNull()) return QualType(); return Importer.getToContext().getElaboratedType(T->getKeyword(), ToQualifier, ToNamedType); } QualType ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) { NestedNameSpecifier *NNS = Importer.Import(T->getQualifier()); assert(NNS || !T->getQualifier()); if (!NNS && T->getQualifier()) return QualType(); IdentifierInfo *Name = Importer.Import(T->getIdentifier()); assert(Name); if (!Name) return QualType(); // Can be null type QualType Canon = (T == T->getCanonicalTypeInternal().getTypePtr()) ? QualType() : Importer.Import(T->getCanonicalTypeInternal()); if (!Canon.isNull()) Canon = Canon.getCanonicalType(); return Importer.getToContext().getDependentNameType( T->getKeyword(), NNS, Name, Canon); } QualType ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) { QualType Pattern = Importer.Import(T->getPattern()); assert(!Pattern.isNull()); if (Pattern.isNull()) return QualType(); return Importer.getToContext().getPackExpansionType(Pattern, T->getNumExpansions()); } QualType ASTNodeImporter::VisitDependentTemplateSpecializationType( const DependentTemplateSpecializationType *T) { NestedNameSpecifier *Qualifier = Importer.Import(T->getQualifier()); assert(Qualifier || !T->getQualifier()); if (!Qualifier && T->getQualifier()) return QualType(); IdentifierInfo *Name = Importer.Import(T->getIdentifier()); assert(Name || !T->getIdentifier()); if (!Name && T->getIdentifier()) return QualType(); SmallVector ToPack; ToPack.reserve(T->getNumArgs()); if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToPack)) { assert(false); return QualType(); } return Importer.getToContext().getDependentTemplateSpecializationType( T->getKeyword(), Qualifier, Name, T->getNumArgs(), ToPack.data()); } QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { ObjCInterfaceDecl *Class = dyn_cast_or_null(Importer.Import(T->getDecl())); if (!Class) return QualType(); return Importer.getToContext().getObjCInterfaceType(Class); } QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) { QualType ToBaseType = Importer.Import(T->getBaseType()); if (ToBaseType.isNull()) return QualType(); SmallVector Protocols; for (ObjCObjectType::qual_iterator P = T->qual_begin(), PEnd = T->qual_end(); P != PEnd; ++P) { ObjCProtocolDecl *Protocol = dyn_cast_or_null(Importer.Import(*P)); if (!Protocol) return QualType(); Protocols.push_back(Protocol); } return Importer.getToContext().getObjCObjectType(ToBaseType, Protocols.data(), Protocols.size()); } QualType ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return QualType(); return Importer.getToContext().getObjCObjectPointerType(ToPointeeType); } //---------------------------------------------------------------------------- // Import Declarations //---------------------------------------------------------------------------- bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, DeclarationName &Name, SourceLocation &Loc) { // Import the context of this declaration. DC = Importer.ImportContext(D->getDeclContext()); if (!DC) return true; LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return true; } // Import the name of this declaration. Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return true; // Import the location of this declaration. Loc = Importer.Import(D->getLocation()); return false; } void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { if (!FromD) return; if (!ToD) { ToD = Importer.Import(FromD); if (!ToD) return; } if (RecordDecl *FromRecord = dyn_cast(FromD)) { if (RecordDecl *ToRecord = cast_or_null(ToD)) { if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) { ImportDefinition(FromRecord, ToRecord); } } return; } if (EnumDecl *FromEnum = dyn_cast(FromD)) { if (EnumDecl *ToEnum = cast_or_null(ToD)) { if (FromEnum->getDefinition() && !ToEnum->getDefinition()) { ImportDefinition(FromEnum, ToEnum); } } return; } } void ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From, DeclarationNameInfo& To) { // NOTE: To.Name and To.Loc are already imported. // We only have to import To.LocInfo. switch (To.getName().getNameKind()) { case DeclarationName::Identifier: case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: case DeclarationName::CXXUsingDirective: return; case DeclarationName::CXXOperatorName: { SourceRange Range = From.getCXXOperatorNameRange(); To.setCXXOperatorNameRange(Importer.Import(Range)); return; } case DeclarationName::CXXLiteralOperatorName: { SourceLocation Loc = From.getCXXLiteralOperatorNameLoc(); To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc)); return; } case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: { TypeSourceInfo *FromTInfo = From.getNamedTypeInfo(); To.setNamedTypeInfo(Importer.Import(FromTInfo)); return; } } llvm_unreachable("Unknown name kind."); } bool ASTNodeImporter::ImportDefinition(FunctionDecl *From, FunctionDecl *To) { To->setBody(Importer.Import(From->getBody())); CXXConstructorDecl *CD = dyn_cast(From); if (!CD) return false; unsigned NumInitializers = CD->getNumCtorInitializers(); if (!NumInitializers) return false; ASTContext &Context = Importer.getToContext(); CXXCtorInitializer **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; int cnt = 0; for (CXXConstructorDecl::init_iterator I = CD->init_begin(), E = CD->init_end(); I != E; ++I) { CXXCtorInitializer *Init = *I; TypeSourceInfo *TInfo = 0; bool IsBaseVirtual = false; FieldDecl *Member = 0; IndirectFieldDecl *IndirectMember = 0; if (Init->isBaseInitializer()) { TInfo = Importer.Import(Init->getTypeSourceInfo()); IsBaseVirtual = Init->isBaseVirtual(); } else if (Init->isDelegatingInitializer()) { TInfo = Importer.Import(Init->getTypeSourceInfo()); } else if (Init->isMemberInitializer()) { Member = cast_or_null(Importer.Import(Init->getMember())); assert(Member); if (!Member) return true; } else if (Init->isIndirectMemberInitializer()) { IndirectMember = cast_or_null( Importer.Import(Init->getIndirectMember())); assert(IndirectMember); if (!IndirectMember) return true; } SourceLocation MemberOrEllipsisLoc = Importer.Import(Init->getMemberLocation()); Expr *InitE = Importer.Import(Init->getInit()); assert(InitE || !Init->getInit()); if (!InitE && Init->getInit()) return true; SourceLocation LParenLoc = Importer.Import(Init->getLParenLoc()); SourceLocation RParenLoc = Importer.Import(Init->getRParenLoc()); bool IsWritten = Init->isWritten(); unsigned SourceOrderOrNumArrayIndices; SmallVector Indices; SourceOrderOrNumArrayIndices = Init->getNumArrayIndices(); if (!IsWritten) { Indices.reserve(SourceOrderOrNumArrayIndices); for (unsigned i = 0; i != SourceOrderOrNumArrayIndices; ++i) { VarDecl *VD = cast_or_null(Init->getArrayIndex(i)); assert(VD); if (!VD) return true; else Indices.push_back(VD); } } CXXCtorInitializer *ToInit; if (Init->isBaseInitializer()) { ToInit = new (Context) CXXCtorInitializer( Context, TInfo, IsBaseVirtual, LParenLoc, InitE, RParenLoc, MemberOrEllipsisLoc); } else if (Init->isDelegatingInitializer()) { ToInit = new (Context) CXXCtorInitializer( Context, TInfo, LParenLoc, InitE, RParenLoc); } else if (IsWritten) { if (Member) ToInit = new (Context) CXXCtorInitializer( Context, Member, MemberOrEllipsisLoc, LParenLoc, InitE, RParenLoc); else ToInit = new (Context) CXXCtorInitializer( Context, IndirectMember, MemberOrEllipsisLoc, LParenLoc, InitE, RParenLoc); } else { if (IndirectMember) { assert(Indices.empty() && "Indirect field improperly initialized"); ToInit = new (Context) CXXCtorInitializer( Context, IndirectMember, MemberOrEllipsisLoc, LParenLoc, InitE, RParenLoc); } else { ToInit = CXXCtorInitializer::Create( Context, Member, MemberOrEllipsisLoc, LParenLoc, InitE, RParenLoc, Indices.data(), Indices.size()); } } if (IsWritten) ToInit->setSourceOrder(SourceOrderOrNumArrayIndices); CtorInitializers[cnt] = ToInit; cnt++; } CXXConstructorDecl *ToCD = cast(To); ToCD->setCtorInitializers(CtorInitializers); ToCD->setNumCtorInitializers(NumInitializers); return false; } void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { if (Importer.isMinimalImport() && !ForceImport) { Importer.ImportContext(FromDC); return; } for (DeclContext::decl_iterator From = FromDC->decls_begin(), FromEnd = FromDC->decls_end(); From != FromEnd; ++From) Importer.Import(*From); // Reorder declarations in RecordDecls because they may have another // valuable order if (!isa(FromDC)) return; DeclContext *ToDC = cast_or_null( Importer.Import(cast(FromDC))); for (DeclContext::decl_iterator From = FromDC->decls_begin(), FromEnd = FromDC->decls_end(); From != FromEnd; ++From) { Decl *To = Importer.GetImported(*From); assert(To); if (ToDC == To->getDeclContext() && ToDC->containsDecl(To)) ToDC->removeDecl(To); } assert(cast(ToDC)->field_empty()); for (DeclContext::decl_iterator From = FromDC->decls_begin(), FromEnd = FromDC->decls_end(); From != FromEnd; ++From) { Decl *To = Importer.GetImported(*From); assert(To); if (ToDC == To->getDeclContext() && ToDC == To->getLexicalDeclContext() && !ToDC->containsDecl(To)) ToDC->addDeclInternal(To); } } bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) ImportDeclContext(From, /*ForceImport=*/true); return false; } To->startDefinition(); // Add base classes. if (CXXRecordDecl *ToCXX = dyn_cast(To)) { if (CXXRecordDecl *FromCXX = dyn_cast(From)) { struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data(); struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data(); ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor; ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers; ToData.Aggregate = true; ToData.PlainOldData = FromData.PlainOldData; ToData.Empty = FromData.Empty; ToData.Polymorphic = FromData.Polymorphic; ToData.Abstract = FromData.Abstract; ToData.IsStandardLayout = FromData.IsStandardLayout; ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases; ToData.HasPrivateFields = FromData.HasPrivateFields; ToData.HasProtectedFields = FromData.HasProtectedFields; ToData.HasPublicFields = FromData.HasPublicFields; ToData.HasMutableFields = FromData.HasMutableFields; ToData.HasOnlyCMembers = FromData.HasOnlyCMembers; ToData.HasInClassInitializer = FromData.HasInClassInitializer; ToData.HasUninitializedReferenceMember = FromData.HasUninitializedReferenceMember; ToData.NeedOverloadResolutionForMoveConstructor = FromData.NeedOverloadResolutionForMoveConstructor; ToData.NeedOverloadResolutionForMoveAssignment = FromData.NeedOverloadResolutionForMoveAssignment; ToData.NeedOverloadResolutionForDestructor = FromData.NeedOverloadResolutionForDestructor; ToData.DefaultedMoveConstructorIsDeleted = FromData.DefaultedMoveConstructorIsDeleted; ToData.DefaultedMoveAssignmentIsDeleted = FromData.DefaultedMoveAssignmentIsDeleted; ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted; ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers; ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor; ToData.HasConstexprNonCopyMoveConstructor = FromData.HasConstexprNonCopyMoveConstructor; ToData.DefaultedDefaultConstructorIsConstexpr = FromData.DefaultedDefaultConstructorIsConstexpr; ToData.HasConstexprDefaultConstructor = FromData.HasConstexprDefaultConstructor; ToData.HasNonLiteralTypeFieldsOrBases = FromData.HasNonLiteralTypeFieldsOrBases; // ComputedVisibleConversions not imported. ToData.UserProvidedDefaultConstructor = FromData.UserProvidedDefaultConstructor; ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers; ToData.ImplicitCopyConstructorHasConstParam = FromData.ImplicitCopyConstructorHasConstParam; ToData.ImplicitCopyAssignmentHasConstParam = FromData.ImplicitCopyAssignmentHasConstParam; ToData.HasDeclaredCopyConstructorWithConstParam = FromData.HasDeclaredCopyConstructorWithConstParam; ToData.HasDeclaredCopyAssignmentWithConstParam = FromData.HasDeclaredCopyAssignmentWithConstParam; ToData.IsLambda = FromData.IsLambda; ToData.Definition = cast( Importer.Import(FromData.Definition)); SmallVector Bases; for (CXXRecordDecl::base_class_iterator Base1 = FromCXX->bases_begin(), FromBaseEnd = FromCXX->bases_end(); Base1 != FromBaseEnd; ++Base1) { QualType T = Importer.Import(Base1->getType()); if (T.isNull()) return true; SourceLocation EllipsisLoc; if (Base1->isPackExpansion()) EllipsisLoc = Importer.Import(Base1->getEllipsisLoc()); // Ensure that we have a definition for the base. ImportDefinitionIfNeeded(Base1->getType()->getAsCXXRecordDecl()); Bases.push_back(Importer.Import(Base1)); } if (!Bases.empty()) ToCXX->setBases(Bases.data(), Bases.size()); if (!FromCXX->getDestructor() && FromCXX->needsImplicitDefaultConstructor() && !FromCXX->isDependentType()) { Importer.getFromSema()->DeclareImplicitDestructor(FromCXX); } } else { // We're importing RecordDecl as CXXRecordDecl. That is normal sometimes. // Don't change anything in default ToData. } } if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From, /*ForceImport=*/true); To->completeDefinition(); return false; } bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To, ImportDefinitionKind Kind) { // FIXME: Can we really import any initializer? Alternatively, we could force // ourselves to import every declaration of a variable and then only use // getInit() here. To->setInit(Importer.Import(const_cast(From->getAnyInitializer()))); // FIXME: Other bits to merge? return false; } bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) ImportDeclContext(From, /*ForceImport=*/true); return false; } To->startDefinition(); QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From)); if (T.isNull()) return true; QualType ToPromotionType = Importer.Import(From->getPromotionType()); if (ToPromotionType.isNull()) return true; if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From, /*ForceImport=*/true); // FIXME: we might need to merge the number of positive or negative bits // if the enumerator lists don't match. To->completeDefinition(T, ToPromotionType, From->getNumPositiveBits(), From->getNumNegativeBits()); return false; } TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList( TemplateParameterList *Params) { SmallVector ToParams; ToParams.reserve(Params->size()); for (TemplateParameterList::iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { Decl *To = Importer.Import(*P); if (!To) return 0; ToParams.push_back(cast(To)); } return TemplateParameterList::Create(Importer.getToContext(), Importer.Import(Params->getTemplateLoc()), Importer.Import(Params->getLAngleLoc()), ToParams.data(), ToParams.size(), Importer.Import(Params->getRAngleLoc())); } TemplateArgument ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { switch (From.getKind()) { case TemplateArgument::Null: return TemplateArgument(); case TemplateArgument::Type: { QualType ToType = Importer.Import(From.getAsType()); if (ToType.isNull()) return TemplateArgument(); return TemplateArgument(ToType); } case TemplateArgument::Integral: { QualType ToType = Importer.Import(From.getIntegralType()); if (ToType.isNull()) return TemplateArgument(); return TemplateArgument(From, ToType); } case TemplateArgument::Declaration: { ValueDecl *FromD = From.getAsDecl(); if (ValueDecl *To = cast_or_null(Importer.Import(FromD))) return TemplateArgument(To, From.isDeclForReferenceParam()); return TemplateArgument(); } case TemplateArgument::NullPtr: { QualType ToType = Importer.Import(From.getNullPtrType()); if (ToType.isNull()) return TemplateArgument(); return TemplateArgument(ToType, /*isNullPtr*/true); } case TemplateArgument::Template: { TemplateName ToTemplate = Importer.Import(From.getAsTemplate()); if (ToTemplate.isNull()) return TemplateArgument(); return TemplateArgument(ToTemplate); } case TemplateArgument::TemplateExpansion: { TemplateName ToTemplate = Importer.Import(From.getAsTemplateOrTemplatePattern()); if (ToTemplate.isNull()) return TemplateArgument(); return TemplateArgument(ToTemplate, From.getNumTemplateExpansions()); } case TemplateArgument::Expression: if (Expr *ToExpr = Importer.Import(From.getAsExpr())) return TemplateArgument(ToExpr); return TemplateArgument(); case TemplateArgument::Pack: { SmallVector ToPack; ToPack.reserve(From.pack_size()); if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack)) return TemplateArgument(); TemplateArgument *ToArgs = new (Importer.getToContext()) TemplateArgument[ToPack.size()]; std::copy(ToPack.begin(), ToPack.end(), ToArgs); return TemplateArgument(ToArgs, ToPack.size()); } } llvm_unreachable("Invalid template argument kind"); } TemplateArgumentLoc ASTNodeImporter::ImportTemplateArgumentLoc( const TemplateArgumentLoc &TALoc) { TemplateArgument Arg = ImportTemplateArgument(TALoc.getArgument()); TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo(); TemplateArgumentLocInfo ToInfo; if (Arg.getKind() == TemplateArgument::Expression) { Expr *E = Importer.Import(FromInfo.getAsExpr()); assert(E); ToInfo = TemplateArgumentLocInfo(E); } else if (Arg.getKind() == TemplateArgument::Type) { TypeSourceInfo *TSI = Importer.Import(FromInfo.getAsTypeSourceInfo()); assert(TSI); ToInfo = TemplateArgumentLocInfo(TSI); } else { ToInfo = TemplateArgumentLocInfo( Importer.Import(FromInfo.getTemplateQualifierLoc()), Importer.Import(FromInfo.getTemplateNameLoc()), Importer.Import(FromInfo.getTemplateEllipsisLoc())); } return TemplateArgumentLoc(Arg, ToInfo); } bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs, unsigned NumFromArgs, SmallVectorImpl &ToArgs) { for (unsigned I = 0; I != NumFromArgs; ++I) { TemplateArgument To = ImportTemplateArgument(FromArgs[I]); if (To.isNull() && !FromArgs[I].isNull()) return true; ToArgs.push_back(To); } return false; } bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, bool Complain) { // Eliminate a potential failure point where we attempt to re-import // something we're trying to import while completing ToRecord. Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord); if (ToOrigin) { RecordDecl *ToOriginRecord = dyn_cast(ToOrigin); if (ToOriginRecord) ToRecord = ToOriginRecord; } StructuralEquivalenceContext Ctx(Importer.getFromContext(), ToRecord->getASTContext(), Importer.getNonEquivalentDecls(), false, Complain); return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord); } bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, bool Complain) { StructuralEquivalenceContext Ctx( Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls(), false, Complain); return Ctx.IsStructurallyEquivalent(FromVar, ToVar); } bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) { StructuralEquivalenceContext Ctx(Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls()); return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum); } bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC) { const llvm::APSInt &FromVal = FromEC->getInitVal(); const llvm::APSInt &ToVal = ToEC->getInitVal(); return FromVal.isSigned() == ToVal.isSigned() && FromVal.getBitWidth() == ToVal.getBitWidth() && FromVal == ToVal; } bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To, bool Complain) { StructuralEquivalenceContext Ctx(Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls(), false, Complain); return Ctx.IsStructurallyEquivalent(From, To); } bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From, FunctionTemplateDecl *To) { StructuralEquivalenceContext Ctx(Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls(), false, false); return Ctx.IsStructurallyEquivalent(From, To); } bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To) { StructuralEquivalenceContext Ctx(Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls()); return Ctx.IsStructurallyEquivalent(From, To); } Decl *ASTNodeImporter::VisitDecl(Decl *D) { Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) << D->getDeclKindName(); return 0; } Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { TranslationUnitDecl *ToD = Importer.getToContext().getTranslationUnitDecl(); Importer.Imported(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { // Does anybody know how to import it correctly? // Import the context of this declaration. DeclContext *DC = Importer.ImportContext(D->getDeclContext()); assert(DC); if (!DC) return NULL; DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); assert(LexicalDC); if (!LexicalDC) return NULL; } // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); EmptyDecl *ToD = EmptyDecl::Create(Importer.getToContext(), DC, Loc); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); return ToD; } Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { // Import the major distinguishing characteristics of this namespace. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; NamespaceDecl *MergeWithNamespace = 0; if (!Name) { // This is an anonymous namespace. Adopt an existing anonymous // namespace if we can. // FIXME: Not testable. if (TranslationUnitDecl *TU = dyn_cast(DC)) MergeWithNamespace = TU->getAnonymousNamespace(); else MergeWithNamespace = cast(DC)->getAnonymousNamespace(); } else { SmallVector ConflictingDecls; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace)) continue; if (NamespaceDecl *FoundNS = dyn_cast(FoundDecls[I])) { MergeWithNamespace = FoundNS; ConflictingDecls.clear(); break; } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(), ConflictingDecls.size()); } } // Create the "to" namespace, if needed. NamespaceDecl *ToNamespace = MergeWithNamespace; if (!ToNamespace) { ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC, D->isInline(), Importer.Import(D->getLocStart()), Loc, Name.getAsIdentifierInfo(), /*PrevDecl=*/0); // If this is an anonymous namespace, register it as the anonymous // namespace within its context. if (!Name) { if (TranslationUnitDecl *TU = dyn_cast(DC)) TU->setAnonymousNamespace(ToNamespace); else cast(DC)->setAnonymousNamespace(ToNamespace); } Importer.Imported(D, ToNamespace); Decl *ToPrevD = Importer.Import(D->getPreviousDecl()); assert(ToPrevD || !D->getPreviousDecl()); // Setting a previous declaration to NULL explicitly resets all redeclaration // chains already built if (ToPrevD && ToPrevD != ToNamespace) { ToNamespace->setPreviousDecl(cast_or_null(ToPrevD)); } ToNamespace->AnonOrFirstNamespaceAndInline.setPointer( ToNamespace->getFirstDecl()); ToNamespace->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToNamespace); } Importer.Imported(D, ToNamespace); ImportDeclContext(D); ImportAttributes(D, ToNamespace); return ToNamespace; } Decl *ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { // Import the major distinguishing characteristics of this namespace. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // If this typedef is not in block scope, determine whether we've // seen a typedef with the same name (that we can merge with) or any // other entity by that name (which name lookup could conflict with). if (!DC->isFunctionOrMethod()) { SmallVector ConflictingDecls; unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (NamespaceAliasDecl *FoundAlias= dyn_cast(FoundDecls[I])) { // FIXME: Is check for POINTEE identifier is a solution? if (IsStructurallyEquivalent(D->getIdentifier(), FoundAlias->getIdentifier())) return Importer.Imported(D, FoundAlias); } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) { assert(false); return NULL; } } } NamespaceDecl *TargetDecl = cast( Importer.Import(D->getNamespace())); assert(TargetDecl); if (!TargetDecl) return NULL; IdentifierInfo *ToII = Importer.Import(D->getIdentifier()); if (!ToII) { assert(false); return NULL; } NestedNameSpecifierLoc ToQLoc = Importer.Import(D->getQualifierLoc()); NamespaceAliasDecl *ToD = NamespaceAliasDecl::Create( Importer.getToContext(), DC, Importer.Import(D->getNamespaceLoc()), Importer.Import(D->getAliasLoc()), ToII, ToQLoc, Importer.Import(D->getTargetNameLoc()), TargetDecl); Importer.Imported(D, ToD); ImportAttributes(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) { DeclContext *DC = Importer.ImportContext(D->getDeclContext()); if (!DC) return NULL; DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return NULL; } // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); Expr *AssertExpr = Importer.Import(D->getAssertExpr()); assert(AssertExpr); if (!AssertExpr) return NULL; StringLiteral *Message = cast_or_null( Importer.Import(D->getMessage())); assert(Message); if (!Message) return NULL; StaticAssertDecl *ToD = StaticAssertDecl::Create( Importer.getToContext(), DC, Loc, AssertExpr, Message, Importer.Import(D->getRParenLoc()), D->isFailed()); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); Importer.Imported(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) { DeclContext *DC = Importer.ImportContext(D->getDeclContext()); if (!DC) return NULL; DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return NULL; } AccessSpecDecl *ToD = AccessSpecDecl::Create( Importer.getToContext(), D->getAccess(), DC, Importer.Import(D->getAccessSpecifierLoc()), Importer.Import(D->getColonLoc())); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); Importer.Imported(D, ToD); ImportAttributes(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { // Import the major distinguishing characteristics of this typedef. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // If this typedef is not in block scope, determine whether we've // seen a typedef with the same name (that we can merge with) or any // other entity by that name (which name lookup could conflict with). if (!DC->isFunctionOrMethod()) { SmallVector ConflictingDecls; unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (TypedefNameDecl *FoundTypedef = dyn_cast(FoundDecls[I])) { if (!FoundTypedef->getUnderlyingType()->isIncompleteType() && Importer.IsStructurallyEquivalent( D->getUnderlyingType(), FoundTypedef->getUnderlyingType(), false, false)) return Importer.Imported(D, FoundTypedef); } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } } // Import the underlying type of this typedef; QualType T = Importer.Import(D->getUnderlyingType()); if (T.isNull()) return 0; // Create the new typedef node. TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); SourceLocation StartL = Importer.Import(D->getLocStart()); TypedefNameDecl *ToTypedef; if (IsAlias) ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC, StartL, Loc, Name.getAsIdentifierInfo(), TInfo); else ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC, StartL, Loc, Name.getAsIdentifierInfo(), TInfo); ImportAttributes(D, ToTypedef); ToTypedef->setAccess(D->getAccess()); Importer.Imported(D, ToTypedef); ToTypedef->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToTypedef); return ToTypedef; } Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) { return VisitTypedefNameDecl(D, /*IsAlias=*/false); } Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) { return VisitTypedefNameDecl(D, /*IsAlias=*/true); } Decl *ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { // Import the major distinguishing characteristics of this typedef. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // If this typedef is not in block scope, determine whether we've // seen a typedef with the same name (that we can merge with) or any // other entity by that name (which name lookup could conflict with). if (!DC->isFunctionOrMethod()) { SmallVector ConflictingDecls; unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (TypeAliasTemplateDecl *FoundAlias = dyn_cast(FoundDecls[I])) return Importer.Imported(D, FoundAlias); ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } } TemplateParameterList *Params = ImportTemplateParameterList( D->getTemplateParameters()); assert(Params); if (!Params) return NULL; NamedDecl *TemplDecl = cast(Importer.Import(D->getTemplatedDecl())); assert(TemplDecl); if (!TemplDecl) return NULL; TypeAliasTemplateDecl *ToD = TypeAliasTemplateDecl::Create( Importer.getToContext(), DC, Loc, Name, Params, TemplDecl); ImportAttributes(D, ToD); ToD->setAccess(D->getAccess()); Importer.Imported(D, ToD); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); return ToD; } Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) { // Import the major distinguishing characteristics of this label. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; assert(LexicalDC->isFunctionOrMethod()); LabelDecl *Res = NULL; if (D->isGnuLocal()) Res = LabelDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getLocation()), Name.getAsIdentifierInfo(), Importer.Import(D->getLocStart())); else Res = LabelDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getLocation()), Name.getAsIdentifierInfo()); Importer.Imported(D, Res); Res->setStmt(cast(Importer.Import(D->getStmt()))); Res->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(Res); ImportAttributes(D, Res); return Res; } Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { // Import the major distinguishing characteristics of this enum. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Figure out what enum name we're looking for. unsigned IDNS = Decl::IDNS_Tag; DeclarationName SearchName = Name; if (!SearchName && D->getTypedefNameForAnonDecl()) { SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName()); IDNS = Decl::IDNS_Ordinary; } else if (Importer.getToContext().getLangOpts().CPlusPlus) IDNS |= Decl::IDNS_Ordinary; // We may already have an enum of the same name; try to find and match it. if (!DC->isFunctionOrMethod() && SearchName) { SmallVector ConflictingDecls; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; Decl *Found = FoundDecls[I]; if (TypedefNameDecl *Typedef = dyn_cast(Found)) { if (const TagType *Tag = Typedef->getUnderlyingType()->getAs()) Found = Tag->getDecl(); } if (EnumDecl *FoundEnum = dyn_cast(Found)) { if (IsStructuralMatch(D, FoundEnum)) return Importer.Imported(D, FoundEnum); } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); } } // Create the enum declaration. EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getLocStart()), Loc, Name.getAsIdentifierInfo(), 0, D->isScoped(), D->isScopedUsingClassTag(), D->isFixed()); // Import the qualifier, if any. D2->setQualifierInfo(Importer.Import(D->getQualifierLoc())); ImportAttributes(D, D2); D2->setAccess(D->getAccess()); Importer.Imported(D, D2); D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); // Import the integer type. QualType ToIntegerType = Importer.Import(D->getIntegerType()); // getIntegerType().isNull == true for forward enum declarations assert(!ToIntegerType.isNull() || D->getIntegerType().isNull()); if (ToIntegerType.isNull() && !D->getIntegerType().isNull()) return 0; D2->setIntegerType(ToIntegerType); // Import the definition if (D->isCompleteDefinition() && ImportDefinition(D, D2)) return 0; if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) { TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind(); EnumDecl *ND = cast_or_null( Importer.Import(D->getInstantiatedFromMemberEnum())); assert(ND); D2->setInstantiationOfMemberEnum(ND, SK); D2->getMemberSpecializationInfo()->setPointOfInstantiation( Importer.Import(MemberInfo->getPointOfInstantiation())); } return D2; } Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { // If this record has a definition in the translation unit we're coming from, // but this particular declaration is not that definition, import the // definition and map to that. TagDecl *Definition = D->getDefinition(); if (Definition && Definition != D) { Decl *ImportedDef = Importer.Import(Definition); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } // Import the major distinguishing characteristics of this record. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; if (Decl *Imp = Importer.GetImported(D)) return Imp; // Figure out what structure name we're looking for. unsigned IDNS = Decl::IDNS_Tag; DeclarationName SearchName = Name; if (!SearchName && D->getTypedefNameForAnonDecl()) { SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName()); IDNS |= Decl::IDNS_Ordinary; } else if (Importer.getToContext().getLangOpts().CPlusPlus) IDNS |= Decl::IDNS_Ordinary; // We may already have a record of the same name; try to find and match it. RecordDecl *AdoptDecl = 0; if (!DC->isFunctionOrMethod()) { SmallVector ConflictingDecls; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; Decl *Found = FoundDecls[I]; if (TypedefNameDecl *Typedef = dyn_cast(Found)) { if (const TagType *Tag = Typedef->getUnderlyingType()->getAs()) Found = Tag->getDecl(); } if (RecordDecl *FoundRecord = dyn_cast(Found)) { if (D->isAnonymousStructOrUnion() && FoundRecord->isAnonymousStructOrUnion()) { // If both anonymous structs/unions are in a record context, make sure // they occur in the same location in the context records. if (Optional Index1 = findAnonymousStructOrUnionIndex(D)) { if (Optional Index2 = findAnonymousStructOrUnionIndex(FoundRecord)) { if (*Index1 != *Index2) continue; } } } if (RecordDecl *FoundDef = FoundRecord->getDefinition()) { if ((SearchName && !D->isCompleteDefinition()) || (D->isCompleteDefinition() && D->isAnonymousStructOrUnion() == FoundDef->isAnonymousStructOrUnion() && IsStructuralMatch(D, FoundDef, false))) { // The record types structurally match, or the "from" translation // unit only had a forward declaration anyway; call it the same // function. // FIXME: For C++, we should also merge methods here. if (CXXRecordDecl *CRD = dyn_cast(FoundDef)) if (!CRD->isDependentType() && CRD->needsImplicitDestructor() && !CRD->getDestructor()) Importer.getToSema()->DeclareImplicitDestructor(CRD); return Importer.Imported(D, FoundDef); } } else if (!D->isCompleteDefinition()) { // We have a forward declaration of this type, so adopt that forward // declaration rather than building a new one. AdoptDecl = FoundRecord; continue; } else if (SearchName && D->isCompleteDefinition()) { // We have a complete declaration of this type, so adopt found forward // declaration rather than building a new one. AdoptDecl = FoundRecord; continue; } else if (!SearchName) { continue; } } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty() && SearchName) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); } } // Create the record declaration. RecordDecl *D2 = AdoptDecl; SourceLocation StartLoc = Importer.Import(D->getLocStart()); if (!D2) { if (isa(D) || Importer.getToContext().getLangOpts().CPlusPlus) { CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc, Name.getAsIdentifierInfo()); D2 = D2CXX; D2->setAccess(D->getAccess()); Importer.Imported(D, D2); if (CXXRecordDecl *FromCXX = dyn_cast(D)) { if (ClassTemplateDecl *FromDescribed = FromCXX->getDescribedClassTemplate()) { ClassTemplateDecl *ToDescribed = cast_or_null( Importer.Import(FromDescribed)); assert(ToDescribed); if (!ToDescribed) return NULL; D2CXX->setDescribedClassTemplate(ToDescribed); } else if (MemberSpecializationInfo *MemberInfo = FromCXX->getMemberSpecializationInfo()) { TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind(); CXXRecordDecl *RD = cast_or_null( Importer.Import(FromCXX->getInstantiatedFromMemberClass())); assert(RD); D2CXX->setInstantiationOfMemberClass(RD, SK); D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( Importer.Import(MemberInfo->getPointOfInstantiation())); } } } else { D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc, Name.getAsIdentifierInfo()); } D2->setQualifierInfo(Importer.Import(D->getQualifierLoc())); if (D->isAnonymousStructOrUnion()) D2->setAnonymousStructOrUnion(true); Importer.Imported(D, D2); D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); } ImportAttributes(D, D2); Importer.Imported(D, D2); D2->setImplicit(D->isImplicit()); if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default)) return 0; /* RecordDecl *Def = D->getDefinition(); RecordDecl *ToDef = cast_or_null(Importer.Import(Def)); assert(ToDef || !Def); if (Def && !ToDef) return 0; */ return D2; } Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { // Import the major distinguishing characteristics of this enumerator. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; // Determine whether there are any other declarations with the same name and // in the same context. if (!LexicalDC->isFunctionOrMethod()) { SmallVector ConflictingDecls; unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (EnumConstantDecl *FoundEnumConstant = dyn_cast(FoundDecls[I])) { if (IsStructuralMatch(D, FoundEnumConstant)) return Importer.Imported(D, FoundEnumConstant); } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } } Expr *Init = Importer.Import(D->getInitExpr()); if (D->getInitExpr() && !Init) return 0; EnumConstantDecl *ToEnumerator = EnumConstantDecl::Create(Importer.getToContext(), cast(DC), Loc, Name.getAsIdentifierInfo(), T, Init, D->getInitVal()); ImportAttributes(D, ToEnumerator); ToEnumerator->setAccess(D->getAccess()); ToEnumerator->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToEnumerator); LexicalDC->addDeclInternal(ToEnumerator); return ToEnumerator; } Decl *ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { // Import the major distinguishing characteristics of this function. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Try to find a function in our own ("to") context with the same name, same // type, and in the same context as the function we're importing. if (!LexicalDC->isFunctionOrMethod()) { unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (FunctionTemplateDecl *FoundFunction = dyn_cast(FoundDecls[I])) { if (FoundFunction->hasExternalFormalLinkage() && D->hasExternalFormalLinkage()) { if (IsStructuralMatch(D, FoundFunction)) { Importer.Imported(D, FoundFunction); // FIXME: Actually try to merge the body and other attributes. return FoundFunction; } } } } } std::vector Decls; TemplateParameterList *SourceParamList = D->getTemplateParameters(); for (TemplateParameterList::iterator I = SourceParamList->begin(), E = SourceParamList->end(); I != E; ++I) { if (NamedDecl *ND = cast_or_null(Importer.Import(*I))) Decls.push_back(ND); else { assert(false); return NULL; } } FunctionDecl *TemplatedFD = cast_or_null( Importer.Import(D->getTemplatedDecl())); assert(TemplatedFD); if (!TemplatedFD) return NULL; FunctionTemplateDecl *ToFunction = FunctionTemplateDecl::Create( Importer.getToContext(), DC, Importer.Import(D->getLocation()), Name, TemplateParameterList::Create( Importer.getToContext(), Importer.Import(SourceParamList->getTemplateLoc()), Importer.Import(SourceParamList->getLAngleLoc()), Decls.data(), Decls.size(), Importer.Import(SourceParamList->getRAngleLoc())), TemplatedFD); TemplatedFD->setDescribedFunctionTemplate(ToFunction); ImportAttributes(D, ToFunction); ToFunction->setAccess(D->getAccess()); ToFunction->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToFunction); // Add this function to the lexical context. LexicalDC->addDeclInternal(ToFunction); return ToFunction; } Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { // Import the major distinguishing characteristics of this function. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; const FunctionDecl *FoundWithoutBody = NULL; // Try to find a function in our own ("to") context with the same name, same // type, and in the same context as the function we're importing. if (!LexicalDC->isFunctionOrMethod()) { SmallVector ConflictingDecls; unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (FunctionDecl *FoundFunction = dyn_cast(FoundDecls[I])) { if (FoundFunction->hasExternalFormalLinkage() && D->hasExternalFormalLinkage()) { if (Importer.IsStructurallyEquivalent(D->getType(), FoundFunction->getType(), false)) { // FIXME: Actually try to merge the body and other attributes. const FunctionDecl *FromBodyDecl = NULL; D->hasBody(FromBodyDecl); if (D == FromBodyDecl && !FoundFunction->hasBody()) { // This function is needed to merge completely. FoundWithoutBody = FoundFunction; break; } Importer.Imported(D, FoundFunction); return FoundFunction; } // FIXME: Check for overloading more carefully, e.g., by boosting // Sema::IsOverload out to the AST library. // Function overloading is okay in C++. if (Importer.getToContext().getLangOpts().CPlusPlus || Importer.getFromContext().getLangOpts().CPlusPlus) continue; // Complain about inconsistent function types. Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent) << Name << D->getType() << FoundFunction->getType(); Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) << FoundFunction->getType(); } } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } } DeclarationNameInfo NameInfo(Name, Loc); // Import additional name location/type info. ImportDeclarationNameLoc(D->getNameInfo(), NameInfo); QualType FromTy = D->getType(); bool usedDifferentExceptionSpec = false; if (const FunctionProtoType * FromFPT = D->getType()->getAs()) { FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo(); // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the // FunctionDecl that we are importing the FunctionProtoType for. // To avoid an infinite recursion when importing, create the FunctionDecl // with a simplified function type and update it afterwards. if (FromEPI.ExceptionSpecDecl || FromEPI.ExceptionSpecTemplate || FromEPI.NoexceptExpr) { FunctionProtoType::ExtProtoInfo DefaultEPI; FromTy = Importer.getFromContext().getFunctionType( FromFPT->getResultType(), FromFPT->getArgTypes(), DefaultEPI); usedDifferentExceptionSpec = true; } } // Import the type. QualType T = Importer.Import(FromTy); if (T.isNull()) return 0; // Import the function parameters. SmallVector Parameters; for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end(); P != PEnd; ++P) { ParmVarDecl *ToP = cast_or_null(Importer.Import(*P)); if (!ToP) return 0; Parameters.push_back(ToP); } // Create the imported function. TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); FunctionDecl *ToFunction = 0; if (CXXConstructorDecl *FromConstructor = dyn_cast(D)) { ToFunction = CXXConstructorDecl::Create(Importer.getToContext(), cast(DC), Importer.Import(D->getInnerLocStart()), NameInfo, T, TInfo, FromConstructor->isExplicit(), D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()); } else if (isa(D)) { ToFunction = CXXDestructorDecl::Create(Importer.getToContext(), cast(DC), Importer.Import(D->getInnerLocStart()), NameInfo, T, TInfo, D->isInlineSpecified(), D->isImplicit()); } else if (CXXConversionDecl *FromConversion = dyn_cast(D)) { ToFunction = CXXConversionDecl::Create(Importer.getToContext(), cast(DC), Importer.Import(D->getInnerLocStart()), NameInfo, T, TInfo, D->isInlineSpecified(), FromConversion->isExplicit(), D->isConstexpr(), Importer.Import(D->getLocEnd())); } else if (CXXMethodDecl *Method = dyn_cast(D)) { ToFunction = CXXMethodDecl::Create(Importer.getToContext(), cast(DC), Importer.Import(D->getInnerLocStart()), NameInfo, T, TInfo, Method->getCanonicalDecl()->getStorageClass(), Method->isInlineSpecified(), D->isConstexpr(), Importer.Import(D->getLocEnd())); } else { ToFunction = FunctionDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getInnerLocStart()), NameInfo, T, TInfo, D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(), D->hasWrittenPrototype(), D->isConstexpr()); } // Import the qualifier, if any. ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc())); ImportAttributes(D, ToFunction); ToFunction->setAccess(D->getAccess()); ToFunction->setLexicalDeclContext(LexicalDC); ToFunction->setVirtualAsWritten(D->isVirtualAsWritten()); ToFunction->setTrivial(D->isTrivial()); ToFunction->setPure(D->isPure()); Importer.Imported(D, ToFunction); // Set the parameters. for (unsigned I = 0, N = Parameters.size(); I != N; ++I) Parameters[I]->setOwningFunction(ToFunction); ToFunction->setParams(Parameters); if (usedDifferentExceptionSpec) { // Update FunctionProtoType::ExtProtoInfo. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; ToFunction->setType(T); } // If it is a template, import all related things. switch (D->getTemplatedKind()) { case FunctionDecl::TK_NonTemplate: break; case FunctionDecl::TK_FunctionTemplate: { break; } case FunctionDecl::TK_MemberSpecialization: { FunctionDecl *InstFD = cast_or_null( Importer.Import(D->getInstantiatedFromMemberFunction())); assert(InstFD); if (!InstFD) return NULL; TemplateSpecializationKind TSK = D->getTemplateSpecializationKind(); SourceLocation POI = Importer.Import(D->getMemberSpecializationInfo() ->getPointOfInstantiation()); ToFunction->setInstantiationOfMemberFunction(InstFD, TSK); ToFunction->getMemberSpecializationInfo()->setPointOfInstantiation(POI); break; } case FunctionDecl::TK_FunctionTemplateSpecialization: { FunctionTemplateSpecializationInfo * FTSInfo = D->getTemplateSpecializationInfo(); FunctionTemplateDecl *Template = cast_or_null( Importer.Import(FTSInfo->getTemplate())); TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind(); // Template arguments. llvm::ArrayRef TemplArgs = FTSInfo->TemplateArguments->asArray(); SmallVector ToTemplArgs; ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), ToTemplArgs); TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy( Importer.getToContext(), ToTemplArgs.data(), ToTemplArgs.size()); SourceLocation LAngleLoc, RAngleLoc; TemplateArgumentListInfo FromTAInfo, ToTAInfo; if (FTSInfo->TemplateArgumentsAsWritten) { // Import TemplateArgumentListInfo LAngleLoc = Importer.Import(FTSInfo->TemplateArgumentsAsWritten ->LAngleLoc); RAngleLoc = Importer.Import(FTSInfo->TemplateArgumentsAsWritten ->RAngleLoc); ToTAInfo = TemplateArgumentListInfo(LAngleLoc, RAngleLoc); FTSInfo->TemplateArgumentsAsWritten->copyInto(FromTAInfo); for (unsigned i = 0, e = FromTAInfo.size(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromTAInfo[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } } SourceLocation POI = Importer.Import(FTSInfo->getPointOfInstantiation()); FunctionTemplateSpecializationInfo *ToFTInfo = FunctionTemplateSpecializationInfo::Create( Importer.getToContext(), ToFunction, Template, TSK, ToTAList, FTSInfo->TemplateArgumentsAsWritten ? &ToTAInfo : 0, POI); ToFunction->TemplateOrSpecialization = ToFTInfo; break; } case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { // Templates. DependentFunctionTemplateSpecializationInfo *FromInfo = D->getDependentSpecializationInfo(); UnresolvedSet<8> TemplDecls; unsigned NumTemplates = FromInfo->getNumTemplates(); for (unsigned i = 0; i < NumTemplates; i++) TemplDecls.addDecl(FromInfo->getTemplate(i)); // Templates args. // Import TemplateArgumentListInfo SourceLocation LAngleLoc = Importer.Import(FromInfo->getLAngleLoc()); SourceLocation RAngleLoc = Importer.Import(FromInfo->getRAngleLoc()); TemplateArgumentListInfo ToTAInfo(LAngleLoc, RAngleLoc), FromTAInfo; for (unsigned i = 0, e = FromTAInfo.size(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromInfo->getTemplateArg(i); ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } ToFunction->setDependentTemplateSpecialization( Importer.getToContext(), TemplDecls, ToTAInfo); break; } } // Add this function to the lexical context. LexicalDC->addDeclInternal(ToFunction); const FunctionDecl *BodyDecl = NULL; D->hasBody(BodyDecl); if (D == BodyDecl) ImportDefinition(D, ToFunction); else if (BodyDecl) { Decl *ToDef = Importer.Import(const_cast(BodyDecl)); assert(ToDef); } if (FoundWithoutBody) { FunctionDecl *Recent = const_cast( FoundWithoutBody->getMostRecentDecl()); ToFunction->setPreviousDecl(Recent); } // FIXME: Other bits to merge? // Add overrided methods for MethodDecl if (const CXXMethodDecl *MD = dyn_cast(D)) { CXXMethodDecl *ToMD = cast(ToFunction); if (ToMD->isCanonicalDecl()) { for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), E = MD->end_overridden_methods(); I != E; ++I) { // FIXME: refactor const_cast CXXMethodDecl *Overridden = cast_or_null( Importer.Import(const_cast(*I))); assert(Overridden); if (!Overridden) return NULL; Importer.getToContext().addOverriddenMethod( ToMD, Overridden->getCanonicalDecl()); } } } return ToFunction; } Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) { return VisitFunctionDecl(D); } Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) { return VisitCXXMethodDecl(D); } Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) { return VisitCXXMethodDecl(D); } Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) { return VisitCXXMethodDecl(D); } static unsigned getFieldIndex(Decl *F) { RecordDecl *Owner = dyn_cast(F->getDeclContext()); if (!Owner) return 0; unsigned Index = 1; for (DeclContext::decl_iterator D = Owner->decls_begin(), DEnd = Owner->decls_end(); D != DEnd; ++D) { if (*D == F) return Index; if (isa(*D) || isa(*D)) ++Index; } return Index; } Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { // Import the major distinguishing characteristics of a variable. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Determine whether we've already imported this field. SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (FieldDecl *FoundField = dyn_cast(FoundDecls[I])) { // For anonymous fields, match up by index. if (!Name && getFieldIndex(D) != getFieldIndex(FoundField)) continue; StructuralEquivalenceContext Ctx(Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls()); if (IsStructurallyEquivalent(Ctx, D, FoundField)) { Importer.Imported(D, FoundField); return FoundField; } Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent) << Name << D->getType() << FoundField->getType(); Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) << FoundField->getType(); return 0; } } // Lookup failed. Check if a name was redefined (see adb/sysdeps.h mess) // This is a workaround for cases where field names are redefined by a macro // so we need to import a field with another name. // We need to do this because we our RecordDecl maybe already in main TU // and have a complete layout. Adding a field to this RD is unacceptable. // We do it for fields only because it does not affect other cases // (just a new declaration is constructed). if (RecordDecl *RD = dyn_cast(DC)) { for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); I != E; ++I) { SourceManager &ToMgr = Importer.getToContext().getSourceManager(); if (ToMgr.getSpellingLoc(I->getLocation()) != I->getLocation()) // suddenly macro if (SourceLocationEqual(D->getLocation(), Importer.getFromContext().getSourceManager(), ToMgr.getExpansionLoc(I->getLocation()), ToMgr)) { StructuralEquivalenceContext Ctx(Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls()); if (IsStructurallyEquivalent(Ctx, D->getType(), I->getType())) { Importer.Imported(D, *I); return *I; } } } } // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); Expr *BitWidth = Importer.Import(D->getBitWidth()); if (!BitWidth && D->getBitWidth()) return 0; if (Decl *Imp = Importer.GetImported(D)) return Imp; FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getInnerLocStart()), Loc, Name.getAsIdentifierInfo(), T, TInfo, BitWidth, D->isMutable(), D->getInClassInitStyle()); ImportAttributes(D, ToField); AccessSpecifier AccessSpec = D->getAccess(); if (isa(DC) && !isa(D->getDeclContext())) AccessSpec = AS_public; ToField->setAccess(AccessSpec); ToField->setLexicalDeclContext(LexicalDC); if (ToField->hasInClassInitializer()) ToField->setInClassInitializer(Importer.Import(D->getInClassInitializer())); ToField->setImplicit(D->isImplicit()); Importer.Imported(D, ToField); LexicalDC->addDeclInternal(ToField); return ToField; } Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { // Import the major distinguishing characteristics of a variable. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Determine whether we've already imported this field. SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (IndirectFieldDecl *FoundField = dyn_cast(FoundDecls[I])) { // For anonymous indirect fields, match up by index. if (!Name && getFieldIndex(D) != getFieldIndex(FoundField)) continue; if (Importer.IsStructurallyEquivalent(D->getType(), FoundField->getType(), !Name.isEmpty())) { Importer.Imported(D, FoundField); return FoundField; } // If there are more anonymous fields to check, continue. if (!Name && I < N-1) continue; Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent) << Name << D->getType() << FoundField->getType(); Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) << FoundField->getType(); return 0; } } // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; NamedDecl **NamedChain = new (Importer.getToContext())NamedDecl*[D->getChainingSize()]; unsigned i = 0; for (IndirectFieldDecl::chain_iterator PI = D->chain_begin(), PE = D->chain_end(); PI != PE; ++PI) { Decl* D = Importer.Import(*PI); if (!D) return 0; NamedChain[i++] = cast(D); } IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create( Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T, NamedChain, D->getChainingSize()); ImportAttributes(D, ToIndirectField); AccessSpecifier AccessSpec = D->getAccess(); if (isa(DC) && !isa(D->getDeclContext())) AccessSpec = AS_public; ToIndirectField->setAccess(AccessSpec); ToIndirectField->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToIndirectField); LexicalDC->addDeclInternal(ToIndirectField); return ToIndirectField; } Decl *ASTNodeImporter::VisitFriendDecl(FriendDecl *D) { // Import the major distinguishing characteristics of a variable. DeclContext *DC = Importer.ImportContext(D->getDeclContext()); DeclContext *LexicalDC = D->getDeclContext() == D->getLexicalDeclContext() ? DC : Importer.ImportContext(D->getDeclContext()); assert(DC && LexicalDC); if (!DC || !LexicalDC) return NULL; // Determine whether we've already imported this field. CXXRecordDecl *RD = dyn_cast(DC); FriendDecl *ImportedFriend = RD->getFirstFriend(); StructuralEquivalenceContext Context( Importer.getFromContext(), Importer.getToContext(), Importer.getNonEquivalentDecls(), false, false); while (ImportedFriend) { if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) { if (Context.IsStructurallyEquivalent(D->getFriendDecl(), ImportedFriend->getFriendDecl())) return Importer.Imported(D, ImportedFriend); } else if (D->getFriendType() && ImportedFriend->getFriendType()) { if (Importer.IsStructurallyEquivalent( D->getFriendType()->getType(), ImportedFriend->getFriendType()->getType(), true, true)) return Importer.Imported(D, ImportedFriend); } ImportedFriend = ImportedFriend->getNextFriend(); } // Not found. Create it. FriendDecl::FriendUnion ToFU; if (NamedDecl *FriendD = D->getFriendDecl()) ToFU = cast(Importer.Import(FriendD)); else ToFU = Importer.Import(D->getFriendType()); assert(ToFU); if (!ToFU) return NULL; SmallVector ToTPLists; ToTPLists.reserve(D->NumTPLists); TemplateParameterList **FromTPLists = D->getTPLists(); for (int i = 0; i < D->NumTPLists; i++) { TemplateParameterList *List = ImportTemplateParameterList(FromTPLists[i]); assert(List); if (!List) return NULL; ToTPLists.push_back(List); } size_t Size = sizeof(FriendDecl) + ToTPLists.size() * sizeof(TemplateParameterList*); void *Mem = Importer.getToContext().Allocate(Size); FriendDecl *FrD = new (Mem) FriendDecl(DC, Importer.Import(D->getLocation()), ToFU, Importer.Import(D->getFriendLoc()), ToTPLists); Importer.Imported(D, FrD); RD->pushFriendDecl(FrD); ImportAttributes(D, FrD); FrD->setAccess(D->getAccess()); FrD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(FrD); // Seems like we don't need to set NextFriend return FrD; } Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) { // Import the major distinguishing characteristics of an ivar. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Determine whether we've already imported this ivar SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (ObjCIvarDecl *FoundIvar = dyn_cast(FoundDecls[I])) { if (Importer.IsStructurallyEquivalent(D->getType(), FoundIvar->getType())) { Importer.Imported(D, FoundIvar); return FoundIvar; } Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent) << Name << D->getType() << FoundIvar->getType(); Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here) << FoundIvar->getType(); return 0; } } // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); Expr *BitWidth = Importer.Import(D->getBitWidth()); if (!BitWidth && D->getBitWidth()) return 0; ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(), cast(DC), Importer.Import(D->getInnerLocStart()), Loc, Name.getAsIdentifierInfo(), T, TInfo, D->getAccessControl(), BitWidth, D->getSynthesize(), D->getBackingIvarReferencedInAccessor()); ImportAttributes(D, ToIvar); ToIvar->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToIvar); LexicalDC->addDeclInternal(ToIvar); return ToIvar; } bool ASTNodeImporter::ImportVarDeclInfo(VarDecl *From, VarDecl *To) { ImportAttributes(From, To); To->setConstexpr(From->isConstexpr()); To->setCXXForRangeDecl(From->isCXXForRangeDecl()); To->setExceptionVariable(From->isExceptionVariable()); To->setARCPseudoStrong(From->isARCPseudoStrong()); To->setImplicit(From->isImplicit()); To->setInitCapture(From->isInitCapture()); To->setInitStyle(From->getInitStyle()); To->setNRVOVariable(From->isNRVOVariable()); To->setTSCSpec(From->getTSCSpec()); if (VarTemplateDecl *TemplD = From->getDescribedVarTemplate()) { VarTemplateDecl *ToTempl = cast_or_null( Importer.Import(TemplD)); assert(ToTempl); if (!ToTempl) return true; To->setDescribedVarTemplate(TemplD); } else if (MemberSpecializationInfo *MemberInfo = From->getMemberSpecializationInfo()) { TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind(); VarDecl *VD = cast_or_null( Importer.Import(From->getInstantiatedFromStaticDataMember())); assert(VD); if (!VD) return true; To->setInstantiationOfStaticDataMember(VD, SK); To->getMemberSpecializationInfo()->setPointOfInstantiation( Importer.Import(MemberInfo->getPointOfInstantiation())); } return false; } Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { // Import the major distinguishing characteristics of a variable. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Try to find a variable in our own ("to") context with the same name and // in the same context as the variable we're importing. if (D->isFileVarDecl()) { VarDecl *MergeWithVar = 0; SmallVector ConflictingDecls; unsigned IDNS = Decl::IDNS_Ordinary; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; if (VarDecl *FoundVar = dyn_cast(FoundDecls[I])) { // We have found a variable that we may need to merge with. Check it. if (FoundVar->hasExternalFormalLinkage() && D->hasExternalFormalLinkage()) { if (Importer.IsStructurallyEquivalent(D->getType(), FoundVar->getType())) { MergeWithVar = FoundVar; break; } const ArrayType *FoundArray = Importer.getToContext().getAsArrayType(FoundVar->getType()); const ArrayType *TArray = Importer.getToContext().getAsArrayType(D->getType()); if (FoundArray && TArray) { if (isa(FoundArray) && (isa(TArray) || isa(TArray))) { // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; FoundVar->setType(T); MergeWithVar = FoundVar; break; } else if (isa(TArray) && isa(FoundArray)) { MergeWithVar = FoundVar; break; } } Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent) << Name << D->getType() << FoundVar->getType(); Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here) << FoundVar->getType(); // Try to merge a found variable without any guarantee it is good. // There were some cases where an external variable was declared // without a qualifier and declared with a qualifier. // Also throw a diagnostic as a warning for a programmer. if (Importer.IsStructurallyEquivalent(D->getType(), FoundVar->getType(), true, false)) { MergeWithVar = FoundVar; break; } } } ConflictingDecls.push_back(FoundDecls[I]); } if (MergeWithVar) { // An equivalent variable with external linkage has been found. Link // the two declarations, then merge them. Importer.Imported(D, MergeWithVar); if (VarDecl *DDef = D->getDefinition()) { if (!MergeWithVar->getDefinition()) { Expr *Init = Importer.Import(DDef->getInit()); MergeWithVar->setInit(Init); if (DDef->isInitKnownICE()) { EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt(); Eval->CheckedICE = true; Eval->IsICE = DDef->isInitICE(); } } } return MergeWithVar; } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } } // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; // Create the imported variable. TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getInnerLocStart()), Loc, Name.getAsIdentifierInfo(), T, TInfo, D->getStorageClass()); ImportVarDeclInfo(D, ToVar); ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc())); ToVar->setAccess(D->getAccess()); Importer.Imported(D, ToVar); ToVar->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToVar); // Merge the initializer. if (D->hasInit()) if (ImportDefinition(D, ToVar)) return 0; return ToVar; } Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { // Parameters are created in the translation unit's context, then moved // into the function declaration's context afterward. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return 0; // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); // Import the parameter's type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; // Create the imported parameter. ImplicitParamDecl *ToParm = ImplicitParamDecl::Create(Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T); Importer.Imported(D, ToParm); ImportVarDeclInfo(D, ToParm); return ToParm; } Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { // Parameters are created in the translation unit's context, then moved // into the function declaration's context afterward. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return 0; // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); // Import the parameter's type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; // Create the imported parameter. TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getInnerLocStart()), Loc, Name.getAsIdentifierInfo(), T, TInfo, D->getStorageClass(), /*FIXME: Default argument*/ 0); Importer.Imported(D, ToParm); ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg()); ToParm->setKNRPromoted(D->isKNRPromoted()); ImportVarDeclInfo(D, ToParm); if (D->hasUninstantiatedDefaultArg()) { Expr *UDArg = D->getUninstantiatedDefaultArg(); Expr *ToUD = Importer.Import(UDArg); assert(ToUD); if (!ToUD) return NULL; ToParm->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg()); } else if (Expr *DefaultArg = D->getDefaultArg()) { Expr *ToDefaultArg = Importer.Import(DefaultArg); assert(ToDefaultArg); if (!ToDefaultArg) return NULL; ToParm->setDefaultArg(ToDefaultArg); } if (D->hasUnparsedDefaultArg()) ToParm->setUnparsedDefaultArg(); return ToParm; } Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { // Import the major distinguishing characteristics of a method. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (ObjCMethodDecl *FoundMethod = dyn_cast(FoundDecls[I])) { if (FoundMethod->isInstanceMethod() != D->isInstanceMethod()) continue; // Check return types. if (!Importer.IsStructurallyEquivalent(D->getResultType(), FoundMethod->getResultType())) { Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent) << D->isInstanceMethod() << Name << D->getResultType() << FoundMethod->getResultType(); Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return 0; } // Check the number of parameters. if (D->param_size() != FoundMethod->param_size()) { Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent) << D->isInstanceMethod() << Name << D->param_size() << FoundMethod->param_size(); Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return 0; } // Check parameter types. for (ObjCMethodDecl::param_iterator P = D->param_begin(), PEnd = D->param_end(), FoundP = FoundMethod->param_begin(); P != PEnd; ++P, ++FoundP) { if (!Importer.IsStructurallyEquivalent((*P)->getType(), (*FoundP)->getType())) { Importer.FromDiag((*P)->getLocation(), diag::err_odr_objc_method_param_type_inconsistent) << D->isInstanceMethod() << Name << (*P)->getType() << (*FoundP)->getType(); Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here) << (*FoundP)->getType(); return 0; } } // Check variadic/non-variadic. // Check the number of parameters. if (D->isVariadic() != FoundMethod->isVariadic()) { Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent) << D->isInstanceMethod() << Name; Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return 0; } // FIXME: Any other bits we need to merge? return Importer.Imported(D, FoundMethod); } } // Import the result type. QualType ResultTy = Importer.Import(D->getResultType()); if (ResultTy.isNull()) return 0; TypeSourceInfo *ResultTInfo = Importer.Import(D->getResultTypeSourceInfo()); ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()), Name.getObjCSelector(), ResultTy, ResultTInfo, DC, D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(), D->getImplementationControl(), D->hasRelatedResultType()); // FIXME: When we decide to merge method definitions, we'll need to // deal with implicit parameters. // Import the parameters SmallVector ToParams; for (ObjCMethodDecl::param_iterator FromP = D->param_begin(), FromPEnd = D->param_end(); FromP != FromPEnd; ++FromP) { ParmVarDecl *ToP = cast_or_null(Importer.Import(*FromP)); if (!ToP) return 0; ToParams.push_back(ToP); } // Set the parameters. for (unsigned I = 0, N = ToParams.size(); I != N; ++I) ToParams[I]->setOwningFunction(ToMethod); SmallVector SelLocs; D->getSelectorLocs(SelLocs); for (int i = 0, e = SelLocs.size(); i < e; i++) SelLocs[i] = Importer.Import(SelLocs[i]); ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs); ImportAttributes(D, ToMethod); ToMethod->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToMethod); LexicalDC->addDeclInternal(ToMethod); return ToMethod; } Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { // Import the major distinguishing characteristics of a category. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; ObjCInterfaceDecl *ToInterface = cast_or_null(Importer.Import(D->getClassInterface())); if (!ToInterface) return 0; // Determine if we've already encountered this category. ObjCCategoryDecl *MergeWithCategory = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); ObjCCategoryDecl *ToCategory = MergeWithCategory; if (!ToCategory) { ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getAtStartLoc()), Loc, Importer.Import(D->getCategoryNameLoc()), Name.getAsIdentifierInfo(), ToInterface, Importer.Import(D->getIvarLBraceLoc()), Importer.Import(D->getIvarRBraceLoc())); ToCategory->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToCategory); Importer.Imported(D, ToCategory); // Import protocols SmallVector Protocols; SmallVector ProtocolLocs; ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc = D->protocol_loc_begin(); for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(), FromProtoEnd = D->protocol_end(); FromProto != FromProtoEnd; ++FromProto, ++FromProtoLoc) { ObjCProtocolDecl *ToProto = cast_or_null(Importer.Import(*FromProto)); if (!ToProto) return 0; Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } // FIXME: If we're merging, make sure that the protocol list is the same. ToCategory->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); } else { Importer.Imported(D, ToCategory); } // Import all of the members of this category. ImportDeclContext(D); // If we have an implementation, import it as well. if (D->getImplementation()) { ObjCCategoryImplDecl *Impl = cast_or_null( Importer.Import(D->getImplementation())); if (!Impl) return 0; ToCategory->setImplementation(Impl); } ImportAttributes(D, ToCategory); return ToCategory; } bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition()) { if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From); return false; } // Start the protocol definition To->startDefinition(); // Import protocols SmallVector Protocols; SmallVector ProtocolLocs; ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), FromProtoEnd = From->protocol_end(); FromProto != FromProtoEnd; ++FromProto, ++FromProtoLoc) { ObjCProtocolDecl *ToProto = cast_or_null(Importer.Import(*FromProto)); if (!ToProto) return true; Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } // FIXME: If we're merging, make sure that the protocol list is the same. To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); if (shouldForceImportDeclContext(Kind)) { // Import all of the members of this protocol. ImportDeclContext(From, /*ForceImport=*/true); } return false; } Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { // If this protocol has a definition in the translation unit we're coming // from, but this particular declaration is not that definition, import the // definition and map to that. ObjCProtocolDecl *Definition = D->getDefinition(); if (Definition && Definition != D) { Decl *ImportedDef = Importer.Import(Definition); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } // Import the major distinguishing characteristics of a protocol. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; ObjCProtocolDecl *MergeWithProtocol = 0; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) continue; if ((MergeWithProtocol = dyn_cast(FoundDecls[I]))) break; } ObjCProtocolDecl *ToProto = MergeWithProtocol; if (!ToProto) { ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC, Name.getAsIdentifierInfo(), Loc, Importer.Import(D->getAtStartLoc()), /*PrevDecl=*/0); Importer.Imported(D, ToProto); ToProto->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToProto); } Importer.Imported(D, ToProto); if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto)) return 0; ImportAttributes(D, ToProto); return ToProto; } void ASTNodeImporter::ImportAttributes(Decl *From, Decl *To) { for (Decl::attr_iterator I = From->attr_begin(), E = From->attr_end(); I != E; ++I) { Attr *ToAttr = (*I)->clone(Importer.getToContext()); ToAttr->setRange(Importer.Import((*I)->getRange())); To->addAttr(ToAttr); } } Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { DeclContext *DC = Importer.ImportContext(D->getDeclContext()); DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); SourceLocation ExternLoc = Importer.Import(D->getExternLoc()); SourceLocation LangLoc = Importer.Import(D->getLocation()); bool HasBraces = D->hasBraces(); LinkageSpecDecl *ToLinkageSpec = LinkageSpecDecl::Create(Importer.getToContext(), DC, ExternLoc, LangLoc, D->getLanguage(), HasBraces); if (HasBraces) { SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc()); ToLinkageSpec->setRBraceLoc(RBraceLoc); } ToLinkageSpec->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToLinkageSpec); Importer.Imported(D, ToLinkageSpec); ImportAttributes(D, ToLinkageSpec); return ToLinkageSpec; } Decl *ASTNodeImporter::VisitUsingDecl(UsingDecl *D) { DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return NULL; DeclarationNameInfo NameInfo(Name, Importer.Import(D->getNameInfo().getLoc())); ImportDeclarationNameLoc(D->getNameInfo(), NameInfo); // Check if it is already imported after ImportDeclParts. // This may happen because UsingShadowDecl has a pointer to its UsingDecl if (Decl *Found = Importer.GetImported(D)) return cast(Found); UsingDecl *ToD = UsingDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()), Importer.Import(D->getQualifierLoc()), NameInfo, D->hasTypename()); ImportAttributes(D, ToD); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); Importer.Imported(D, ToD); for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); I != E; ++I) { UsingShadowDecl *SD = cast(Importer.Import(*I)); ToD->addShadowDecl(SD); } return ToD; } Decl *ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) { assert(false); return NULL; } DeclContext *ToCA = Importer.ImportContext(D->getCommonAncestor()); if (!ToCA) { assert(false); return NULL; } NamespaceDecl *ToNom = cast_or_null( Importer.Import(D->getNominatedNamespace())); if (!ToNom) { assert(ToNom); return NULL; } UsingDirectiveDecl *ToD = UsingDirectiveDecl::Create( Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()), Importer.Import(D->getNamespaceKeyLocation()), Importer.Import(D->getQualifierLoc()), Importer.Import(D->getIdentLocation()), ToNom, ToCA); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); Importer.Imported(D, ToD); ImportAttributes(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitUnresolvedUsingValueDecl( UnresolvedUsingValueDecl *D) { DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return NULL; DeclarationNameInfo NameInfo(Name, Importer.Import(D->getNameInfo().getLoc())); ImportDeclarationNameLoc(D->getNameInfo(), NameInfo); UnresolvedUsingValueDecl *ToD = UnresolvedUsingValueDecl::Create( Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()), Importer.Import(D->getQualifierLoc()), NameInfo); Importer.Imported(D, ToD); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); ImportAttributes(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( UnresolvedUsingTypenameDecl *D) { DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return NULL; UnresolvedUsingTypenameDecl *ToD = UnresolvedUsingTypenameDecl::Create( Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()), Importer.Import(D->getTypenameLoc()), Importer.Import(D->getQualifierLoc()), Loc, Name); Importer.Imported(D, ToD); ToD->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToD); ImportAttributes(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) { DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return NULL; UsingShadowDecl *ToD = UsingShadowDecl::Create( Importer.getToContext(), DC, Loc, cast(Importer.Import(D->getUsingDecl())), cast_or_null(Importer.Import(D->getTargetDecl()))); ImportAttributes(D, ToD); ToD->setAccess(D->getAccess()); ToD->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToD); LexicalDC->addDeclInternal(ToD); return ToD; } bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition()) { // Check consistency of superclass. ObjCInterfaceDecl *FromSuper = From->getSuperClass(); if (FromSuper) { FromSuper = cast_or_null(Importer.Import(FromSuper)); if (!FromSuper) return true; } ObjCInterfaceDecl *ToSuper = To->getSuperClass(); if ((bool)FromSuper != (bool)ToSuper || (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { Importer.ToDiag(To->getLocation(), diag::err_odr_objc_superclass_inconsistent) << To->getDeclName(); if (ToSuper) Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) << To->getSuperClass()->getDeclName(); else Importer.ToDiag(To->getLocation(), diag::note_odr_objc_missing_superclass); if (From->getSuperClass()) Importer.FromDiag(From->getSuperClassLoc(), diag::note_odr_objc_superclass) << From->getSuperClass()->getDeclName(); else Importer.FromDiag(From->getLocation(), diag::note_odr_objc_missing_superclass); } if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From); return false; } // Start the definition. To->startDefinition(); // If this class has a superclass, import it. if (From->getSuperClass()) { ObjCInterfaceDecl *Super = cast_or_null( Importer.Import(From->getSuperClass())); if (!Super) return true; To->setSuperClass(Super); To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc())); } // Import protocols SmallVector Protocols; SmallVector ProtocolLocs; ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), FromProtoEnd = From->protocol_end(); FromProto != FromProtoEnd; ++FromProto, ++FromProtoLoc) { ObjCProtocolDecl *ToProto = cast_or_null(Importer.Import(*FromProto)); if (!ToProto) return true; Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } // FIXME: If we're merging, make sure that the protocol list is the same. To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); // Import categories. When the categories themselves are imported, they'll // hook themselves into this interface. for (ObjCInterfaceDecl::known_categories_iterator Cat = From->known_categories_begin(), CatEnd = From->known_categories_end(); Cat != CatEnd; ++Cat) { Importer.Import(*Cat); } // If we have an @implementation, import it as well. if (From->getImplementation()) { ObjCImplementationDecl *Impl = cast_or_null( Importer.Import(From->getImplementation())); if (!Impl) return true; To->setImplementation(Impl); } if (shouldForceImportDeclContext(Kind)) { // Import all of the members of this class. ImportDeclContext(From, /*ForceImport=*/true); } return false; } Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { // If this class has a definition in the translation unit we're coming from, // but this particular declaration is not that definition, import the // definition and map to that. ObjCInterfaceDecl *Definition = D->getDefinition(); if (Definition && Definition != D) { Decl *ImportedDef = Importer.Import(Definition); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } // Import the major distinguishing characteristics of an @interface. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Look for an existing interface with the same name. ObjCInterfaceDecl *MergeWithIface = 0; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary)) continue; if ((MergeWithIface = dyn_cast(FoundDecls[I]))) break; } // Create an interface declaration, if one does not already exist. ObjCInterfaceDecl *ToIface = MergeWithIface; if (!ToIface) { ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getAtStartLoc()), Name.getAsIdentifierInfo(), /*PrevDecl=*/0,Loc, D->isImplicitInterfaceDecl()); Importer.Imported(D, ToIface); ToIface->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToIface); } Importer.Imported(D, ToIface); if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface)) return 0; ImportAttributes(D, ToIface); return ToIface; } Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { ObjCCategoryDecl *Category = cast_or_null( Importer.Import(D->getCategoryDecl())); if (!Category) return 0; ObjCCategoryImplDecl *ToImpl = Category->getImplementation(); if (!ToImpl) { DeclContext *DC = Importer.ImportContext(D->getDeclContext()); if (!DC) return 0; SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc()); ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getIdentifier()), Category->getClassInterface(), Importer.Import(D->getLocation()), Importer.Import(D->getAtStartLoc()), CategoryNameLoc); DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return 0; ToImpl->setLexicalDeclContext(LexicalDC); } LexicalDC->addDeclInternal(ToImpl); Category->setImplementation(ToImpl); } Importer.Imported(D, ToImpl); ImportDeclContext(D); ImportAttributes(D, ToImpl); return ToImpl; } Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { // Find the corresponding interface. ObjCInterfaceDecl *Iface = cast_or_null( Importer.Import(D->getClassInterface())); if (!Iface) return 0; // Import the superclass, if any. ObjCInterfaceDecl *Super = 0; if (D->getSuperClass()) { Super = cast_or_null( Importer.Import(D->getSuperClass())); if (!Super) return 0; } ObjCImplementationDecl *Impl = Iface->getImplementation(); if (!Impl) { // We haven't imported an implementation yet. Create a new @implementation // now. Impl = ObjCImplementationDecl::Create(Importer.getToContext(), Importer.ImportContext(D->getDeclContext()), Iface, Super, Importer.Import(D->getLocation()), Importer.Import(D->getAtStartLoc()), Importer.Import(D->getSuperClassLoc()), Importer.Import(D->getIvarLBraceLoc()), Importer.Import(D->getIvarRBraceLoc())); if (D->getDeclContext() != D->getLexicalDeclContext()) { DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return 0; Impl->setLexicalDeclContext(LexicalDC); } // Associate the implementation with the class it implements. Iface->setImplementation(Impl); Importer.Imported(D, Iface->getImplementation()); } else { Importer.Imported(D, Iface->getImplementation()); // Verify that the existing @implementation has the same superclass. if ((Super && !Impl->getSuperClass()) || (!Super && Impl->getSuperClass()) || (Super && Impl->getSuperClass() && !declaresSameEntity(Super->getCanonicalDecl(), Impl->getSuperClass()))) { Importer.ToDiag(Impl->getLocation(), diag::err_odr_objc_superclass_inconsistent) << Iface->getDeclName(); // FIXME: It would be nice to have the location of the superclass // below. if (Impl->getSuperClass()) Importer.ToDiag(Impl->getLocation(), diag::note_odr_objc_superclass) << Impl->getSuperClass()->getDeclName(); else Importer.ToDiag(Impl->getLocation(), diag::note_odr_objc_missing_superclass); if (D->getSuperClass()) Importer.FromDiag(D->getLocation(), diag::note_odr_objc_superclass) << D->getSuperClass()->getDeclName(); else Importer.FromDiag(D->getLocation(), diag::note_odr_objc_missing_superclass); return 0; } } // Import all of the members of this @implementation. ImportDeclContext(D); ImportAttributes(D, Impl); return Impl; } Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { // Import the major distinguishing characteristics of an @property. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // Check whether we have already imported this property. SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (ObjCPropertyDecl *FoundProp = dyn_cast(FoundDecls[I])) { // Check property types. if (!Importer.IsStructurallyEquivalent(D->getType(), FoundProp->getType())) { Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent) << Name << D->getType() << FoundProp->getType(); Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here) << FoundProp->getType(); return 0; } // FIXME: Check property attributes, getters, setters, etc.? // Consider these properties to be equivalent. Importer.Imported(D, FoundProp); return FoundProp; } } // Import the type. TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo()); if (!T) return 0; // Create the new property. ObjCPropertyDecl *ToProperty = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), Importer.Import(D->getAtLoc()), Importer.Import(D->getLParenLoc()), T, D->getPropertyImplementation()); Importer.Imported(D, ToProperty); ImportAttributes(D, ToProperty); ToProperty->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToProperty); ToProperty->setPropertyAttributes(D->getPropertyAttributes()); ToProperty->setPropertyAttributesAsWritten( D->getPropertyAttributesAsWritten()); ToProperty->setGetterName(Importer.Import(D->getGetterName())); ToProperty->setSetterName(Importer.Import(D->getSetterName())); ToProperty->setGetterMethodDecl( cast_or_null(Importer.Import(D->getGetterMethodDecl()))); ToProperty->setSetterMethodDecl( cast_or_null(Importer.Import(D->getSetterMethodDecl()))); ToProperty->setPropertyIvarDecl( cast_or_null(Importer.Import(D->getPropertyIvarDecl()))); return ToProperty; } Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { ObjCPropertyDecl *Property = cast_or_null( Importer.Import(D->getPropertyDecl())); if (!Property) return 0; DeclContext *DC = Importer.ImportContext(D->getDeclContext()); if (!DC) return 0; // Import the lexical declaration context. DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return 0; } ObjCImplDecl *InImpl = dyn_cast(LexicalDC); if (!InImpl) return 0; // Import the ivar (for an @synthesize). ObjCIvarDecl *Ivar = 0; if (D->getPropertyIvarDecl()) { Ivar = cast_or_null( Importer.Import(D->getPropertyIvarDecl())); if (!Ivar) return 0; } ObjCPropertyImplDecl *ToImpl = InImpl->FindPropertyImplDecl(Property->getIdentifier()); if (!ToImpl) { ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC, Importer.Import(D->getLocStart()), Importer.Import(D->getLocation()), Property, D->getPropertyImplementation(), Ivar, Importer.Import(D->getPropertyIvarDeclLoc())); ToImpl->setLexicalDeclContext(LexicalDC); Importer.Imported(D, ToImpl); LexicalDC->addDeclInternal(ToImpl); } else { // Check that we have the same kind of property implementation (@synthesize // vs. @dynamic). if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { Importer.ToDiag(ToImpl->getLocation(), diag::err_odr_objc_property_impl_kind_inconsistent) << Property->getDeclName() << (ToImpl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); Importer.FromDiag(D->getLocation(), diag::note_odr_objc_property_impl_kind) << D->getPropertyDecl()->getDeclName() << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); return 0; } // For @synthesize, check that we have the same if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && Ivar != ToImpl->getPropertyIvarDecl()) { Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), diag::err_odr_objc_synthesize_ivar_inconsistent) << Property->getDeclName() << ToImpl->getPropertyIvarDecl()->getDeclName() << Ivar->getDeclName(); Importer.FromDiag(D->getPropertyIvarDeclLoc(), diag::note_odr_objc_synthesize_ivar_here) << D->getPropertyIvarDecl()->getDeclName(); return 0; } // Merge the existing implementation with the new implementation. Importer.Imported(D, ToImpl); } ImportAttributes(D, ToImpl); return ToImpl; } Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { // For template arguments, we adopt the translation unit as our declaration // context. This context will be fixed when the actual template declaration // is created. // FIXME: Import default argument. TemplateTypeParmDecl *ToD = TemplateTypeParmDecl::Create( Importer.getToContext(), Importer.getToContext().getTranslationUnitDecl(), Importer.Import(D->getLocStart()), Importer.Import(D->getLocation()), D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()), D->wasDeclaredWithTypename(), D->isParameterPack()); ImportAttributes(D, ToD); return ToD; } Decl * ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return 0; // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); // Import the type of this declaration. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; // Import type-source information. TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); if (D->getTypeSourceInfo() && !TInfo) return 0; // FIXME: Import default argument. NonTypeTemplateParmDecl *ToD = NonTypeTemplateParmDecl::Create( Importer.getToContext(), Importer.getToContext().getTranslationUnitDecl(), Importer.Import(D->getInnerLocStart()), Loc, D->getDepth(), D->getPosition(), Name.getAsIdentifierInfo(), T, D->isParameterPack(), TInfo); ImportAttributes(D, ToD); return ToD; } Decl * ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return 0; // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); // Import template parameters. TemplateParameterList *TemplateParams = ImportTemplateParameterList(D->getTemplateParameters()); if (!TemplateParams) return 0; // FIXME: Import default argument. TemplateTemplateParmDecl *ToD = TemplateTemplateParmDecl::Create( Importer.getToContext(), Importer.getToContext().getTranslationUnitDecl(), Loc, D->getDepth(), D->getPosition(), D->isParameterPack(), Name.getAsIdentifierInfo(), TemplateParams); ImportAttributes(D, ToD); return ToD; } Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { // If this record has a definition in the translation unit we're coming from, // but this particular declaration is not that definition, import the // definition and map to that. CXXRecordDecl *Definition = cast_or_null(D->getTemplatedDecl()->getDefinition()); if (Definition && Definition != D->getTemplatedDecl()) { Decl *ImportedDef = Importer.Import(Definition->getDescribedClassTemplate()); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } // Import the major distinguishing characteristics of this class template. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; if (Decl *Imp = Importer.GetImported(D)) return Imp; // We may already have a template of the same name; try to find and match it. if (!DC->isFunctionOrMethod()) { SmallVector ConflictingDecls; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary)) continue; Decl *Found = FoundDecls[I]; if (ClassTemplateDecl *FoundTemplate = dyn_cast(Found)) { if (IsStructuralMatch(D, FoundTemplate, false)) { // The class templates structurally match; call it the same template. // FIXME: We may be filling in a forward declaration here. Handle // this case! Importer.Imported(D->getTemplatedDecl(), FoundTemplate->getTemplatedDecl()); return Importer.Imported(D, FoundTemplate); } } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } } CXXRecordDecl *DTemplated = D->getTemplatedDecl(); // Create the declaration that is being templated. CXXRecordDecl *D2Templated = cast_or_null( Importer.Import(DTemplated)); assert(D2Templated); if (!D2Templated) return NULL; if (Decl *Imp = Importer.GetImported(D)) return Imp; // Create the class template declaration itself. TemplateParameterList *TemplateParams = ImportTemplateParameterList(D->getTemplateParameters()); if (!TemplateParams) return 0; ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated, /*PrevDecl=*/0); D2Templated->setDescribedClassTemplate(D2); D2->setAccess(D->getAccess()); D2->setLexicalDeclContext(LexicalDC); // Note the relationship between the class templates. Importer.Imported(D, D2); LexicalDC->addDeclInternal(D2); if (DTemplated->isCompleteDefinition() && !D2Templated->isCompleteDefinition()) { // FIXME: Import definition! } ImportAttributes(D, D2); return D2; } Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( ClassTemplateSpecializationDecl *D) { // If this record has a definition in the translation unit we're coming from, // but this particular declaration is not that definition, import the // definition and map to that. TagDecl *Definition = D->getDefinition(); if (Definition && Definition != D) { Decl *ImportedDef = Importer.Import(Definition); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } ClassTemplateDecl *ClassTemplate = cast_or_null(Importer.Import( D->getSpecializedTemplate())); if (!ClassTemplate) { assert(false); return 0; } // Import the context of this declaration. DeclContext *DC = ClassTemplate->getDeclContext(); assert(DC); if (!DC) return 0; DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); assert(LexicalDC); if (!LexicalDC) return 0; } // Import the location of this declaration. SourceLocation StartLoc = Importer.Import(D->getLocStart()); SourceLocation IdLoc = Importer.Import(D->getLocation()); // Import template arguments. SmallVector TemplateArgs; if (ImportTemplateArguments(D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) return 0; // Try to find an existing specialization with these template arguments. void *InsertPos = 0; ClassTemplateSpecializationDecl *D2 = ClassTemplate->findSpecialization(TemplateArgs.data(), TemplateArgs.size(), InsertPos); if (D2) { // We already have a class template specialization with these template // arguments. // FIXME: Check for specialization vs. instantiation errors. if (RecordDecl *FoundDef = D2->getDefinition()) { if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef, false)) { // The record types structurally match, or the "from" translation // unit only had a forward declaration anyway; call it the same // function. if (CXXRecordDecl *CRD = dyn_cast(FoundDef)) if (!CRD->isDependentType() && CRD->needsImplicitDestructor() && !CRD->getDestructor()) Importer.getToSema()->DeclareImplicitDestructor(CRD); return Importer.Imported(D, FoundDef); } } } else { // Create a new specialization. if (ClassTemplatePartialSpecializationDecl *PartialSpec = dyn_cast(D)) { // Import TemplateArgumentListInfo TemplateArgumentListInfo FromTAInfo, ToTAInfo; PartialSpec->getTemplateArgsAsWritten()->copyInto(FromTAInfo); for (unsigned i = 0, e = FromTAInfo.size(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromTAInfo[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } QualType CanonInjType = Importer.Import( PartialSpec->getInjectedSpecializationType()); if (CanonInjType.isNull()) { assert(CanonInjType.isNull()); return NULL; } CanonInjType = CanonInjType.getCanonicalType(); TemplateParameterList *ToTPList = ImportTemplateParameterList( PartialSpec->getTemplateParameters()); assert(ToTPList || !PartialSpec->getTemplateParameters()); if (!ToTPList && PartialSpec->getTemplateParameters()) return NULL; D2 = ClassTemplatePartialSpecializationDecl::Create( Importer.getToContext(), D->getTagKind(), DC, StartLoc, IdLoc, ToTPList, ClassTemplate, TemplateArgs.data(), TemplateArgs.size(), ToTAInfo, CanonInjType, NULL); } else { D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(), D->getTagKind(), DC, StartLoc, IdLoc, ClassTemplate, TemplateArgs.data(), TemplateArgs.size(), /*PrevDecl=*/0); } D2->setSpecializationKind(D->getSpecializationKind()); // Add this specialization to the class template. ClassTemplate->AddSpecialization(D2, InsertPos); // Import the qualifier, if any. D2->setQualifierInfo(Importer.Import(D->getQualifierLoc())); ImportAttributes(D, D2); Importer.Imported(D, D2); if (D->getTypeAsWritten()) { TypeSourceInfo *TInfo = Importer.Import(D->getTypeAsWritten()); assert(TInfo); if (!TInfo) return NULL; D2->setTypeAsWritten(TInfo); D2->setTemplateKeywordLoc(Importer.Import(D->getTemplateKeywordLoc())); D2->setExternLoc(Importer.Import(D->getExternLoc())); } SourceLocation POI = Importer.Import(D->getPointOfInstantiation()); assert(POI.isValid() || D->getPointOfInstantiation().isInvalid()); if (POI.isValid()) D2->setPointOfInstantiation(POI); D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind()); // Add the specialization to this context. D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); } Importer.Imported(D, D2); if (D->isCompleteDefinition() && ImportDefinition(D, D2)) return 0; return D2; } Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { // If this variable has a definition in the translation unit we're coming // from, // but this particular declaration is not that definition, import the // definition and map to that. VarDecl *Definition = cast_or_null(D->getTemplatedDecl()->getDefinition()); if (Definition && Definition != D->getTemplatedDecl()) { Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate()); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } // Import the major distinguishing characteristics of this variable template. DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; if (ImportDeclParts(D, DC, LexicalDC, Name, Loc)) return 0; // We may already have a template of the same name; try to find and match it. assert(!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope"); SmallVector ConflictingDecls; SmallVector FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary)) continue; Decl *Found = FoundDecls[I]; if (VarTemplateDecl *FoundTemplate = dyn_cast(Found)) { if (IsStructuralMatch(D, FoundTemplate)) { // The variable templates structurally match; call it the same template. Importer.Imported(D->getTemplatedDecl(), FoundTemplate->getTemplatedDecl()); return Importer.Imported(D, FoundTemplate); } } ConflictingDecls.push_back(FoundDecls[I]); } if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return 0; } VarDecl *DTemplated = D->getTemplatedDecl(); // Import the type. QualType T = Importer.Import(DTemplated->getType()); if (T.isNull()) return 0; // Create the declaration that is being templated. VarDecl *D2Templated = cast_or_null( Importer.Import(D->getTemplatedDecl())); assert(D2Templated); if (!D2Templated) return NULL; // Merge the initializer. if (ImportDefinition(DTemplated, D2Templated)) return 0; // Create the variable template declaration itself. TemplateParameterList *TemplateParams = ImportTemplateParameterList(D->getTemplateParameters()); if (!TemplateParams) return 0; VarTemplateDecl *D2 = VarTemplateDecl::Create( Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated, /*PrevDecl=*/0); D2Templated->setDescribedVarTemplate(D2); D2->setAccess(D->getAccess()); // Note the relationship between the variable templates. Importer.Imported(D, D2); D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); if (DTemplated->isThisDeclarationADefinition() && !D2Templated->isThisDeclarationADefinition()) { // FIXME: Import definition! } ImportAttributes(D, D2); return D2; } Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *D) { // If this record has a definition in the translation unit we're coming from, // but this particular declaration is not that definition, import the // definition and map to that. VarDecl *Definition = D->getDefinition(); if (Definition && Definition != D) { Decl *ImportedDef = Importer.Import(Definition); if (!ImportedDef) return 0; return Importer.Imported(D, ImportedDef); } VarTemplateDecl *VarTemplate = cast_or_null( Importer.Import(D->getSpecializedTemplate())); if (!VarTemplate) return 0; // Import the context of this declaration. DeclContext *DC = VarTemplate->getDeclContext(); if (!DC) return 0; DeclContext *LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return 0; } // Import the location of this declaration. SourceLocation StartLoc = Importer.Import(D->getLocStart()); SourceLocation IdLoc = Importer.Import(D->getLocation()); // Import template arguments. SmallVector TemplateArgs; if (ImportTemplateArguments(D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) return 0; // Try to find an existing specialization with these template arguments. void *InsertPos = 0; VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization( TemplateArgs.data(), TemplateArgs.size(), InsertPos); if (D2) { // We already have a variable template specialization with these template // arguments. // FIXME: Check for specialization vs. instantiation errors. if (VarDecl *FoundDef = D2->getDefinition()) { if (!D->isThisDeclarationADefinition() || IsStructuralMatch(D, FoundDef)) { // The record types structurally match, or the "from" translation // unit only had a forward declaration anyway; call it the same // variable. return Importer.Imported(D, FoundDef); } } } else { // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) return 0; TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); // Create a new specialization. if (VarTemplatePartialSpecializationDecl *PartialSpec = dyn_cast(D)) { // Import TemplateArgumentListInfo TemplateArgumentListInfo FromTAInfo, ToTAInfo; PartialSpec->getTemplateArgsAsWritten()->copyInto(FromTAInfo); for (unsigned i = 0, e = FromTAInfo.size(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromTAInfo[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } TemplateParameterList *ToTPList = ImportTemplateParameterList( PartialSpec->getTemplateParameters()); assert(ToTPList || !PartialSpec->getTemplateParameters()); if (!ToTPList && PartialSpec->getTemplateParameters()) return NULL; D2 = VarTemplatePartialSpecializationDecl::Create( Importer.getToContext(), DC, StartLoc, IdLoc, ToTPList, VarTemplate, T, TInfo, D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size(), ToTAInfo); } else { D2 = VarTemplateSpecializationDecl::Create( Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo, D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size()); } D2->setPointOfInstantiation(Importer.Import(D->getPointOfInstantiation())); D2->setSpecializationKind(D->getSpecializationKind()); const TemplateArgumentListInfo &FromTAInfo = D->getTemplateArgsInfo(); TemplateArgumentListInfo ToTAInfo( Importer.Import(FromTAInfo.getLAngleLoc()), Importer.Import(FromTAInfo.getRAngleLoc())); for (unsigned i = 0, e = FromTAInfo.size(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromTAInfo[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } D2->setTemplateArgsInfo(ToTAInfo); // Add this specialization to the class template. VarTemplate->AddSpecialization(D2, InsertPos); // Import the qualifier, if any. D2->setQualifierInfo(Importer.Import(D->getQualifierLoc())); Importer.Imported(D, D2); // Add the specialization to this context. D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); } Importer.Imported(D, D2); if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2)) return 0; ImportAttributes(D, D2); return D2; } //---------------------------------------------------------------------------- // Import Statements //---------------------------------------------------------------------------- Stmt *ASTNodeImporter::VisitStmt(Stmt *S) { Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node) << S->getStmtClassName(); return 0; } //---------------------------------------------------------------------------- // Import Expressions //---------------------------------------------------------------------------- Expr *ASTNodeImporter::VisitExpr(Expr *E) { Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node) << E->getStmtClassName(); return 0; } Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr && E->getSubExpr()) { assert(false); return NULL; } TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo()); if (!TInfo) { assert(false); return 0; } return new (Importer.getToContext()) VAArgExpr( Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo, Importer.Import(E->getRParenLoc()), T); } Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } return new (Importer.getToContext()) GNUNullExpr( T, Importer.Import(E->getExprLoc())); } Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } return new (Importer.getToContext()) PredefinedExpr( Importer.Import(E->getExprLoc()), T, E->getIdentType()); } Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) { QualType T = Importer.Import(ILE->getType()); if (T.isNull()) { assert(false); return NULL; } std::vector Exprs; for (InitListExpr::iterator I = ILE->begin(), E = ILE->end(); I != E; ++I) { if (Expr *Arg = cast_or_null(Importer.Import(*I))) Exprs.push_back(Arg); else { assert(false); return NULL; } } InitListExpr *To = new (Importer.getToContext()) InitListExpr( Importer.getToContext(), Importer.Import(ILE->getLBraceLoc()), Exprs, Importer.Import(ILE->getLBraceLoc())); To->setType(T); if (ILE->hasArrayFiller()) { Expr *Filter = Importer.Import(ILE->getArrayFiller()); if (!Filter && ILE->getArrayFiller()) { assert(false); return NULL; } To->setArrayFiller(Filter); } FieldDecl *ToFD = cast_or_null( Importer.Import(ILE->getInitializedFieldInUnion())); if (!ToFD && ILE->getInitializedFieldInUnion()) { assert(false); return NULL; } To->setInitializedFieldInUnion(ToFD); if (InitListExpr *SyntForm = ILE->getSyntacticForm()) { InitListExpr *ToSyntForm = cast_or_null( Importer.Import(SyntForm)); if (!ToSyntForm) { assert(false); return NULL; } To->setSyntacticForm(ToSyntForm); } To->setValueDependent(ILE->isValueDependent()); To->setInstantiationDependent(ILE->isInstantiationDependent()); return To; } ASTNodeImporter::Designator ASTNodeImporter::ImportDesignator(const Designator &D) { if (D.isFieldDesignator()) { IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName()); if (!ToFieldName) { assert(ToFieldName); return Designator(); } return Designator(ToFieldName, Importer.Import(D.getDotLoc()), Importer.Import(D.getFieldLoc())); } if (D.isArrayDesignator()) return Designator(D.getFirstExprIndex(), Importer.Import(D.getLBracketLoc()), Importer.Import(D.getRBracketLoc())); // ArrayRangeDesignator return Designator(D.getFirstExprIndex(), Importer.Import(D.getLBracketLoc()), Importer.Import(D.getEllipsisLoc()), Importer.Import(D.getRBracketLoc())); } Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) { Expr *Init = cast_or_null(Importer.Import(DIE->getInit())); if (!Init) { assert(Init); return NULL; } std::vector IndexExprs; // List elements from the second, the first is Init itself for (unsigned i = 1, e = DIE->getNumSubExprs(); i < e; i++) { if (Expr *Arg = cast_or_null(Importer.Import(DIE->getSubExpr(i)))) IndexExprs.push_back(Arg); else { assert(Arg); return NULL; } } std::vector Designators; for (DesignatedInitExpr::designators_iterator I = DIE->designators_begin(), E = DIE->designators_end(); I != E; ++I) Designators.push_back(ImportDesignator(*I)); return DesignatedInitExpr::Create( Importer.getToContext(), Designators.data(), Designators.size(), IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()), DIE->usesGNUSyntax(), Init); } Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { ValueDecl *ToD = cast_or_null(Importer.Import(E->getDecl())); if (!ToD) return 0; NamedDecl *FoundD = 0; if (E->getDecl() != E->getFoundDecl()) { FoundD = cast_or_null(Importer.Import(E->getFoundDecl())); if (!FoundD) return 0; } QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } TemplateArgumentListInfo ToTAInfo; TemplateArgumentListInfo *ResInfo = NULL; if (E->hasExplicitTemplateArgs()) { const TemplateArgumentLoc *FromArgArray = E->getTemplateArgs(); for (unsigned i = 0, e = E->getNumTemplateArgs(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromArgArray[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } ResInfo = &ToTAInfo; } DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), ToD, E->refersToEnclosingLocal(), Importer.Import(E->getLocation()), T, E->getValueKind(), FoundD, ResInfo); if (E->hadMultipleCandidates()) DRE->setHadMultipleCandidates(true); DRE->setValueDependent(E->isValueDependent()); DRE->setInstantiationDependent(E->isInstantiationDependent()); return DRE; } Expr *ASTNodeImporter::VisitDependentScopeDeclRefExpr( DependentScopeDeclRefExpr *E) { DeclarationNameInfo NameInfo(Importer.Import(E->getDeclName()), Importer.Import(E->getExprLoc())); ImportDeclarationNameLoc(E->getNameInfo(), NameInfo); TemplateArgumentListInfo ToTAInfo; TemplateArgumentListInfo *ResInfo = NULL; if (E->hasExplicitTemplateArgs()) { const TemplateArgumentLoc *FromArgArray = E->getTemplateArgs(); for (unsigned i = 0, e = E->getNumTemplateArgs(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromArgArray[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } ResInfo = &ToTAInfo; } return DependentScopeDeclRefExpr::Create( Importer.getToContext(), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), NameInfo, ResInfo); } Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; return new (Importer.getToContext()) CXXNullPtrLiteralExpr( T, Importer.Import(E->getExprLoc())); } Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; return new (Importer.getToContext()) CXXBoolLiteralExpr( E->getValue(), T, Importer.Import(E->getExprLoc())); } Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; return IntegerLiteral::Create(Importer.getToContext(), E->getValue(), T, Importer.Import(E->getLocation())); } Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; return FloatingLiteral::Create(Importer.getToContext(), E->getValue(), E->isExact(), T, Importer.Import(E->getLocation())); } Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; return new (Importer.getToContext()) CharacterLiteral(E->getValue(), E->getKind(), T, Importer.Import(E->getLocation())); } Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; return StringLiteral::Create(Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(), T, Importer.Import(E->getExprLoc())); } Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return 0; TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo()); assert(TInfo); if (!TInfo) return NULL; Expr *Init = Importer.Import(E->getInitializer()); assert(Init); if (!Init) return NULL; return new (Importer.getToContext()) CompoundLiteralExpr( Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(), Init, E->isFileScope()); } Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) { std::vector Names; for (int i = 0, e = S->getNumOutputs(); i != e; i++) { IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(i)); Names.push_back(ToII); if (!ToII && S->getOutputIdentifier(i)) { assert(false); return NULL; } } for (int i = 0, e = S->getNumInputs(); i != e; i++) { IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(i)); Names.push_back(ToII); if (!ToII && S->getInputIdentifier(i)) { assert(false); return NULL; } } std::vector Clobbers; for (int i = 0, e = S->getNumClobbers(); i != e; i++) Clobbers.push_back(cast( Importer.Import(S->getClobberStringLiteral(i)))); std::vector Constraints; for (int i = 0, e = S->getNumOutputs(); i != e; i++) Constraints.push_back(cast( Importer.Import(S->getOutputConstraintLiteral(i)))); for (int i = 0, e = S->getNumInputs(); i != e; i++) Constraints.push_back(cast( Importer.Import(S->getInputConstraintLiteral(i)))); std::vector Exprs; for (int i = 0, e = S->getNumOutputs(); i != e; i++) { if (Expr *Out = Importer.Import(S->getOutputExpr(i))) Exprs.push_back(Out); else { assert(false); return NULL; } } for (int i = 0, e = S->getNumInputs(); i != e; i++) { if (Expr *Out = Importer.Import(S->getInputExpr(i))) Exprs.push_back(Out); else { assert(false); return NULL; } } return new (Importer.getToContext()) GCCAsmStmt( Importer.getToContext(), Importer.Import(S->getAsmLoc()), S->isSimple(), S->isVolatile(), S->getNumOutputs(), S->getNumInputs(), Names.data(), Constraints.data(), Exprs.data(), cast(Importer.Import(S->getAsmString())), S->getNumClobbers(), Clobbers.data(), Importer.Import(S->getRParenLoc())); } Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) { return new (Importer.getToContext()) GotoStmt( cast(Importer.Import(S->getLabel())), Importer.Import(S->getGotoLoc()), Importer.Import(S->getLabelLoc())); } Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) { Expr *Target = Importer.Import(S->getTarget()); assert(Target); if (!Target) return NULL; return new (Importer.getToContext()) IndirectGotoStmt( Importer.Import(S->getGotoLoc()), Importer.Import(S->getStarLoc()), Target); } Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) { Stmt *ToSubStmt = Importer.Import(S->getSubStmt()); assert(ToSubStmt); if (!ToSubStmt) return NULL; return new (Importer.getToContext()) LabelStmt( Importer.Import(S->getIdentLoc()), cast(Importer.Import(S->getDecl())), ToSubStmt); } Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) { Stmt *ToSubStmt = Importer.Import(S->getSubStmt()); if (!ToSubStmt) { assert(ToSubStmt); return NULL; } std::vector ToAttrs; ArrayRef FromAttrs = S->getAttrs(); for (size_t i = 0, e = FromAttrs.size(); i < e; i++) { Attr *ToAttr = FromAttrs[i]->clone(Importer.getToContext()); ToAttr->setRange(Importer.Import(FromAttrs[i]->getRange())); ToAttrs.push_back(ToAttr); } return AttributedStmt::Create(Importer.getToContext(), Importer.Import(S->getLocStart()), ToAttrs, ToSubStmt); } Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) { std::vector Stmts; for (CompoundStmt::body_iterator I = S->body_begin(), E = S->body_end(); I != E; ++I) { if (Stmt *Out = Importer.Import(*I)) Stmts.push_back(Out); else { assert(false); return NULL; } } return new (Importer.getToContext()) CompoundStmt( Importer.getToContext(), Stmts, Importer.Import(S->getLBracLoc()), Importer.Import(S->getRBracLoc())); } Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) { std::vector Decls; for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end(); I != E; ++I) { Decl *D = Importer.Import(*I); assert(D); if (D) Decls.push_back(D); else return NULL; } assert(!Decls.empty()); return new (Importer.getToContext()) DeclStmt( DeclGroupRef(DeclGroupRef::Create(Importer.getToContext(), Decls.data(), Decls.size())), Importer.Import(S->getStartLoc()), Importer.Import(S->getEndLoc())); } Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) { VarDecl *ToCondVar = cast_or_null( Importer.Import(S->getConditionVariable())); if (!ToCondVar && S->getConditionVariable()) { assert(false); return NULL; } Expr *ToCond = Importer.Import(S->getCond()); assert(ToCond); if (!ToCond) return NULL; Stmt *ToThen = Importer.Import(S->getThen()); assert(ToThen); if (!ToThen) return NULL; Stmt *ToElse = Importer.Import(S->getElse()); if (!ToElse && S->getElse()) { assert(false); return NULL; } return new (Importer.getToContext()) IfStmt( Importer.getToContext(), Importer.Import(S->getIfLoc()), ToCondVar, ToCond, ToThen, Importer.Import(S->getElseLoc()), ToElse); } Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) { VarDecl *ToCondVar = cast_or_null( Importer.Import(S->getConditionVariable())); if (!ToCondVar && S->getConditionVariable()) { assert(false); return NULL; } Expr *ToCond = Importer.Import(S->getCond()); if (!ToCond && S->getCond()) { assert(false); return NULL; } Expr *ToInc = Importer.Import(S->getInc()); if (!ToInc && S->getInc()) { assert(false); return NULL; } Stmt *ToInit = Importer.Import(S->getInit()); if (!ToInit && S->getInit()) { assert(false); return NULL; } Stmt *ToBody = Importer.Import(S->getBody()); if (!ToBody && S->getBody()) { assert(false); return NULL; } return new (Importer.getToContext()) ForStmt( Importer.getToContext(), ToInit, ToCond, ToCondVar, ToInc, ToBody, Importer.Import(S->getForLoc()), Importer.Import(S->getLParenLoc()), Importer.Import(S->getRParenLoc())); } Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) { Expr *ToCond = Importer.Import(S->getCond()); if (!ToCond && S->getCond()) { assert(false); return NULL; } Stmt *ToBody = Importer.Import(S->getBody()); if (!ToBody && S->getBody()) { assert(false); return NULL; } return new (Importer.getToContext()) DoStmt( ToBody, ToCond, Importer.Import(S->getDoLoc()), Importer.Import(S->getWhileLoc()), Importer.Import(S->getRParenLoc())); } Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) { VarDecl *ToCondVar = cast_or_null( Importer.Import(S->getConditionVariable())); if (!ToCondVar && S->getConditionVariable()) { assert(false); return NULL; } Expr *ToCond = Importer.Import(S->getCond()); if (!ToCond && S->getCond()) { assert(false); return NULL; } Stmt *ToBody = Importer.Import(S->getBody()); if (!ToBody && S->getBody()) { assert(false); return NULL; } return new (Importer.getToContext()) WhileStmt( Importer.getToContext(), ToCondVar, ToCond, ToBody, Importer.Import(S->getWhileLoc())); } Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) { VarDecl *ToCondVar = cast_or_null( Importer.Import(S->getConditionVariable())); if (!ToCondVar && S->getConditionVariable()) { assert(false); return NULL; } Expr *ToCond = Importer.Import(S->getCond()); if (!ToCond && S->getCond()) { assert(false); return NULL; } Stmt *ToBody = Importer.Import(S->getBody()); if (!ToBody && S->getBody()) { assert(false); return NULL; } SwitchStmt *Res = new (Importer.getToContext()) SwitchStmt( Importer.getToContext(), ToCondVar, ToCond); Res->setBody(ToBody); // Import SwitchCase list SwitchCase *SCurrent = S->getSwitchCaseList(); SwitchCase *Head = cast_or_null( Importer.Import(S->getSwitchCaseList())); if (!Head && SCurrent) { assert(false); return NULL; } SwitchCase *Current = Head; while (SCurrent) { SwitchCase *SNext = SCurrent->getNextSwitchCase(); SwitchCase *Next = cast_or_null(Importer.Import(SNext)); if (!Next && SNext) { assert(false); return NULL; } Current->setNextSwitchCase(Next); Current = Next; SCurrent = SNext; } Res->setSwitchCaseList(Head); if (S->isAllEnumCasesCovered()) Res->setAllEnumCasesCovered(); Res->setSwitchLoc(Importer.Import(S->getSwitchLoc())); return Res; } Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) { Expr *ToLHS = Importer.Import(S->getLHS()); if (!ToLHS && S->getLHS()) { assert(false); return NULL; } Expr *ToRHS = Importer.Import(S->getRHS()); if (!ToRHS && S->getRHS()) { assert(false); return NULL; } Stmt *ToSubStmt = Importer.Import(S->getSubStmt()); if (!ToSubStmt && S->getSubStmt()) { assert(false); return NULL; } CaseStmt *Res = new (Importer.getToContext()) CaseStmt( ToLHS, ToRHS, Importer.Import(S->getCaseLoc()), Importer.Import(S->getEllipsisLoc()), Importer.Import(S->getColonLoc())); Res->setSubStmt(ToSubStmt); return Res; } Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) { Stmt *ToSubStmt = Importer.Import(S->getSubStmt()); if (!ToSubStmt && S->getSubStmt()) { assert(false); return NULL; } return new (Importer.getToContext()) DefaultStmt( Importer.Import(S->getDefaultLoc()), Importer.Import(S->getColonLoc()), ToSubStmt); } Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) { return new (Importer.getToContext()) ContinueStmt( Importer.Import(S->getContinueLoc())); } Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) { return new (Importer.getToContext()) BreakStmt( Importer.Import(S->getBreakLoc())); } Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) { return new (Importer.getToContext()) NullStmt( Importer.Import(S->getSemiLoc()), S->hasLeadingEmptyMacro()); } Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) { // FIXME: Refactor const_cast VarDecl *ToNRVO = cast_or_null( Importer.Import(const_cast(S->getNRVOCandidate()))); if (!ToNRVO && S->getNRVOCandidate()) { assert(false); return NULL; } return new (Importer.getToContext()) ReturnStmt( Importer.Import(S->getReturnLoc()), Importer.Import(S->getRetValue()), ToNRVO); } Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) { // FIXME: Refactor const_cast std::vector Handlers; for (unsigned i = 0, e = S->getNumHandlers(); i < e; ++i) { if (Stmt *Handler = Importer.Import(const_cast( S->getHandler(i)))) Handlers.push_back(Handler); else { assert(false); return NULL; } } return CXXTryStmt::Create(Importer.getToContext(), Importer.Import(S->getTryLoc()), Importer.Import(S->getTryBlock()), Handlers); } Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) { VarDecl *ToExcDecl = cast_or_null( Importer.Import(S->getExceptionDecl())); if (!ToExcDecl && S->getExceptionDecl()) { assert(false); return NULL; } Stmt *Handler = Importer.Import(S->getHandlerBlock()); assert(Handler); if (!Handler) return NULL; return new (Importer.getToContext()) CXXCatchStmt( Importer.Import(S->getCatchLoc()), ToExcDecl, Handler); } Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } std::vector Exprs; for (int i = 0, e = E->getNumSubExprs(); i < e; ++i) { if (Expr *Ex = Importer.Import(E->getSubExprs()[i])) { Exprs.push_back(Ex); } else { assert(false); return NULL; } } return new (Importer.getToContext()) AtomicExpr( Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(), Importer.Import(E->getRParenLoc())); } Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } LabelDecl *ToLabel = cast_or_null(Importer.Import(E->getLabel())); if (!ToLabel) { assert(false); return NULL; } return new (Importer.getToContext()) AddrLabelExpr( Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()), ToLabel, T); } Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) { Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr && E->getSubExpr()) { assert(false); return 0; } return new (Importer.getToContext()) ParenExpr(Importer.Import(E->getLParen()), Importer.Import(E->getRParen()), SubExpr); } Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) { std::vector Exprs; for (int i = 0, e = E->getNumExprs(); i < e; ++i) { if (Expr *Ex = Importer.Import(E->getExpr(i))) { Exprs.push_back(Ex); } else { assert(false); return NULL; } } return new (Importer.getToContext()) ParenListExpr( Importer.getToContext(), Importer.Import(E->getLParenLoc()), Exprs, Importer.Import(E->getLParenLoc())); } Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } CompoundStmt *ToSubStmt = cast_or_null( Importer.Import(E->getSubStmt())); if (!ToSubStmt && E->getSubStmt()) { assert(false); return NULL; } return new (Importer.getToContext()) StmtExpr(ToSubStmt, T, Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc())); } Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr) { assert(false); return 0; } return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(), Importer.Import(E->getOperatorLoc())); } Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr( UnaryExprOrTypeTraitExpr *E) { QualType ResultType = Importer.Import(E->getType()); if (ResultType.isNull()) { assert(false); return NULL; } if (E->isArgumentType()) { TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo()); if (!TInfo) { assert(false); return 0; } return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(), TInfo, ResultType, Importer.Import(E->getOperatorLoc()), Importer.Import(E->getRParenLoc())); } Expr *SubExpr = Importer.Import(E->getArgumentExpr()); if (!SubExpr) { assert(false); return 0; } return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(), SubExpr, ResultType, Importer.Import(E->getOperatorLoc()), Importer.Import(E->getRParenLoc())); } Expr *ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *ToLHS = Importer.Import(E->getLHS()); if (!ToLHS && E->getLHS()) { assert(false); return NULL; } Expr *ToRHS = Importer.Import(E->getRHS()); assert(ToRHS); if (!ToRHS && E->getRHS()) { assert(false); return NULL; } return new (Importer.getToContext()) ArraySubscriptExpr( ToLHS, ToRHS, T, E->getValueKind(), E->getObjectKind(), Importer.Import(E->getRBracketLoc())); } Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } if (E->isLogicalOp()) // This assertion is violated in dumped ASTs sometimes // assert(E->getType() == Importer.getFromContext().getLogicalOperationType()); // FIXME: This is a hack since logical operators can be overloaded if (E->getType() != Importer.getFromContext().getLogicalOperationType()) T = Importer.getToContext().getLogicalOperationType(); Expr *LHS = Importer.Import(E->getLHS()); if (!LHS) { assert(false); return 0; } Expr *RHS = Importer.Import(E->getRHS()); if (!RHS) { assert(false); return 0; } return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(), Importer.Import(E->getOperatorLoc()), E->isFPContractable()); } Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *ToLHS = Importer.Import(E->getLHS()); if (!ToLHS && E->getLHS()) { assert(false); return NULL; } Expr *ToRHS = Importer.Import(E->getRHS()); assert(ToRHS); if (!ToRHS && E->getRHS()) { assert(false); return NULL; } Expr *ToCond = Importer.Import(E->getCond()); if (!ToCond && E->getCond()) { assert(false); return NULL; } return new (Importer.getToContext()) ConditionalOperator( ToCond, Importer.Import(E->getQuestionLoc()), ToLHS, Importer.Import(E->getColonLoc()), ToRHS, T, E->getValueKind(), E->getObjectKind()); } Expr *ASTNodeImporter::VisitBinaryConditionalOperator( BinaryConditionalOperator *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } Expr *Common = Importer.Import(E->getCommon()); assert(Common); if (!Common) return NULL; Expr *Cond = Importer.Import(E->getCond()); assert(Cond); if (!Cond) return NULL; OpaqueValueExpr *OpaqueValue = cast_or_null( Importer.Import(E->getOpaqueValue())); assert(OpaqueValue); if (!OpaqueValue) return NULL; Expr *TrueExpr = Importer.Import(E->getTrueExpr()); assert(TrueExpr); if (!TrueExpr) return NULL; Expr *FalseExpr = Importer.Import(E->getFalseExpr()); assert(FalseExpr); if (!FalseExpr) return NULL; return new (Importer.getToContext()) BinaryConditionalOperator( Common, OpaqueValue, Cond, TrueExpr, FalseExpr, Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()), T, E->getValueKind(), E->getObjectKind()); } Expr *ASTNodeImporter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } TypeSourceInfo *LhsType = Importer.Import(E->getLhsTypeSourceInfo()); assert(LhsType); if (!LhsType) return NULL; TypeSourceInfo *RhsType = Importer.Import(E->getRhsTypeSourceInfo()); assert(RhsType); if (!RhsType) return NULL; return new (Importer.getToContext()) BinaryTypeTraitExpr( Importer.Import(E->getExprLoc()), E->getTrait(), LhsType, RhsType, E->getValue(), Importer.Import(E->getLocEnd()), T); } Expr *ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } Expr *ToQueried = Importer.Import(E->getQueriedExpression()); assert(ToQueried); if (!ToQueried) return NULL; return new (Importer.getToContext()) ExpressionTraitExpr( Importer.Import(E->getExprLoc()), E->getTrait(), ToQueried, E->getValue(), Importer.Import(E->getLocEnd()), T); } Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } Expr *SourceExpr = Importer.Import(E->getSourceExpr()); if (!SourceExpr && E->getSourceExpr()) { assert(false); return NULL; } return new (Importer.getToContext()) OpaqueValueExpr( Importer.Import(E->getExprLoc()), T, E->getValueKind(), E->getObjectKind(), SourceExpr); } Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } QualType CompLHSType = Importer.Import(E->getComputationLHSType()); if (CompLHSType.isNull()) { assert(false); return NULL; } QualType CompResultType = Importer.Import(E->getComputationResultType()); if (CompResultType.isNull()) { assert(false); return NULL; } Expr *ToLHS = Importer.Import(E->getLHS()); if (!ToLHS && E->getLHS()) { assert(false); return NULL; } Expr *ToRHS = Importer.Import(E->getRHS()); assert(ToRHS); if (!ToRHS && E->getRHS()) { assert(false); return NULL; } return new (Importer.getToContext()) CompoundAssignOperator(ToLHS, ToRHS, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(), CompLHSType, CompResultType, Importer.Import(E->getOperatorLoc()), E->isFPContractable()); } bool ASTNodeImporter::ImportCastPath(CastExpr *CE, CXXCastPath &Path) { for (CastExpr::path_iterator I = CE->path_begin(), E = CE->path_end(); I != E; ++I) { if (CXXBaseSpecifier *Spec = Importer.Import(*I)) Path.push_back(Spec); else return true; } return false; } Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr) { assert(false); return 0; } CXXCastPath BasePath; if (ImportCastPath(E, BasePath)) { assert(false); return 0; } return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(), SubExpr, &BasePath, E->getValueKind()); } Expr *ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr) { assert(false); return 0; } TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten()); if (!TInfo && E->getTypeInfoAsWritten()) { assert(false); return 0; } CXXCastPath BasePath; if (ImportCastPath(E, BasePath)) { assert(false); return 0; } switch (E->getStmtClass()) { case Stmt::CStyleCastExprClass: { CStyleCastExpr *CCE = cast(E); return CStyleCastExpr::Create(Importer.getToContext(), T, E->getValueKind(), E->getCastKind(), SubExpr, &BasePath, TInfo, Importer.Import(CCE->getLParenLoc()), Importer.Import(CCE->getRParenLoc())); } case Stmt::CXXFunctionalCastExprClass: { CXXFunctionalCastExpr *FCE = cast(E); return CXXFunctionalCastExpr::Create(Importer.getToContext(), T, E->getValueKind(), TInfo, E->getCastKind(), SubExpr, &BasePath, Importer.Import(FCE->getLParenLoc()), Importer.Import(FCE->getRParenLoc())); } case Stmt::ObjCBridgedCastExprClass: { ObjCBridgedCastExpr *OCE = cast(E); return new (Importer.getToContext()) ObjCBridgedCastExpr( Importer.Import(OCE->getLParenLoc()), OCE->getBridgeKind(), E->getCastKind(), Importer.Import(OCE->getBridgeKeywordLoc()), TInfo, SubExpr); } default: break; // just fall through } CXXNamedCastExpr *Named = cast(E); SourceLocation ExprLoc = Importer.Import(Named->getExprLoc()), RParenLoc = Importer.Import(Named->getRParenLoc()); SourceRange Brackets = Importer.Import(Named->getAngleBrackets()); switch (E->getStmtClass()) { case Stmt::CXXStaticCastExprClass: return CXXStaticCastExpr::Create(Importer.getToContext(), T, E->getValueKind(), E->getCastKind(), SubExpr, &BasePath, TInfo, ExprLoc, RParenLoc, Brackets); case Stmt::CXXDynamicCastExprClass: return CXXDynamicCastExpr::Create(Importer.getToContext(), T, E->getValueKind(), E->getCastKind(), SubExpr, &BasePath, TInfo, ExprLoc, RParenLoc, Brackets); case Stmt::CXXReinterpretCastExprClass: return CXXReinterpretCastExpr::Create(Importer.getToContext(), T, E->getValueKind(), E->getCastKind(), SubExpr, &BasePath, TInfo, ExprLoc, RParenLoc, Brackets); case Stmt::CXXConstCastExprClass: return CXXConstCastExpr::Create(Importer.getToContext(), T, E->getValueKind(), SubExpr, TInfo, ExprLoc, RParenLoc, Brackets); default: return NULL; // unreachable } } Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } return new (Importer.getToContext()) ImplicitValueInitExpr(T); } Expr *ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } std::vector Nodes; for (int i = 0, e = E->getNumComponents(); i < e; ++i) { // TODO: Make a separate Import(OffsetOfExpr::OffsetOfNode &)? const OffsetOfExpr::OffsetOfNode &Node = E->getComponent(i); switch (Node.getKind()) { case OffsetOfExpr::OffsetOfNode::Array: Nodes.push_back(OffsetOfExpr::OffsetOfNode( Importer.Import(Node.getLocStart()), Node.getArrayExprIndex(), Importer.Import(Node.getLocEnd()))); break; case OffsetOfExpr::OffsetOfNode::Base: { CXXBaseSpecifier *BS = Importer.Import(Node.getBase()); if (!BS && Node.getBase()) { assert(false); return NULL; } Nodes.push_back(OffsetOfExpr::OffsetOfNode(BS)); break; } case OffsetOfExpr::OffsetOfNode::Field: Nodes.push_back(OffsetOfExpr::OffsetOfNode( Importer.Import(Node.getLocStart()), cast(Importer.Import(Node.getField())), Importer.Import(Node.getLocEnd()))); break; case OffsetOfExpr::OffsetOfNode::Identifier: { IdentifierInfo *ToII = Importer.Import(Node.getFieldName()); if (ToII) { assert(false); return NULL; } Nodes.push_back(OffsetOfExpr::OffsetOfNode( Importer.Import(Node.getLocStart()), ToII, Importer.Import(Node.getLocEnd()))); break; } } } std::vector Exprs; for (int i = 0, e = E->getNumExpressions(); i < e; ++i) { Expr *ToIndexExpr = Importer.Import(E->getIndexExpr(i)); if (!ToIndexExpr) { assert(false); return NULL; } Exprs.push_back(ToIndexExpr); } TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo()); if (!TInfo && E->getTypeSourceInfo()) { assert(false); return NULL; } return OffsetOfExpr::Create(Importer.getToContext(), T, Importer.Import(E->getOperatorLoc()), TInfo, Nodes, Exprs, Importer.Import(E->getRParenLoc())); } Expr *ASTNodeImporter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } TypeSourceInfo *TInfo = Importer.Import(E->getQueriedTypeSourceInfo()); if (!TInfo) { assert(false); return NULL; } return new (Importer.getToContext()) UnaryTypeTraitExpr( Importer.Import(E->getExprLoc()), E->getTrait(), TInfo, E->getValue(), Importer.Import(E->getLocEnd()), T); } Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } return new (Importer.getToContext()) CXXThisExpr( Importer.Import(E->getExprLoc()), T, E->isImplicit()); } Expr *ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *Operand = Importer.Import(E->getOperand()); assert(Operand); if (!Operand) return NULL; // We cannot get source CanThrowVal so correction is required after init CXXNoexceptExpr *ToE = new (Importer.getToContext()) CXXNoexceptExpr( T, Operand, E->getValue() ? CT_Cannot : CT_Dependent, Importer.Import(E->getLocStart()), Importer.Import(E->getLocEnd())); ToE->setInstantiationDependent(E->isInstantiationDependent()); ToE->setValueDependent(E->isValueDependent()); return ToE; } Expr *ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr && E->getSubExpr()) { assert(false); return 0; } return new (Importer.getToContext()) CXXThrowExpr( SubExpr, T, Importer.Import(E->getExprLoc()), E->isThrownVariableInScope()); } Expr *ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { ParmVarDecl *Param = cast_or_null(Importer.Import(E->getParam())); if (!Param && E->getParam()) { assert(false); return NULL; } Expr *SubExpr = Importer.Import(E->getExpr()); if (!SubExpr && E->getExpr()) { assert(false); return 0; } return CXXDefaultArgExpr::Create( Importer.getToContext(), Importer.Import(E->getExprLoc()), Param, SubExpr); } Expr *ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } TypeSourceInfo *TypeInfo = Importer.Import(E->getTypeSourceInfo()); assert(TypeInfo); if (!TypeInfo) return NULL; return new (Importer.getToContext()) CXXScalarValueInitExpr( T, TypeInfo, Importer.Import(E->getRParenLoc())); } Expr *ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr && E->getSubExpr()) { assert(false); return 0; } return CXXBindTemporaryExpr::Create( Importer.getToContext(), CXXTemporary::Create( Importer.getToContext(), cast(Importer.Import( const_cast( E->getTemporary()->getDestructor())))), SubExpr); } Expr *ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE) { QualType T = Importer.Import(CE->getType()); if (T.isNull()) { assert(false); return 0; } std::vector Args; for (CXXTemporaryObjectExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { if (Expr *Arg = Importer.Import(*I)) Args.push_back(Arg); else { assert(false); return NULL; } } return CXXTemporaryObjectExpr::Create( Importer.getToContext(), T, Importer.Import(CE->getExprLoc()), cast(Importer.Import(CE->getConstructor())), CE->isElidable(), Args, CE->hadMultipleCandidates(), CE->isListInitialization(), CE->requiresZeroInitialization(), CE->getConstructionKind(), Importer.Import(CE->getParenOrBraceRange())); } Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return 0; } Expr *BaseE = Importer.Import(E->getBase()); if (!BaseE && E->getBase()) { assert(false); return NULL; } DeclAccessPair FoundDecl = E->getFoundDecl(); NamedDecl *ND = cast(Importer.Import(FoundDecl.getDecl())); DeclAccessPair ImportedFoundDecl = DeclAccessPair::make(ND, FoundDecl.getAccess()); ValueDecl *MD = cast(Importer.Import(E->getMemberDecl())); DeclarationNameInfo NameInfo(MD->getDeclName(), Importer.Import(E->getMemberLoc())); ImportDeclarationNameLoc(E->getMemberNameInfo(), NameInfo); TemplateArgumentListInfo ToTAInfo; TemplateArgumentListInfo *ResInfo = NULL; if (E->hasExplicitTemplateArgs()) { const TemplateArgumentLoc *FromArgArray = E->getTemplateArgs(); for (unsigned i = 0, e = E->getNumTemplateArgs(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromArgArray[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } ResInfo = &ToTAInfo; } return MemberExpr::Create(Importer.getToContext(), BaseE, E->isArrow(), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), MD, ImportedFoundDecl, NameInfo, ResInfo, T, E->getValueKind(), E->getObjectKind()); } Expr * ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } Expr *TempE = Importer.Import(E->GetTemporaryExpr()); assert(TempE); if (!TempE) return NULL; ValueDecl *VD = cast_or_null( Importer.Import(const_cast(E->getExtendingDecl()))); if (!VD && E->getExtendingDecl()) { assert(false); return NULL; } // FIXME: Refactor const_cast return new (Importer.getToContext()) MaterializeTemporaryExpr( T, TempE, E->isBoundToLvalueReference(), VD); } Expr *ASTNodeImporter::VisitOverloadExpr(OverloadExpr *E) { QualType BaseType = Importer.Import(E->getType()); if (BaseType.isNull()) return NULL; DeclarationName Name = Importer.Import(E->getName()); assert(Name); if (!Name) { assert(false); return NULL; } DeclarationNameInfo NameInfo(Name, Importer.Import(E->getNameLoc())); ImportDeclarationNameLoc(E->getNameInfo(), NameInfo); TemplateArgumentListInfo ToTAInfo; TemplateArgumentListInfo *ResInfo = NULL; if (E->hasExplicitTemplateArgs()) { const TemplateArgumentLoc *FromArgArray = E->getTemplateArgs(); for (unsigned i = 0, e = E->getNumTemplateArgs(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromArgArray[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } ResInfo = &ToTAInfo; } UnresolvedSet<2> USet; for (UnresolvedMemberExpr::decls_iterator UI = E->decls_begin(), UE = E->decls_end(); UI != UE; ++UI) USet.addDecl(cast(Importer.Import(*UI))); if (UnresolvedLookupExpr *ULE = dyn_cast(E)) { CXXRecordDecl *NamingClass = cast_or_null( Importer.Import(ULE->getNamingClass())); if (!NamingClass && ULE->getNamingClass()) { assert(false); return NULL; } if (ResInfo || ULE->getTemplateKeywordLoc().isValid()) return UnresolvedLookupExpr::Create( Importer.getToContext(), NamingClass, Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), NameInfo, ULE->requiresADL(), ResInfo, USet.begin(), USet.end()); else return UnresolvedLookupExpr::Create( Importer.getToContext(), NamingClass, Importer.Import(E->getQualifierLoc()), NameInfo, ULE->requiresADL(), ULE->isOverloaded(), USet.begin(), USet.end()); } UnresolvedMemberExpr *UME = cast(E); Expr *BaseE = UME->isImplicitAccess() ? NULL : Importer.Import(UME->getBase()); if (!BaseE && !UME->isImplicitAccess() && UME->getBase()) { assert(false); return NULL; } return UnresolvedMemberExpr::Create( Importer.getToContext(), UME->hasUnresolvedUsing(), BaseE, BaseType, UME->isArrow(), Importer.Import(UME->getOperatorLoc()), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), NameInfo, ResInfo, USet.begin(), USet.end()); } Expr *ASTNodeImporter::VisitCXXDependentScopeMemberExpr( CXXDependentScopeMemberExpr *E) { DeclarationName Name = Importer.Import(E->getMember()); assert(Name); if (!Name) return NULL; DeclarationNameInfo NameInfo(Name, Importer.Import(E->getMemberLoc())); ImportDeclarationNameLoc(E->getMemberNameInfo(), NameInfo); TemplateArgumentListInfo ToTAInfo; TemplateArgumentListInfo *ResInfo = NULL; if (E->hasExplicitTemplateArgs()) { const TemplateArgumentLoc *FromArgArray = E->getTemplateArgs(); for (unsigned i = 0, e = E->getNumTemplateArgs(); i < e; i++) { const TemplateArgumentLoc &FromLoc = FromArgArray[i]; ToTAInfo.addArgument(ImportTemplateArgumentLoc(FromLoc)); } ResInfo = &ToTAInfo; } Expr *BaseE = NULL; if (!E->isImplicitAccess()) { BaseE = Importer.Import(E->getBase()); assert(BaseE); if (!BaseE) return NULL; } return CXXDependentScopeMemberExpr::Create( Importer.getToContext(), BaseE, Importer.Import(E->getBaseType()), E->isArrow(), Importer.Import(E->getOperatorLoc()), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), cast_or_null(Importer.Import( E->getFirstQualifierFoundInScope())), NameInfo, ResInfo); } Expr *ASTNodeImporter::VisitCXXUnresolvedConstructExpr( CXXUnresolvedConstructExpr *CE) { std::vector Args; for (CXXUnresolvedConstructExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { if (Expr *Arg = Importer.Import(*I)) Args.push_back(Arg); else { assert(false); return NULL; } } return CXXUnresolvedConstructExpr::Create( Importer.getToContext(), Importer.Import(CE->getTypeSourceInfo()), Importer.Import(CE->getLParenLoc()), Args, Importer.Import(CE->getRParenLoc())); } Expr *ASTNodeImporter::VisitCXXPseudoDestructorExpr( CXXPseudoDestructorExpr *E) { Expr *BaseE = Importer.Import(E->getBase()); assert(BaseE); if (!BaseE) return NULL; // May be NULL? TypeSourceInfo *ScopeInfo = Importer.Import(E->getScopeTypeInfo()); PseudoDestructorTypeStorage Storage; if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) { IdentifierInfo *ToII = Importer.Import(FromII); assert(ToII); if (!ToII) return NULL; Storage = PseudoDestructorTypeStorage( ToII, Importer.Import(E->getDestroyedTypeLoc())); } else { TypeSourceInfo *TI = Importer.Import(E->getDestroyedTypeInfo()); assert(TI); if (!TI) return NULL; Storage = PseudoDestructorTypeStorage(TI); } return new (Importer.getToContext()) CXXPseudoDestructorExpr( Importer.getToContext(), BaseE, E->isArrow(), Importer.Import(E->getOperatorLoc()), Importer.Import(E->getQualifierLoc()), ScopeInfo, Importer.Import(E->getColonColonLoc()), Importer.Import(E->getTildeLoc()), Storage); } Expr *ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr( SubstNonTypeTemplateParmExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } NonTypeTemplateParmDecl *Param = cast_or_null( Importer.Import(E->getParameter())); assert(Param); if (!Param) return NULL; Expr *Replacement = Importer.Import(E->getReplacement()); if (!Replacement) { assert(false); return NULL; } return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr( T, E->getValueKind(), Importer.Import(E->getExprLoc()), Param, Replacement); } Expr *ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } Expr *Pattern = Importer.Import(E->getPattern()); if (!Pattern) { assert(false); return NULL; } return new (Importer.getToContext()) PackExpansionExpr( T, Pattern, Importer.Import(E->getEllipsisLoc()), E->getNumExpansions()); } Expr *ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) { assert(false); return NULL; } NamedDecl *Pack = cast_or_null(E->getPack()); assert(Pack); if (!Pack) return NULL; if (E->isValueDependent()) return new (Importer.getToContext()) SizeOfPackExpr( T, Importer.Import(E->getOperatorLoc()), Pack, Importer.Import(E->getPackLoc()), Importer.Import(E->getRParenLoc())); return new (Importer.getToContext()) SizeOfPackExpr( T, Importer.Import(E->getOperatorLoc()), Pack, Importer.Import(E->getPackLoc()), Importer.Import(E->getRParenLoc()), E->getPackLength()); } Expr *ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *CE) { QualType T = Importer.Import(CE->getType()); if (T.isNull()) { assert(false); return NULL; } std::vector PlacementArgs; for (CXXNewExpr::arg_iterator I = CE->placement_arg_begin(), E = CE->placement_arg_end(); I != E; ++I) { if (Expr *Arg = Importer.Import(*I)) PlacementArgs.push_back(Arg); else { assert(false); return NULL; } } FunctionDecl *OperatorNewDecl = cast_or_null( Importer.Import(CE->getOperatorNew())); assert(OperatorNewDecl || !CE->getOperatorNew()); FunctionDecl *OperatorDeleteDecl = cast_or_null( Importer.Import(CE->getOperatorDelete())); assert(OperatorDeleteDecl || !CE->getOperatorDelete()); Expr *ToInit = Importer.Import(CE->getInitializer()); if (!ToInit && CE->getInitializer()) { assert(false); return NULL; } TypeSourceInfo *TI = Importer.Import(CE->getAllocatedTypeSourceInfo()); assert(TI); if (!TI) return NULL; Expr *ToArrSize = Importer.Import(CE->getArraySize()); if (!ToArrSize && CE->getArraySize()) { assert(false); return NULL; } return new (Importer.getToContext()) CXXNewExpr( Importer.getToContext(), CE->isGlobalNew(), OperatorNewDecl, OperatorDeleteDecl, CE->doesUsualArrayDeleteWantSize(), PlacementArgs, Importer.Import(CE->getTypeIdParens()), ToArrSize, CE->getInitializationStyle(), ToInit, T, TI, Importer.Import(CE->getSourceRange()), Importer.Import(CE->getDirectInitRange())); } Expr *ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { QualType T = Importer.Import(E->getType()); assert(!T.isNull()); if (T.isNull()) return NULL; FunctionDecl *OperatorDeleteDecl = cast_or_null( Importer.Import(E->getOperatorDelete())); assert(OperatorDeleteDecl || !E->getOperatorDelete()); if (!OperatorDeleteDecl && E->getOperatorDelete()) return NULL; Expr *ToArg = Importer.Import(E->getArgument()); if (!ToArg && E->getArgument()) { assert(false); return NULL; } return new (Importer.getToContext()) CXXDeleteExpr( T, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(), E->doesUsualArrayDeleteWantSize(), OperatorDeleteDecl, ToArg, Importer.Import(E->getExprLoc())); } Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *CE) { QualType T = Importer.Import(CE->getType()); if (T.isNull()) { assert(false); return NULL; } std::vector Args; for (CXXConstructExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { if (Expr *Arg = Importer.Import(*I)) Args.push_back(Arg); else { assert(false); return NULL; } } return CXXConstructExpr::Create( Importer.getToContext(), T, Importer.Import(CE->getExprLoc()), cast(Importer.Import(CE->getConstructor())), CE->isElidable(), Args, CE->hadMultipleCandidates(), CE->isListInitialization(), CE->requiresZeroInitialization(), CE->getConstructionKind(), Importer.Import(CE->getParenOrBraceRange())); } Expr *ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) { Expr *SubExpr = Importer.Import(E->getSubExpr()); if (!SubExpr && E->getSubExpr()) { assert(false); return NULL; } std::vector Objs; for (unsigned i = 0, e = E->getNumObjects(); i < e; i++) if (ExprWithCleanups::CleanupObject Obj = cast(Importer.Import(E->getObject(i)))) Objs.push_back(Obj); else { assert(false); return NULL; } return ExprWithCleanups::Create(Importer.getToContext(), SubExpr, Objs); } Expr *ASTNodeImporter::VisitCallExpr(CallExpr *CE) { QualType T = Importer.Import(CE->getType()); if (T.isNull()) { assert(false); return NULL; } Expr *Callee = Importer.Import(CE->getCallee()); if (!Callee && CE->getCallee()) { assert(false); return NULL; } std::vector Args; for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { if (Expr *Arg = Importer.Import(*I)) Args.push_back(Arg); else { assert(false); return NULL; } } if (isa(CE)) return new (Importer.getToContext()) CXXMemberCallExpr( Importer.getToContext(), Callee, Args, T, CE->getValueKind(), Importer.Import(CE->getRParenLoc())); if (CXXOperatorCallExpr *OCE = dyn_cast(CE)) return new (Importer.getToContext()) CXXOperatorCallExpr( Importer.getToContext(), OCE->getOperator(), Callee, Args, T, CE->getValueKind(), Importer.Import(OCE->getOperatorLoc()), OCE->isFPContractable()); return new (Importer.getToContext()) CallExpr( Importer.getToContext(), Callee, Args, T, CE->getValueKind(), Importer.Import(CE->getRParenLoc())); } ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport) : ToContext(ToContext), FromContext(FromContext), FromSema(NULL), ToSema(NULL), ToFileManager(ToFileManager), FromFileManager(FromFileManager), Minimal(MinimalImport), LastDiagFromFrom(false) { ImportedDecls[FromContext.getTranslationUnitDecl()] = ToContext.getTranslationUnitDecl(); } ASTImporter::~ASTImporter() { } QualType ASTImporter::Import(QualType FromT) { if (FromT.isNull()) return QualType(); const Type *fromTy = FromT.getTypePtr(); // Check whether we've already imported this type. llvm::DenseMap::iterator Pos = ImportedTypes.find(fromTy); if (Pos != ImportedTypes.end()) return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers()); // Import the type ASTNodeImporter Importer(*this); QualType ToT = Importer.Visit(fromTy); assert(!ToT.isNull()); if (ToT.isNull()) return ToT; // Record the imported type. ImportedTypes[fromTy] = ToT.getTypePtr(); return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers()); } TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) { if (!FromTSI) return FromTSI; // FIXME: For now we just create a "trivial" type source info based // on the type and a single location. Implement a real version of this. QualType T = Import(FromTSI->getType()); if (T.isNull()) return 0; return ToContext.getTrivialTypeSourceInfo(T, Import(FromTSI->getTypeLoc().getLocStart())); } Decl *ASTImporter::GetImported(Decl *FromD) { llvm::DenseMap::iterator Pos = ImportedDecls.find(FromD); return Pos != ImportedDecls.end() ? Pos->second : NULL; } Decl *ASTImporter::Import(Decl *FromD) { if (!FromD) return 0; ASTNodeImporter Importer(*this); // Check whether we've already imported this declaration. if (Decl *ToD = GetImported(FromD)) { Importer.ImportDefinitionIfNeeded(FromD, ToD); return ToD; } // Import the type Decl *ToD = Importer.Visit(FromD); if (!ToD) return 0; // Record the imported declaration. ImportedDecls[FromD] = ToD; // Keep linkage information if (ToD->hasCachedLinkage()) ToD->setCachedLinkage(FromD->getCachedLinkage()); else if (NamedDecl *ND = dyn_cast(FromD)) ToD->setCachedLinkage(ND->getLinkageInternal()); if (TagDecl *FromTag = dyn_cast(FromD)) { // Keep track of anonymous tags that have an associated typedef. if (FromTag->getTypedefNameForAnonDecl()) AnonTagsWithPendingTypedefs.push_back(FromTag); } else if (TypedefNameDecl *FromTypedef = dyn_cast(FromD)) { // When we've finished transforming a typedef, see whether it was the // typedef for an anonymous tag. for (SmallVectorImpl::iterator FromTag = AnonTagsWithPendingTypedefs.begin(), FromTagEnd = AnonTagsWithPendingTypedefs.end(); FromTag != FromTagEnd; ++FromTag) { if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) { if (TagDecl *ToTag = cast_or_null(Import(*FromTag))) { // We found the typedef for an anonymous tag; link them. ToTag->setTypedefNameForAnonDecl(cast(ToD)); AnonTagsWithPendingTypedefs.erase(FromTag); break; } } } } return ToD; } DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { if (!FromDC) return FromDC; DeclContext *ToDC = cast_or_null(Import(cast(FromDC))); if (!ToDC) return 0; // When we're using a record/enum/Objective-C class/protocol as a context, we // need it to have a definition. if (RecordDecl *ToRecord = dyn_cast(ToDC)) { RecordDecl *FromRecord = cast(FromDC); if (ToRecord->isCompleteDefinition()) { // Do nothing. } else if (FromRecord->isCompleteDefinition()) { ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord, ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToRecord); } } else if (EnumDecl *ToEnum = dyn_cast(ToDC)) { EnumDecl *FromEnum = cast(FromDC); if (ToEnum->isCompleteDefinition()) { // Do nothing. } else if (FromEnum->isCompleteDefinition()) { ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum, ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToEnum); } } else if (ObjCInterfaceDecl *ToClass = dyn_cast(ToDC)) { ObjCInterfaceDecl *FromClass = cast(FromDC); if (ToClass->getDefinition()) { // Do nothing. } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) { ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass, ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToClass); } } else if (ObjCProtocolDecl *ToProto = dyn_cast(ToDC)) { ObjCProtocolDecl *FromProto = cast(FromDC); if (ToProto->getDefinition()) { // Do nothing. } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) { ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto, ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToProto); } } return ToDC; } Expr *ASTImporter::Import(Expr *FromE) { if (!FromE) return 0; return cast_or_null(Import(cast(FromE))); } Stmt *ASTImporter::Import(Stmt *FromS) { if (!FromS) return 0; // Check whether we've already imported this declaration. llvm::DenseMap::iterator Pos = ImportedStmts.find(FromS); if (Pos != ImportedStmts.end()) return Pos->second; // Import the type ASTNodeImporter Importer(*this); Stmt *ToS = Importer.Visit(FromS); if (!ToS) return 0; // Record the imported declaration. ImportedStmts[FromS] = ToS; return ToS; } NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) { if (!FromNNS) return 0; NestedNameSpecifier *prefix = Import(FromNNS->getPrefix()); switch (FromNNS->getKind()) { case NestedNameSpecifier::Identifier: if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) { return NestedNameSpecifier::Create(ToContext, prefix, II); } assert(false); return 0; case NestedNameSpecifier::Namespace: if (NamespaceDecl *NS = cast(Import(FromNNS->getAsNamespace()))) { return NestedNameSpecifier::Create(ToContext, prefix, NS); } assert(false); return 0; case NestedNameSpecifier::NamespaceAlias: if (NamespaceAliasDecl *NSAD = cast(Import(FromNNS->getAsNamespaceAlias()))) { return NestedNameSpecifier::Create(ToContext, prefix, NSAD); } assert(false); return 0; case NestedNameSpecifier::Global: return NestedNameSpecifier::GlobalSpecifier(ToContext); case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = Import(QualType(FromNNS->getAsType(), 0u)); if (!T.isNull()) { bool bTemplate = FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; return NestedNameSpecifier::Create(ToContext, prefix, bTemplate, T.getTypePtr()); } } assert(false); return 0; } llvm_unreachable("Invalid nested name specifier kind"); } NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) { // Copied from NestedNameSpecifier mostly. SmallVector NestedNames; NestedNameSpecifierLoc NNS = FromNNS; // Push each of the nested-name-specifiers's onto a stack for // serialization in reverse order. while (NNS) { NestedNames.push_back(NNS); NNS = NNS.getPrefix(); } // FIXME: check if this list is inverted NestedNameSpecifierLocBuilder Builder; while(!NestedNames.empty()) { NNS = NestedNames.pop_back_val(); NestedNameSpecifier *Spec = Import(NNS.getNestedNameSpecifier()); NestedNameSpecifier::SpecifierKind Kind = Spec->getKind(); switch (Kind) { case NestedNameSpecifier::Identifier: Builder.Extend(getToContext(), Spec->getAsIdentifier(), Import(NNS.getLocalBeginLoc()), Import(NNS.getLocalEndLoc())); break; case NestedNameSpecifier::Namespace: Builder.Extend(getToContext(), Spec->getAsNamespace(), Import(NNS.getLocalBeginLoc()), Import(NNS.getLocalEndLoc())); break; case NestedNameSpecifier::NamespaceAlias: Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(), Import(NNS.getLocalBeginLoc()), Import(NNS.getLocalEndLoc())); break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo( QualType(Spec->getAsType() ,0)); Builder.Extend(getToContext(), // FIXME: Is 'Data' serialization good? Import(NNS.getLocalBeginLoc()), TSI->getTypeLoc(), Import(NNS.getLocalEndLoc())); break; } case NestedNameSpecifier::Global: Builder.MakeGlobal(getToContext(), Import(NNS.getLocalBeginLoc())); break; } } return Builder.getWithLocInContext(getToContext()); } TemplateName ASTImporter::Import(TemplateName From) { switch (From.getKind()) { case TemplateName::Template: if (TemplateDecl *ToTemplate = cast_or_null(Import(From.getAsTemplateDecl()))) return TemplateName(ToTemplate); return TemplateName(); case TemplateName::OverloadedTemplate: { OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); UnresolvedSet<2> ToTemplates; for (OverloadedTemplateStorage::iterator I = FromStorage->begin(), E = FromStorage->end(); I != E; ++I) { if (NamedDecl *To = cast_or_null(Import(*I))) ToTemplates.addDecl(To); else return TemplateName(); } return ToContext.getOverloadedTemplateName(ToTemplates.begin(), ToTemplates.end()); } case TemplateName::QualifiedTemplate: { QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); NestedNameSpecifier *Qualifier = Import(QTN->getQualifier()); if (!Qualifier) return TemplateName(); if (TemplateDecl *ToTemplate = cast_or_null(Import(From.getAsTemplateDecl()))) return ToContext.getQualifiedTemplateName(Qualifier, QTN->hasTemplateKeyword(), ToTemplate); return TemplateName(); } case TemplateName::DependentTemplate: { DependentTemplateName *DTN = From.getAsDependentTemplateName(); NestedNameSpecifier *Qualifier = Import(DTN->getQualifier()); if (!Qualifier) return TemplateName(); if (DTN->isIdentifier()) { return ToContext.getDependentTemplateName(Qualifier, Import(DTN->getIdentifier())); } return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator()); } case TemplateName::SubstTemplateTemplateParm: { SubstTemplateTemplateParmStorage *subst = From.getAsSubstTemplateTemplateParm(); TemplateTemplateParmDecl *param = cast_or_null(Import(subst->getParameter())); if (!param) return TemplateName(); TemplateName replacement = Import(subst->getReplacement()); if (replacement.isNull()) return TemplateName(); return ToContext.getSubstTemplateTemplateParm(param, replacement); } case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *SubstPack = From.getAsSubstTemplateTemplateParmPack(); TemplateTemplateParmDecl *Param = cast_or_null( Import(SubstPack->getParameterPack())); if (!Param) return TemplateName(); ASTNodeImporter Importer(*this); TemplateArgument ArgPack = Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); if (ArgPack.isNull()) return TemplateName(); return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack); } } llvm_unreachable("Invalid template name kind"); } SourceLocation ASTImporter::Import(SourceLocation FromLoc) { if (FromLoc.isInvalid()) return SourceLocation(); SourceManager &FromSM = FromContext.getSourceManager(); // For now, map everything down to its spelling location, so that we // don't have to import macro expansions. // FIXME: Import macro expansions! std::pair Decomposed = FromSM.getDecomposedExpansionLoc(FromLoc); SourceManager &ToSM = ToContext.getSourceManager(); FileID ToFileID = Import(Decomposed.first); if (ToFileID.isInvalid()) return SourceLocation(); return ToSM.getLocForStartOfFile(ToFileID) .getLocWithOffset(Decomposed.second); } SourceRange ASTImporter::Import(SourceRange FromRange) { return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd())); } FileID ASTImporter::Import(FileID FromID) { llvm::DenseMap::iterator Pos = ImportedFileIDs.find(FromID); if (Pos != ImportedFileIDs.end()) return Pos->second; SourceManager &FromSM = FromContext.getSourceManager(); SourceManager &ToSM = ToContext.getSourceManager(); const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); assert(FromSLoc.isFile() && "Cannot handle macro expansions yet"); // Include location of this file. SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc()); // Map the FileID for to the "to" source manager. FileID ToID; const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache(); if (Cache->OrigEntry) { // FIXME: We probably want to use getVirtualFile(), so we don't hit the // disk again // FIXME: We definitely want to re-use the existing MemoryBuffer, rather // than mmap the files several times. const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName()); if (!Entry) return FileID(); ToID = ToSM.createFileID(Entry, ToIncludeLoc, FromSLoc.getFile().getFileCharacteristic()); } else { // FIXME: We want to re-use the existing MemoryBuffer! const llvm::MemoryBuffer * FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM); llvm::MemoryBuffer *ToBuf = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(), FromBuf->getBufferIdentifier()); ToID = ToSM.createFileIDForMemBuffer(ToBuf, FromSLoc.getFile().getFileCharacteristic()); } ImportedFileIDs[FromID] = ToID; return ToID; } CXXBaseSpecifier *ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) { ImportedCXXBaseSpecifierMap::const_iterator Pos = ImportedCXXBaseSpecifiers.find(BaseSpec); if (Pos != ImportedCXXBaseSpecifiers.end()) return Pos->second; CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier( Import(BaseSpec->getSourceRange()), BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(), BaseSpec->getAccessSpecifierAsWritten(), Import(BaseSpec->getTypeSourceInfo()), Import(BaseSpec->getEllipsisLoc())); ImportedCXXBaseSpecifiers[BaseSpec] = Imported; return Imported; } void ASTImporter::ImportDefinition(Decl *From) { Decl *To = Import(From); if (!To) return; if (DeclContext *FromDC = cast(From)) { ASTNodeImporter Importer(*this); if (RecordDecl *ToRecord = dyn_cast(To)) { if (!ToRecord->getDefinition()) { Importer.ImportDefinition(cast(FromDC), ToRecord, ASTNodeImporter::IDK_Everything); return; } } if (EnumDecl *ToEnum = dyn_cast(To)) { if (!ToEnum->getDefinition()) { Importer.ImportDefinition(cast(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); return; } } if (ObjCInterfaceDecl *ToIFace = dyn_cast(To)) { if (!ToIFace->getDefinition()) { Importer.ImportDefinition(cast(FromDC), ToIFace, ASTNodeImporter::IDK_Everything); return; } } if (ObjCProtocolDecl *ToProto = dyn_cast(To)) { if (!ToProto->getDefinition()) { Importer.ImportDefinition(cast(FromDC), ToProto, ASTNodeImporter::IDK_Everything); return; } } Importer.ImportDeclContext(FromDC, true); } } DeclarationName ASTImporter::Import(DeclarationName FromName) { if (!FromName) return DeclarationName(); switch (FromName.getNameKind()) { case DeclarationName::Identifier: return Import(FromName.getAsIdentifierInfo()); case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: return Import(FromName.getObjCSelector()); case DeclarationName::CXXConstructorName: { QualType T = Import(FromName.getCXXNameType()); if (T.isNull()) return DeclarationName(); return ToContext.DeclarationNames.getCXXConstructorName( ToContext.getCanonicalType(T)); } case DeclarationName::CXXDestructorName: { QualType T = Import(FromName.getCXXNameType()); if (T.isNull()) return DeclarationName(); return ToContext.DeclarationNames.getCXXDestructorName( ToContext.getCanonicalType(T)); } case DeclarationName::CXXConversionFunctionName: { QualType T = Import(FromName.getCXXNameType()); if (T.isNull()) return DeclarationName(); return ToContext.DeclarationNames.getCXXConversionFunctionName( ToContext.getCanonicalType(T)); } case DeclarationName::CXXOperatorName: return ToContext.DeclarationNames.getCXXOperatorName( FromName.getCXXOverloadedOperator()); case DeclarationName::CXXLiteralOperatorName: return ToContext.DeclarationNames.getCXXLiteralOperatorName( Import(FromName.getCXXLiteralIdentifier())); case DeclarationName::CXXUsingDirective: // FIXME: STATICS! return DeclarationName::getUsingDirectiveName(); } llvm_unreachable("Invalid DeclarationName Kind!"); } IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) { if (!FromId) return 0; return &ToContext.Idents.get(FromId->getName()); } Selector ASTImporter::Import(Selector FromSel) { if (FromSel.isNull()) return Selector(); SmallVector Idents; Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0))); for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I) Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I))); return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data()); } DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name, DeclContext *DC, unsigned IDNS, NamedDecl **Decls, unsigned NumDecls) { return Name; } DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) { if (LastDiagFromFrom) ToContext.getDiagnostics().notePriorDiagnosticFrom( FromContext.getDiagnostics()); LastDiagFromFrom = false; return ToContext.getDiagnostics().Report(Loc, DiagID); } DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) { if (!LastDiagFromFrom) FromContext.getDiagnostics().notePriorDiagnosticFrom( ToContext.getDiagnostics()); LastDiagFromFrom = true; return FromContext.getDiagnostics().Report(Loc, DiagID); } void ASTImporter::CompleteDecl (Decl *D) { if (ObjCInterfaceDecl *ID = dyn_cast(D)) { if (!ID->getDefinition()) ID->startDefinition(); } else if (ObjCProtocolDecl *PD = dyn_cast(D)) { if (!PD->getDefinition()) PD->startDefinition(); } else if (TagDecl *TD = dyn_cast(D)) { if (!TD->getDefinition() && !TD->isBeingDefined()) { TD->startDefinition(); TD->setCompleteDefinition(true); } } else { assert (0 && "CompleteDecl called on a Decl that can't be completed"); } } Decl *ASTImporter::Imported(Decl *From, Decl *To) { ImportedDecls[From] = To; return To; } bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To, bool Complain, bool CheckQualifiers) { llvm::DenseMap::iterator Pos = ImportedTypes.find(From.getTypePtr()); if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To)) return true; StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls, false, Complain); return Ctx.IsStructurallyEquivalent(From, To, CheckQualifiers); }