1 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTImporter class which imports AST nodes from one
11 // context into another context.
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/Support/MemoryBuffer.h"
28 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
29 public DeclVisitor<ASTNodeImporter, Decl *>,
30 public StmtVisitor<ASTNodeImporter, Stmt *> {
31 ASTImporter &Importer;
34 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
36 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
37 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
38 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
41 QualType VisitType(const Type *T);
42 QualType VisitBuiltinType(const BuiltinType *T);
43 QualType VisitComplexType(const ComplexType *T);
44 QualType VisitPointerType(const PointerType *T);
45 QualType VisitBlockPointerType(const BlockPointerType *T);
46 QualType VisitLValueReferenceType(const LValueReferenceType *T);
47 QualType VisitRValueReferenceType(const RValueReferenceType *T);
48 QualType VisitMemberPointerType(const MemberPointerType *T);
49 QualType VisitConstantArrayType(const ConstantArrayType *T);
50 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
51 QualType VisitVariableArrayType(const VariableArrayType *T);
52 // FIXME: DependentSizedArrayType
53 // FIXME: DependentSizedExtVectorType
54 QualType VisitVectorType(const VectorType *T);
55 QualType VisitExtVectorType(const ExtVectorType *T);
56 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
57 QualType VisitFunctionProtoType(const FunctionProtoType *T);
58 // FIXME: UnresolvedUsingType
59 QualType VisitParenType(const ParenType *T);
60 QualType VisitTypedefType(const TypedefType *T);
61 QualType VisitTypeOfExprType(const TypeOfExprType *T);
62 // FIXME: DependentTypeOfExprType
63 QualType VisitTypeOfType(const TypeOfType *T);
64 QualType VisitDecltypeType(const DecltypeType *T);
65 QualType VisitUnaryTransformType(const UnaryTransformType *T);
66 QualType VisitAutoType(const AutoType *T);
67 // FIXME: DependentDecltypeType
68 QualType VisitRecordType(const RecordType *T);
69 QualType VisitEnumType(const EnumType *T);
70 // FIXME: TemplateTypeParmType
71 // FIXME: SubstTemplateTypeParmType
72 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
73 QualType VisitElaboratedType(const ElaboratedType *T);
74 // FIXME: DependentNameType
75 // FIXME: DependentTemplateSpecializationType
76 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
77 QualType VisitObjCObjectType(const ObjCObjectType *T);
78 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
80 // Importing declarations
81 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
82 DeclContext *&LexicalDC, DeclarationName &Name,
84 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = 0);
85 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
86 DeclarationNameInfo& To);
87 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89 /// \brief What we should import from the definition.
90 enum ImportDefinitionKind {
91 /// \brief Import the default subset of the definition, which might be
92 /// nothing (if minimal import is set) or might be everything (if minimal
93 /// import is not set).
95 /// \brief Import everything.
97 /// \brief Import only the bare bones needed to establish a valid
102 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
103 return IDK == IDK_Everything ||
104 (IDK == IDK_Default && !Importer.isMinimalImport());
107 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
108 ImportDefinitionKind Kind = IDK_Default);
109 bool ImportDefinition(VarDecl *From, VarDecl *To,
110 ImportDefinitionKind Kind = IDK_Default);
111 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
112 ImportDefinitionKind Kind = IDK_Default);
113 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
114 ImportDefinitionKind Kind = IDK_Default);
115 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
116 ImportDefinitionKind Kind = IDK_Default);
117 TemplateParameterList *ImportTemplateParameterList(
118 TemplateParameterList *Params);
119 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
120 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
121 unsigned NumFromArgs,
122 SmallVectorImpl<TemplateArgument> &ToArgs);
123 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
124 bool Complain = true);
125 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
126 bool Complain = true);
127 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
128 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
129 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
130 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
131 Decl *VisitDecl(Decl *D);
132 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
133 Decl *VisitNamespaceDecl(NamespaceDecl *D);
134 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
135 Decl *VisitTypedefDecl(TypedefDecl *D);
136 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
137 Decl *VisitEnumDecl(EnumDecl *D);
138 Decl *VisitRecordDecl(RecordDecl *D);
139 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
140 Decl *VisitFunctionDecl(FunctionDecl *D);
141 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
142 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
143 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
144 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
145 Decl *VisitFieldDecl(FieldDecl *D);
146 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
147 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
148 Decl *VisitVarDecl(VarDecl *D);
149 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
150 Decl *VisitParmVarDecl(ParmVarDecl *D);
151 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
152 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
153 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
154 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
155 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
156 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
157 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
158 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
159 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
160 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
161 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
162 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
163 Decl *VisitClassTemplateSpecializationDecl(
164 ClassTemplateSpecializationDecl *D);
165 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
166 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
168 // Importing statements
169 Stmt *VisitStmt(Stmt *S);
171 // Importing expressions
172 Expr *VisitExpr(Expr *E);
173 Expr *VisitDeclRefExpr(DeclRefExpr *E);
174 Expr *VisitIntegerLiteral(IntegerLiteral *E);
175 Expr *VisitCharacterLiteral(CharacterLiteral *E);
176 Expr *VisitParenExpr(ParenExpr *E);
177 Expr *VisitUnaryOperator(UnaryOperator *E);
178 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
179 Expr *VisitBinaryOperator(BinaryOperator *E);
180 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
181 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
182 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
185 using namespace clang;
187 //----------------------------------------------------------------------------
188 // Structural Equivalence
189 //----------------------------------------------------------------------------
192 struct StructuralEquivalenceContext {
193 /// \brief AST contexts for which we are checking structural equivalence.
196 /// \brief The set of "tentative" equivalences between two canonical
197 /// declarations, mapping from a declaration in the first context to the
198 /// declaration in the second context that we believe to be equivalent.
199 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
201 /// \brief Queue of declarations in the first context whose equivalence
202 /// with a declaration in the second context still needs to be verified.
203 std::deque<Decl *> DeclsToCheck;
205 /// \brief Declaration (from, to) pairs that are known not to be equivalent
206 /// (which we have already complained about).
207 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
209 /// \brief Whether we're being strict about the spelling of types when
210 /// unifying two types.
211 bool StrictTypeSpelling;
213 /// \brief Whether to complain about failures.
216 /// \brief \c true if the last diagnostic came from C2.
219 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
220 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
221 bool StrictTypeSpelling = false,
222 bool Complain = true)
223 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
224 StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
225 LastDiagFromC2(false) {}
227 /// \brief Determine whether the two declarations are structurally
229 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
231 /// \brief Determine whether the two types are structurally equivalent.
232 bool IsStructurallyEquivalent(QualType T1, QualType T2);
235 /// \brief Finish checking all of the structural equivalences.
237 /// \returns true if an error occurred, false otherwise.
241 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
242 assert(Complain && "Not allowed to complain");
244 C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
245 LastDiagFromC2 = false;
246 return C1.getDiagnostics().Report(Loc, DiagID);
249 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
250 assert(Complain && "Not allowed to complain");
252 C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
253 LastDiagFromC2 = true;
254 return C2.getDiagnostics().Report(Loc, DiagID);
259 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
260 QualType T1, QualType T2);
261 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
264 /// \brief Determine structural equivalence of two expressions.
265 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
266 Expr *E1, Expr *E2) {
270 // FIXME: Actually perform a structural comparison!
274 /// \brief Determine whether two identifiers are equivalent.
275 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
276 const IdentifierInfo *Name2) {
277 if (!Name1 || !Name2)
278 return Name1 == Name2;
280 return Name1->getName() == Name2->getName();
283 /// \brief Determine whether two nested-name-specifiers are equivalent.
284 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
285 NestedNameSpecifier *NNS1,
286 NestedNameSpecifier *NNS2) {
291 /// \brief Determine whether two template arguments are equivalent.
292 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
293 const TemplateArgument &Arg1,
294 const TemplateArgument &Arg2) {
295 if (Arg1.getKind() != Arg2.getKind())
298 switch (Arg1.getKind()) {
299 case TemplateArgument::Null:
302 case TemplateArgument::Type:
303 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
305 case TemplateArgument::Integral:
306 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
307 Arg2.getIntegralType()))
310 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
312 case TemplateArgument::Declaration:
313 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
315 case TemplateArgument::NullPtr:
316 return true; // FIXME: Is this correct?
318 case TemplateArgument::Template:
319 return IsStructurallyEquivalent(Context,
320 Arg1.getAsTemplate(),
321 Arg2.getAsTemplate());
323 case TemplateArgument::TemplateExpansion:
324 return IsStructurallyEquivalent(Context,
325 Arg1.getAsTemplateOrTemplatePattern(),
326 Arg2.getAsTemplateOrTemplatePattern());
328 case TemplateArgument::Expression:
329 return IsStructurallyEquivalent(Context,
330 Arg1.getAsExpr(), Arg2.getAsExpr());
332 case TemplateArgument::Pack:
333 if (Arg1.pack_size() != Arg2.pack_size())
336 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
337 if (!IsStructurallyEquivalent(Context,
338 Arg1.pack_begin()[I],
339 Arg2.pack_begin()[I]))
345 llvm_unreachable("Invalid template argument kind");
348 /// \brief Determine structural equivalence for the common part of array
350 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
351 const ArrayType *Array1,
352 const ArrayType *Array2) {
353 if (!IsStructurallyEquivalent(Context,
354 Array1->getElementType(),
355 Array2->getElementType()))
357 if (Array1->getSizeModifier() != Array2->getSizeModifier())
359 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
365 /// \brief Determine structural equivalence of two types.
366 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
367 QualType T1, QualType T2) {
368 if (T1.isNull() || T2.isNull())
369 return T1.isNull() && T2.isNull();
371 if (!Context.StrictTypeSpelling) {
372 // We aren't being strict about token-to-token equivalence of types,
373 // so map down to the canonical type.
374 T1 = Context.C1.getCanonicalType(T1);
375 T2 = Context.C2.getCanonicalType(T2);
378 if (T1.getQualifiers() != T2.getQualifiers())
381 Type::TypeClass TC = T1->getTypeClass();
383 if (T1->getTypeClass() != T2->getTypeClass()) {
384 // Compare function types with prototypes vs. without prototypes as if
385 // both did not have prototypes.
386 if (T1->getTypeClass() == Type::FunctionProto &&
387 T2->getTypeClass() == Type::FunctionNoProto)
388 TC = Type::FunctionNoProto;
389 else if (T1->getTypeClass() == Type::FunctionNoProto &&
390 T2->getTypeClass() == Type::FunctionProto)
391 TC = Type::FunctionNoProto;
398 // FIXME: Deal with Char_S/Char_U.
399 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
404 if (!IsStructurallyEquivalent(Context,
405 cast<ComplexType>(T1)->getElementType(),
406 cast<ComplexType>(T2)->getElementType()))
411 if (!IsStructurallyEquivalent(Context,
412 cast<DecayedType>(T1)->getPointeeType(),
413 cast<DecayedType>(T2)->getPointeeType()))
418 if (!IsStructurallyEquivalent(Context,
419 cast<PointerType>(T1)->getPointeeType(),
420 cast<PointerType>(T2)->getPointeeType()))
424 case Type::BlockPointer:
425 if (!IsStructurallyEquivalent(Context,
426 cast<BlockPointerType>(T1)->getPointeeType(),
427 cast<BlockPointerType>(T2)->getPointeeType()))
431 case Type::LValueReference:
432 case Type::RValueReference: {
433 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
434 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
435 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
437 if (Ref1->isInnerRef() != Ref2->isInnerRef())
439 if (!IsStructurallyEquivalent(Context,
440 Ref1->getPointeeTypeAsWritten(),
441 Ref2->getPointeeTypeAsWritten()))
446 case Type::MemberPointer: {
447 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
448 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
449 if (!IsStructurallyEquivalent(Context,
450 MemPtr1->getPointeeType(),
451 MemPtr2->getPointeeType()))
453 if (!IsStructurallyEquivalent(Context,
454 QualType(MemPtr1->getClass(), 0),
455 QualType(MemPtr2->getClass(), 0)))
460 case Type::ConstantArray: {
461 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
462 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
463 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
466 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
471 case Type::IncompleteArray:
472 if (!IsArrayStructurallyEquivalent(Context,
474 cast<ArrayType>(T2)))
478 case Type::VariableArray: {
479 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
480 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
481 if (!IsStructurallyEquivalent(Context,
482 Array1->getSizeExpr(), Array2->getSizeExpr()))
485 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
491 case Type::DependentSizedArray: {
492 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
493 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
494 if (!IsStructurallyEquivalent(Context,
495 Array1->getSizeExpr(), Array2->getSizeExpr()))
498 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
504 case Type::DependentSizedExtVector: {
505 const DependentSizedExtVectorType *Vec1
506 = cast<DependentSizedExtVectorType>(T1);
507 const DependentSizedExtVectorType *Vec2
508 = cast<DependentSizedExtVectorType>(T2);
509 if (!IsStructurallyEquivalent(Context,
510 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
512 if (!IsStructurallyEquivalent(Context,
513 Vec1->getElementType(),
514 Vec2->getElementType()))
520 case Type::ExtVector: {
521 const VectorType *Vec1 = cast<VectorType>(T1);
522 const VectorType *Vec2 = cast<VectorType>(T2);
523 if (!IsStructurallyEquivalent(Context,
524 Vec1->getElementType(),
525 Vec2->getElementType()))
527 if (Vec1->getNumElements() != Vec2->getNumElements())
529 if (Vec1->getVectorKind() != Vec2->getVectorKind())
534 case Type::FunctionProto: {
535 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
536 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
537 if (Proto1->getNumArgs() != Proto2->getNumArgs())
539 for (unsigned I = 0, N = Proto1->getNumArgs(); I != N; ++I) {
540 if (!IsStructurallyEquivalent(Context,
541 Proto1->getArgType(I),
542 Proto2->getArgType(I)))
545 if (Proto1->isVariadic() != Proto2->isVariadic())
547 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
549 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
550 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
552 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
553 if (!IsStructurallyEquivalent(Context,
554 Proto1->getExceptionType(I),
555 Proto2->getExceptionType(I)))
558 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
559 if (!IsStructurallyEquivalent(Context,
560 Proto1->getNoexceptExpr(),
561 Proto2->getNoexceptExpr()))
564 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
567 // Fall through to check the bits common with FunctionNoProtoType.
570 case Type::FunctionNoProto: {
571 const FunctionType *Function1 = cast<FunctionType>(T1);
572 const FunctionType *Function2 = cast<FunctionType>(T2);
573 if (!IsStructurallyEquivalent(Context,
574 Function1->getResultType(),
575 Function2->getResultType()))
577 if (Function1->getExtInfo() != Function2->getExtInfo())
582 case Type::UnresolvedUsing:
583 if (!IsStructurallyEquivalent(Context,
584 cast<UnresolvedUsingType>(T1)->getDecl(),
585 cast<UnresolvedUsingType>(T2)->getDecl()))
590 case Type::Attributed:
591 if (!IsStructurallyEquivalent(Context,
592 cast<AttributedType>(T1)->getModifiedType(),
593 cast<AttributedType>(T2)->getModifiedType()))
595 if (!IsStructurallyEquivalent(Context,
596 cast<AttributedType>(T1)->getEquivalentType(),
597 cast<AttributedType>(T2)->getEquivalentType()))
602 if (!IsStructurallyEquivalent(Context,
603 cast<ParenType>(T1)->getInnerType(),
604 cast<ParenType>(T2)->getInnerType()))
609 if (!IsStructurallyEquivalent(Context,
610 cast<TypedefType>(T1)->getDecl(),
611 cast<TypedefType>(T2)->getDecl()))
615 case Type::TypeOfExpr:
616 if (!IsStructurallyEquivalent(Context,
617 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
618 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
623 if (!IsStructurallyEquivalent(Context,
624 cast<TypeOfType>(T1)->getUnderlyingType(),
625 cast<TypeOfType>(T2)->getUnderlyingType()))
629 case Type::UnaryTransform:
630 if (!IsStructurallyEquivalent(Context,
631 cast<UnaryTransformType>(T1)->getUnderlyingType(),
632 cast<UnaryTransformType>(T1)->getUnderlyingType()))
637 if (!IsStructurallyEquivalent(Context,
638 cast<DecltypeType>(T1)->getUnderlyingExpr(),
639 cast<DecltypeType>(T2)->getUnderlyingExpr()))
644 if (!IsStructurallyEquivalent(Context,
645 cast<AutoType>(T1)->getDeducedType(),
646 cast<AutoType>(T2)->getDeducedType()))
652 if (!IsStructurallyEquivalent(Context,
653 cast<TagType>(T1)->getDecl(),
654 cast<TagType>(T2)->getDecl()))
658 case Type::TemplateTypeParm: {
659 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
660 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
661 if (Parm1->getDepth() != Parm2->getDepth())
663 if (Parm1->getIndex() != Parm2->getIndex())
665 if (Parm1->isParameterPack() != Parm2->isParameterPack())
668 // Names of template type parameters are never significant.
672 case Type::SubstTemplateTypeParm: {
673 const SubstTemplateTypeParmType *Subst1
674 = cast<SubstTemplateTypeParmType>(T1);
675 const SubstTemplateTypeParmType *Subst2
676 = cast<SubstTemplateTypeParmType>(T2);
677 if (!IsStructurallyEquivalent(Context,
678 QualType(Subst1->getReplacedParameter(), 0),
679 QualType(Subst2->getReplacedParameter(), 0)))
681 if (!IsStructurallyEquivalent(Context,
682 Subst1->getReplacementType(),
683 Subst2->getReplacementType()))
688 case Type::SubstTemplateTypeParmPack: {
689 const SubstTemplateTypeParmPackType *Subst1
690 = cast<SubstTemplateTypeParmPackType>(T1);
691 const SubstTemplateTypeParmPackType *Subst2
692 = cast<SubstTemplateTypeParmPackType>(T2);
693 if (!IsStructurallyEquivalent(Context,
694 QualType(Subst1->getReplacedParameter(), 0),
695 QualType(Subst2->getReplacedParameter(), 0)))
697 if (!IsStructurallyEquivalent(Context,
698 Subst1->getArgumentPack(),
699 Subst2->getArgumentPack()))
703 case Type::TemplateSpecialization: {
704 const TemplateSpecializationType *Spec1
705 = cast<TemplateSpecializationType>(T1);
706 const TemplateSpecializationType *Spec2
707 = cast<TemplateSpecializationType>(T2);
708 if (!IsStructurallyEquivalent(Context,
709 Spec1->getTemplateName(),
710 Spec2->getTemplateName()))
712 if (Spec1->getNumArgs() != Spec2->getNumArgs())
714 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
715 if (!IsStructurallyEquivalent(Context,
716 Spec1->getArg(I), Spec2->getArg(I)))
722 case Type::Elaborated: {
723 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
724 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
725 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
726 if (Elab1->getKeyword() != Elab2->getKeyword())
728 if (!IsStructurallyEquivalent(Context,
729 Elab1->getQualifier(),
730 Elab2->getQualifier()))
732 if (!IsStructurallyEquivalent(Context,
733 Elab1->getNamedType(),
734 Elab2->getNamedType()))
739 case Type::InjectedClassName: {
740 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
741 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
742 if (!IsStructurallyEquivalent(Context,
743 Inj1->getInjectedSpecializationType(),
744 Inj2->getInjectedSpecializationType()))
749 case Type::DependentName: {
750 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
751 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
752 if (!IsStructurallyEquivalent(Context,
753 Typename1->getQualifier(),
754 Typename2->getQualifier()))
756 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
757 Typename2->getIdentifier()))
763 case Type::DependentTemplateSpecialization: {
764 const DependentTemplateSpecializationType *Spec1 =
765 cast<DependentTemplateSpecializationType>(T1);
766 const DependentTemplateSpecializationType *Spec2 =
767 cast<DependentTemplateSpecializationType>(T2);
768 if (!IsStructurallyEquivalent(Context,
769 Spec1->getQualifier(),
770 Spec2->getQualifier()))
772 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
773 Spec2->getIdentifier()))
775 if (Spec1->getNumArgs() != Spec2->getNumArgs())
777 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
778 if (!IsStructurallyEquivalent(Context,
779 Spec1->getArg(I), Spec2->getArg(I)))
785 case Type::PackExpansion:
786 if (!IsStructurallyEquivalent(Context,
787 cast<PackExpansionType>(T1)->getPattern(),
788 cast<PackExpansionType>(T2)->getPattern()))
792 case Type::ObjCInterface: {
793 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
794 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
795 if (!IsStructurallyEquivalent(Context,
796 Iface1->getDecl(), Iface2->getDecl()))
801 case Type::ObjCObject: {
802 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
803 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
804 if (!IsStructurallyEquivalent(Context,
806 Obj2->getBaseType()))
808 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
810 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
811 if (!IsStructurallyEquivalent(Context,
812 Obj1->getProtocol(I),
813 Obj2->getProtocol(I)))
819 case Type::ObjCObjectPointer: {
820 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
821 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
822 if (!IsStructurallyEquivalent(Context,
823 Ptr1->getPointeeType(),
824 Ptr2->getPointeeType()))
830 if (!IsStructurallyEquivalent(Context,
831 cast<AtomicType>(T1)->getValueType(),
832 cast<AtomicType>(T2)->getValueType()))
842 /// \brief Determine structural equivalence of two fields.
843 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
844 FieldDecl *Field1, FieldDecl *Field2) {
845 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
847 // For anonymous structs/unions, match up the anonymous struct/union type
848 // declarations directly, so that we don't go off searching for anonymous
850 if (Field1->isAnonymousStructOrUnion() &&
851 Field2->isAnonymousStructOrUnion()) {
852 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
853 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
854 return IsStructurallyEquivalent(Context, D1, D2);
857 // Check for equivalent field names.
858 IdentifierInfo *Name1 = Field1->getIdentifier();
859 IdentifierInfo *Name2 = Field2->getIdentifier();
860 if (!::IsStructurallyEquivalent(Name1, Name2))
863 if (!IsStructurallyEquivalent(Context,
864 Field1->getType(), Field2->getType())) {
865 if (Context.Complain) {
866 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
867 << Context.C2.getTypeDeclType(Owner2);
868 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
869 << Field2->getDeclName() << Field2->getType();
870 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
871 << Field1->getDeclName() << Field1->getType();
876 if (Field1->isBitField() != Field2->isBitField()) {
877 if (Context.Complain) {
878 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
879 << Context.C2.getTypeDeclType(Owner2);
880 if (Field1->isBitField()) {
881 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
882 << Field1->getDeclName() << Field1->getType()
883 << Field1->getBitWidthValue(Context.C1);
884 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
885 << Field2->getDeclName();
887 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
888 << Field2->getDeclName() << Field2->getType()
889 << Field2->getBitWidthValue(Context.C2);
890 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
891 << Field1->getDeclName();
897 if (Field1->isBitField()) {
898 // Make sure that the bit-fields are the same length.
899 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
900 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
902 if (Bits1 != Bits2) {
903 if (Context.Complain) {
904 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
905 << Context.C2.getTypeDeclType(Owner2);
906 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
907 << Field2->getDeclName() << Field2->getType() << Bits2;
908 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
909 << Field1->getDeclName() << Field1->getType() << Bits1;
918 /// \brief Find the index of the given anonymous struct/union within its
921 /// \returns Returns the index of this anonymous struct/union in its context,
922 /// including the next assigned index (if none of them match). Returns an
923 /// empty option if the context is not a record, i.e.. if the anonymous
924 /// struct/union is at namespace or block scope.
925 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
926 ASTContext &Context = Anon->getASTContext();
927 QualType AnonTy = Context.getRecordType(Anon);
929 RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
934 for (DeclContext::decl_iterator D = Owner->noload_decls_begin(),
935 DEnd = Owner->noload_decls_end();
937 FieldDecl *F = dyn_cast<FieldDecl>(*D);
938 if (!F || !F->isAnonymousStructOrUnion())
941 if (Context.hasSameType(F->getType(), AnonTy))
950 /// \brief Determine structural equivalence of two records.
951 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
952 RecordDecl *D1, RecordDecl *D2) {
953 if (D1->isUnion() != D2->isUnion()) {
954 if (Context.Complain) {
955 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
956 << Context.C2.getTypeDeclType(D2);
957 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
958 << D1->getDeclName() << (unsigned)D1->getTagKind();
963 if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
964 // If both anonymous structs/unions are in a record context, make sure
965 // they occur in the same location in the context records.
966 if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
967 if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
968 if (*Index1 != *Index2)
974 // If both declarations are class template specializations, we know
975 // the ODR applies, so check the template and template arguments.
976 ClassTemplateSpecializationDecl *Spec1
977 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
978 ClassTemplateSpecializationDecl *Spec2
979 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
980 if (Spec1 && Spec2) {
981 // Check that the specialized templates are the same.
982 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
983 Spec2->getSpecializedTemplate()))
986 // Check that the template arguments are the same.
987 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
990 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
991 if (!IsStructurallyEquivalent(Context,
992 Spec1->getTemplateArgs().get(I),
993 Spec2->getTemplateArgs().get(I)))
996 // If one is a class template specialization and the other is not, these
997 // structures are different.
998 else if (Spec1 || Spec2)
1001 // Compare the definitions of these two records. If either or both are
1002 // incomplete, we assume that they are equivalent.
1003 D1 = D1->getDefinition();
1004 D2 = D2->getDefinition();
1008 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1009 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1010 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1011 if (Context.Complain) {
1012 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1013 << Context.C2.getTypeDeclType(D2);
1014 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1015 << D2CXX->getNumBases();
1016 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1017 << D1CXX->getNumBases();
1022 // Check the base classes.
1023 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1024 BaseEnd1 = D1CXX->bases_end(),
1025 Base2 = D2CXX->bases_begin();
1028 if (!IsStructurallyEquivalent(Context,
1029 Base1->getType(), Base2->getType())) {
1030 if (Context.Complain) {
1031 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1032 << Context.C2.getTypeDeclType(D2);
1033 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1035 << Base2->getSourceRange();
1036 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1038 << Base1->getSourceRange();
1043 // Check virtual vs. non-virtual inheritance mismatch.
1044 if (Base1->isVirtual() != Base2->isVirtual()) {
1045 if (Context.Complain) {
1046 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1047 << Context.C2.getTypeDeclType(D2);
1048 Context.Diag2(Base2->getLocStart(),
1049 diag::note_odr_virtual_base)
1050 << Base2->isVirtual() << Base2->getSourceRange();
1051 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1052 << Base1->isVirtual()
1053 << Base1->getSourceRange();
1058 } else if (D1CXX->getNumBases() > 0) {
1059 if (Context.Complain) {
1060 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1061 << Context.C2.getTypeDeclType(D2);
1062 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1063 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1065 << Base1->getSourceRange();
1066 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1072 // Check the fields for consistency.
1073 RecordDecl::field_iterator Field2 = D2->field_begin(),
1074 Field2End = D2->field_end();
1075 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1076 Field1End = D1->field_end();
1077 Field1 != Field1End;
1078 ++Field1, ++Field2) {
1079 if (Field2 == Field2End) {
1080 if (Context.Complain) {
1081 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1082 << Context.C2.getTypeDeclType(D2);
1083 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1084 << Field1->getDeclName() << Field1->getType();
1085 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1090 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1094 if (Field2 != Field2End) {
1095 if (Context.Complain) {
1096 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1097 << Context.C2.getTypeDeclType(D2);
1098 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1099 << Field2->getDeclName() << Field2->getType();
1100 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1108 /// \brief Determine structural equivalence of two enums.
1109 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1110 EnumDecl *D1, EnumDecl *D2) {
1111 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1112 EC2End = D2->enumerator_end();
1113 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1114 EC1End = D1->enumerator_end();
1115 EC1 != EC1End; ++EC1, ++EC2) {
1116 if (EC2 == EC2End) {
1117 if (Context.Complain) {
1118 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1119 << Context.C2.getTypeDeclType(D2);
1120 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1121 << EC1->getDeclName()
1122 << EC1->getInitVal().toString(10);
1123 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1128 llvm::APSInt Val1 = EC1->getInitVal();
1129 llvm::APSInt Val2 = EC2->getInitVal();
1130 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1131 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1132 if (Context.Complain) {
1133 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1134 << Context.C2.getTypeDeclType(D2);
1135 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1136 << EC2->getDeclName()
1137 << EC2->getInitVal().toString(10);
1138 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1139 << EC1->getDeclName()
1140 << EC1->getInitVal().toString(10);
1146 if (EC2 != EC2End) {
1147 if (Context.Complain) {
1148 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1149 << Context.C2.getTypeDeclType(D2);
1150 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1151 << EC2->getDeclName()
1152 << EC2->getInitVal().toString(10);
1153 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1161 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1162 TemplateParameterList *Params1,
1163 TemplateParameterList *Params2) {
1164 if (Params1->size() != Params2->size()) {
1165 if (Context.Complain) {
1166 Context.Diag2(Params2->getTemplateLoc(),
1167 diag::err_odr_different_num_template_parameters)
1168 << Params1->size() << Params2->size();
1169 Context.Diag1(Params1->getTemplateLoc(),
1170 diag::note_odr_template_parameter_list);
1175 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1176 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1177 if (Context.Complain) {
1178 Context.Diag2(Params2->getParam(I)->getLocation(),
1179 diag::err_odr_different_template_parameter_kind);
1180 Context.Diag1(Params1->getParam(I)->getLocation(),
1181 diag::note_odr_template_parameter_here);
1186 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1187 Params2->getParam(I))) {
1196 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1197 TemplateTypeParmDecl *D1,
1198 TemplateTypeParmDecl *D2) {
1199 if (D1->isParameterPack() != D2->isParameterPack()) {
1200 if (Context.Complain) {
1201 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1202 << D2->isParameterPack();
1203 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1204 << D1->isParameterPack();
1212 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1213 NonTypeTemplateParmDecl *D1,
1214 NonTypeTemplateParmDecl *D2) {
1215 if (D1->isParameterPack() != D2->isParameterPack()) {
1216 if (Context.Complain) {
1217 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1218 << D2->isParameterPack();
1219 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1220 << D1->isParameterPack();
1226 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1227 if (Context.Complain) {
1228 Context.Diag2(D2->getLocation(),
1229 diag::err_odr_non_type_parameter_type_inconsistent)
1230 << D2->getType() << D1->getType();
1231 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1240 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1241 TemplateTemplateParmDecl *D1,
1242 TemplateTemplateParmDecl *D2) {
1243 if (D1->isParameterPack() != D2->isParameterPack()) {
1244 if (Context.Complain) {
1245 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1246 << D2->isParameterPack();
1247 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1248 << D1->isParameterPack();
1253 // Check template parameter lists.
1254 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1255 D2->getTemplateParameters());
1258 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1259 ClassTemplateDecl *D1,
1260 ClassTemplateDecl *D2) {
1261 // Check template parameters.
1262 if (!IsStructurallyEquivalent(Context,
1263 D1->getTemplateParameters(),
1264 D2->getTemplateParameters()))
1267 // Check the templated declaration.
1268 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1269 D2->getTemplatedDecl());
1272 /// \brief Determine structural equivalence of two declarations.
1273 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1274 Decl *D1, Decl *D2) {
1275 // FIXME: Check for known structural equivalences via a callback of some sort.
1277 // Check whether we already know that these two declarations are not
1278 // structurally equivalent.
1279 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1280 D2->getCanonicalDecl())))
1283 // Determine whether we've already produced a tentative equivalence for D1.
1284 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1286 return EquivToD1 == D2->getCanonicalDecl();
1288 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1289 EquivToD1 = D2->getCanonicalDecl();
1290 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1294 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1296 if (!::IsStructurallyEquivalent(*this, D1, D2))
1302 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1304 if (!::IsStructurallyEquivalent(*this, T1, T2))
1310 bool StructuralEquivalenceContext::Finish() {
1311 while (!DeclsToCheck.empty()) {
1312 // Check the next declaration.
1313 Decl *D1 = DeclsToCheck.front();
1314 DeclsToCheck.pop_front();
1316 Decl *D2 = TentativeEquivalences[D1];
1317 assert(D2 && "Unrecorded tentative equivalence?");
1319 bool Equivalent = true;
1321 // FIXME: Switch on all declaration kinds. For now, we're just going to
1322 // check the obvious ones.
1323 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1324 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1325 // Check for equivalent structure names.
1326 IdentifierInfo *Name1 = Record1->getIdentifier();
1327 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1328 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1329 IdentifierInfo *Name2 = Record2->getIdentifier();
1330 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1331 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1332 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1333 !::IsStructurallyEquivalent(*this, Record1, Record2))
1336 // Record/non-record mismatch.
1339 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1340 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1341 // Check for equivalent enum names.
1342 IdentifierInfo *Name1 = Enum1->getIdentifier();
1343 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1344 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1345 IdentifierInfo *Name2 = Enum2->getIdentifier();
1346 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1347 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1348 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1349 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1352 // Enum/non-enum mismatch
1355 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1356 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1357 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1358 Typedef2->getIdentifier()) ||
1359 !::IsStructurallyEquivalent(*this,
1360 Typedef1->getUnderlyingType(),
1361 Typedef2->getUnderlyingType()))
1364 // Typedef/non-typedef mismatch.
1367 } else if (ClassTemplateDecl *ClassTemplate1
1368 = dyn_cast<ClassTemplateDecl>(D1)) {
1369 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1370 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1371 ClassTemplate2->getIdentifier()) ||
1372 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1375 // Class template/non-class-template mismatch.
1378 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1379 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1380 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1386 } else if (NonTypeTemplateParmDecl *NTTP1
1387 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1388 if (NonTypeTemplateParmDecl *NTTP2
1389 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1390 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1396 } else if (TemplateTemplateParmDecl *TTP1
1397 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1398 if (TemplateTemplateParmDecl *TTP2
1399 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1400 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1409 // Note that these two declarations are not equivalent (and we already
1411 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1412 D2->getCanonicalDecl()));
1415 // FIXME: Check other declaration kinds!
1421 //----------------------------------------------------------------------------
1423 //----------------------------------------------------------------------------
1425 QualType ASTNodeImporter::VisitType(const Type *T) {
1426 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1427 << T->getTypeClassName();
1431 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1432 switch (T->getKind()) {
1433 #define SHARED_SINGLETON_TYPE(Expansion)
1434 #define BUILTIN_TYPE(Id, SingletonId) \
1435 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1436 #include "clang/AST/BuiltinTypes.def"
1438 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1439 // context supports C++.
1441 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1442 // context supports ObjC.
1444 case BuiltinType::Char_U:
1445 // The context we're importing from has an unsigned 'char'. If we're
1446 // importing into a context with a signed 'char', translate to
1447 // 'unsigned char' instead.
1448 if (Importer.getToContext().getLangOpts().CharIsSigned)
1449 return Importer.getToContext().UnsignedCharTy;
1451 return Importer.getToContext().CharTy;
1453 case BuiltinType::Char_S:
1454 // The context we're importing from has an unsigned 'char'. If we're
1455 // importing into a context with a signed 'char', translate to
1456 // 'unsigned char' instead.
1457 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1458 return Importer.getToContext().SignedCharTy;
1460 return Importer.getToContext().CharTy;
1462 case BuiltinType::WChar_S:
1463 case BuiltinType::WChar_U:
1464 // FIXME: If not in C++, shall we translate to the C equivalent of
1466 return Importer.getToContext().WCharTy;
1469 llvm_unreachable("Invalid BuiltinType Kind!");
1472 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1473 QualType ToElementType = Importer.Import(T->getElementType());
1474 if (ToElementType.isNull())
1477 return Importer.getToContext().getComplexType(ToElementType);
1480 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1481 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1482 if (ToPointeeType.isNull())
1485 return Importer.getToContext().getPointerType(ToPointeeType);
1488 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1489 // FIXME: Check for blocks support in "to" context.
1490 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1491 if (ToPointeeType.isNull())
1494 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1498 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1499 // FIXME: Check for C++ support in "to" context.
1500 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1501 if (ToPointeeType.isNull())
1504 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1508 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1509 // FIXME: Check for C++0x support in "to" context.
1510 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1511 if (ToPointeeType.isNull())
1514 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1517 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1518 // FIXME: Check for C++ support in "to" context.
1519 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1520 if (ToPointeeType.isNull())
1523 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1524 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1525 ClassType.getTypePtr());
1528 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1529 QualType ToElementType = Importer.Import(T->getElementType());
1530 if (ToElementType.isNull())
1533 return Importer.getToContext().getConstantArrayType(ToElementType,
1535 T->getSizeModifier(),
1536 T->getIndexTypeCVRQualifiers());
1540 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1541 QualType ToElementType = Importer.Import(T->getElementType());
1542 if (ToElementType.isNull())
1545 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1546 T->getSizeModifier(),
1547 T->getIndexTypeCVRQualifiers());
1550 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1551 QualType ToElementType = Importer.Import(T->getElementType());
1552 if (ToElementType.isNull())
1555 Expr *Size = Importer.Import(T->getSizeExpr());
1559 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1560 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1561 T->getSizeModifier(),
1562 T->getIndexTypeCVRQualifiers(),
1566 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1567 QualType ToElementType = Importer.Import(T->getElementType());
1568 if (ToElementType.isNull())
1571 return Importer.getToContext().getVectorType(ToElementType,
1572 T->getNumElements(),
1573 T->getVectorKind());
1576 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1577 QualType ToElementType = Importer.Import(T->getElementType());
1578 if (ToElementType.isNull())
1581 return Importer.getToContext().getExtVectorType(ToElementType,
1582 T->getNumElements());
1586 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1587 // FIXME: What happens if we're importing a function without a prototype
1588 // into C++? Should we make it variadic?
1589 QualType ToResultType = Importer.Import(T->getResultType());
1590 if (ToResultType.isNull())
1593 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1597 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1598 QualType ToResultType = Importer.Import(T->getResultType());
1599 if (ToResultType.isNull())
1602 // Import argument types
1603 SmallVector<QualType, 4> ArgTypes;
1604 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
1605 AEnd = T->arg_type_end();
1607 QualType ArgType = Importer.Import(*A);
1608 if (ArgType.isNull())
1610 ArgTypes.push_back(ArgType);
1613 // Import exception types
1614 SmallVector<QualType, 4> ExceptionTypes;
1615 for (FunctionProtoType::exception_iterator E = T->exception_begin(),
1616 EEnd = T->exception_end();
1618 QualType ExceptionType = Importer.Import(*E);
1619 if (ExceptionType.isNull())
1621 ExceptionTypes.push_back(ExceptionType);
1624 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1625 FunctionProtoType::ExtProtoInfo ToEPI;
1627 ToEPI.ExtInfo = FromEPI.ExtInfo;
1628 ToEPI.Variadic = FromEPI.Variadic;
1629 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1630 ToEPI.TypeQuals = FromEPI.TypeQuals;
1631 ToEPI.RefQualifier = FromEPI.RefQualifier;
1632 ToEPI.NumExceptions = ExceptionTypes.size();
1633 ToEPI.Exceptions = ExceptionTypes.data();
1634 ToEPI.ConsumedArguments = FromEPI.ConsumedArguments;
1635 ToEPI.ExceptionSpecType = FromEPI.ExceptionSpecType;
1636 ToEPI.NoexceptExpr = Importer.Import(FromEPI.NoexceptExpr);
1637 ToEPI.ExceptionSpecDecl = cast_or_null<FunctionDecl>(
1638 Importer.Import(FromEPI.ExceptionSpecDecl));
1639 ToEPI.ExceptionSpecTemplate = cast_or_null<FunctionDecl>(
1640 Importer.Import(FromEPI.ExceptionSpecTemplate));
1642 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1645 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1646 QualType ToInnerType = Importer.Import(T->getInnerType());
1647 if (ToInnerType.isNull())
1650 return Importer.getToContext().getParenType(ToInnerType);
1653 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1654 TypedefNameDecl *ToDecl
1655 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1659 return Importer.getToContext().getTypeDeclType(ToDecl);
1662 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1663 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1667 return Importer.getToContext().getTypeOfExprType(ToExpr);
1670 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1671 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1672 if (ToUnderlyingType.isNull())
1675 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1678 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1679 // FIXME: Make sure that the "to" context supports C++0x!
1680 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1684 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1685 if (UnderlyingType.isNull())
1688 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1691 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1692 QualType ToBaseType = Importer.Import(T->getBaseType());
1693 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1694 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1697 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1702 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1703 // FIXME: Make sure that the "to" context supports C++11!
1704 QualType FromDeduced = T->getDeducedType();
1706 if (!FromDeduced.isNull()) {
1707 ToDeduced = Importer.Import(FromDeduced);
1708 if (ToDeduced.isNull())
1712 return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto(),
1713 /*IsDependent*/false);
1716 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1718 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1722 return Importer.getToContext().getTagDeclType(ToDecl);
1725 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1727 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1731 return Importer.getToContext().getTagDeclType(ToDecl);
1734 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1735 const TemplateSpecializationType *T) {
1736 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1737 if (ToTemplate.isNull())
1740 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1741 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1744 QualType ToCanonType;
1745 if (!QualType(T, 0).isCanonical()) {
1746 QualType FromCanonType
1747 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1748 ToCanonType =Importer.Import(FromCanonType);
1749 if (ToCanonType.isNull())
1752 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1753 ToTemplateArgs.data(),
1754 ToTemplateArgs.size(),
1758 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1759 NestedNameSpecifier *ToQualifier = 0;
1760 // Note: the qualifier in an ElaboratedType is optional.
1761 if (T->getQualifier()) {
1762 ToQualifier = Importer.Import(T->getQualifier());
1767 QualType ToNamedType = Importer.Import(T->getNamedType());
1768 if (ToNamedType.isNull())
1771 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1772 ToQualifier, ToNamedType);
1775 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1776 ObjCInterfaceDecl *Class
1777 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1781 return Importer.getToContext().getObjCInterfaceType(Class);
1784 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1785 QualType ToBaseType = Importer.Import(T->getBaseType());
1786 if (ToBaseType.isNull())
1789 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1790 for (ObjCObjectType::qual_iterator P = T->qual_begin(),
1791 PEnd = T->qual_end();
1793 ObjCProtocolDecl *Protocol
1794 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1797 Protocols.push_back(Protocol);
1800 return Importer.getToContext().getObjCObjectType(ToBaseType,
1806 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1807 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1808 if (ToPointeeType.isNull())
1811 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1814 //----------------------------------------------------------------------------
1815 // Import Declarations
1816 //----------------------------------------------------------------------------
1817 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1818 DeclContext *&LexicalDC,
1819 DeclarationName &Name,
1820 SourceLocation &Loc) {
1821 // Import the context of this declaration.
1822 DC = Importer.ImportContext(D->getDeclContext());
1827 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1828 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1833 // Import the name of this declaration.
1834 Name = Importer.Import(D->getDeclName());
1835 if (D->getDeclName() && !Name)
1838 // Import the location of this declaration.
1839 Loc = Importer.Import(D->getLocation());
1843 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1848 ToD = Importer.Import(FromD);
1853 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1854 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1855 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1856 ImportDefinition(FromRecord, ToRecord);
1862 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1863 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1864 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1865 ImportDefinition(FromEnum, ToEnum);
1873 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1874 DeclarationNameInfo& To) {
1875 // NOTE: To.Name and To.Loc are already imported.
1876 // We only have to import To.LocInfo.
1877 switch (To.getName().getNameKind()) {
1878 case DeclarationName::Identifier:
1879 case DeclarationName::ObjCZeroArgSelector:
1880 case DeclarationName::ObjCOneArgSelector:
1881 case DeclarationName::ObjCMultiArgSelector:
1882 case DeclarationName::CXXUsingDirective:
1885 case DeclarationName::CXXOperatorName: {
1886 SourceRange Range = From.getCXXOperatorNameRange();
1887 To.setCXXOperatorNameRange(Importer.Import(Range));
1890 case DeclarationName::CXXLiteralOperatorName: {
1891 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1892 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1895 case DeclarationName::CXXConstructorName:
1896 case DeclarationName::CXXDestructorName:
1897 case DeclarationName::CXXConversionFunctionName: {
1898 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1899 To.setNamedTypeInfo(Importer.Import(FromTInfo));
1903 llvm_unreachable("Unknown name kind.");
1906 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1907 if (Importer.isMinimalImport() && !ForceImport) {
1908 Importer.ImportContext(FromDC);
1912 for (DeclContext::decl_iterator From = FromDC->decls_begin(),
1913 FromEnd = FromDC->decls_end();
1916 Importer.Import(*From);
1919 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1920 ImportDefinitionKind Kind) {
1921 if (To->getDefinition() || To->isBeingDefined()) {
1922 if (Kind == IDK_Everything)
1923 ImportDeclContext(From, /*ForceImport=*/true);
1928 To->startDefinition();
1930 // Add base classes.
1931 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1932 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1934 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1935 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1936 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1937 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1938 ToData.Aggregate = FromData.Aggregate;
1939 ToData.PlainOldData = FromData.PlainOldData;
1940 ToData.Empty = FromData.Empty;
1941 ToData.Polymorphic = FromData.Polymorphic;
1942 ToData.Abstract = FromData.Abstract;
1943 ToData.IsStandardLayout = FromData.IsStandardLayout;
1944 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
1945 ToData.HasPrivateFields = FromData.HasPrivateFields;
1946 ToData.HasProtectedFields = FromData.HasProtectedFields;
1947 ToData.HasPublicFields = FromData.HasPublicFields;
1948 ToData.HasMutableFields = FromData.HasMutableFields;
1949 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1950 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1951 ToData.HasUninitializedReferenceMember
1952 = FromData.HasUninitializedReferenceMember;
1953 ToData.NeedOverloadResolutionForMoveConstructor
1954 = FromData.NeedOverloadResolutionForMoveConstructor;
1955 ToData.NeedOverloadResolutionForMoveAssignment
1956 = FromData.NeedOverloadResolutionForMoveAssignment;
1957 ToData.NeedOverloadResolutionForDestructor
1958 = FromData.NeedOverloadResolutionForDestructor;
1959 ToData.DefaultedMoveConstructorIsDeleted
1960 = FromData.DefaultedMoveConstructorIsDeleted;
1961 ToData.DefaultedMoveAssignmentIsDeleted
1962 = FromData.DefaultedMoveAssignmentIsDeleted;
1963 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1964 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1965 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1966 ToData.HasConstexprNonCopyMoveConstructor
1967 = FromData.HasConstexprNonCopyMoveConstructor;
1968 ToData.DefaultedDefaultConstructorIsConstexpr
1969 = FromData.DefaultedDefaultConstructorIsConstexpr;
1970 ToData.HasConstexprDefaultConstructor
1971 = FromData.HasConstexprDefaultConstructor;
1972 ToData.HasNonLiteralTypeFieldsOrBases
1973 = FromData.HasNonLiteralTypeFieldsOrBases;
1974 // ComputedVisibleConversions not imported.
1975 ToData.UserProvidedDefaultConstructor
1976 = FromData.UserProvidedDefaultConstructor;
1977 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1978 ToData.ImplicitCopyConstructorHasConstParam
1979 = FromData.ImplicitCopyConstructorHasConstParam;
1980 ToData.ImplicitCopyAssignmentHasConstParam
1981 = FromData.ImplicitCopyAssignmentHasConstParam;
1982 ToData.HasDeclaredCopyConstructorWithConstParam
1983 = FromData.HasDeclaredCopyConstructorWithConstParam;
1984 ToData.HasDeclaredCopyAssignmentWithConstParam
1985 = FromData.HasDeclaredCopyAssignmentWithConstParam;
1986 ToData.IsLambda = FromData.IsLambda;
1988 SmallVector<CXXBaseSpecifier *, 4> Bases;
1989 for (CXXRecordDecl::base_class_iterator
1990 Base1 = FromCXX->bases_begin(),
1991 FromBaseEnd = FromCXX->bases_end();
1992 Base1 != FromBaseEnd;
1994 QualType T = Importer.Import(Base1->getType());
1998 SourceLocation EllipsisLoc;
1999 if (Base1->isPackExpansion())
2000 EllipsisLoc = Importer.Import(Base1->getEllipsisLoc());
2002 // Ensure that we have a definition for the base.
2003 ImportDefinitionIfNeeded(Base1->getType()->getAsCXXRecordDecl());
2006 new (Importer.getToContext())
2007 CXXBaseSpecifier(Importer.Import(Base1->getSourceRange()),
2009 Base1->isBaseOfClass(),
2010 Base1->getAccessSpecifierAsWritten(),
2011 Importer.Import(Base1->getTypeSourceInfo()),
2015 ToCXX->setBases(Bases.data(), Bases.size());
2018 if (shouldForceImportDeclContext(Kind))
2019 ImportDeclContext(From, /*ForceImport=*/true);
2021 To->completeDefinition();
2025 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2026 ImportDefinitionKind Kind) {
2027 if (To->getDefinition())
2030 // FIXME: Can we really import any initializer? Alternatively, we could force
2031 // ourselves to import every declaration of a variable and then only use
2033 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2035 // FIXME: Other bits to merge?
2040 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2041 ImportDefinitionKind Kind) {
2042 if (To->getDefinition() || To->isBeingDefined()) {
2043 if (Kind == IDK_Everything)
2044 ImportDeclContext(From, /*ForceImport=*/true);
2048 To->startDefinition();
2050 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2054 QualType ToPromotionType = Importer.Import(From->getPromotionType());
2055 if (ToPromotionType.isNull())
2058 if (shouldForceImportDeclContext(Kind))
2059 ImportDeclContext(From, /*ForceImport=*/true);
2061 // FIXME: we might need to merge the number of positive or negative bits
2062 // if the enumerator lists don't match.
2063 To->completeDefinition(T, ToPromotionType,
2064 From->getNumPositiveBits(),
2065 From->getNumNegativeBits());
2069 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2070 TemplateParameterList *Params) {
2071 SmallVector<NamedDecl *, 4> ToParams;
2072 ToParams.reserve(Params->size());
2073 for (TemplateParameterList::iterator P = Params->begin(),
2074 PEnd = Params->end();
2076 Decl *To = Importer.Import(*P);
2080 ToParams.push_back(cast<NamedDecl>(To));
2083 return TemplateParameterList::Create(Importer.getToContext(),
2084 Importer.Import(Params->getTemplateLoc()),
2085 Importer.Import(Params->getLAngleLoc()),
2086 ToParams.data(), ToParams.size(),
2087 Importer.Import(Params->getRAngleLoc()));
2091 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2092 switch (From.getKind()) {
2093 case TemplateArgument::Null:
2094 return TemplateArgument();
2096 case TemplateArgument::Type: {
2097 QualType ToType = Importer.Import(From.getAsType());
2098 if (ToType.isNull())
2099 return TemplateArgument();
2100 return TemplateArgument(ToType);
2103 case TemplateArgument::Integral: {
2104 QualType ToType = Importer.Import(From.getIntegralType());
2105 if (ToType.isNull())
2106 return TemplateArgument();
2107 return TemplateArgument(From, ToType);
2110 case TemplateArgument::Declaration: {
2111 ValueDecl *FromD = From.getAsDecl();
2112 if (ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(FromD)))
2113 return TemplateArgument(To, From.isDeclForReferenceParam());
2114 return TemplateArgument();
2117 case TemplateArgument::NullPtr: {
2118 QualType ToType = Importer.Import(From.getNullPtrType());
2119 if (ToType.isNull())
2120 return TemplateArgument();
2121 return TemplateArgument(ToType, /*isNullPtr*/true);
2124 case TemplateArgument::Template: {
2125 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2126 if (ToTemplate.isNull())
2127 return TemplateArgument();
2129 return TemplateArgument(ToTemplate);
2132 case TemplateArgument::TemplateExpansion: {
2133 TemplateName ToTemplate
2134 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2135 if (ToTemplate.isNull())
2136 return TemplateArgument();
2138 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2141 case TemplateArgument::Expression:
2142 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2143 return TemplateArgument(ToExpr);
2144 return TemplateArgument();
2146 case TemplateArgument::Pack: {
2147 SmallVector<TemplateArgument, 2> ToPack;
2148 ToPack.reserve(From.pack_size());
2149 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2150 return TemplateArgument();
2152 TemplateArgument *ToArgs
2153 = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
2154 std::copy(ToPack.begin(), ToPack.end(), ToArgs);
2155 return TemplateArgument(ToArgs, ToPack.size());
2159 llvm_unreachable("Invalid template argument kind");
2162 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2163 unsigned NumFromArgs,
2164 SmallVectorImpl<TemplateArgument> &ToArgs) {
2165 for (unsigned I = 0; I != NumFromArgs; ++I) {
2166 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2167 if (To.isNull() && !FromArgs[I].isNull())
2170 ToArgs.push_back(To);
2176 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2177 RecordDecl *ToRecord, bool Complain) {
2178 // Eliminate a potential failure point where we attempt to re-import
2179 // something we're trying to import while completing ToRecord.
2180 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2182 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2184 ToRecord = ToOriginRecord;
2187 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2188 ToRecord->getASTContext(),
2189 Importer.getNonEquivalentDecls(),
2191 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2194 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2196 StructuralEquivalenceContext Ctx(
2197 Importer.getFromContext(), Importer.getToContext(),
2198 Importer.getNonEquivalentDecls(), false, Complain);
2199 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2202 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2203 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2204 Importer.getToContext(),
2205 Importer.getNonEquivalentDecls());
2206 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2209 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2210 EnumConstantDecl *ToEC)
2212 const llvm::APSInt &FromVal = FromEC->getInitVal();
2213 const llvm::APSInt &ToVal = ToEC->getInitVal();
2215 return FromVal.isSigned() == ToVal.isSigned() &&
2216 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2220 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2221 ClassTemplateDecl *To) {
2222 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2223 Importer.getToContext(),
2224 Importer.getNonEquivalentDecls());
2225 return Ctx.IsStructurallyEquivalent(From, To);
2228 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2229 VarTemplateDecl *To) {
2230 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2231 Importer.getToContext(),
2232 Importer.getNonEquivalentDecls());
2233 return Ctx.IsStructurallyEquivalent(From, To);
2236 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2237 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2238 << D->getDeclKindName();
2242 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2243 TranslationUnitDecl *ToD =
2244 Importer.getToContext().getTranslationUnitDecl();
2246 Importer.Imported(D, ToD);
2251 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2252 // Import the major distinguishing characteristics of this namespace.
2253 DeclContext *DC, *LexicalDC;
2254 DeclarationName Name;
2256 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2259 NamespaceDecl *MergeWithNamespace = 0;
2261 // This is an anonymous namespace. Adopt an existing anonymous
2262 // namespace if we can.
2263 // FIXME: Not testable.
2264 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2265 MergeWithNamespace = TU->getAnonymousNamespace();
2267 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2269 SmallVector<NamedDecl *, 4> ConflictingDecls;
2270 SmallVector<NamedDecl *, 2> FoundDecls;
2271 DC->localUncachedLookup(Name, FoundDecls);
2272 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2273 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2276 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2277 MergeWithNamespace = FoundNS;
2278 ConflictingDecls.clear();
2282 ConflictingDecls.push_back(FoundDecls[I]);
2285 if (!ConflictingDecls.empty()) {
2286 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2287 ConflictingDecls.data(),
2288 ConflictingDecls.size());
2292 // Create the "to" namespace, if needed.
2293 NamespaceDecl *ToNamespace = MergeWithNamespace;
2295 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2297 Importer.Import(D->getLocStart()),
2298 Loc, Name.getAsIdentifierInfo(),
2300 ToNamespace->setLexicalDeclContext(LexicalDC);
2301 LexicalDC->addDeclInternal(ToNamespace);
2303 // If this is an anonymous namespace, register it as the anonymous
2304 // namespace within its context.
2306 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2307 TU->setAnonymousNamespace(ToNamespace);
2309 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2312 Importer.Imported(D, ToNamespace);
2314 ImportDeclContext(D);
2319 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2320 // Import the major distinguishing characteristics of this typedef.
2321 DeclContext *DC, *LexicalDC;
2322 DeclarationName Name;
2324 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2327 // If this typedef is not in block scope, determine whether we've
2328 // seen a typedef with the same name (that we can merge with) or any
2329 // other entity by that name (which name lookup could conflict with).
2330 if (!DC->isFunctionOrMethod()) {
2331 SmallVector<NamedDecl *, 4> ConflictingDecls;
2332 unsigned IDNS = Decl::IDNS_Ordinary;
2333 SmallVector<NamedDecl *, 2> FoundDecls;
2334 DC->localUncachedLookup(Name, FoundDecls);
2335 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2336 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2338 if (TypedefNameDecl *FoundTypedef =
2339 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2340 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2341 FoundTypedef->getUnderlyingType()))
2342 return Importer.Imported(D, FoundTypedef);
2345 ConflictingDecls.push_back(FoundDecls[I]);
2348 if (!ConflictingDecls.empty()) {
2349 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2350 ConflictingDecls.data(),
2351 ConflictingDecls.size());
2357 // Import the underlying type of this typedef;
2358 QualType T = Importer.Import(D->getUnderlyingType());
2362 // Create the new typedef node.
2363 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2364 SourceLocation StartL = Importer.Import(D->getLocStart());
2365 TypedefNameDecl *ToTypedef;
2367 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2369 Name.getAsIdentifierInfo(),
2372 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2374 Name.getAsIdentifierInfo(),
2377 ToTypedef->setAccess(D->getAccess());
2378 ToTypedef->setLexicalDeclContext(LexicalDC);
2379 Importer.Imported(D, ToTypedef);
2380 LexicalDC->addDeclInternal(ToTypedef);
2385 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2386 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2389 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2390 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2393 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2394 // Import the major distinguishing characteristics of this enum.
2395 DeclContext *DC, *LexicalDC;
2396 DeclarationName Name;
2398 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2401 // Figure out what enum name we're looking for.
2402 unsigned IDNS = Decl::IDNS_Tag;
2403 DeclarationName SearchName = Name;
2404 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2405 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2406 IDNS = Decl::IDNS_Ordinary;
2407 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2408 IDNS |= Decl::IDNS_Ordinary;
2410 // We may already have an enum of the same name; try to find and match it.
2411 if (!DC->isFunctionOrMethod() && SearchName) {
2412 SmallVector<NamedDecl *, 4> ConflictingDecls;
2413 SmallVector<NamedDecl *, 2> FoundDecls;
2414 DC->localUncachedLookup(SearchName, FoundDecls);
2415 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2416 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2419 Decl *Found = FoundDecls[I];
2420 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2421 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2422 Found = Tag->getDecl();
2425 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2426 if (IsStructuralMatch(D, FoundEnum))
2427 return Importer.Imported(D, FoundEnum);
2430 ConflictingDecls.push_back(FoundDecls[I]);
2433 if (!ConflictingDecls.empty()) {
2434 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2435 ConflictingDecls.data(),
2436 ConflictingDecls.size());
2440 // Create the enum declaration.
2441 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2442 Importer.Import(D->getLocStart()),
2443 Loc, Name.getAsIdentifierInfo(), 0,
2444 D->isScoped(), D->isScopedUsingClassTag(),
2446 // Import the qualifier, if any.
2447 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2448 D2->setAccess(D->getAccess());
2449 D2->setLexicalDeclContext(LexicalDC);
2450 Importer.Imported(D, D2);
2451 LexicalDC->addDeclInternal(D2);
2453 // Import the integer type.
2454 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2455 if (ToIntegerType.isNull())
2457 D2->setIntegerType(ToIntegerType);
2459 // Import the definition
2460 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2466 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2467 // If this record has a definition in the translation unit we're coming from,
2468 // but this particular declaration is not that definition, import the
2469 // definition and map to that.
2470 TagDecl *Definition = D->getDefinition();
2471 if (Definition && Definition != D) {
2472 Decl *ImportedDef = Importer.Import(Definition);
2476 return Importer.Imported(D, ImportedDef);
2479 // Import the major distinguishing characteristics of this record.
2480 DeclContext *DC, *LexicalDC;
2481 DeclarationName Name;
2483 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2486 // Figure out what structure name we're looking for.
2487 unsigned IDNS = Decl::IDNS_Tag;
2488 DeclarationName SearchName = Name;
2489 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2490 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2491 IDNS = Decl::IDNS_Ordinary;
2492 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2493 IDNS |= Decl::IDNS_Ordinary;
2495 // We may already have a record of the same name; try to find and match it.
2496 RecordDecl *AdoptDecl = 0;
2497 if (!DC->isFunctionOrMethod()) {
2498 SmallVector<NamedDecl *, 4> ConflictingDecls;
2499 SmallVector<NamedDecl *, 2> FoundDecls;
2500 DC->localUncachedLookup(SearchName, FoundDecls);
2501 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2502 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2505 Decl *Found = FoundDecls[I];
2506 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2507 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2508 Found = Tag->getDecl();
2511 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2512 if (D->isAnonymousStructOrUnion() &&
2513 FoundRecord->isAnonymousStructOrUnion()) {
2514 // If both anonymous structs/unions are in a record context, make sure
2515 // they occur in the same location in the context records.
2516 if (Optional<unsigned> Index1
2517 = findAnonymousStructOrUnionIndex(D)) {
2518 if (Optional<unsigned> Index2 =
2519 findAnonymousStructOrUnionIndex(FoundRecord)) {
2520 if (*Index1 != *Index2)
2526 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2527 if ((SearchName && !D->isCompleteDefinition())
2528 || (D->isCompleteDefinition() &&
2529 D->isAnonymousStructOrUnion()
2530 == FoundDef->isAnonymousStructOrUnion() &&
2531 IsStructuralMatch(D, FoundDef))) {
2532 // The record types structurally match, or the "from" translation
2533 // unit only had a forward declaration anyway; call it the same
2535 // FIXME: For C++, we should also merge methods here.
2536 return Importer.Imported(D, FoundDef);
2538 } else if (!D->isCompleteDefinition()) {
2539 // We have a forward declaration of this type, so adopt that forward
2540 // declaration rather than building a new one.
2541 AdoptDecl = FoundRecord;
2543 } else if (!SearchName) {
2548 ConflictingDecls.push_back(FoundDecls[I]);
2551 if (!ConflictingDecls.empty() && SearchName) {
2552 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2553 ConflictingDecls.data(),
2554 ConflictingDecls.size());
2558 // Create the record declaration.
2559 RecordDecl *D2 = AdoptDecl;
2560 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2562 if (isa<CXXRecordDecl>(D)) {
2563 CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2566 Name.getAsIdentifierInfo());
2568 D2->setAccess(D->getAccess());
2570 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2571 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2574 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2575 D2->setLexicalDeclContext(LexicalDC);
2576 LexicalDC->addDeclInternal(D2);
2577 if (D->isAnonymousStructOrUnion())
2578 D2->setAnonymousStructOrUnion(true);
2581 Importer.Imported(D, D2);
2583 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2589 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2590 // Import the major distinguishing characteristics of this enumerator.
2591 DeclContext *DC, *LexicalDC;
2592 DeclarationName Name;
2594 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2597 QualType T = Importer.Import(D->getType());
2601 // Determine whether there are any other declarations with the same name and
2602 // in the same context.
2603 if (!LexicalDC->isFunctionOrMethod()) {
2604 SmallVector<NamedDecl *, 4> ConflictingDecls;
2605 unsigned IDNS = Decl::IDNS_Ordinary;
2606 SmallVector<NamedDecl *, 2> FoundDecls;
2607 DC->localUncachedLookup(Name, FoundDecls);
2608 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2609 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2612 if (EnumConstantDecl *FoundEnumConstant
2613 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2614 if (IsStructuralMatch(D, FoundEnumConstant))
2615 return Importer.Imported(D, FoundEnumConstant);
2618 ConflictingDecls.push_back(FoundDecls[I]);
2621 if (!ConflictingDecls.empty()) {
2622 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2623 ConflictingDecls.data(),
2624 ConflictingDecls.size());
2630 Expr *Init = Importer.Import(D->getInitExpr());
2631 if (D->getInitExpr() && !Init)
2634 EnumConstantDecl *ToEnumerator
2635 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2636 Name.getAsIdentifierInfo(), T,
2637 Init, D->getInitVal());
2638 ToEnumerator->setAccess(D->getAccess());
2639 ToEnumerator->setLexicalDeclContext(LexicalDC);
2640 Importer.Imported(D, ToEnumerator);
2641 LexicalDC->addDeclInternal(ToEnumerator);
2642 return ToEnumerator;
2645 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2646 // Import the major distinguishing characteristics of this function.
2647 DeclContext *DC, *LexicalDC;
2648 DeclarationName Name;
2650 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2653 // Try to find a function in our own ("to") context with the same name, same
2654 // type, and in the same context as the function we're importing.
2655 if (!LexicalDC->isFunctionOrMethod()) {
2656 SmallVector<NamedDecl *, 4> ConflictingDecls;
2657 unsigned IDNS = Decl::IDNS_Ordinary;
2658 SmallVector<NamedDecl *, 2> FoundDecls;
2659 DC->localUncachedLookup(Name, FoundDecls);
2660 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2661 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2664 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2665 if (FoundFunction->hasExternalFormalLinkage() &&
2666 D->hasExternalFormalLinkage()) {
2667 if (Importer.IsStructurallyEquivalent(D->getType(),
2668 FoundFunction->getType())) {
2669 // FIXME: Actually try to merge the body and other attributes.
2670 return Importer.Imported(D, FoundFunction);
2673 // FIXME: Check for overloading more carefully, e.g., by boosting
2674 // Sema::IsOverload out to the AST library.
2676 // Function overloading is okay in C++.
2677 if (Importer.getToContext().getLangOpts().CPlusPlus)
2680 // Complain about inconsistent function types.
2681 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2682 << Name << D->getType() << FoundFunction->getType();
2683 Importer.ToDiag(FoundFunction->getLocation(),
2684 diag::note_odr_value_here)
2685 << FoundFunction->getType();
2689 ConflictingDecls.push_back(FoundDecls[I]);
2692 if (!ConflictingDecls.empty()) {
2693 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2694 ConflictingDecls.data(),
2695 ConflictingDecls.size());
2701 DeclarationNameInfo NameInfo(Name, Loc);
2702 // Import additional name location/type info.
2703 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2705 QualType FromTy = D->getType();
2706 bool usedDifferentExceptionSpec = false;
2708 if (const FunctionProtoType *
2709 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2710 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2711 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2712 // FunctionDecl that we are importing the FunctionProtoType for.
2713 // To avoid an infinite recursion when importing, create the FunctionDecl
2714 // with a simplified function type and update it afterwards.
2715 if (FromEPI.ExceptionSpecDecl || FromEPI.ExceptionSpecTemplate ||
2716 FromEPI.NoexceptExpr) {
2717 FunctionProtoType::ExtProtoInfo DefaultEPI;
2718 FromTy = Importer.getFromContext().getFunctionType(
2719 FromFPT->getResultType(), FromFPT->getArgTypes(), DefaultEPI);
2720 usedDifferentExceptionSpec = true;
2725 QualType T = Importer.Import(FromTy);
2729 // Import the function parameters.
2730 SmallVector<ParmVarDecl *, 8> Parameters;
2731 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
2733 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*P));
2737 Parameters.push_back(ToP);
2740 // Create the imported function.
2741 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2742 FunctionDecl *ToFunction = 0;
2743 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2744 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2745 cast<CXXRecordDecl>(DC),
2746 D->getInnerLocStart(),
2748 FromConstructor->isExplicit(),
2749 D->isInlineSpecified(),
2752 } else if (isa<CXXDestructorDecl>(D)) {
2753 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2754 cast<CXXRecordDecl>(DC),
2755 D->getInnerLocStart(),
2757 D->isInlineSpecified(),
2759 } else if (CXXConversionDecl *FromConversion
2760 = dyn_cast<CXXConversionDecl>(D)) {
2761 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2762 cast<CXXRecordDecl>(DC),
2763 D->getInnerLocStart(),
2765 D->isInlineSpecified(),
2766 FromConversion->isExplicit(),
2768 Importer.Import(D->getLocEnd()));
2769 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2770 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2771 cast<CXXRecordDecl>(DC),
2772 D->getInnerLocStart(),
2774 Method->getStorageClass(),
2775 Method->isInlineSpecified(),
2777 Importer.Import(D->getLocEnd()));
2779 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2780 D->getInnerLocStart(),
2781 NameInfo, T, TInfo, D->getStorageClass(),
2782 D->isInlineSpecified(),
2783 D->hasWrittenPrototype(),
2787 // Import the qualifier, if any.
2788 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2789 ToFunction->setAccess(D->getAccess());
2790 ToFunction->setLexicalDeclContext(LexicalDC);
2791 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2792 ToFunction->setTrivial(D->isTrivial());
2793 ToFunction->setPure(D->isPure());
2794 Importer.Imported(D, ToFunction);
2796 // Set the parameters.
2797 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2798 Parameters[I]->setOwningFunction(ToFunction);
2799 ToFunction->addDeclInternal(Parameters[I]);
2801 ToFunction->setParams(Parameters);
2803 if (usedDifferentExceptionSpec) {
2804 // Update FunctionProtoType::ExtProtoInfo.
2805 QualType T = Importer.Import(D->getType());
2808 ToFunction->setType(T);
2811 // FIXME: Other bits to merge?
2813 // Add this function to the lexical context.
2814 LexicalDC->addDeclInternal(ToFunction);
2819 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2820 return VisitFunctionDecl(D);
2823 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2824 return VisitCXXMethodDecl(D);
2827 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2828 return VisitCXXMethodDecl(D);
2831 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2832 return VisitCXXMethodDecl(D);
2835 static unsigned getFieldIndex(Decl *F) {
2836 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2841 for (DeclContext::decl_iterator D = Owner->noload_decls_begin(),
2842 DEnd = Owner->noload_decls_end();
2847 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2854 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2855 // Import the major distinguishing characteristics of a variable.
2856 DeclContext *DC, *LexicalDC;
2857 DeclarationName Name;
2859 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2862 // Determine whether we've already imported this field.
2863 SmallVector<NamedDecl *, 2> FoundDecls;
2864 DC->localUncachedLookup(Name, FoundDecls);
2865 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2866 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2867 // For anonymous fields, match up by index.
2868 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2871 if (Importer.IsStructurallyEquivalent(D->getType(),
2872 FoundField->getType())) {
2873 Importer.Imported(D, FoundField);
2877 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2878 << Name << D->getType() << FoundField->getType();
2879 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2880 << FoundField->getType();
2886 QualType T = Importer.Import(D->getType());
2890 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2891 Expr *BitWidth = Importer.Import(D->getBitWidth());
2892 if (!BitWidth && D->getBitWidth())
2895 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2896 Importer.Import(D->getInnerLocStart()),
2897 Loc, Name.getAsIdentifierInfo(),
2898 T, TInfo, BitWidth, D->isMutable(),
2899 D->getInClassInitStyle());
2900 ToField->setAccess(D->getAccess());
2901 ToField->setLexicalDeclContext(LexicalDC);
2902 if (ToField->hasInClassInitializer())
2903 ToField->setInClassInitializer(D->getInClassInitializer());
2904 ToField->setImplicit(D->isImplicit());
2905 Importer.Imported(D, ToField);
2906 LexicalDC->addDeclInternal(ToField);
2910 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2911 // Import the major distinguishing characteristics of a variable.
2912 DeclContext *DC, *LexicalDC;
2913 DeclarationName Name;
2915 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2918 // Determine whether we've already imported this field.
2919 SmallVector<NamedDecl *, 2> FoundDecls;
2920 DC->localUncachedLookup(Name, FoundDecls);
2921 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2922 if (IndirectFieldDecl *FoundField
2923 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2924 // For anonymous indirect fields, match up by index.
2925 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2928 if (Importer.IsStructurallyEquivalent(D->getType(),
2929 FoundField->getType(),
2931 Importer.Imported(D, FoundField);
2935 // If there are more anonymous fields to check, continue.
2936 if (!Name && I < N-1)
2939 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2940 << Name << D->getType() << FoundField->getType();
2941 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2942 << FoundField->getType();
2948 QualType T = Importer.Import(D->getType());
2952 NamedDecl **NamedChain =
2953 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2956 for (IndirectFieldDecl::chain_iterator PI = D->chain_begin(),
2957 PE = D->chain_end(); PI != PE; ++PI) {
2958 Decl* D = Importer.Import(*PI);
2961 NamedChain[i++] = cast<NamedDecl>(D);
2964 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2965 Importer.getToContext(), DC,
2966 Loc, Name.getAsIdentifierInfo(), T,
2967 NamedChain, D->getChainingSize());
2968 ToIndirectField->setAccess(D->getAccess());
2969 ToIndirectField->setLexicalDeclContext(LexicalDC);
2970 Importer.Imported(D, ToIndirectField);
2971 LexicalDC->addDeclInternal(ToIndirectField);
2972 return ToIndirectField;
2975 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2976 // Import the major distinguishing characteristics of an ivar.
2977 DeclContext *DC, *LexicalDC;
2978 DeclarationName Name;
2980 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2983 // Determine whether we've already imported this ivar
2984 SmallVector<NamedDecl *, 2> FoundDecls;
2985 DC->localUncachedLookup(Name, FoundDecls);
2986 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2987 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
2988 if (Importer.IsStructurallyEquivalent(D->getType(),
2989 FoundIvar->getType())) {
2990 Importer.Imported(D, FoundIvar);
2994 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
2995 << Name << D->getType() << FoundIvar->getType();
2996 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
2997 << FoundIvar->getType();
3003 QualType T = Importer.Import(D->getType());
3007 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3008 Expr *BitWidth = Importer.Import(D->getBitWidth());
3009 if (!BitWidth && D->getBitWidth())
3012 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3013 cast<ObjCContainerDecl>(DC),
3014 Importer.Import(D->getInnerLocStart()),
3015 Loc, Name.getAsIdentifierInfo(),
3016 T, TInfo, D->getAccessControl(),
3017 BitWidth, D->getSynthesize(),
3018 D->getBackingIvarReferencedInAccessor());
3019 ToIvar->setLexicalDeclContext(LexicalDC);
3020 Importer.Imported(D, ToIvar);
3021 LexicalDC->addDeclInternal(ToIvar);
3026 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3027 // Import the major distinguishing characteristics of a variable.
3028 DeclContext *DC, *LexicalDC;
3029 DeclarationName Name;
3031 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3034 // Try to find a variable in our own ("to") context with the same name and
3035 // in the same context as the variable we're importing.
3036 if (D->isFileVarDecl()) {
3037 VarDecl *MergeWithVar = 0;
3038 SmallVector<NamedDecl *, 4> ConflictingDecls;
3039 unsigned IDNS = Decl::IDNS_Ordinary;
3040 SmallVector<NamedDecl *, 2> FoundDecls;
3041 DC->localUncachedLookup(Name, FoundDecls);
3042 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3043 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3046 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3047 // We have found a variable that we may need to merge with. Check it.
3048 if (FoundVar->hasExternalFormalLinkage() &&
3049 D->hasExternalFormalLinkage()) {
3050 if (Importer.IsStructurallyEquivalent(D->getType(),
3051 FoundVar->getType())) {
3052 MergeWithVar = FoundVar;
3056 const ArrayType *FoundArray
3057 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3058 const ArrayType *TArray
3059 = Importer.getToContext().getAsArrayType(D->getType());
3060 if (FoundArray && TArray) {
3061 if (isa<IncompleteArrayType>(FoundArray) &&
3062 isa<ConstantArrayType>(TArray)) {
3064 QualType T = Importer.Import(D->getType());
3068 FoundVar->setType(T);
3069 MergeWithVar = FoundVar;
3071 } else if (isa<IncompleteArrayType>(TArray) &&
3072 isa<ConstantArrayType>(FoundArray)) {
3073 MergeWithVar = FoundVar;
3078 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3079 << Name << D->getType() << FoundVar->getType();
3080 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3081 << FoundVar->getType();
3085 ConflictingDecls.push_back(FoundDecls[I]);
3089 // An equivalent variable with external linkage has been found. Link
3090 // the two declarations, then merge them.
3091 Importer.Imported(D, MergeWithVar);
3093 if (VarDecl *DDef = D->getDefinition()) {
3094 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3095 Importer.ToDiag(ExistingDef->getLocation(),
3096 diag::err_odr_variable_multiple_def)
3098 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3100 Expr *Init = Importer.Import(DDef->getInit());
3101 MergeWithVar->setInit(Init);
3102 if (DDef->isInitKnownICE()) {
3103 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3104 Eval->CheckedICE = true;
3105 Eval->IsICE = DDef->isInitICE();
3110 return MergeWithVar;
3113 if (!ConflictingDecls.empty()) {
3114 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3115 ConflictingDecls.data(),
3116 ConflictingDecls.size());
3123 QualType T = Importer.Import(D->getType());
3127 // Create the imported variable.
3128 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3129 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3130 Importer.Import(D->getInnerLocStart()),
3131 Loc, Name.getAsIdentifierInfo(),
3133 D->getStorageClass());
3134 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3135 ToVar->setAccess(D->getAccess());
3136 ToVar->setLexicalDeclContext(LexicalDC);
3137 Importer.Imported(D, ToVar);
3138 LexicalDC->addDeclInternal(ToVar);
3140 // Merge the initializer.
3141 if (ImportDefinition(D, ToVar))
3147 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3148 // Parameters are created in the translation unit's context, then moved
3149 // into the function declaration's context afterward.
3150 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3152 // Import the name of this declaration.
3153 DeclarationName Name = Importer.Import(D->getDeclName());
3154 if (D->getDeclName() && !Name)
3157 // Import the location of this declaration.
3158 SourceLocation Loc = Importer.Import(D->getLocation());
3160 // Import the parameter's type.
3161 QualType T = Importer.Import(D->getType());
3165 // Create the imported parameter.
3166 ImplicitParamDecl *ToParm
3167 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3168 Loc, Name.getAsIdentifierInfo(),
3170 return Importer.Imported(D, ToParm);
3173 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3174 // Parameters are created in the translation unit's context, then moved
3175 // into the function declaration's context afterward.
3176 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3178 // Import the name of this declaration.
3179 DeclarationName Name = Importer.Import(D->getDeclName());
3180 if (D->getDeclName() && !Name)
3183 // Import the location of this declaration.
3184 SourceLocation Loc = Importer.Import(D->getLocation());
3186 // Import the parameter's type.
3187 QualType T = Importer.Import(D->getType());
3191 // Create the imported parameter.
3192 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3193 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3194 Importer.Import(D->getInnerLocStart()),
3195 Loc, Name.getAsIdentifierInfo(),
3196 T, TInfo, D->getStorageClass(),
3197 /*FIXME: Default argument*/ 0);
3198 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3199 return Importer.Imported(D, ToParm);
3202 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3203 // Import the major distinguishing characteristics of a method.
3204 DeclContext *DC, *LexicalDC;
3205 DeclarationName Name;
3207 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3210 SmallVector<NamedDecl *, 2> FoundDecls;
3211 DC->localUncachedLookup(Name, FoundDecls);
3212 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3213 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3214 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3217 // Check return types.
3218 if (!Importer.IsStructurallyEquivalent(D->getResultType(),
3219 FoundMethod->getResultType())) {
3220 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3221 << D->isInstanceMethod() << Name
3222 << D->getResultType() << FoundMethod->getResultType();
3223 Importer.ToDiag(FoundMethod->getLocation(),
3224 diag::note_odr_objc_method_here)
3225 << D->isInstanceMethod() << Name;
3229 // Check the number of parameters.
3230 if (D->param_size() != FoundMethod->param_size()) {
3231 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3232 << D->isInstanceMethod() << Name
3233 << D->param_size() << FoundMethod->param_size();
3234 Importer.ToDiag(FoundMethod->getLocation(),
3235 diag::note_odr_objc_method_here)
3236 << D->isInstanceMethod() << Name;
3240 // Check parameter types.
3241 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3242 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3243 P != PEnd; ++P, ++FoundP) {
3244 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3245 (*FoundP)->getType())) {
3246 Importer.FromDiag((*P)->getLocation(),
3247 diag::err_odr_objc_method_param_type_inconsistent)
3248 << D->isInstanceMethod() << Name
3249 << (*P)->getType() << (*FoundP)->getType();
3250 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3251 << (*FoundP)->getType();
3256 // Check variadic/non-variadic.
3257 // Check the number of parameters.
3258 if (D->isVariadic() != FoundMethod->isVariadic()) {
3259 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3260 << D->isInstanceMethod() << Name;
3261 Importer.ToDiag(FoundMethod->getLocation(),
3262 diag::note_odr_objc_method_here)
3263 << D->isInstanceMethod() << Name;
3267 // FIXME: Any other bits we need to merge?
3268 return Importer.Imported(D, FoundMethod);
3272 // Import the result type.
3273 QualType ResultTy = Importer.Import(D->getResultType());
3274 if (ResultTy.isNull())
3277 TypeSourceInfo *ResultTInfo = Importer.Import(D->getResultTypeSourceInfo());
3279 ObjCMethodDecl *ToMethod
3280 = ObjCMethodDecl::Create(Importer.getToContext(),
3282 Importer.Import(D->getLocEnd()),
3283 Name.getObjCSelector(),
3284 ResultTy, ResultTInfo, DC,
3285 D->isInstanceMethod(),
3287 D->isPropertyAccessor(),
3290 D->getImplementationControl(),
3291 D->hasRelatedResultType());
3293 // FIXME: When we decide to merge method definitions, we'll need to
3294 // deal with implicit parameters.
3296 // Import the parameters
3297 SmallVector<ParmVarDecl *, 5> ToParams;
3298 for (ObjCMethodDecl::param_iterator FromP = D->param_begin(),
3299 FromPEnd = D->param_end();
3302 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*FromP));
3306 ToParams.push_back(ToP);
3309 // Set the parameters.
3310 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3311 ToParams[I]->setOwningFunction(ToMethod);
3312 ToMethod->addDeclInternal(ToParams[I]);
3314 SmallVector<SourceLocation, 12> SelLocs;
3315 D->getSelectorLocs(SelLocs);
3316 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3318 ToMethod->setLexicalDeclContext(LexicalDC);
3319 Importer.Imported(D, ToMethod);
3320 LexicalDC->addDeclInternal(ToMethod);
3324 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3325 // Import the major distinguishing characteristics of a category.
3326 DeclContext *DC, *LexicalDC;
3327 DeclarationName Name;
3329 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3332 ObjCInterfaceDecl *ToInterface
3333 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3337 // Determine if we've already encountered this category.
3338 ObjCCategoryDecl *MergeWithCategory
3339 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3340 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3342 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3343 Importer.Import(D->getAtStartLoc()),
3345 Importer.Import(D->getCategoryNameLoc()),
3346 Name.getAsIdentifierInfo(),
3348 Importer.Import(D->getIvarLBraceLoc()),
3349 Importer.Import(D->getIvarRBraceLoc()));
3350 ToCategory->setLexicalDeclContext(LexicalDC);
3351 LexicalDC->addDeclInternal(ToCategory);
3352 Importer.Imported(D, ToCategory);
3355 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3356 SmallVector<SourceLocation, 4> ProtocolLocs;
3357 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3358 = D->protocol_loc_begin();
3359 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3360 FromProtoEnd = D->protocol_end();
3361 FromProto != FromProtoEnd;
3362 ++FromProto, ++FromProtoLoc) {
3363 ObjCProtocolDecl *ToProto
3364 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3367 Protocols.push_back(ToProto);
3368 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3371 // FIXME: If we're merging, make sure that the protocol list is the same.
3372 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3373 ProtocolLocs.data(), Importer.getToContext());
3376 Importer.Imported(D, ToCategory);
3379 // Import all of the members of this category.
3380 ImportDeclContext(D);
3382 // If we have an implementation, import it as well.
3383 if (D->getImplementation()) {
3384 ObjCCategoryImplDecl *Impl
3385 = cast_or_null<ObjCCategoryImplDecl>(
3386 Importer.Import(D->getImplementation()));
3390 ToCategory->setImplementation(Impl);
3396 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3397 ObjCProtocolDecl *To,
3398 ImportDefinitionKind Kind) {
3399 if (To->getDefinition()) {
3400 if (shouldForceImportDeclContext(Kind))
3401 ImportDeclContext(From);
3405 // Start the protocol definition
3406 To->startDefinition();
3409 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3410 SmallVector<SourceLocation, 4> ProtocolLocs;
3411 ObjCProtocolDecl::protocol_loc_iterator
3412 FromProtoLoc = From->protocol_loc_begin();
3413 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3414 FromProtoEnd = From->protocol_end();
3415 FromProto != FromProtoEnd;
3416 ++FromProto, ++FromProtoLoc) {
3417 ObjCProtocolDecl *ToProto
3418 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3421 Protocols.push_back(ToProto);
3422 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3425 // FIXME: If we're merging, make sure that the protocol list is the same.
3426 To->setProtocolList(Protocols.data(), Protocols.size(),
3427 ProtocolLocs.data(), Importer.getToContext());
3429 if (shouldForceImportDeclContext(Kind)) {
3430 // Import all of the members of this protocol.
3431 ImportDeclContext(From, /*ForceImport=*/true);
3436 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3437 // If this protocol has a definition in the translation unit we're coming
3438 // from, but this particular declaration is not that definition, import the
3439 // definition and map to that.
3440 ObjCProtocolDecl *Definition = D->getDefinition();
3441 if (Definition && Definition != D) {
3442 Decl *ImportedDef = Importer.Import(Definition);
3446 return Importer.Imported(D, ImportedDef);
3449 // Import the major distinguishing characteristics of a protocol.
3450 DeclContext *DC, *LexicalDC;
3451 DeclarationName Name;
3453 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3456 ObjCProtocolDecl *MergeWithProtocol = 0;
3457 SmallVector<NamedDecl *, 2> FoundDecls;
3458 DC->localUncachedLookup(Name, FoundDecls);
3459 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3460 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3463 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3467 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3469 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3470 Name.getAsIdentifierInfo(), Loc,
3471 Importer.Import(D->getAtStartLoc()),
3473 ToProto->setLexicalDeclContext(LexicalDC);
3474 LexicalDC->addDeclInternal(ToProto);
3477 Importer.Imported(D, ToProto);
3479 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3485 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3486 ObjCInterfaceDecl *To,
3487 ImportDefinitionKind Kind) {
3488 if (To->getDefinition()) {
3489 // Check consistency of superclass.
3490 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3492 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3497 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3498 if ((bool)FromSuper != (bool)ToSuper ||
3499 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3500 Importer.ToDiag(To->getLocation(),
3501 diag::err_odr_objc_superclass_inconsistent)
3502 << To->getDeclName();
3504 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3505 << To->getSuperClass()->getDeclName();
3507 Importer.ToDiag(To->getLocation(),
3508 diag::note_odr_objc_missing_superclass);
3509 if (From->getSuperClass())
3510 Importer.FromDiag(From->getSuperClassLoc(),
3511 diag::note_odr_objc_superclass)
3512 << From->getSuperClass()->getDeclName();
3514 Importer.FromDiag(From->getLocation(),
3515 diag::note_odr_objc_missing_superclass);
3518 if (shouldForceImportDeclContext(Kind))
3519 ImportDeclContext(From);
3523 // Start the definition.
3524 To->startDefinition();
3526 // If this class has a superclass, import it.
3527 if (From->getSuperClass()) {
3528 ObjCInterfaceDecl *Super = cast_or_null<ObjCInterfaceDecl>(
3529 Importer.Import(From->getSuperClass()));
3533 To->setSuperClass(Super);
3534 To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
3538 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3539 SmallVector<SourceLocation, 4> ProtocolLocs;
3540 ObjCInterfaceDecl::protocol_loc_iterator
3541 FromProtoLoc = From->protocol_loc_begin();
3543 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3544 FromProtoEnd = From->protocol_end();
3545 FromProto != FromProtoEnd;
3546 ++FromProto, ++FromProtoLoc) {
3547 ObjCProtocolDecl *ToProto
3548 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3551 Protocols.push_back(ToProto);
3552 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3555 // FIXME: If we're merging, make sure that the protocol list is the same.
3556 To->setProtocolList(Protocols.data(), Protocols.size(),
3557 ProtocolLocs.data(), Importer.getToContext());
3559 // Import categories. When the categories themselves are imported, they'll
3560 // hook themselves into this interface.
3561 for (ObjCInterfaceDecl::known_categories_iterator
3562 Cat = From->known_categories_begin(),
3563 CatEnd = From->known_categories_end();
3564 Cat != CatEnd; ++Cat) {
3565 Importer.Import(*Cat);
3568 // If we have an @implementation, import it as well.
3569 if (From->getImplementation()) {
3570 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3571 Importer.Import(From->getImplementation()));
3575 To->setImplementation(Impl);
3578 if (shouldForceImportDeclContext(Kind)) {
3579 // Import all of the members of this class.
3580 ImportDeclContext(From, /*ForceImport=*/true);
3585 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3586 // If this class has a definition in the translation unit we're coming from,
3587 // but this particular declaration is not that definition, import the
3588 // definition and map to that.
3589 ObjCInterfaceDecl *Definition = D->getDefinition();
3590 if (Definition && Definition != D) {
3591 Decl *ImportedDef = Importer.Import(Definition);
3595 return Importer.Imported(D, ImportedDef);
3598 // Import the major distinguishing characteristics of an @interface.
3599 DeclContext *DC, *LexicalDC;
3600 DeclarationName Name;
3602 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3605 // Look for an existing interface with the same name.
3606 ObjCInterfaceDecl *MergeWithIface = 0;
3607 SmallVector<NamedDecl *, 2> FoundDecls;
3608 DC->localUncachedLookup(Name, FoundDecls);
3609 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3610 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3613 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3617 // Create an interface declaration, if one does not already exist.
3618 ObjCInterfaceDecl *ToIface = MergeWithIface;
3620 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3621 Importer.Import(D->getAtStartLoc()),
3622 Name.getAsIdentifierInfo(),
3624 D->isImplicitInterfaceDecl());
3625 ToIface->setLexicalDeclContext(LexicalDC);
3626 LexicalDC->addDeclInternal(ToIface);
3628 Importer.Imported(D, ToIface);
3630 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3636 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3637 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3638 Importer.Import(D->getCategoryDecl()));
3642 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3644 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3648 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3649 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3650 Importer.Import(D->getIdentifier()),
3651 Category->getClassInterface(),
3652 Importer.Import(D->getLocation()),
3653 Importer.Import(D->getAtStartLoc()),
3656 DeclContext *LexicalDC = DC;
3657 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3658 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3662 ToImpl->setLexicalDeclContext(LexicalDC);
3665 LexicalDC->addDeclInternal(ToImpl);
3666 Category->setImplementation(ToImpl);
3669 Importer.Imported(D, ToImpl);
3670 ImportDeclContext(D);
3674 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3675 // Find the corresponding interface.
3676 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3677 Importer.Import(D->getClassInterface()));
3681 // Import the superclass, if any.
3682 ObjCInterfaceDecl *Super = 0;
3683 if (D->getSuperClass()) {
3684 Super = cast_or_null<ObjCInterfaceDecl>(
3685 Importer.Import(D->getSuperClass()));
3690 ObjCImplementationDecl *Impl = Iface->getImplementation();
3692 // We haven't imported an implementation yet. Create a new @implementation
3694 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3695 Importer.ImportContext(D->getDeclContext()),
3697 Importer.Import(D->getLocation()),
3698 Importer.Import(D->getAtStartLoc()),
3699 Importer.Import(D->getSuperClassLoc()),
3700 Importer.Import(D->getIvarLBraceLoc()),
3701 Importer.Import(D->getIvarRBraceLoc()));
3703 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3704 DeclContext *LexicalDC
3705 = Importer.ImportContext(D->getLexicalDeclContext());
3708 Impl->setLexicalDeclContext(LexicalDC);
3711 // Associate the implementation with the class it implements.
3712 Iface->setImplementation(Impl);
3713 Importer.Imported(D, Iface->getImplementation());
3715 Importer.Imported(D, Iface->getImplementation());
3717 // Verify that the existing @implementation has the same superclass.
3718 if ((Super && !Impl->getSuperClass()) ||
3719 (!Super && Impl->getSuperClass()) ||
3720 (Super && Impl->getSuperClass() &&
3721 !declaresSameEntity(Super->getCanonicalDecl(), Impl->getSuperClass()))) {
3722 Importer.ToDiag(Impl->getLocation(),
3723 diag::err_odr_objc_superclass_inconsistent)
3724 << Iface->getDeclName();
3725 // FIXME: It would be nice to have the location of the superclass
3727 if (Impl->getSuperClass())
3728 Importer.ToDiag(Impl->getLocation(),
3729 diag::note_odr_objc_superclass)
3730 << Impl->getSuperClass()->getDeclName();
3732 Importer.ToDiag(Impl->getLocation(),
3733 diag::note_odr_objc_missing_superclass);
3734 if (D->getSuperClass())
3735 Importer.FromDiag(D->getLocation(),
3736 diag::note_odr_objc_superclass)
3737 << D->getSuperClass()->getDeclName();
3739 Importer.FromDiag(D->getLocation(),
3740 diag::note_odr_objc_missing_superclass);
3745 // Import all of the members of this @implementation.
3746 ImportDeclContext(D);
3751 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3752 // Import the major distinguishing characteristics of an @property.
3753 DeclContext *DC, *LexicalDC;
3754 DeclarationName Name;
3756 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3759 // Check whether we have already imported this property.
3760 SmallVector<NamedDecl *, 2> FoundDecls;
3761 DC->localUncachedLookup(Name, FoundDecls);
3762 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3763 if (ObjCPropertyDecl *FoundProp
3764 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3765 // Check property types.
3766 if (!Importer.IsStructurallyEquivalent(D->getType(),
3767 FoundProp->getType())) {
3768 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3769 << Name << D->getType() << FoundProp->getType();
3770 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3771 << FoundProp->getType();
3775 // FIXME: Check property attributes, getters, setters, etc.?
3777 // Consider these properties to be equivalent.
3778 Importer.Imported(D, FoundProp);
3784 TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
3788 // Create the new property.
3789 ObjCPropertyDecl *ToProperty
3790 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3791 Name.getAsIdentifierInfo(),
3792 Importer.Import(D->getAtLoc()),
3793 Importer.Import(D->getLParenLoc()),
3795 D->getPropertyImplementation());
3796 Importer.Imported(D, ToProperty);
3797 ToProperty->setLexicalDeclContext(LexicalDC);
3798 LexicalDC->addDeclInternal(ToProperty);
3800 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3801 ToProperty->setPropertyAttributesAsWritten(
3802 D->getPropertyAttributesAsWritten());
3803 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
3804 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
3805 ToProperty->setGetterMethodDecl(
3806 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3807 ToProperty->setSetterMethodDecl(
3808 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3809 ToProperty->setPropertyIvarDecl(
3810 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3814 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3815 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3816 Importer.Import(D->getPropertyDecl()));
3820 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3824 // Import the lexical declaration context.
3825 DeclContext *LexicalDC = DC;
3826 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3827 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3832 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3836 // Import the ivar (for an @synthesize).
3837 ObjCIvarDecl *Ivar = 0;
3838 if (D->getPropertyIvarDecl()) {
3839 Ivar = cast_or_null<ObjCIvarDecl>(
3840 Importer.Import(D->getPropertyIvarDecl()));
3845 ObjCPropertyImplDecl *ToImpl
3846 = InImpl->FindPropertyImplDecl(Property->getIdentifier());
3848 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3849 Importer.Import(D->getLocStart()),
3850 Importer.Import(D->getLocation()),
3852 D->getPropertyImplementation(),
3854 Importer.Import(D->getPropertyIvarDeclLoc()));
3855 ToImpl->setLexicalDeclContext(LexicalDC);
3856 Importer.Imported(D, ToImpl);
3857 LexicalDC->addDeclInternal(ToImpl);
3859 // Check that we have the same kind of property implementation (@synthesize
3861 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3862 Importer.ToDiag(ToImpl->getLocation(),
3863 diag::err_odr_objc_property_impl_kind_inconsistent)
3864 << Property->getDeclName()
3865 << (ToImpl->getPropertyImplementation()
3866 == ObjCPropertyImplDecl::Dynamic);
3867 Importer.FromDiag(D->getLocation(),
3868 diag::note_odr_objc_property_impl_kind)
3869 << D->getPropertyDecl()->getDeclName()
3870 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3874 // For @synthesize, check that we have the same
3875 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3876 Ivar != ToImpl->getPropertyIvarDecl()) {
3877 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3878 diag::err_odr_objc_synthesize_ivar_inconsistent)
3879 << Property->getDeclName()
3880 << ToImpl->getPropertyIvarDecl()->getDeclName()
3881 << Ivar->getDeclName();
3882 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3883 diag::note_odr_objc_synthesize_ivar_here)
3884 << D->getPropertyIvarDecl()->getDeclName();
3888 // Merge the existing implementation with the new implementation.
3889 Importer.Imported(D, ToImpl);
3895 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3896 // For template arguments, we adopt the translation unit as our declaration
3897 // context. This context will be fixed when the actual template declaration
3900 // FIXME: Import default argument.
3901 return TemplateTypeParmDecl::Create(Importer.getToContext(),
3902 Importer.getToContext().getTranslationUnitDecl(),
3903 Importer.Import(D->getLocStart()),
3904 Importer.Import(D->getLocation()),
3907 Importer.Import(D->getIdentifier()),
3908 D->wasDeclaredWithTypename(),
3909 D->isParameterPack());
3913 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3914 // Import the name of this declaration.
3915 DeclarationName Name = Importer.Import(D->getDeclName());
3916 if (D->getDeclName() && !Name)
3919 // Import the location of this declaration.
3920 SourceLocation Loc = Importer.Import(D->getLocation());
3922 // Import the type of this declaration.
3923 QualType T = Importer.Import(D->getType());
3927 // Import type-source information.
3928 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3929 if (D->getTypeSourceInfo() && !TInfo)
3932 // FIXME: Import default argument.
3934 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3935 Importer.getToContext().getTranslationUnitDecl(),
3936 Importer.Import(D->getInnerLocStart()),
3937 Loc, D->getDepth(), D->getPosition(),
3938 Name.getAsIdentifierInfo(),
3939 T, D->isParameterPack(), TInfo);
3943 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3944 // Import the name of this declaration.
3945 DeclarationName Name = Importer.Import(D->getDeclName());
3946 if (D->getDeclName() && !Name)
3949 // Import the location of this declaration.
3950 SourceLocation Loc = Importer.Import(D->getLocation());
3952 // Import template parameters.
3953 TemplateParameterList *TemplateParams
3954 = ImportTemplateParameterList(D->getTemplateParameters());
3955 if (!TemplateParams)
3958 // FIXME: Import default argument.
3960 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3961 Importer.getToContext().getTranslationUnitDecl(),
3962 Loc, D->getDepth(), D->getPosition(),
3963 D->isParameterPack(),
3964 Name.getAsIdentifierInfo(),
3968 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
3969 // If this record has a definition in the translation unit we're coming from,
3970 // but this particular declaration is not that definition, import the
3971 // definition and map to that.
3972 CXXRecordDecl *Definition
3973 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
3974 if (Definition && Definition != D->getTemplatedDecl()) {
3976 = Importer.Import(Definition->getDescribedClassTemplate());
3980 return Importer.Imported(D, ImportedDef);
3983 // Import the major distinguishing characteristics of this class template.
3984 DeclContext *DC, *LexicalDC;
3985 DeclarationName Name;
3987 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3990 // We may already have a template of the same name; try to find and match it.
3991 if (!DC->isFunctionOrMethod()) {
3992 SmallVector<NamedDecl *, 4> ConflictingDecls;
3993 SmallVector<NamedDecl *, 2> FoundDecls;
3994 DC->localUncachedLookup(Name, FoundDecls);
3995 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3996 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3999 Decl *Found = FoundDecls[I];
4000 if (ClassTemplateDecl *FoundTemplate
4001 = dyn_cast<ClassTemplateDecl>(Found)) {
4002 if (IsStructuralMatch(D, FoundTemplate)) {
4003 // The class templates structurally match; call it the same template.
4004 // FIXME: We may be filling in a forward declaration here. Handle
4006 Importer.Imported(D->getTemplatedDecl(),
4007 FoundTemplate->getTemplatedDecl());
4008 return Importer.Imported(D, FoundTemplate);
4012 ConflictingDecls.push_back(FoundDecls[I]);
4015 if (!ConflictingDecls.empty()) {
4016 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4017 ConflictingDecls.data(),
4018 ConflictingDecls.size());
4025 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4027 // Create the declaration that is being templated.
4028 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4029 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4030 CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4031 DTemplated->getTagKind(),
4032 DC, StartLoc, IdLoc,
4033 Name.getAsIdentifierInfo());
4034 D2Templated->setAccess(DTemplated->getAccess());
4035 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4036 D2Templated->setLexicalDeclContext(LexicalDC);
4038 // Create the class template declaration itself.
4039 TemplateParameterList *TemplateParams
4040 = ImportTemplateParameterList(D->getTemplateParameters());
4041 if (!TemplateParams)
4044 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4045 Loc, Name, TemplateParams,
4048 D2Templated->setDescribedClassTemplate(D2);
4050 D2->setAccess(D->getAccess());
4051 D2->setLexicalDeclContext(LexicalDC);
4052 LexicalDC->addDeclInternal(D2);
4054 // Note the relationship between the class templates.
4055 Importer.Imported(D, D2);
4056 Importer.Imported(DTemplated, D2Templated);
4058 if (DTemplated->isCompleteDefinition() &&
4059 !D2Templated->isCompleteDefinition()) {
4060 // FIXME: Import definition!
4066 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4067 ClassTemplateSpecializationDecl *D) {
4068 // If this record has a definition in the translation unit we're coming from,
4069 // but this particular declaration is not that definition, import the
4070 // definition and map to that.
4071 TagDecl *Definition = D->getDefinition();
4072 if (Definition && Definition != D) {
4073 Decl *ImportedDef = Importer.Import(Definition);
4077 return Importer.Imported(D, ImportedDef);
4080 ClassTemplateDecl *ClassTemplate
4081 = cast_or_null<ClassTemplateDecl>(Importer.Import(
4082 D->getSpecializedTemplate()));
4086 // Import the context of this declaration.
4087 DeclContext *DC = ClassTemplate->getDeclContext();
4091 DeclContext *LexicalDC = DC;
4092 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4093 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4098 // Import the location of this declaration.
4099 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4100 SourceLocation IdLoc = Importer.Import(D->getLocation());
4102 // Import template arguments.
4103 SmallVector<TemplateArgument, 2> TemplateArgs;
4104 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4105 D->getTemplateArgs().size(),
4109 // Try to find an existing specialization with these template arguments.
4110 void *InsertPos = 0;
4111 ClassTemplateSpecializationDecl *D2
4112 = ClassTemplate->findSpecialization(TemplateArgs.data(),
4113 TemplateArgs.size(), InsertPos);
4115 // We already have a class template specialization with these template
4118 // FIXME: Check for specialization vs. instantiation errors.
4120 if (RecordDecl *FoundDef = D2->getDefinition()) {
4121 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4122 // The record types structurally match, or the "from" translation
4123 // unit only had a forward declaration anyway; call it the same
4125 return Importer.Imported(D, FoundDef);
4129 // Create a new specialization.
4130 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4131 D->getTagKind(), DC,
4134 TemplateArgs.data(),
4135 TemplateArgs.size(),
4137 D2->setSpecializationKind(D->getSpecializationKind());
4139 // Add this specialization to the class template.
4140 ClassTemplate->AddSpecialization(D2, InsertPos);
4142 // Import the qualifier, if any.
4143 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4145 // Add the specialization to this context.
4146 D2->setLexicalDeclContext(LexicalDC);
4147 LexicalDC->addDeclInternal(D2);
4149 Importer.Imported(D, D2);
4151 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4157 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4158 // If this variable has a definition in the translation unit we're coming
4160 // but this particular declaration is not that definition, import the
4161 // definition and map to that.
4162 VarDecl *Definition =
4163 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4164 if (Definition && Definition != D->getTemplatedDecl()) {
4165 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4169 return Importer.Imported(D, ImportedDef);
4172 // Import the major distinguishing characteristics of this variable template.
4173 DeclContext *DC, *LexicalDC;
4174 DeclarationName Name;
4176 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
4179 // We may already have a template of the same name; try to find and match it.
4180 assert(!DC->isFunctionOrMethod() &&
4181 "Variable templates cannot be declared at function scope");
4182 SmallVector<NamedDecl *, 4> ConflictingDecls;
4183 SmallVector<NamedDecl *, 2> FoundDecls;
4184 DC->localUncachedLookup(Name, FoundDecls);
4185 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4186 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4189 Decl *Found = FoundDecls[I];
4190 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4191 if (IsStructuralMatch(D, FoundTemplate)) {
4192 // The variable templates structurally match; call it the same template.
4193 Importer.Imported(D->getTemplatedDecl(),
4194 FoundTemplate->getTemplatedDecl());
4195 return Importer.Imported(D, FoundTemplate);
4199 ConflictingDecls.push_back(FoundDecls[I]);
4202 if (!ConflictingDecls.empty()) {
4203 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4204 ConflictingDecls.data(),
4205 ConflictingDecls.size());
4211 VarDecl *DTemplated = D->getTemplatedDecl();
4214 QualType T = Importer.Import(DTemplated->getType());
4218 // Create the declaration that is being templated.
4219 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4220 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4221 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4222 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4223 IdLoc, Name.getAsIdentifierInfo(), T,
4224 TInfo, DTemplated->getStorageClass());
4225 D2Templated->setAccess(DTemplated->getAccess());
4226 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4227 D2Templated->setLexicalDeclContext(LexicalDC);
4229 // Importer.Imported(DTemplated, D2Templated);
4230 // LexicalDC->addDeclInternal(D2Templated);
4232 // Merge the initializer.
4233 if (ImportDefinition(DTemplated, D2Templated))
4236 // Create the variable template declaration itself.
4237 TemplateParameterList *TemplateParams =
4238 ImportTemplateParameterList(D->getTemplateParameters());
4239 if (!TemplateParams)
4242 VarTemplateDecl *D2 = VarTemplateDecl::Create(
4243 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated,
4245 D2Templated->setDescribedVarTemplate(D2);
4247 D2->setAccess(D->getAccess());
4248 D2->setLexicalDeclContext(LexicalDC);
4249 LexicalDC->addDeclInternal(D2);
4251 // Note the relationship between the variable templates.
4252 Importer.Imported(D, D2);
4253 Importer.Imported(DTemplated, D2Templated);
4255 if (DTemplated->isThisDeclarationADefinition() &&
4256 !D2Templated->isThisDeclarationADefinition()) {
4257 // FIXME: Import definition!
4263 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4264 VarTemplateSpecializationDecl *D) {
4265 // If this record has a definition in the translation unit we're coming from,
4266 // but this particular declaration is not that definition, import the
4267 // definition and map to that.
4268 VarDecl *Definition = D->getDefinition();
4269 if (Definition && Definition != D) {
4270 Decl *ImportedDef = Importer.Import(Definition);
4274 return Importer.Imported(D, ImportedDef);
4277 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4278 Importer.Import(D->getSpecializedTemplate()));
4282 // Import the context of this declaration.
4283 DeclContext *DC = VarTemplate->getDeclContext();
4287 DeclContext *LexicalDC = DC;
4288 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4289 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4294 // Import the location of this declaration.
4295 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4296 SourceLocation IdLoc = Importer.Import(D->getLocation());
4298 // Import template arguments.
4299 SmallVector<TemplateArgument, 2> TemplateArgs;
4300 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4301 D->getTemplateArgs().size(), TemplateArgs))
4304 // Try to find an existing specialization with these template arguments.
4305 void *InsertPos = 0;
4306 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4307 TemplateArgs.data(), TemplateArgs.size(), InsertPos);
4309 // We already have a variable template specialization with these template
4312 // FIXME: Check for specialization vs. instantiation errors.
4314 if (VarDecl *FoundDef = D2->getDefinition()) {
4315 if (!D->isThisDeclarationADefinition() ||
4316 IsStructuralMatch(D, FoundDef)) {
4317 // The record types structurally match, or the "from" translation
4318 // unit only had a forward declaration anyway; call it the same
4320 return Importer.Imported(D, FoundDef);
4326 QualType T = Importer.Import(D->getType());
4329 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4331 // Create a new specialization.
4332 D2 = VarTemplateSpecializationDecl::Create(
4333 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4334 D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4335 D2->setSpecializationKind(D->getSpecializationKind());
4336 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4338 // Add this specialization to the class template.
4339 VarTemplate->AddSpecialization(D2, InsertPos);
4341 // Import the qualifier, if any.
4342 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4344 // Add the specialization to this context.
4345 D2->setLexicalDeclContext(LexicalDC);
4346 LexicalDC->addDeclInternal(D2);
4348 Importer.Imported(D, D2);
4350 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4356 //----------------------------------------------------------------------------
4357 // Import Statements
4358 //----------------------------------------------------------------------------
4360 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4361 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4362 << S->getStmtClassName();
4366 //----------------------------------------------------------------------------
4367 // Import Expressions
4368 //----------------------------------------------------------------------------
4369 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
4370 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
4371 << E->getStmtClassName();
4375 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
4376 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
4380 NamedDecl *FoundD = 0;
4381 if (E->getDecl() != E->getFoundDecl()) {
4382 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
4387 QualType T = Importer.Import(E->getType());
4391 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
4392 Importer.Import(E->getQualifierLoc()),
4393 Importer.Import(E->getTemplateKeywordLoc()),
4395 E->refersToEnclosingLocal(),
4396 Importer.Import(E->getLocation()),
4397 T, E->getValueKind(),
4399 /*FIXME:TemplateArgs=*/0);
4400 if (E->hadMultipleCandidates())
4401 DRE->setHadMultipleCandidates(true);
4405 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
4406 QualType T = Importer.Import(E->getType());
4410 return IntegerLiteral::Create(Importer.getToContext(),
4412 Importer.Import(E->getLocation()));
4415 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
4416 QualType T = Importer.Import(E->getType());
4420 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
4422 Importer.Import(E->getLocation()));
4425 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
4426 Expr *SubExpr = Importer.Import(E->getSubExpr());
4430 return new (Importer.getToContext())
4431 ParenExpr(Importer.Import(E->getLParen()),
4432 Importer.Import(E->getRParen()),
4436 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
4437 QualType T = Importer.Import(E->getType());
4441 Expr *SubExpr = Importer.Import(E->getSubExpr());
4445 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
4446 T, E->getValueKind(),
4448 Importer.Import(E->getOperatorLoc()));
4451 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
4452 UnaryExprOrTypeTraitExpr *E) {
4453 QualType ResultType = Importer.Import(E->getType());
4455 if (E->isArgumentType()) {
4456 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
4460 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4462 Importer.Import(E->getOperatorLoc()),
4463 Importer.Import(E->getRParenLoc()));
4466 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
4470 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4471 SubExpr, ResultType,
4472 Importer.Import(E->getOperatorLoc()),
4473 Importer.Import(E->getRParenLoc()));
4476 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
4477 QualType T = Importer.Import(E->getType());
4481 Expr *LHS = Importer.Import(E->getLHS());
4485 Expr *RHS = Importer.Import(E->getRHS());
4489 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
4490 T, E->getValueKind(),
4492 Importer.Import(E->getOperatorLoc()),
4493 E->isFPContractable());
4496 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
4497 QualType T = Importer.Import(E->getType());
4501 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
4502 if (CompLHSType.isNull())
4505 QualType CompResultType = Importer.Import(E->getComputationResultType());
4506 if (CompResultType.isNull())
4509 Expr *LHS = Importer.Import(E->getLHS());
4513 Expr *RHS = Importer.Import(E->getRHS());
4517 return new (Importer.getToContext())
4518 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
4519 T, E->getValueKind(),
4521 CompLHSType, CompResultType,
4522 Importer.Import(E->getOperatorLoc()),
4523 E->isFPContractable());
4526 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
4527 if (E->path_empty()) return false;
4529 // TODO: import cast paths
4533 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
4534 QualType T = Importer.Import(E->getType());
4538 Expr *SubExpr = Importer.Import(E->getSubExpr());
4542 CXXCastPath BasePath;
4543 if (ImportCastPath(E, BasePath))
4546 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
4547 SubExpr, &BasePath, E->getValueKind());
4550 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
4551 QualType T = Importer.Import(E->getType());
4555 Expr *SubExpr = Importer.Import(E->getSubExpr());
4559 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
4560 if (!TInfo && E->getTypeInfoAsWritten())
4563 CXXCastPath BasePath;
4564 if (ImportCastPath(E, BasePath))
4567 return CStyleCastExpr::Create(Importer.getToContext(), T,
4568 E->getValueKind(), E->getCastKind(),
4569 SubExpr, &BasePath, TInfo,
4570 Importer.Import(E->getLParenLoc()),
4571 Importer.Import(E->getRParenLoc()));
4574 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
4575 ASTContext &FromContext, FileManager &FromFileManager,
4577 : ToContext(ToContext), FromContext(FromContext),
4578 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
4579 Minimal(MinimalImport), LastDiagFromFrom(false)
4581 ImportedDecls[FromContext.getTranslationUnitDecl()]
4582 = ToContext.getTranslationUnitDecl();
4585 ASTImporter::~ASTImporter() { }
4587 QualType ASTImporter::Import(QualType FromT) {
4591 const Type *fromTy = FromT.getTypePtr();
4593 // Check whether we've already imported this type.
4594 llvm::DenseMap<const Type *, const Type *>::iterator Pos
4595 = ImportedTypes.find(fromTy);
4596 if (Pos != ImportedTypes.end())
4597 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
4600 ASTNodeImporter Importer(*this);
4601 QualType ToT = Importer.Visit(fromTy);
4605 // Record the imported type.
4606 ImportedTypes[fromTy] = ToT.getTypePtr();
4608 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
4611 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
4615 // FIXME: For now we just create a "trivial" type source info based
4616 // on the type and a single location. Implement a real version of this.
4617 QualType T = Import(FromTSI->getType());
4621 return ToContext.getTrivialTypeSourceInfo(T,
4622 FromTSI->getTypeLoc().getLocStart());
4625 Decl *ASTImporter::Import(Decl *FromD) {
4629 ASTNodeImporter Importer(*this);
4631 // Check whether we've already imported this declaration.
4632 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
4633 if (Pos != ImportedDecls.end()) {
4634 Decl *ToD = Pos->second;
4635 Importer.ImportDefinitionIfNeeded(FromD, ToD);
4640 Decl *ToD = Importer.Visit(FromD);
4644 // Record the imported declaration.
4645 ImportedDecls[FromD] = ToD;
4647 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
4648 // Keep track of anonymous tags that have an associated typedef.
4649 if (FromTag->getTypedefNameForAnonDecl())
4650 AnonTagsWithPendingTypedefs.push_back(FromTag);
4651 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
4652 // When we've finished transforming a typedef, see whether it was the
4653 // typedef for an anonymous tag.
4654 for (SmallVectorImpl<TagDecl *>::iterator
4655 FromTag = AnonTagsWithPendingTypedefs.begin(),
4656 FromTagEnd = AnonTagsWithPendingTypedefs.end();
4657 FromTag != FromTagEnd; ++FromTag) {
4658 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
4659 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
4660 // We found the typedef for an anonymous tag; link them.
4661 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
4662 AnonTagsWithPendingTypedefs.erase(FromTag);
4672 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
4676 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
4680 // When we're using a record/enum/Objective-C class/protocol as a context, we
4681 // need it to have a definition.
4682 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
4683 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
4684 if (ToRecord->isCompleteDefinition()) {
4686 } else if (FromRecord->isCompleteDefinition()) {
4687 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
4688 ASTNodeImporter::IDK_Basic);
4690 CompleteDecl(ToRecord);
4692 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
4693 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
4694 if (ToEnum->isCompleteDefinition()) {
4696 } else if (FromEnum->isCompleteDefinition()) {
4697 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
4698 ASTNodeImporter::IDK_Basic);
4700 CompleteDecl(ToEnum);
4702 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
4703 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
4704 if (ToClass->getDefinition()) {
4706 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
4707 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
4708 ASTNodeImporter::IDK_Basic);
4710 CompleteDecl(ToClass);
4712 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
4713 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
4714 if (ToProto->getDefinition()) {
4716 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
4717 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
4718 ASTNodeImporter::IDK_Basic);
4720 CompleteDecl(ToProto);
4727 Expr *ASTImporter::Import(Expr *FromE) {
4731 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
4734 Stmt *ASTImporter::Import(Stmt *FromS) {
4738 // Check whether we've already imported this declaration.
4739 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
4740 if (Pos != ImportedStmts.end())
4744 ASTNodeImporter Importer(*this);
4745 Stmt *ToS = Importer.Visit(FromS);
4749 // Record the imported declaration.
4750 ImportedStmts[FromS] = ToS;
4754 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
4758 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
4760 switch (FromNNS->getKind()) {
4761 case NestedNameSpecifier::Identifier:
4762 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
4763 return NestedNameSpecifier::Create(ToContext, prefix, II);
4767 case NestedNameSpecifier::Namespace:
4768 if (NamespaceDecl *NS =
4769 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
4770 return NestedNameSpecifier::Create(ToContext, prefix, NS);
4774 case NestedNameSpecifier::NamespaceAlias:
4775 if (NamespaceAliasDecl *NSAD =
4776 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
4777 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
4781 case NestedNameSpecifier::Global:
4782 return NestedNameSpecifier::GlobalSpecifier(ToContext);
4784 case NestedNameSpecifier::TypeSpec:
4785 case NestedNameSpecifier::TypeSpecWithTemplate: {
4786 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
4788 bool bTemplate = FromNNS->getKind() ==
4789 NestedNameSpecifier::TypeSpecWithTemplate;
4790 return NestedNameSpecifier::Create(ToContext, prefix,
4791 bTemplate, T.getTypePtr());
4797 llvm_unreachable("Invalid nested name specifier kind");
4800 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
4801 // FIXME: Implement!
4802 return NestedNameSpecifierLoc();
4805 TemplateName ASTImporter::Import(TemplateName From) {
4806 switch (From.getKind()) {
4807 case TemplateName::Template:
4808 if (TemplateDecl *ToTemplate
4809 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4810 return TemplateName(ToTemplate);
4812 return TemplateName();
4814 case TemplateName::OverloadedTemplate: {
4815 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
4816 UnresolvedSet<2> ToTemplates;
4817 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
4818 E = FromStorage->end();
4820 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
4821 ToTemplates.addDecl(To);
4823 return TemplateName();
4825 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
4829 case TemplateName::QualifiedTemplate: {
4830 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
4831 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
4833 return TemplateName();
4835 if (TemplateDecl *ToTemplate
4836 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4837 return ToContext.getQualifiedTemplateName(Qualifier,
4838 QTN->hasTemplateKeyword(),
4841 return TemplateName();
4844 case TemplateName::DependentTemplate: {
4845 DependentTemplateName *DTN = From.getAsDependentTemplateName();
4846 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
4848 return TemplateName();
4850 if (DTN->isIdentifier()) {
4851 return ToContext.getDependentTemplateName(Qualifier,
4852 Import(DTN->getIdentifier()));
4855 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
4858 case TemplateName::SubstTemplateTemplateParm: {
4859 SubstTemplateTemplateParmStorage *subst
4860 = From.getAsSubstTemplateTemplateParm();
4861 TemplateTemplateParmDecl *param
4862 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
4864 return TemplateName();
4866 TemplateName replacement = Import(subst->getReplacement());
4867 if (replacement.isNull()) return TemplateName();
4869 return ToContext.getSubstTemplateTemplateParm(param, replacement);
4872 case TemplateName::SubstTemplateTemplateParmPack: {
4873 SubstTemplateTemplateParmPackStorage *SubstPack
4874 = From.getAsSubstTemplateTemplateParmPack();
4875 TemplateTemplateParmDecl *Param
4876 = cast_or_null<TemplateTemplateParmDecl>(
4877 Import(SubstPack->getParameterPack()));
4879 return TemplateName();
4881 ASTNodeImporter Importer(*this);
4882 TemplateArgument ArgPack
4883 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
4884 if (ArgPack.isNull())
4885 return TemplateName();
4887 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
4891 llvm_unreachable("Invalid template name kind");
4894 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
4895 if (FromLoc.isInvalid())
4896 return SourceLocation();
4898 SourceManager &FromSM = FromContext.getSourceManager();
4900 // For now, map everything down to its spelling location, so that we
4901 // don't have to import macro expansions.
4902 // FIXME: Import macro expansions!
4903 FromLoc = FromSM.getSpellingLoc(FromLoc);
4904 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
4905 SourceManager &ToSM = ToContext.getSourceManager();
4906 return ToSM.getLocForStartOfFile(Import(Decomposed.first))
4907 .getLocWithOffset(Decomposed.second);
4910 SourceRange ASTImporter::Import(SourceRange FromRange) {
4911 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
4914 FileID ASTImporter::Import(FileID FromID) {
4915 llvm::DenseMap<FileID, FileID>::iterator Pos
4916 = ImportedFileIDs.find(FromID);
4917 if (Pos != ImportedFileIDs.end())
4920 SourceManager &FromSM = FromContext.getSourceManager();
4921 SourceManager &ToSM = ToContext.getSourceManager();
4922 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
4923 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
4925 // Include location of this file.
4926 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
4928 // Map the FileID for to the "to" source manager.
4930 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
4931 if (Cache->OrigEntry) {
4932 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
4934 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
4935 // than mmap the files several times.
4936 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
4937 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
4938 FromSLoc.getFile().getFileCharacteristic());
4940 // FIXME: We want to re-use the existing MemoryBuffer!
4941 const llvm::MemoryBuffer *
4942 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
4943 llvm::MemoryBuffer *ToBuf
4944 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
4945 FromBuf->getBufferIdentifier());
4946 ToID = ToSM.createFileIDForMemBuffer(ToBuf,
4947 FromSLoc.getFile().getFileCharacteristic());
4951 ImportedFileIDs[FromID] = ToID;
4955 void ASTImporter::ImportDefinition(Decl *From) {
4956 Decl *To = Import(From);
4960 if (DeclContext *FromDC = cast<DeclContext>(From)) {
4961 ASTNodeImporter Importer(*this);
4963 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
4964 if (!ToRecord->getDefinition()) {
4965 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
4966 ASTNodeImporter::IDK_Everything);
4971 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
4972 if (!ToEnum->getDefinition()) {
4973 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
4974 ASTNodeImporter::IDK_Everything);
4979 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
4980 if (!ToIFace->getDefinition()) {
4981 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
4982 ASTNodeImporter::IDK_Everything);
4987 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
4988 if (!ToProto->getDefinition()) {
4989 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
4990 ASTNodeImporter::IDK_Everything);
4995 Importer.ImportDeclContext(FromDC, true);
4999 DeclarationName ASTImporter::Import(DeclarationName FromName) {
5001 return DeclarationName();
5003 switch (FromName.getNameKind()) {
5004 case DeclarationName::Identifier:
5005 return Import(FromName.getAsIdentifierInfo());
5007 case DeclarationName::ObjCZeroArgSelector:
5008 case DeclarationName::ObjCOneArgSelector:
5009 case DeclarationName::ObjCMultiArgSelector:
5010 return Import(FromName.getObjCSelector());
5012 case DeclarationName::CXXConstructorName: {
5013 QualType T = Import(FromName.getCXXNameType());
5015 return DeclarationName();
5017 return ToContext.DeclarationNames.getCXXConstructorName(
5018 ToContext.getCanonicalType(T));
5021 case DeclarationName::CXXDestructorName: {
5022 QualType T = Import(FromName.getCXXNameType());
5024 return DeclarationName();
5026 return ToContext.DeclarationNames.getCXXDestructorName(
5027 ToContext.getCanonicalType(T));
5030 case DeclarationName::CXXConversionFunctionName: {
5031 QualType T = Import(FromName.getCXXNameType());
5033 return DeclarationName();
5035 return ToContext.DeclarationNames.getCXXConversionFunctionName(
5036 ToContext.getCanonicalType(T));
5039 case DeclarationName::CXXOperatorName:
5040 return ToContext.DeclarationNames.getCXXOperatorName(
5041 FromName.getCXXOverloadedOperator());
5043 case DeclarationName::CXXLiteralOperatorName:
5044 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5045 Import(FromName.getCXXLiteralIdentifier()));
5047 case DeclarationName::CXXUsingDirective:
5049 return DeclarationName::getUsingDirectiveName();
5052 llvm_unreachable("Invalid DeclarationName Kind!");
5055 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5059 return &ToContext.Idents.get(FromId->getName());
5062 Selector ASTImporter::Import(Selector FromSel) {
5063 if (FromSel.isNull())
5066 SmallVector<IdentifierInfo *, 4> Idents;
5067 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5068 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5069 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5070 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5073 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5077 unsigned NumDecls) {
5081 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5082 if (LastDiagFromFrom)
5083 ToContext.getDiagnostics().notePriorDiagnosticFrom(
5084 FromContext.getDiagnostics());
5085 LastDiagFromFrom = false;
5086 return ToContext.getDiagnostics().Report(Loc, DiagID);
5089 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5090 if (!LastDiagFromFrom)
5091 FromContext.getDiagnostics().notePriorDiagnosticFrom(
5092 ToContext.getDiagnostics());
5093 LastDiagFromFrom = true;
5094 return FromContext.getDiagnostics().Report(Loc, DiagID);
5097 void ASTImporter::CompleteDecl (Decl *D) {
5098 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5099 if (!ID->getDefinition())
5100 ID->startDefinition();
5102 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5103 if (!PD->getDefinition())
5104 PD->startDefinition();
5106 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5107 if (!TD->getDefinition() && !TD->isBeingDefined()) {
5108 TD->startDefinition();
5109 TD->setCompleteDefinition(true);
5113 assert (0 && "CompleteDecl called on a Decl that can't be completed");
5117 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5118 ImportedDecls[From] = To;
5122 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5124 llvm::DenseMap<const Type *, const Type *>::iterator Pos
5125 = ImportedTypes.find(From.getTypePtr());
5126 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5129 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5131 return Ctx.IsStructurallyEquivalent(From, To);