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 QualType VisitAttributedType(const AttributedType *T);
71 // FIXME: TemplateTypeParmType
72 // FIXME: SubstTemplateTypeParmType
73 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
74 QualType VisitElaboratedType(const ElaboratedType *T);
75 // FIXME: DependentNameType
76 // FIXME: DependentTemplateSpecializationType
77 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
78 QualType VisitObjCObjectType(const ObjCObjectType *T);
79 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
81 // Importing declarations
82 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
83 DeclContext *&LexicalDC, DeclarationName &Name,
84 NamedDecl *&ToD, SourceLocation &Loc);
85 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
86 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87 DeclarationNameInfo& To);
88 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
90 /// \brief What we should import from the definition.
91 enum ImportDefinitionKind {
92 /// \brief Import the default subset of the definition, which might be
93 /// nothing (if minimal import is set) or might be everything (if minimal
94 /// import is not set).
96 /// \brief Import everything.
98 /// \brief Import only the bare bones needed to establish a valid
103 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
104 return IDK == IDK_Everything ||
105 (IDK == IDK_Default && !Importer.isMinimalImport());
108 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
109 ImportDefinitionKind Kind = IDK_Default);
110 bool ImportDefinition(VarDecl *From, VarDecl *To,
111 ImportDefinitionKind Kind = IDK_Default);
112 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
113 ImportDefinitionKind Kind = IDK_Default);
114 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
115 ImportDefinitionKind Kind = IDK_Default);
116 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
117 ImportDefinitionKind Kind = IDK_Default);
118 TemplateParameterList *ImportTemplateParameterList(
119 TemplateParameterList *Params);
120 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
121 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
122 unsigned NumFromArgs,
123 SmallVectorImpl<TemplateArgument> &ToArgs);
124 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
125 bool Complain = true);
126 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
127 bool Complain = true);
128 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
129 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
130 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
131 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
132 Decl *VisitDecl(Decl *D);
133 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
134 Decl *VisitNamespaceDecl(NamespaceDecl *D);
135 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
136 Decl *VisitTypedefDecl(TypedefDecl *D);
137 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
138 Decl *VisitEnumDecl(EnumDecl *D);
139 Decl *VisitRecordDecl(RecordDecl *D);
140 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
141 Decl *VisitFunctionDecl(FunctionDecl *D);
142 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
143 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
144 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
145 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
146 Decl *VisitFieldDecl(FieldDecl *D);
147 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
148 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
149 Decl *VisitVarDecl(VarDecl *D);
150 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
151 Decl *VisitParmVarDecl(ParmVarDecl *D);
152 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
153 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
154 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
155 Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
156 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
157 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
158 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
159 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
160 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
161 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
162 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
163 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
164 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
165 Decl *VisitClassTemplateSpecializationDecl(
166 ClassTemplateSpecializationDecl *D);
167 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
168 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
170 // Importing statements
171 DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
173 Stmt *VisitStmt(Stmt *S);
174 Stmt *VisitDeclStmt(DeclStmt *S);
175 Stmt *VisitNullStmt(NullStmt *S);
176 Stmt *VisitCompoundStmt(CompoundStmt *S);
177 Stmt *VisitCaseStmt(CaseStmt *S);
178 Stmt *VisitDefaultStmt(DefaultStmt *S);
179 Stmt *VisitLabelStmt(LabelStmt *S);
180 Stmt *VisitAttributedStmt(AttributedStmt *S);
181 Stmt *VisitIfStmt(IfStmt *S);
182 Stmt *VisitSwitchStmt(SwitchStmt *S);
183 Stmt *VisitWhileStmt(WhileStmt *S);
184 Stmt *VisitDoStmt(DoStmt *S);
185 Stmt *VisitForStmt(ForStmt *S);
186 Stmt *VisitGotoStmt(GotoStmt *S);
187 Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
188 Stmt *VisitContinueStmt(ContinueStmt *S);
189 Stmt *VisitBreakStmt(BreakStmt *S);
190 Stmt *VisitReturnStmt(ReturnStmt *S);
193 // FIXME: SEHExceptStmt
194 // FIXME: SEHFinallyStmt
196 // FIXME: SEHLeaveStmt
197 // FIXME: CapturedStmt
198 Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
199 Stmt *VisitCXXTryStmt(CXXTryStmt *S);
200 Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
201 // FIXME: MSDependentExistsStmt
202 Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
203 Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
204 Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
205 Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
206 Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
207 Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
208 Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
210 // Importing expressions
211 Expr *VisitExpr(Expr *E);
212 Expr *VisitDeclRefExpr(DeclRefExpr *E);
213 Expr *VisitIntegerLiteral(IntegerLiteral *E);
214 Expr *VisitCharacterLiteral(CharacterLiteral *E);
215 Expr *VisitParenExpr(ParenExpr *E);
216 Expr *VisitUnaryOperator(UnaryOperator *E);
217 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
218 Expr *VisitBinaryOperator(BinaryOperator *E);
219 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
220 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
221 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
222 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
223 Expr *VisitMemberExpr(MemberExpr *E);
224 Expr *VisitCallExpr(CallExpr *E);
227 using namespace clang;
229 //----------------------------------------------------------------------------
230 // Structural Equivalence
231 //----------------------------------------------------------------------------
234 struct StructuralEquivalenceContext {
235 /// \brief AST contexts for which we are checking structural equivalence.
238 /// \brief The set of "tentative" equivalences between two canonical
239 /// declarations, mapping from a declaration in the first context to the
240 /// declaration in the second context that we believe to be equivalent.
241 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
243 /// \brief Queue of declarations in the first context whose equivalence
244 /// with a declaration in the second context still needs to be verified.
245 std::deque<Decl *> DeclsToCheck;
247 /// \brief Declaration (from, to) pairs that are known not to be equivalent
248 /// (which we have already complained about).
249 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
251 /// \brief Whether we're being strict about the spelling of types when
252 /// unifying two types.
253 bool StrictTypeSpelling;
255 /// \brief Whether to complain about failures.
258 /// \brief \c true if the last diagnostic came from C2.
261 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
262 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
263 bool StrictTypeSpelling = false,
264 bool Complain = true)
265 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
266 StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
267 LastDiagFromC2(false) {}
269 /// \brief Determine whether the two declarations are structurally
271 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
273 /// \brief Determine whether the two types are structurally equivalent.
274 bool IsStructurallyEquivalent(QualType T1, QualType T2);
277 /// \brief Finish checking all of the structural equivalences.
279 /// \returns true if an error occurred, false otherwise.
283 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
284 assert(Complain && "Not allowed to complain");
286 C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
287 LastDiagFromC2 = false;
288 return C1.getDiagnostics().Report(Loc, DiagID);
291 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
292 assert(Complain && "Not allowed to complain");
294 C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
295 LastDiagFromC2 = true;
296 return C2.getDiagnostics().Report(Loc, DiagID);
301 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
302 QualType T1, QualType T2);
303 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
306 /// \brief Determine structural equivalence of two expressions.
307 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
308 Expr *E1, Expr *E2) {
312 // FIXME: Actually perform a structural comparison!
316 /// \brief Determine whether two identifiers are equivalent.
317 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
318 const IdentifierInfo *Name2) {
319 if (!Name1 || !Name2)
320 return Name1 == Name2;
322 return Name1->getName() == Name2->getName();
325 /// \brief Determine whether two nested-name-specifiers are equivalent.
326 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
327 NestedNameSpecifier *NNS1,
328 NestedNameSpecifier *NNS2) {
333 /// \brief Determine whether two template arguments are equivalent.
334 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
335 const TemplateArgument &Arg1,
336 const TemplateArgument &Arg2) {
337 if (Arg1.getKind() != Arg2.getKind())
340 switch (Arg1.getKind()) {
341 case TemplateArgument::Null:
344 case TemplateArgument::Type:
345 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
347 case TemplateArgument::Integral:
348 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
349 Arg2.getIntegralType()))
352 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
354 case TemplateArgument::Declaration:
355 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
357 case TemplateArgument::NullPtr:
358 return true; // FIXME: Is this correct?
360 case TemplateArgument::Template:
361 return IsStructurallyEquivalent(Context,
362 Arg1.getAsTemplate(),
363 Arg2.getAsTemplate());
365 case TemplateArgument::TemplateExpansion:
366 return IsStructurallyEquivalent(Context,
367 Arg1.getAsTemplateOrTemplatePattern(),
368 Arg2.getAsTemplateOrTemplatePattern());
370 case TemplateArgument::Expression:
371 return IsStructurallyEquivalent(Context,
372 Arg1.getAsExpr(), Arg2.getAsExpr());
374 case TemplateArgument::Pack:
375 if (Arg1.pack_size() != Arg2.pack_size())
378 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
379 if (!IsStructurallyEquivalent(Context,
380 Arg1.pack_begin()[I],
381 Arg2.pack_begin()[I]))
387 llvm_unreachable("Invalid template argument kind");
390 /// \brief Determine structural equivalence for the common part of array
392 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
393 const ArrayType *Array1,
394 const ArrayType *Array2) {
395 if (!IsStructurallyEquivalent(Context,
396 Array1->getElementType(),
397 Array2->getElementType()))
399 if (Array1->getSizeModifier() != Array2->getSizeModifier())
401 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
407 /// \brief Determine structural equivalence of two types.
408 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
409 QualType T1, QualType T2) {
410 if (T1.isNull() || T2.isNull())
411 return T1.isNull() && T2.isNull();
413 if (!Context.StrictTypeSpelling) {
414 // We aren't being strict about token-to-token equivalence of types,
415 // so map down to the canonical type.
416 T1 = Context.C1.getCanonicalType(T1);
417 T2 = Context.C2.getCanonicalType(T2);
420 if (T1.getQualifiers() != T2.getQualifiers())
423 Type::TypeClass TC = T1->getTypeClass();
425 if (T1->getTypeClass() != T2->getTypeClass()) {
426 // Compare function types with prototypes vs. without prototypes as if
427 // both did not have prototypes.
428 if (T1->getTypeClass() == Type::FunctionProto &&
429 T2->getTypeClass() == Type::FunctionNoProto)
430 TC = Type::FunctionNoProto;
431 else if (T1->getTypeClass() == Type::FunctionNoProto &&
432 T2->getTypeClass() == Type::FunctionProto)
433 TC = Type::FunctionNoProto;
440 // FIXME: Deal with Char_S/Char_U.
441 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
446 if (!IsStructurallyEquivalent(Context,
447 cast<ComplexType>(T1)->getElementType(),
448 cast<ComplexType>(T2)->getElementType()))
454 if (!IsStructurallyEquivalent(Context,
455 cast<AdjustedType>(T1)->getOriginalType(),
456 cast<AdjustedType>(T2)->getOriginalType()))
461 if (!IsStructurallyEquivalent(Context,
462 cast<PointerType>(T1)->getPointeeType(),
463 cast<PointerType>(T2)->getPointeeType()))
467 case Type::BlockPointer:
468 if (!IsStructurallyEquivalent(Context,
469 cast<BlockPointerType>(T1)->getPointeeType(),
470 cast<BlockPointerType>(T2)->getPointeeType()))
474 case Type::LValueReference:
475 case Type::RValueReference: {
476 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
477 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
478 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
480 if (Ref1->isInnerRef() != Ref2->isInnerRef())
482 if (!IsStructurallyEquivalent(Context,
483 Ref1->getPointeeTypeAsWritten(),
484 Ref2->getPointeeTypeAsWritten()))
489 case Type::MemberPointer: {
490 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
491 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
492 if (!IsStructurallyEquivalent(Context,
493 MemPtr1->getPointeeType(),
494 MemPtr2->getPointeeType()))
496 if (!IsStructurallyEquivalent(Context,
497 QualType(MemPtr1->getClass(), 0),
498 QualType(MemPtr2->getClass(), 0)))
503 case Type::ConstantArray: {
504 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
505 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
506 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
509 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
514 case Type::IncompleteArray:
515 if (!IsArrayStructurallyEquivalent(Context,
517 cast<ArrayType>(T2)))
521 case Type::VariableArray: {
522 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
523 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
524 if (!IsStructurallyEquivalent(Context,
525 Array1->getSizeExpr(), Array2->getSizeExpr()))
528 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
534 case Type::DependentSizedArray: {
535 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
536 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
537 if (!IsStructurallyEquivalent(Context,
538 Array1->getSizeExpr(), Array2->getSizeExpr()))
541 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
547 case Type::DependentSizedExtVector: {
548 const DependentSizedExtVectorType *Vec1
549 = cast<DependentSizedExtVectorType>(T1);
550 const DependentSizedExtVectorType *Vec2
551 = cast<DependentSizedExtVectorType>(T2);
552 if (!IsStructurallyEquivalent(Context,
553 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
555 if (!IsStructurallyEquivalent(Context,
556 Vec1->getElementType(),
557 Vec2->getElementType()))
563 case Type::ExtVector: {
564 const VectorType *Vec1 = cast<VectorType>(T1);
565 const VectorType *Vec2 = cast<VectorType>(T2);
566 if (!IsStructurallyEquivalent(Context,
567 Vec1->getElementType(),
568 Vec2->getElementType()))
570 if (Vec1->getNumElements() != Vec2->getNumElements())
572 if (Vec1->getVectorKind() != Vec2->getVectorKind())
577 case Type::FunctionProto: {
578 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
579 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
580 if (Proto1->getNumParams() != Proto2->getNumParams())
582 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
583 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
584 Proto2->getParamType(I)))
587 if (Proto1->isVariadic() != Proto2->isVariadic())
589 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
591 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
592 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
594 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
595 if (!IsStructurallyEquivalent(Context,
596 Proto1->getExceptionType(I),
597 Proto2->getExceptionType(I)))
600 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
601 if (!IsStructurallyEquivalent(Context,
602 Proto1->getNoexceptExpr(),
603 Proto2->getNoexceptExpr()))
606 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
609 // Fall through to check the bits common with FunctionNoProtoType.
612 case Type::FunctionNoProto: {
613 const FunctionType *Function1 = cast<FunctionType>(T1);
614 const FunctionType *Function2 = cast<FunctionType>(T2);
615 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
616 Function2->getReturnType()))
618 if (Function1->getExtInfo() != Function2->getExtInfo())
623 case Type::UnresolvedUsing:
624 if (!IsStructurallyEquivalent(Context,
625 cast<UnresolvedUsingType>(T1)->getDecl(),
626 cast<UnresolvedUsingType>(T2)->getDecl()))
631 case Type::Attributed:
632 if (!IsStructurallyEquivalent(Context,
633 cast<AttributedType>(T1)->getModifiedType(),
634 cast<AttributedType>(T2)->getModifiedType()))
636 if (!IsStructurallyEquivalent(Context,
637 cast<AttributedType>(T1)->getEquivalentType(),
638 cast<AttributedType>(T2)->getEquivalentType()))
643 if (!IsStructurallyEquivalent(Context,
644 cast<ParenType>(T1)->getInnerType(),
645 cast<ParenType>(T2)->getInnerType()))
650 if (!IsStructurallyEquivalent(Context,
651 cast<TypedefType>(T1)->getDecl(),
652 cast<TypedefType>(T2)->getDecl()))
656 case Type::TypeOfExpr:
657 if (!IsStructurallyEquivalent(Context,
658 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
659 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
664 if (!IsStructurallyEquivalent(Context,
665 cast<TypeOfType>(T1)->getUnderlyingType(),
666 cast<TypeOfType>(T2)->getUnderlyingType()))
670 case Type::UnaryTransform:
671 if (!IsStructurallyEquivalent(Context,
672 cast<UnaryTransformType>(T1)->getUnderlyingType(),
673 cast<UnaryTransformType>(T1)->getUnderlyingType()))
678 if (!IsStructurallyEquivalent(Context,
679 cast<DecltypeType>(T1)->getUnderlyingExpr(),
680 cast<DecltypeType>(T2)->getUnderlyingExpr()))
685 if (!IsStructurallyEquivalent(Context,
686 cast<AutoType>(T1)->getDeducedType(),
687 cast<AutoType>(T2)->getDeducedType()))
693 if (!IsStructurallyEquivalent(Context,
694 cast<TagType>(T1)->getDecl(),
695 cast<TagType>(T2)->getDecl()))
699 case Type::TemplateTypeParm: {
700 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
701 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
702 if (Parm1->getDepth() != Parm2->getDepth())
704 if (Parm1->getIndex() != Parm2->getIndex())
706 if (Parm1->isParameterPack() != Parm2->isParameterPack())
709 // Names of template type parameters are never significant.
713 case Type::SubstTemplateTypeParm: {
714 const SubstTemplateTypeParmType *Subst1
715 = cast<SubstTemplateTypeParmType>(T1);
716 const SubstTemplateTypeParmType *Subst2
717 = cast<SubstTemplateTypeParmType>(T2);
718 if (!IsStructurallyEquivalent(Context,
719 QualType(Subst1->getReplacedParameter(), 0),
720 QualType(Subst2->getReplacedParameter(), 0)))
722 if (!IsStructurallyEquivalent(Context,
723 Subst1->getReplacementType(),
724 Subst2->getReplacementType()))
729 case Type::SubstTemplateTypeParmPack: {
730 const SubstTemplateTypeParmPackType *Subst1
731 = cast<SubstTemplateTypeParmPackType>(T1);
732 const SubstTemplateTypeParmPackType *Subst2
733 = cast<SubstTemplateTypeParmPackType>(T2);
734 if (!IsStructurallyEquivalent(Context,
735 QualType(Subst1->getReplacedParameter(), 0),
736 QualType(Subst2->getReplacedParameter(), 0)))
738 if (!IsStructurallyEquivalent(Context,
739 Subst1->getArgumentPack(),
740 Subst2->getArgumentPack()))
744 case Type::TemplateSpecialization: {
745 const TemplateSpecializationType *Spec1
746 = cast<TemplateSpecializationType>(T1);
747 const TemplateSpecializationType *Spec2
748 = cast<TemplateSpecializationType>(T2);
749 if (!IsStructurallyEquivalent(Context,
750 Spec1->getTemplateName(),
751 Spec2->getTemplateName()))
753 if (Spec1->getNumArgs() != Spec2->getNumArgs())
755 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
756 if (!IsStructurallyEquivalent(Context,
757 Spec1->getArg(I), Spec2->getArg(I)))
763 case Type::Elaborated: {
764 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
765 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
766 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
767 if (Elab1->getKeyword() != Elab2->getKeyword())
769 if (!IsStructurallyEquivalent(Context,
770 Elab1->getQualifier(),
771 Elab2->getQualifier()))
773 if (!IsStructurallyEquivalent(Context,
774 Elab1->getNamedType(),
775 Elab2->getNamedType()))
780 case Type::InjectedClassName: {
781 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
782 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
783 if (!IsStructurallyEquivalent(Context,
784 Inj1->getInjectedSpecializationType(),
785 Inj2->getInjectedSpecializationType()))
790 case Type::DependentName: {
791 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
792 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
793 if (!IsStructurallyEquivalent(Context,
794 Typename1->getQualifier(),
795 Typename2->getQualifier()))
797 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
798 Typename2->getIdentifier()))
804 case Type::DependentTemplateSpecialization: {
805 const DependentTemplateSpecializationType *Spec1 =
806 cast<DependentTemplateSpecializationType>(T1);
807 const DependentTemplateSpecializationType *Spec2 =
808 cast<DependentTemplateSpecializationType>(T2);
809 if (!IsStructurallyEquivalent(Context,
810 Spec1->getQualifier(),
811 Spec2->getQualifier()))
813 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
814 Spec2->getIdentifier()))
816 if (Spec1->getNumArgs() != Spec2->getNumArgs())
818 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
819 if (!IsStructurallyEquivalent(Context,
820 Spec1->getArg(I), Spec2->getArg(I)))
826 case Type::PackExpansion:
827 if (!IsStructurallyEquivalent(Context,
828 cast<PackExpansionType>(T1)->getPattern(),
829 cast<PackExpansionType>(T2)->getPattern()))
833 case Type::ObjCInterface: {
834 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
835 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
836 if (!IsStructurallyEquivalent(Context,
837 Iface1->getDecl(), Iface2->getDecl()))
842 case Type::ObjCObject: {
843 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
844 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
845 if (!IsStructurallyEquivalent(Context,
847 Obj2->getBaseType()))
849 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
851 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
852 if (!IsStructurallyEquivalent(Context,
853 Obj1->getProtocol(I),
854 Obj2->getProtocol(I)))
860 case Type::ObjCObjectPointer: {
861 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
862 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
863 if (!IsStructurallyEquivalent(Context,
864 Ptr1->getPointeeType(),
865 Ptr2->getPointeeType()))
871 if (!IsStructurallyEquivalent(Context,
872 cast<AtomicType>(T1)->getValueType(),
873 cast<AtomicType>(T2)->getValueType()))
883 /// \brief Determine structural equivalence of two fields.
884 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
885 FieldDecl *Field1, FieldDecl *Field2) {
886 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
888 // For anonymous structs/unions, match up the anonymous struct/union type
889 // declarations directly, so that we don't go off searching for anonymous
891 if (Field1->isAnonymousStructOrUnion() &&
892 Field2->isAnonymousStructOrUnion()) {
893 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
894 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
895 return IsStructurallyEquivalent(Context, D1, D2);
898 // Check for equivalent field names.
899 IdentifierInfo *Name1 = Field1->getIdentifier();
900 IdentifierInfo *Name2 = Field2->getIdentifier();
901 if (!::IsStructurallyEquivalent(Name1, Name2))
904 if (!IsStructurallyEquivalent(Context,
905 Field1->getType(), Field2->getType())) {
906 if (Context.Complain) {
907 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
908 << Context.C2.getTypeDeclType(Owner2);
909 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
910 << Field2->getDeclName() << Field2->getType();
911 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
912 << Field1->getDeclName() << Field1->getType();
917 if (Field1->isBitField() != Field2->isBitField()) {
918 if (Context.Complain) {
919 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
920 << Context.C2.getTypeDeclType(Owner2);
921 if (Field1->isBitField()) {
922 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
923 << Field1->getDeclName() << Field1->getType()
924 << Field1->getBitWidthValue(Context.C1);
925 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
926 << Field2->getDeclName();
928 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
929 << Field2->getDeclName() << Field2->getType()
930 << Field2->getBitWidthValue(Context.C2);
931 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
932 << Field1->getDeclName();
938 if (Field1->isBitField()) {
939 // Make sure that the bit-fields are the same length.
940 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
941 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
943 if (Bits1 != Bits2) {
944 if (Context.Complain) {
945 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
946 << Context.C2.getTypeDeclType(Owner2);
947 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
948 << Field2->getDeclName() << Field2->getType() << Bits2;
949 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
950 << Field1->getDeclName() << Field1->getType() << Bits1;
959 /// \brief Find the index of the given anonymous struct/union within its
962 /// \returns Returns the index of this anonymous struct/union in its context,
963 /// including the next assigned index (if none of them match). Returns an
964 /// empty option if the context is not a record, i.e.. if the anonymous
965 /// struct/union is at namespace or block scope.
966 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
967 ASTContext &Context = Anon->getASTContext();
968 QualType AnonTy = Context.getRecordType(Anon);
970 RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
975 for (const auto *D : Owner->noload_decls()) {
976 const auto *F = dyn_cast<FieldDecl>(D);
977 if (!F || !F->isAnonymousStructOrUnion())
980 if (Context.hasSameType(F->getType(), AnonTy))
989 /// \brief Determine structural equivalence of two records.
990 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
991 RecordDecl *D1, RecordDecl *D2) {
992 if (D1->isUnion() != D2->isUnion()) {
993 if (Context.Complain) {
994 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
995 << Context.C2.getTypeDeclType(D2);
996 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
997 << D1->getDeclName() << (unsigned)D1->getTagKind();
1002 if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1003 // If both anonymous structs/unions are in a record context, make sure
1004 // they occur in the same location in the context records.
1005 if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
1006 if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
1007 if (*Index1 != *Index2)
1013 // If both declarations are class template specializations, we know
1014 // the ODR applies, so check the template and template arguments.
1015 ClassTemplateSpecializationDecl *Spec1
1016 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1017 ClassTemplateSpecializationDecl *Spec2
1018 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1019 if (Spec1 && Spec2) {
1020 // Check that the specialized templates are the same.
1021 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1022 Spec2->getSpecializedTemplate()))
1025 // Check that the template arguments are the same.
1026 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1029 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1030 if (!IsStructurallyEquivalent(Context,
1031 Spec1->getTemplateArgs().get(I),
1032 Spec2->getTemplateArgs().get(I)))
1035 // If one is a class template specialization and the other is not, these
1036 // structures are different.
1037 else if (Spec1 || Spec2)
1040 // Compare the definitions of these two records. If either or both are
1041 // incomplete, we assume that they are equivalent.
1042 D1 = D1->getDefinition();
1043 D2 = D2->getDefinition();
1047 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1048 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1049 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1050 if (Context.Complain) {
1051 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1052 << Context.C2.getTypeDeclType(D2);
1053 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1054 << D2CXX->getNumBases();
1055 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1056 << D1CXX->getNumBases();
1061 // Check the base classes.
1062 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1063 BaseEnd1 = D1CXX->bases_end(),
1064 Base2 = D2CXX->bases_begin();
1067 if (!IsStructurallyEquivalent(Context,
1068 Base1->getType(), Base2->getType())) {
1069 if (Context.Complain) {
1070 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1071 << Context.C2.getTypeDeclType(D2);
1072 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1074 << Base2->getSourceRange();
1075 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1077 << Base1->getSourceRange();
1082 // Check virtual vs. non-virtual inheritance mismatch.
1083 if (Base1->isVirtual() != Base2->isVirtual()) {
1084 if (Context.Complain) {
1085 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1086 << Context.C2.getTypeDeclType(D2);
1087 Context.Diag2(Base2->getLocStart(),
1088 diag::note_odr_virtual_base)
1089 << Base2->isVirtual() << Base2->getSourceRange();
1090 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1091 << Base1->isVirtual()
1092 << Base1->getSourceRange();
1097 } else if (D1CXX->getNumBases() > 0) {
1098 if (Context.Complain) {
1099 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1100 << Context.C2.getTypeDeclType(D2);
1101 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1102 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1104 << Base1->getSourceRange();
1105 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1111 // Check the fields for consistency.
1112 RecordDecl::field_iterator Field2 = D2->field_begin(),
1113 Field2End = D2->field_end();
1114 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1115 Field1End = D1->field_end();
1116 Field1 != Field1End;
1117 ++Field1, ++Field2) {
1118 if (Field2 == Field2End) {
1119 if (Context.Complain) {
1120 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1121 << Context.C2.getTypeDeclType(D2);
1122 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1123 << Field1->getDeclName() << Field1->getType();
1124 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1129 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1133 if (Field2 != Field2End) {
1134 if (Context.Complain) {
1135 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1136 << Context.C2.getTypeDeclType(D2);
1137 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1138 << Field2->getDeclName() << Field2->getType();
1139 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1147 /// \brief Determine structural equivalence of two enums.
1148 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1149 EnumDecl *D1, EnumDecl *D2) {
1150 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1151 EC2End = D2->enumerator_end();
1152 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1153 EC1End = D1->enumerator_end();
1154 EC1 != EC1End; ++EC1, ++EC2) {
1155 if (EC2 == EC2End) {
1156 if (Context.Complain) {
1157 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1158 << Context.C2.getTypeDeclType(D2);
1159 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1160 << EC1->getDeclName()
1161 << EC1->getInitVal().toString(10);
1162 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1167 llvm::APSInt Val1 = EC1->getInitVal();
1168 llvm::APSInt Val2 = EC2->getInitVal();
1169 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1170 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1171 if (Context.Complain) {
1172 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1173 << Context.C2.getTypeDeclType(D2);
1174 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1175 << EC2->getDeclName()
1176 << EC2->getInitVal().toString(10);
1177 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1178 << EC1->getDeclName()
1179 << EC1->getInitVal().toString(10);
1185 if (EC2 != EC2End) {
1186 if (Context.Complain) {
1187 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1188 << Context.C2.getTypeDeclType(D2);
1189 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1190 << EC2->getDeclName()
1191 << EC2->getInitVal().toString(10);
1192 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1200 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1201 TemplateParameterList *Params1,
1202 TemplateParameterList *Params2) {
1203 if (Params1->size() != Params2->size()) {
1204 if (Context.Complain) {
1205 Context.Diag2(Params2->getTemplateLoc(),
1206 diag::err_odr_different_num_template_parameters)
1207 << Params1->size() << Params2->size();
1208 Context.Diag1(Params1->getTemplateLoc(),
1209 diag::note_odr_template_parameter_list);
1214 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1215 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1216 if (Context.Complain) {
1217 Context.Diag2(Params2->getParam(I)->getLocation(),
1218 diag::err_odr_different_template_parameter_kind);
1219 Context.Diag1(Params1->getParam(I)->getLocation(),
1220 diag::note_odr_template_parameter_here);
1225 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1226 Params2->getParam(I))) {
1235 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1236 TemplateTypeParmDecl *D1,
1237 TemplateTypeParmDecl *D2) {
1238 if (D1->isParameterPack() != D2->isParameterPack()) {
1239 if (Context.Complain) {
1240 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1241 << D2->isParameterPack();
1242 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1243 << D1->isParameterPack();
1251 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1252 NonTypeTemplateParmDecl *D1,
1253 NonTypeTemplateParmDecl *D2) {
1254 if (D1->isParameterPack() != D2->isParameterPack()) {
1255 if (Context.Complain) {
1256 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1257 << D2->isParameterPack();
1258 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1259 << D1->isParameterPack();
1265 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1266 if (Context.Complain) {
1267 Context.Diag2(D2->getLocation(),
1268 diag::err_odr_non_type_parameter_type_inconsistent)
1269 << D2->getType() << D1->getType();
1270 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1279 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1280 TemplateTemplateParmDecl *D1,
1281 TemplateTemplateParmDecl *D2) {
1282 if (D1->isParameterPack() != D2->isParameterPack()) {
1283 if (Context.Complain) {
1284 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1285 << D2->isParameterPack();
1286 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1287 << D1->isParameterPack();
1292 // Check template parameter lists.
1293 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1294 D2->getTemplateParameters());
1297 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1298 ClassTemplateDecl *D1,
1299 ClassTemplateDecl *D2) {
1300 // Check template parameters.
1301 if (!IsStructurallyEquivalent(Context,
1302 D1->getTemplateParameters(),
1303 D2->getTemplateParameters()))
1306 // Check the templated declaration.
1307 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1308 D2->getTemplatedDecl());
1311 /// \brief Determine structural equivalence of two declarations.
1312 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1313 Decl *D1, Decl *D2) {
1314 // FIXME: Check for known structural equivalences via a callback of some sort.
1316 // Check whether we already know that these two declarations are not
1317 // structurally equivalent.
1318 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1319 D2->getCanonicalDecl())))
1322 // Determine whether we've already produced a tentative equivalence for D1.
1323 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1325 return EquivToD1 == D2->getCanonicalDecl();
1327 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1328 EquivToD1 = D2->getCanonicalDecl();
1329 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1333 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1335 if (!::IsStructurallyEquivalent(*this, D1, D2))
1341 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1343 if (!::IsStructurallyEquivalent(*this, T1, T2))
1349 bool StructuralEquivalenceContext::Finish() {
1350 while (!DeclsToCheck.empty()) {
1351 // Check the next declaration.
1352 Decl *D1 = DeclsToCheck.front();
1353 DeclsToCheck.pop_front();
1355 Decl *D2 = TentativeEquivalences[D1];
1356 assert(D2 && "Unrecorded tentative equivalence?");
1358 bool Equivalent = true;
1360 // FIXME: Switch on all declaration kinds. For now, we're just going to
1361 // check the obvious ones.
1362 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1363 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1364 // Check for equivalent structure names.
1365 IdentifierInfo *Name1 = Record1->getIdentifier();
1366 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1367 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1368 IdentifierInfo *Name2 = Record2->getIdentifier();
1369 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1370 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1371 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1372 !::IsStructurallyEquivalent(*this, Record1, Record2))
1375 // Record/non-record mismatch.
1378 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1379 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1380 // Check for equivalent enum names.
1381 IdentifierInfo *Name1 = Enum1->getIdentifier();
1382 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1383 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1384 IdentifierInfo *Name2 = Enum2->getIdentifier();
1385 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1386 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1387 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1388 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1391 // Enum/non-enum mismatch
1394 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1395 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1396 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1397 Typedef2->getIdentifier()) ||
1398 !::IsStructurallyEquivalent(*this,
1399 Typedef1->getUnderlyingType(),
1400 Typedef2->getUnderlyingType()))
1403 // Typedef/non-typedef mismatch.
1406 } else if (ClassTemplateDecl *ClassTemplate1
1407 = dyn_cast<ClassTemplateDecl>(D1)) {
1408 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1409 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1410 ClassTemplate2->getIdentifier()) ||
1411 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1414 // Class template/non-class-template mismatch.
1417 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1418 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1419 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1425 } else if (NonTypeTemplateParmDecl *NTTP1
1426 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1427 if (NonTypeTemplateParmDecl *NTTP2
1428 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1429 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1435 } else if (TemplateTemplateParmDecl *TTP1
1436 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1437 if (TemplateTemplateParmDecl *TTP2
1438 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1439 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1448 // Note that these two declarations are not equivalent (and we already
1450 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1451 D2->getCanonicalDecl()));
1454 // FIXME: Check other declaration kinds!
1460 //----------------------------------------------------------------------------
1462 //----------------------------------------------------------------------------
1464 QualType ASTNodeImporter::VisitType(const Type *T) {
1465 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1466 << T->getTypeClassName();
1470 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1471 switch (T->getKind()) {
1472 #define SHARED_SINGLETON_TYPE(Expansion)
1473 #define BUILTIN_TYPE(Id, SingletonId) \
1474 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1475 #include "clang/AST/BuiltinTypes.def"
1477 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1478 // context supports C++.
1480 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1481 // context supports ObjC.
1483 case BuiltinType::Char_U:
1484 // The context we're importing from has an unsigned 'char'. If we're
1485 // importing into a context with a signed 'char', translate to
1486 // 'unsigned char' instead.
1487 if (Importer.getToContext().getLangOpts().CharIsSigned)
1488 return Importer.getToContext().UnsignedCharTy;
1490 return Importer.getToContext().CharTy;
1492 case BuiltinType::Char_S:
1493 // The context we're importing from has an unsigned 'char'. If we're
1494 // importing into a context with a signed 'char', translate to
1495 // 'unsigned char' instead.
1496 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1497 return Importer.getToContext().SignedCharTy;
1499 return Importer.getToContext().CharTy;
1501 case BuiltinType::WChar_S:
1502 case BuiltinType::WChar_U:
1503 // FIXME: If not in C++, shall we translate to the C equivalent of
1505 return Importer.getToContext().WCharTy;
1508 llvm_unreachable("Invalid BuiltinType Kind!");
1511 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1512 QualType ToElementType = Importer.Import(T->getElementType());
1513 if (ToElementType.isNull())
1516 return Importer.getToContext().getComplexType(ToElementType);
1519 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1520 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1521 if (ToPointeeType.isNull())
1524 return Importer.getToContext().getPointerType(ToPointeeType);
1527 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1528 // FIXME: Check for blocks support in "to" context.
1529 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1530 if (ToPointeeType.isNull())
1533 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1537 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1538 // FIXME: Check for C++ support in "to" context.
1539 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1540 if (ToPointeeType.isNull())
1543 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1547 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1548 // FIXME: Check for C++0x support in "to" context.
1549 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1550 if (ToPointeeType.isNull())
1553 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1556 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1557 // FIXME: Check for C++ support in "to" context.
1558 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1559 if (ToPointeeType.isNull())
1562 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1563 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1564 ClassType.getTypePtr());
1567 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1568 QualType ToElementType = Importer.Import(T->getElementType());
1569 if (ToElementType.isNull())
1572 return Importer.getToContext().getConstantArrayType(ToElementType,
1574 T->getSizeModifier(),
1575 T->getIndexTypeCVRQualifiers());
1579 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1580 QualType ToElementType = Importer.Import(T->getElementType());
1581 if (ToElementType.isNull())
1584 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1585 T->getSizeModifier(),
1586 T->getIndexTypeCVRQualifiers());
1589 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1590 QualType ToElementType = Importer.Import(T->getElementType());
1591 if (ToElementType.isNull())
1594 Expr *Size = Importer.Import(T->getSizeExpr());
1598 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1599 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1600 T->getSizeModifier(),
1601 T->getIndexTypeCVRQualifiers(),
1605 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1606 QualType ToElementType = Importer.Import(T->getElementType());
1607 if (ToElementType.isNull())
1610 return Importer.getToContext().getVectorType(ToElementType,
1611 T->getNumElements(),
1612 T->getVectorKind());
1615 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1616 QualType ToElementType = Importer.Import(T->getElementType());
1617 if (ToElementType.isNull())
1620 return Importer.getToContext().getExtVectorType(ToElementType,
1621 T->getNumElements());
1625 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1626 // FIXME: What happens if we're importing a function without a prototype
1627 // into C++? Should we make it variadic?
1628 QualType ToResultType = Importer.Import(T->getReturnType());
1629 if (ToResultType.isNull())
1632 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1636 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1637 QualType ToResultType = Importer.Import(T->getReturnType());
1638 if (ToResultType.isNull())
1641 // Import argument types
1642 SmallVector<QualType, 4> ArgTypes;
1643 for (const auto &A : T->param_types()) {
1644 QualType ArgType = Importer.Import(A);
1645 if (ArgType.isNull())
1647 ArgTypes.push_back(ArgType);
1650 // Import exception types
1651 SmallVector<QualType, 4> ExceptionTypes;
1652 for (const auto &E : T->exceptions()) {
1653 QualType ExceptionType = Importer.Import(E);
1654 if (ExceptionType.isNull())
1656 ExceptionTypes.push_back(ExceptionType);
1659 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1660 FunctionProtoType::ExtProtoInfo ToEPI;
1662 ToEPI.ExtInfo = FromEPI.ExtInfo;
1663 ToEPI.Variadic = FromEPI.Variadic;
1664 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1665 ToEPI.TypeQuals = FromEPI.TypeQuals;
1666 ToEPI.RefQualifier = FromEPI.RefQualifier;
1667 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1668 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1669 ToEPI.ExceptionSpec.NoexceptExpr =
1670 Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1671 ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1672 Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1673 ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1674 Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1676 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1679 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1680 QualType ToInnerType = Importer.Import(T->getInnerType());
1681 if (ToInnerType.isNull())
1684 return Importer.getToContext().getParenType(ToInnerType);
1687 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1688 TypedefNameDecl *ToDecl
1689 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1693 return Importer.getToContext().getTypeDeclType(ToDecl);
1696 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1697 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1701 return Importer.getToContext().getTypeOfExprType(ToExpr);
1704 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1705 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1706 if (ToUnderlyingType.isNull())
1709 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1712 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1713 // FIXME: Make sure that the "to" context supports C++0x!
1714 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1718 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1719 if (UnderlyingType.isNull())
1722 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1725 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1726 QualType ToBaseType = Importer.Import(T->getBaseType());
1727 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1728 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1731 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1736 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1737 // FIXME: Make sure that the "to" context supports C++11!
1738 QualType FromDeduced = T->getDeducedType();
1740 if (!FromDeduced.isNull()) {
1741 ToDeduced = Importer.Import(FromDeduced);
1742 if (ToDeduced.isNull())
1746 return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto(),
1747 /*IsDependent*/false);
1750 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1752 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1756 return Importer.getToContext().getTagDeclType(ToDecl);
1759 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1761 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1765 return Importer.getToContext().getTagDeclType(ToDecl);
1768 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1769 QualType FromModifiedType = T->getModifiedType();
1770 QualType FromEquivalentType = T->getEquivalentType();
1771 QualType ToModifiedType;
1772 QualType ToEquivalentType;
1774 if (!FromModifiedType.isNull()) {
1775 ToModifiedType = Importer.Import(FromModifiedType);
1776 if (ToModifiedType.isNull())
1779 if (!FromEquivalentType.isNull()) {
1780 ToEquivalentType = Importer.Import(FromEquivalentType);
1781 if (ToEquivalentType.isNull())
1785 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1786 ToModifiedType, ToEquivalentType);
1789 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1790 const TemplateSpecializationType *T) {
1791 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1792 if (ToTemplate.isNull())
1795 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1796 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1799 QualType ToCanonType;
1800 if (!QualType(T, 0).isCanonical()) {
1801 QualType FromCanonType
1802 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1803 ToCanonType =Importer.Import(FromCanonType);
1804 if (ToCanonType.isNull())
1807 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1808 ToTemplateArgs.data(),
1809 ToTemplateArgs.size(),
1813 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1814 NestedNameSpecifier *ToQualifier = nullptr;
1815 // Note: the qualifier in an ElaboratedType is optional.
1816 if (T->getQualifier()) {
1817 ToQualifier = Importer.Import(T->getQualifier());
1822 QualType ToNamedType = Importer.Import(T->getNamedType());
1823 if (ToNamedType.isNull())
1826 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1827 ToQualifier, ToNamedType);
1830 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1831 ObjCInterfaceDecl *Class
1832 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1836 return Importer.getToContext().getObjCInterfaceType(Class);
1839 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1840 QualType ToBaseType = Importer.Import(T->getBaseType());
1841 if (ToBaseType.isNull())
1844 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1845 for (auto *P : T->quals()) {
1846 ObjCProtocolDecl *Protocol
1847 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1850 Protocols.push_back(Protocol);
1853 return Importer.getToContext().getObjCObjectType(ToBaseType,
1859 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1860 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1861 if (ToPointeeType.isNull())
1864 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1867 //----------------------------------------------------------------------------
1868 // Import Declarations
1869 //----------------------------------------------------------------------------
1870 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1871 DeclContext *&LexicalDC,
1872 DeclarationName &Name,
1874 SourceLocation &Loc) {
1875 // Import the context of this declaration.
1876 DC = Importer.ImportContext(D->getDeclContext());
1881 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1882 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1887 // Import the name of this declaration.
1888 Name = Importer.Import(D->getDeclName());
1889 if (D->getDeclName() && !Name)
1892 // Import the location of this declaration.
1893 Loc = Importer.Import(D->getLocation());
1894 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1898 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1903 ToD = Importer.Import(FromD);
1908 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1909 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1910 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1911 ImportDefinition(FromRecord, ToRecord);
1917 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1918 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1919 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1920 ImportDefinition(FromEnum, ToEnum);
1928 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1929 DeclarationNameInfo& To) {
1930 // NOTE: To.Name and To.Loc are already imported.
1931 // We only have to import To.LocInfo.
1932 switch (To.getName().getNameKind()) {
1933 case DeclarationName::Identifier:
1934 case DeclarationName::ObjCZeroArgSelector:
1935 case DeclarationName::ObjCOneArgSelector:
1936 case DeclarationName::ObjCMultiArgSelector:
1937 case DeclarationName::CXXUsingDirective:
1940 case DeclarationName::CXXOperatorName: {
1941 SourceRange Range = From.getCXXOperatorNameRange();
1942 To.setCXXOperatorNameRange(Importer.Import(Range));
1945 case DeclarationName::CXXLiteralOperatorName: {
1946 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1947 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1950 case DeclarationName::CXXConstructorName:
1951 case DeclarationName::CXXDestructorName:
1952 case DeclarationName::CXXConversionFunctionName: {
1953 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1954 To.setNamedTypeInfo(Importer.Import(FromTInfo));
1958 llvm_unreachable("Unknown name kind.");
1961 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1962 if (Importer.isMinimalImport() && !ForceImport) {
1963 Importer.ImportContext(FromDC);
1967 for (auto *From : FromDC->decls())
1968 Importer.Import(From);
1971 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1972 ImportDefinitionKind Kind) {
1973 if (To->getDefinition() || To->isBeingDefined()) {
1974 if (Kind == IDK_Everything)
1975 ImportDeclContext(From, /*ForceImport=*/true);
1980 To->startDefinition();
1982 // Add base classes.
1983 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1984 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1986 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1987 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1988 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1989 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1990 ToData.Aggregate = FromData.Aggregate;
1991 ToData.PlainOldData = FromData.PlainOldData;
1992 ToData.Empty = FromData.Empty;
1993 ToData.Polymorphic = FromData.Polymorphic;
1994 ToData.Abstract = FromData.Abstract;
1995 ToData.IsStandardLayout = FromData.IsStandardLayout;
1996 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
1997 ToData.HasPrivateFields = FromData.HasPrivateFields;
1998 ToData.HasProtectedFields = FromData.HasProtectedFields;
1999 ToData.HasPublicFields = FromData.HasPublicFields;
2000 ToData.HasMutableFields = FromData.HasMutableFields;
2001 ToData.HasVariantMembers = FromData.HasVariantMembers;
2002 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2003 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2004 ToData.HasUninitializedReferenceMember
2005 = FromData.HasUninitializedReferenceMember;
2006 ToData.NeedOverloadResolutionForMoveConstructor
2007 = FromData.NeedOverloadResolutionForMoveConstructor;
2008 ToData.NeedOverloadResolutionForMoveAssignment
2009 = FromData.NeedOverloadResolutionForMoveAssignment;
2010 ToData.NeedOverloadResolutionForDestructor
2011 = FromData.NeedOverloadResolutionForDestructor;
2012 ToData.DefaultedMoveConstructorIsDeleted
2013 = FromData.DefaultedMoveConstructorIsDeleted;
2014 ToData.DefaultedMoveAssignmentIsDeleted
2015 = FromData.DefaultedMoveAssignmentIsDeleted;
2016 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2017 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2018 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2019 ToData.HasConstexprNonCopyMoveConstructor
2020 = FromData.HasConstexprNonCopyMoveConstructor;
2021 ToData.DefaultedDefaultConstructorIsConstexpr
2022 = FromData.DefaultedDefaultConstructorIsConstexpr;
2023 ToData.HasConstexprDefaultConstructor
2024 = FromData.HasConstexprDefaultConstructor;
2025 ToData.HasNonLiteralTypeFieldsOrBases
2026 = FromData.HasNonLiteralTypeFieldsOrBases;
2027 // ComputedVisibleConversions not imported.
2028 ToData.UserProvidedDefaultConstructor
2029 = FromData.UserProvidedDefaultConstructor;
2030 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2031 ToData.ImplicitCopyConstructorHasConstParam
2032 = FromData.ImplicitCopyConstructorHasConstParam;
2033 ToData.ImplicitCopyAssignmentHasConstParam
2034 = FromData.ImplicitCopyAssignmentHasConstParam;
2035 ToData.HasDeclaredCopyConstructorWithConstParam
2036 = FromData.HasDeclaredCopyConstructorWithConstParam;
2037 ToData.HasDeclaredCopyAssignmentWithConstParam
2038 = FromData.HasDeclaredCopyAssignmentWithConstParam;
2039 ToData.IsLambda = FromData.IsLambda;
2041 SmallVector<CXXBaseSpecifier *, 4> Bases;
2042 for (const auto &Base1 : FromCXX->bases()) {
2043 QualType T = Importer.Import(Base1.getType());
2047 SourceLocation EllipsisLoc;
2048 if (Base1.isPackExpansion())
2049 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2051 // Ensure that we have a definition for the base.
2052 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2055 new (Importer.getToContext())
2056 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2058 Base1.isBaseOfClass(),
2059 Base1.getAccessSpecifierAsWritten(),
2060 Importer.Import(Base1.getTypeSourceInfo()),
2064 ToCXX->setBases(Bases.data(), Bases.size());
2067 if (shouldForceImportDeclContext(Kind))
2068 ImportDeclContext(From, /*ForceImport=*/true);
2070 To->completeDefinition();
2074 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2075 ImportDefinitionKind Kind) {
2076 if (To->getAnyInitializer())
2079 // FIXME: Can we really import any initializer? Alternatively, we could force
2080 // ourselves to import every declaration of a variable and then only use
2082 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2084 // FIXME: Other bits to merge?
2089 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2090 ImportDefinitionKind Kind) {
2091 if (To->getDefinition() || To->isBeingDefined()) {
2092 if (Kind == IDK_Everything)
2093 ImportDeclContext(From, /*ForceImport=*/true);
2097 To->startDefinition();
2099 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2103 QualType ToPromotionType = Importer.Import(From->getPromotionType());
2104 if (ToPromotionType.isNull())
2107 if (shouldForceImportDeclContext(Kind))
2108 ImportDeclContext(From, /*ForceImport=*/true);
2110 // FIXME: we might need to merge the number of positive or negative bits
2111 // if the enumerator lists don't match.
2112 To->completeDefinition(T, ToPromotionType,
2113 From->getNumPositiveBits(),
2114 From->getNumNegativeBits());
2118 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2119 TemplateParameterList *Params) {
2120 SmallVector<NamedDecl *, 4> ToParams;
2121 ToParams.reserve(Params->size());
2122 for (TemplateParameterList::iterator P = Params->begin(),
2123 PEnd = Params->end();
2125 Decl *To = Importer.Import(*P);
2129 ToParams.push_back(cast<NamedDecl>(To));
2132 return TemplateParameterList::Create(Importer.getToContext(),
2133 Importer.Import(Params->getTemplateLoc()),
2134 Importer.Import(Params->getLAngleLoc()),
2135 ToParams.data(), ToParams.size(),
2136 Importer.Import(Params->getRAngleLoc()));
2140 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2141 switch (From.getKind()) {
2142 case TemplateArgument::Null:
2143 return TemplateArgument();
2145 case TemplateArgument::Type: {
2146 QualType ToType = Importer.Import(From.getAsType());
2147 if (ToType.isNull())
2148 return TemplateArgument();
2149 return TemplateArgument(ToType);
2152 case TemplateArgument::Integral: {
2153 QualType ToType = Importer.Import(From.getIntegralType());
2154 if (ToType.isNull())
2155 return TemplateArgument();
2156 return TemplateArgument(From, ToType);
2159 case TemplateArgument::Declaration: {
2160 ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2161 QualType ToType = Importer.Import(From.getParamTypeForDecl());
2162 if (!To || ToType.isNull())
2163 return TemplateArgument();
2164 return TemplateArgument(To, ToType);
2167 case TemplateArgument::NullPtr: {
2168 QualType ToType = Importer.Import(From.getNullPtrType());
2169 if (ToType.isNull())
2170 return TemplateArgument();
2171 return TemplateArgument(ToType, /*isNullPtr*/true);
2174 case TemplateArgument::Template: {
2175 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2176 if (ToTemplate.isNull())
2177 return TemplateArgument();
2179 return TemplateArgument(ToTemplate);
2182 case TemplateArgument::TemplateExpansion: {
2183 TemplateName ToTemplate
2184 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2185 if (ToTemplate.isNull())
2186 return TemplateArgument();
2188 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2191 case TemplateArgument::Expression:
2192 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2193 return TemplateArgument(ToExpr);
2194 return TemplateArgument();
2196 case TemplateArgument::Pack: {
2197 SmallVector<TemplateArgument, 2> ToPack;
2198 ToPack.reserve(From.pack_size());
2199 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2200 return TemplateArgument();
2202 TemplateArgument *ToArgs
2203 = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
2204 std::copy(ToPack.begin(), ToPack.end(), ToArgs);
2205 return TemplateArgument(ToArgs, ToPack.size());
2209 llvm_unreachable("Invalid template argument kind");
2212 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2213 unsigned NumFromArgs,
2214 SmallVectorImpl<TemplateArgument> &ToArgs) {
2215 for (unsigned I = 0; I != NumFromArgs; ++I) {
2216 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2217 if (To.isNull() && !FromArgs[I].isNull())
2220 ToArgs.push_back(To);
2226 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2227 RecordDecl *ToRecord, bool Complain) {
2228 // Eliminate a potential failure point where we attempt to re-import
2229 // something we're trying to import while completing ToRecord.
2230 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2232 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2234 ToRecord = ToOriginRecord;
2237 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2238 ToRecord->getASTContext(),
2239 Importer.getNonEquivalentDecls(),
2241 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2244 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2246 StructuralEquivalenceContext Ctx(
2247 Importer.getFromContext(), Importer.getToContext(),
2248 Importer.getNonEquivalentDecls(), false, Complain);
2249 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2252 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2253 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2254 Importer.getToContext(),
2255 Importer.getNonEquivalentDecls());
2256 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2259 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2260 EnumConstantDecl *ToEC)
2262 const llvm::APSInt &FromVal = FromEC->getInitVal();
2263 const llvm::APSInt &ToVal = ToEC->getInitVal();
2265 return FromVal.isSigned() == ToVal.isSigned() &&
2266 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2270 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2271 ClassTemplateDecl *To) {
2272 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2273 Importer.getToContext(),
2274 Importer.getNonEquivalentDecls());
2275 return Ctx.IsStructurallyEquivalent(From, To);
2278 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2279 VarTemplateDecl *To) {
2280 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2281 Importer.getToContext(),
2282 Importer.getNonEquivalentDecls());
2283 return Ctx.IsStructurallyEquivalent(From, To);
2286 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2287 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2288 << D->getDeclKindName();
2292 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2293 TranslationUnitDecl *ToD =
2294 Importer.getToContext().getTranslationUnitDecl();
2296 Importer.Imported(D, ToD);
2301 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2302 // Import the major distinguishing characteristics of this namespace.
2303 DeclContext *DC, *LexicalDC;
2304 DeclarationName Name;
2307 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2312 NamespaceDecl *MergeWithNamespace = nullptr;
2314 // This is an anonymous namespace. Adopt an existing anonymous
2315 // namespace if we can.
2316 // FIXME: Not testable.
2317 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2318 MergeWithNamespace = TU->getAnonymousNamespace();
2320 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2322 SmallVector<NamedDecl *, 4> ConflictingDecls;
2323 SmallVector<NamedDecl *, 2> FoundDecls;
2324 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2325 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2326 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2329 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2330 MergeWithNamespace = FoundNS;
2331 ConflictingDecls.clear();
2335 ConflictingDecls.push_back(FoundDecls[I]);
2338 if (!ConflictingDecls.empty()) {
2339 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2340 ConflictingDecls.data(),
2341 ConflictingDecls.size());
2345 // Create the "to" namespace, if needed.
2346 NamespaceDecl *ToNamespace = MergeWithNamespace;
2348 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2350 Importer.Import(D->getLocStart()),
2351 Loc, Name.getAsIdentifierInfo(),
2352 /*PrevDecl=*/nullptr);
2353 ToNamespace->setLexicalDeclContext(LexicalDC);
2354 LexicalDC->addDeclInternal(ToNamespace);
2356 // If this is an anonymous namespace, register it as the anonymous
2357 // namespace within its context.
2359 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2360 TU->setAnonymousNamespace(ToNamespace);
2362 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2365 Importer.Imported(D, ToNamespace);
2367 ImportDeclContext(D);
2372 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2373 // Import the major distinguishing characteristics of this typedef.
2374 DeclContext *DC, *LexicalDC;
2375 DeclarationName Name;
2378 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2383 // If this typedef is not in block scope, determine whether we've
2384 // seen a typedef with the same name (that we can merge with) or any
2385 // other entity by that name (which name lookup could conflict with).
2386 if (!DC->isFunctionOrMethod()) {
2387 SmallVector<NamedDecl *, 4> ConflictingDecls;
2388 unsigned IDNS = Decl::IDNS_Ordinary;
2389 SmallVector<NamedDecl *, 2> FoundDecls;
2390 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2391 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2392 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2394 if (TypedefNameDecl *FoundTypedef =
2395 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2396 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2397 FoundTypedef->getUnderlyingType()))
2398 return Importer.Imported(D, FoundTypedef);
2401 ConflictingDecls.push_back(FoundDecls[I]);
2404 if (!ConflictingDecls.empty()) {
2405 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2406 ConflictingDecls.data(),
2407 ConflictingDecls.size());
2413 // Import the underlying type of this typedef;
2414 QualType T = Importer.Import(D->getUnderlyingType());
2418 // Create the new typedef node.
2419 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2420 SourceLocation StartL = Importer.Import(D->getLocStart());
2421 TypedefNameDecl *ToTypedef;
2423 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2425 Name.getAsIdentifierInfo(),
2428 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2430 Name.getAsIdentifierInfo(),
2433 ToTypedef->setAccess(D->getAccess());
2434 ToTypedef->setLexicalDeclContext(LexicalDC);
2435 Importer.Imported(D, ToTypedef);
2436 LexicalDC->addDeclInternal(ToTypedef);
2441 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2442 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2445 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2446 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2449 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2450 // Import the major distinguishing characteristics of this enum.
2451 DeclContext *DC, *LexicalDC;
2452 DeclarationName Name;
2455 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2460 // Figure out what enum name we're looking for.
2461 unsigned IDNS = Decl::IDNS_Tag;
2462 DeclarationName SearchName = Name;
2463 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2464 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2465 IDNS = Decl::IDNS_Ordinary;
2466 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2467 IDNS |= Decl::IDNS_Ordinary;
2469 // We may already have an enum of the same name; try to find and match it.
2470 if (!DC->isFunctionOrMethod() && SearchName) {
2471 SmallVector<NamedDecl *, 4> ConflictingDecls;
2472 SmallVector<NamedDecl *, 2> FoundDecls;
2473 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2474 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2475 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2478 Decl *Found = FoundDecls[I];
2479 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2480 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2481 Found = Tag->getDecl();
2484 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2485 if (IsStructuralMatch(D, FoundEnum))
2486 return Importer.Imported(D, FoundEnum);
2489 ConflictingDecls.push_back(FoundDecls[I]);
2492 if (!ConflictingDecls.empty()) {
2493 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2494 ConflictingDecls.data(),
2495 ConflictingDecls.size());
2499 // Create the enum declaration.
2500 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2501 Importer.Import(D->getLocStart()),
2502 Loc, Name.getAsIdentifierInfo(), nullptr,
2503 D->isScoped(), D->isScopedUsingClassTag(),
2505 // Import the qualifier, if any.
2506 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2507 D2->setAccess(D->getAccess());
2508 D2->setLexicalDeclContext(LexicalDC);
2509 Importer.Imported(D, D2);
2510 LexicalDC->addDeclInternal(D2);
2512 // Import the integer type.
2513 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2514 if (ToIntegerType.isNull())
2516 D2->setIntegerType(ToIntegerType);
2518 // Import the definition
2519 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2525 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2526 // If this record has a definition in the translation unit we're coming from,
2527 // but this particular declaration is not that definition, import the
2528 // definition and map to that.
2529 TagDecl *Definition = D->getDefinition();
2530 if (Definition && Definition != D) {
2531 Decl *ImportedDef = Importer.Import(Definition);
2535 return Importer.Imported(D, ImportedDef);
2538 // Import the major distinguishing characteristics of this record.
2539 DeclContext *DC, *LexicalDC;
2540 DeclarationName Name;
2543 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2548 // Figure out what structure name we're looking for.
2549 unsigned IDNS = Decl::IDNS_Tag;
2550 DeclarationName SearchName = Name;
2551 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2552 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2553 IDNS = Decl::IDNS_Ordinary;
2554 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2555 IDNS |= Decl::IDNS_Ordinary;
2557 // We may already have a record of the same name; try to find and match it.
2558 RecordDecl *AdoptDecl = nullptr;
2559 if (!DC->isFunctionOrMethod()) {
2560 SmallVector<NamedDecl *, 4> ConflictingDecls;
2561 SmallVector<NamedDecl *, 2> FoundDecls;
2562 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2563 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2564 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2567 Decl *Found = FoundDecls[I];
2568 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2569 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2570 Found = Tag->getDecl();
2573 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2574 if (D->isAnonymousStructOrUnion() &&
2575 FoundRecord->isAnonymousStructOrUnion()) {
2576 // If both anonymous structs/unions are in a record context, make sure
2577 // they occur in the same location in the context records.
2578 if (Optional<unsigned> Index1
2579 = findAnonymousStructOrUnionIndex(D)) {
2580 if (Optional<unsigned> Index2 =
2581 findAnonymousStructOrUnionIndex(FoundRecord)) {
2582 if (*Index1 != *Index2)
2588 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2589 if ((SearchName && !D->isCompleteDefinition())
2590 || (D->isCompleteDefinition() &&
2591 D->isAnonymousStructOrUnion()
2592 == FoundDef->isAnonymousStructOrUnion() &&
2593 IsStructuralMatch(D, FoundDef))) {
2594 // The record types structurally match, or the "from" translation
2595 // unit only had a forward declaration anyway; call it the same
2597 // FIXME: For C++, we should also merge methods here.
2598 return Importer.Imported(D, FoundDef);
2600 } else if (!D->isCompleteDefinition()) {
2601 // We have a forward declaration of this type, so adopt that forward
2602 // declaration rather than building a new one.
2604 // If one or both can be completed from external storage then try one
2605 // last time to complete and compare them before doing this.
2607 if (FoundRecord->hasExternalLexicalStorage() &&
2608 !FoundRecord->isCompleteDefinition())
2609 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2610 if (D->hasExternalLexicalStorage())
2611 D->getASTContext().getExternalSource()->CompleteType(D);
2613 if (FoundRecord->isCompleteDefinition() &&
2614 D->isCompleteDefinition() &&
2615 !IsStructuralMatch(D, FoundRecord))
2618 AdoptDecl = FoundRecord;
2620 } else if (!SearchName) {
2625 ConflictingDecls.push_back(FoundDecls[I]);
2628 if (!ConflictingDecls.empty() && SearchName) {
2629 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2630 ConflictingDecls.data(),
2631 ConflictingDecls.size());
2635 // Create the record declaration.
2636 RecordDecl *D2 = AdoptDecl;
2637 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2639 if (isa<CXXRecordDecl>(D)) {
2640 CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2643 Name.getAsIdentifierInfo());
2645 D2->setAccess(D->getAccess());
2647 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2648 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2651 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2652 D2->setLexicalDeclContext(LexicalDC);
2653 LexicalDC->addDeclInternal(D2);
2654 if (D->isAnonymousStructOrUnion())
2655 D2->setAnonymousStructOrUnion(true);
2658 Importer.Imported(D, D2);
2660 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2666 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2667 // Import the major distinguishing characteristics of this enumerator.
2668 DeclContext *DC, *LexicalDC;
2669 DeclarationName Name;
2672 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2677 QualType T = Importer.Import(D->getType());
2681 // Determine whether there are any other declarations with the same name and
2682 // in the same context.
2683 if (!LexicalDC->isFunctionOrMethod()) {
2684 SmallVector<NamedDecl *, 4> ConflictingDecls;
2685 unsigned IDNS = Decl::IDNS_Ordinary;
2686 SmallVector<NamedDecl *, 2> FoundDecls;
2687 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2688 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2689 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2692 if (EnumConstantDecl *FoundEnumConstant
2693 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2694 if (IsStructuralMatch(D, FoundEnumConstant))
2695 return Importer.Imported(D, FoundEnumConstant);
2698 ConflictingDecls.push_back(FoundDecls[I]);
2701 if (!ConflictingDecls.empty()) {
2702 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2703 ConflictingDecls.data(),
2704 ConflictingDecls.size());
2710 Expr *Init = Importer.Import(D->getInitExpr());
2711 if (D->getInitExpr() && !Init)
2714 EnumConstantDecl *ToEnumerator
2715 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2716 Name.getAsIdentifierInfo(), T,
2717 Init, D->getInitVal());
2718 ToEnumerator->setAccess(D->getAccess());
2719 ToEnumerator->setLexicalDeclContext(LexicalDC);
2720 Importer.Imported(D, ToEnumerator);
2721 LexicalDC->addDeclInternal(ToEnumerator);
2722 return ToEnumerator;
2725 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2726 // Import the major distinguishing characteristics of this function.
2727 DeclContext *DC, *LexicalDC;
2728 DeclarationName Name;
2731 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2736 // Try to find a function in our own ("to") context with the same name, same
2737 // type, and in the same context as the function we're importing.
2738 if (!LexicalDC->isFunctionOrMethod()) {
2739 SmallVector<NamedDecl *, 4> ConflictingDecls;
2740 unsigned IDNS = Decl::IDNS_Ordinary;
2741 SmallVector<NamedDecl *, 2> FoundDecls;
2742 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2743 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2744 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2747 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2748 if (FoundFunction->hasExternalFormalLinkage() &&
2749 D->hasExternalFormalLinkage()) {
2750 if (Importer.IsStructurallyEquivalent(D->getType(),
2751 FoundFunction->getType())) {
2752 // FIXME: Actually try to merge the body and other attributes.
2753 return Importer.Imported(D, FoundFunction);
2756 // FIXME: Check for overloading more carefully, e.g., by boosting
2757 // Sema::IsOverload out to the AST library.
2759 // Function overloading is okay in C++.
2760 if (Importer.getToContext().getLangOpts().CPlusPlus)
2763 // Complain about inconsistent function types.
2764 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2765 << Name << D->getType() << FoundFunction->getType();
2766 Importer.ToDiag(FoundFunction->getLocation(),
2767 diag::note_odr_value_here)
2768 << FoundFunction->getType();
2772 ConflictingDecls.push_back(FoundDecls[I]);
2775 if (!ConflictingDecls.empty()) {
2776 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2777 ConflictingDecls.data(),
2778 ConflictingDecls.size());
2784 DeclarationNameInfo NameInfo(Name, Loc);
2785 // Import additional name location/type info.
2786 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2788 QualType FromTy = D->getType();
2789 bool usedDifferentExceptionSpec = false;
2791 if (const FunctionProtoType *
2792 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2793 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2794 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2795 // FunctionDecl that we are importing the FunctionProtoType for.
2796 // To avoid an infinite recursion when importing, create the FunctionDecl
2797 // with a simplified function type and update it afterwards.
2798 if (FromEPI.ExceptionSpec.SourceDecl ||
2799 FromEPI.ExceptionSpec.SourceTemplate ||
2800 FromEPI.ExceptionSpec.NoexceptExpr) {
2801 FunctionProtoType::ExtProtoInfo DefaultEPI;
2802 FromTy = Importer.getFromContext().getFunctionType(
2803 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2804 usedDifferentExceptionSpec = true;
2809 QualType T = Importer.Import(FromTy);
2813 // Import the function parameters.
2814 SmallVector<ParmVarDecl *, 8> Parameters;
2815 for (auto P : D->params()) {
2816 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2820 Parameters.push_back(ToP);
2823 // Create the imported function.
2824 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2825 FunctionDecl *ToFunction = nullptr;
2826 SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2827 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2828 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2829 cast<CXXRecordDecl>(DC),
2832 FromConstructor->isExplicit(),
2833 D->isInlineSpecified(),
2836 } else if (isa<CXXDestructorDecl>(D)) {
2837 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2838 cast<CXXRecordDecl>(DC),
2841 D->isInlineSpecified(),
2843 } else if (CXXConversionDecl *FromConversion
2844 = dyn_cast<CXXConversionDecl>(D)) {
2845 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2846 cast<CXXRecordDecl>(DC),
2849 D->isInlineSpecified(),
2850 FromConversion->isExplicit(),
2852 Importer.Import(D->getLocEnd()));
2853 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2854 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2855 cast<CXXRecordDecl>(DC),
2858 Method->getStorageClass(),
2859 Method->isInlineSpecified(),
2861 Importer.Import(D->getLocEnd()));
2863 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2865 NameInfo, T, TInfo, D->getStorageClass(),
2866 D->isInlineSpecified(),
2867 D->hasWrittenPrototype(),
2871 // Import the qualifier, if any.
2872 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2873 ToFunction->setAccess(D->getAccess());
2874 ToFunction->setLexicalDeclContext(LexicalDC);
2875 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2876 ToFunction->setTrivial(D->isTrivial());
2877 ToFunction->setPure(D->isPure());
2878 Importer.Imported(D, ToFunction);
2880 // Set the parameters.
2881 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2882 Parameters[I]->setOwningFunction(ToFunction);
2883 ToFunction->addDeclInternal(Parameters[I]);
2885 ToFunction->setParams(Parameters);
2887 if (usedDifferentExceptionSpec) {
2888 // Update FunctionProtoType::ExtProtoInfo.
2889 QualType T = Importer.Import(D->getType());
2892 ToFunction->setType(T);
2895 // Import the body, if any.
2896 if (Stmt *FromBody = D->getBody()) {
2897 if (Stmt *ToBody = Importer.Import(FromBody)) {
2898 ToFunction->setBody(ToBody);
2902 // FIXME: Other bits to merge?
2904 // Add this function to the lexical context.
2905 LexicalDC->addDeclInternal(ToFunction);
2910 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2911 return VisitFunctionDecl(D);
2914 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2915 return VisitCXXMethodDecl(D);
2918 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2919 return VisitCXXMethodDecl(D);
2922 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2923 return VisitCXXMethodDecl(D);
2926 static unsigned getFieldIndex(Decl *F) {
2927 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2932 for (const auto *D : Owner->noload_decls()) {
2936 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2943 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2944 // Import the major distinguishing characteristics of a variable.
2945 DeclContext *DC, *LexicalDC;
2946 DeclarationName Name;
2949 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2954 // Determine whether we've already imported this field.
2955 SmallVector<NamedDecl *, 2> FoundDecls;
2956 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2957 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2958 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2959 // For anonymous fields, match up by index.
2960 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2963 if (Importer.IsStructurallyEquivalent(D->getType(),
2964 FoundField->getType())) {
2965 Importer.Imported(D, FoundField);
2969 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2970 << Name << D->getType() << FoundField->getType();
2971 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2972 << FoundField->getType();
2978 QualType T = Importer.Import(D->getType());
2982 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2983 Expr *BitWidth = Importer.Import(D->getBitWidth());
2984 if (!BitWidth && D->getBitWidth())
2987 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2988 Importer.Import(D->getInnerLocStart()),
2989 Loc, Name.getAsIdentifierInfo(),
2990 T, TInfo, BitWidth, D->isMutable(),
2991 D->getInClassInitStyle());
2992 ToField->setAccess(D->getAccess());
2993 ToField->setLexicalDeclContext(LexicalDC);
2994 if (ToField->hasInClassInitializer())
2995 ToField->setInClassInitializer(D->getInClassInitializer());
2996 ToField->setImplicit(D->isImplicit());
2997 Importer.Imported(D, ToField);
2998 LexicalDC->addDeclInternal(ToField);
3002 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3003 // Import the major distinguishing characteristics of a variable.
3004 DeclContext *DC, *LexicalDC;
3005 DeclarationName Name;
3008 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3013 // Determine whether we've already imported this field.
3014 SmallVector<NamedDecl *, 2> FoundDecls;
3015 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3016 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3017 if (IndirectFieldDecl *FoundField
3018 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3019 // For anonymous indirect fields, match up by index.
3020 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3023 if (Importer.IsStructurallyEquivalent(D->getType(),
3024 FoundField->getType(),
3026 Importer.Imported(D, FoundField);
3030 // If there are more anonymous fields to check, continue.
3031 if (!Name && I < N-1)
3034 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3035 << Name << D->getType() << FoundField->getType();
3036 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3037 << FoundField->getType();
3043 QualType T = Importer.Import(D->getType());
3047 NamedDecl **NamedChain =
3048 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3051 for (auto *PI : D->chain()) {
3052 Decl *D = Importer.Import(PI);
3055 NamedChain[i++] = cast<NamedDecl>(D);
3058 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3059 Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3060 NamedChain, D->getChainingSize());
3062 for (const auto *Attr : D->attrs())
3063 ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3065 ToIndirectField->setAccess(D->getAccess());
3066 ToIndirectField->setLexicalDeclContext(LexicalDC);
3067 Importer.Imported(D, ToIndirectField);
3068 LexicalDC->addDeclInternal(ToIndirectField);
3069 return ToIndirectField;
3072 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3073 // Import the major distinguishing characteristics of an ivar.
3074 DeclContext *DC, *LexicalDC;
3075 DeclarationName Name;
3078 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3083 // Determine whether we've already imported this ivar
3084 SmallVector<NamedDecl *, 2> FoundDecls;
3085 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3086 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3087 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3088 if (Importer.IsStructurallyEquivalent(D->getType(),
3089 FoundIvar->getType())) {
3090 Importer.Imported(D, FoundIvar);
3094 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3095 << Name << D->getType() << FoundIvar->getType();
3096 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3097 << FoundIvar->getType();
3103 QualType T = Importer.Import(D->getType());
3107 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3108 Expr *BitWidth = Importer.Import(D->getBitWidth());
3109 if (!BitWidth && D->getBitWidth())
3112 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3113 cast<ObjCContainerDecl>(DC),
3114 Importer.Import(D->getInnerLocStart()),
3115 Loc, Name.getAsIdentifierInfo(),
3116 T, TInfo, D->getAccessControl(),
3117 BitWidth, D->getSynthesize());
3118 ToIvar->setLexicalDeclContext(LexicalDC);
3119 Importer.Imported(D, ToIvar);
3120 LexicalDC->addDeclInternal(ToIvar);
3125 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3126 // Import the major distinguishing characteristics of a variable.
3127 DeclContext *DC, *LexicalDC;
3128 DeclarationName Name;
3131 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3136 // Try to find a variable in our own ("to") context with the same name and
3137 // in the same context as the variable we're importing.
3138 if (D->isFileVarDecl()) {
3139 VarDecl *MergeWithVar = nullptr;
3140 SmallVector<NamedDecl *, 4> ConflictingDecls;
3141 unsigned IDNS = Decl::IDNS_Ordinary;
3142 SmallVector<NamedDecl *, 2> FoundDecls;
3143 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3144 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3145 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3148 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3149 // We have found a variable that we may need to merge with. Check it.
3150 if (FoundVar->hasExternalFormalLinkage() &&
3151 D->hasExternalFormalLinkage()) {
3152 if (Importer.IsStructurallyEquivalent(D->getType(),
3153 FoundVar->getType())) {
3154 MergeWithVar = FoundVar;
3158 const ArrayType *FoundArray
3159 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3160 const ArrayType *TArray
3161 = Importer.getToContext().getAsArrayType(D->getType());
3162 if (FoundArray && TArray) {
3163 if (isa<IncompleteArrayType>(FoundArray) &&
3164 isa<ConstantArrayType>(TArray)) {
3166 QualType T = Importer.Import(D->getType());
3170 FoundVar->setType(T);
3171 MergeWithVar = FoundVar;
3173 } else if (isa<IncompleteArrayType>(TArray) &&
3174 isa<ConstantArrayType>(FoundArray)) {
3175 MergeWithVar = FoundVar;
3180 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3181 << Name << D->getType() << FoundVar->getType();
3182 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3183 << FoundVar->getType();
3187 ConflictingDecls.push_back(FoundDecls[I]);
3191 // An equivalent variable with external linkage has been found. Link
3192 // the two declarations, then merge them.
3193 Importer.Imported(D, MergeWithVar);
3195 if (VarDecl *DDef = D->getDefinition()) {
3196 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3197 Importer.ToDiag(ExistingDef->getLocation(),
3198 diag::err_odr_variable_multiple_def)
3200 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3202 Expr *Init = Importer.Import(DDef->getInit());
3203 MergeWithVar->setInit(Init);
3204 if (DDef->isInitKnownICE()) {
3205 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3206 Eval->CheckedICE = true;
3207 Eval->IsICE = DDef->isInitICE();
3212 return MergeWithVar;
3215 if (!ConflictingDecls.empty()) {
3216 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3217 ConflictingDecls.data(),
3218 ConflictingDecls.size());
3225 QualType T = Importer.Import(D->getType());
3229 // Create the imported variable.
3230 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3231 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3232 Importer.Import(D->getInnerLocStart()),
3233 Loc, Name.getAsIdentifierInfo(),
3235 D->getStorageClass());
3236 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3237 ToVar->setAccess(D->getAccess());
3238 ToVar->setLexicalDeclContext(LexicalDC);
3239 Importer.Imported(D, ToVar);
3240 LexicalDC->addDeclInternal(ToVar);
3242 if (!D->isFileVarDecl() &&
3246 // Merge the initializer.
3247 if (ImportDefinition(D, ToVar))
3253 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3254 // Parameters are created in the translation unit's context, then moved
3255 // into the function declaration's context afterward.
3256 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3258 // Import the name of this declaration.
3259 DeclarationName Name = Importer.Import(D->getDeclName());
3260 if (D->getDeclName() && !Name)
3263 // Import the location of this declaration.
3264 SourceLocation Loc = Importer.Import(D->getLocation());
3266 // Import the parameter's type.
3267 QualType T = Importer.Import(D->getType());
3271 // Create the imported parameter.
3272 ImplicitParamDecl *ToParm
3273 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3274 Loc, Name.getAsIdentifierInfo(),
3276 return Importer.Imported(D, ToParm);
3279 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3280 // Parameters are created in the translation unit's context, then moved
3281 // into the function declaration's context afterward.
3282 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3284 // Import the name of this declaration.
3285 DeclarationName Name = Importer.Import(D->getDeclName());
3286 if (D->getDeclName() && !Name)
3289 // Import the location of this declaration.
3290 SourceLocation Loc = Importer.Import(D->getLocation());
3292 // Import the parameter's type.
3293 QualType T = Importer.Import(D->getType());
3297 // Create the imported parameter.
3298 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3299 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3300 Importer.Import(D->getInnerLocStart()),
3301 Loc, Name.getAsIdentifierInfo(),
3302 T, TInfo, D->getStorageClass(),
3303 /*FIXME: Default argument*/nullptr);
3304 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3307 ToParm->setIsUsed();
3309 return Importer.Imported(D, ToParm);
3312 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3313 // Import the major distinguishing characteristics of a method.
3314 DeclContext *DC, *LexicalDC;
3315 DeclarationName Name;
3318 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3323 SmallVector<NamedDecl *, 2> FoundDecls;
3324 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3325 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3326 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3327 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3330 // Check return types.
3331 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3332 FoundMethod->getReturnType())) {
3333 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3334 << D->isInstanceMethod() << Name << D->getReturnType()
3335 << FoundMethod->getReturnType();
3336 Importer.ToDiag(FoundMethod->getLocation(),
3337 diag::note_odr_objc_method_here)
3338 << D->isInstanceMethod() << Name;
3342 // Check the number of parameters.
3343 if (D->param_size() != FoundMethod->param_size()) {
3344 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3345 << D->isInstanceMethod() << Name
3346 << D->param_size() << FoundMethod->param_size();
3347 Importer.ToDiag(FoundMethod->getLocation(),
3348 diag::note_odr_objc_method_here)
3349 << D->isInstanceMethod() << Name;
3353 // Check parameter types.
3354 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3355 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3356 P != PEnd; ++P, ++FoundP) {
3357 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3358 (*FoundP)->getType())) {
3359 Importer.FromDiag((*P)->getLocation(),
3360 diag::err_odr_objc_method_param_type_inconsistent)
3361 << D->isInstanceMethod() << Name
3362 << (*P)->getType() << (*FoundP)->getType();
3363 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3364 << (*FoundP)->getType();
3369 // Check variadic/non-variadic.
3370 // Check the number of parameters.
3371 if (D->isVariadic() != FoundMethod->isVariadic()) {
3372 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3373 << D->isInstanceMethod() << Name;
3374 Importer.ToDiag(FoundMethod->getLocation(),
3375 diag::note_odr_objc_method_here)
3376 << D->isInstanceMethod() << Name;
3380 // FIXME: Any other bits we need to merge?
3381 return Importer.Imported(D, FoundMethod);
3385 // Import the result type.
3386 QualType ResultTy = Importer.Import(D->getReturnType());
3387 if (ResultTy.isNull())
3390 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3392 ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3393 Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3394 Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3395 D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3396 D->getImplementationControl(), D->hasRelatedResultType());
3398 // FIXME: When we decide to merge method definitions, we'll need to
3399 // deal with implicit parameters.
3401 // Import the parameters
3402 SmallVector<ParmVarDecl *, 5> ToParams;
3403 for (auto *FromP : D->params()) {
3404 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3408 ToParams.push_back(ToP);
3411 // Set the parameters.
3412 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3413 ToParams[I]->setOwningFunction(ToMethod);
3414 ToMethod->addDeclInternal(ToParams[I]);
3416 SmallVector<SourceLocation, 12> SelLocs;
3417 D->getSelectorLocs(SelLocs);
3418 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3420 ToMethod->setLexicalDeclContext(LexicalDC);
3421 Importer.Imported(D, ToMethod);
3422 LexicalDC->addDeclInternal(ToMethod);
3426 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3427 // Import the major distinguishing characteristics of a category.
3428 DeclContext *DC, *LexicalDC;
3429 DeclarationName Name;
3432 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3437 ObjCInterfaceDecl *ToInterface
3438 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3442 // Determine if we've already encountered this category.
3443 ObjCCategoryDecl *MergeWithCategory
3444 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3445 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3447 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3448 Importer.Import(D->getAtStartLoc()),
3450 Importer.Import(D->getCategoryNameLoc()),
3451 Name.getAsIdentifierInfo(),
3453 Importer.Import(D->getIvarLBraceLoc()),
3454 Importer.Import(D->getIvarRBraceLoc()));
3455 ToCategory->setLexicalDeclContext(LexicalDC);
3456 LexicalDC->addDeclInternal(ToCategory);
3457 Importer.Imported(D, ToCategory);
3460 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3461 SmallVector<SourceLocation, 4> ProtocolLocs;
3462 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3463 = D->protocol_loc_begin();
3464 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3465 FromProtoEnd = D->protocol_end();
3466 FromProto != FromProtoEnd;
3467 ++FromProto, ++FromProtoLoc) {
3468 ObjCProtocolDecl *ToProto
3469 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3472 Protocols.push_back(ToProto);
3473 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3476 // FIXME: If we're merging, make sure that the protocol list is the same.
3477 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3478 ProtocolLocs.data(), Importer.getToContext());
3481 Importer.Imported(D, ToCategory);
3484 // Import all of the members of this category.
3485 ImportDeclContext(D);
3487 // If we have an implementation, import it as well.
3488 if (D->getImplementation()) {
3489 ObjCCategoryImplDecl *Impl
3490 = cast_or_null<ObjCCategoryImplDecl>(
3491 Importer.Import(D->getImplementation()));
3495 ToCategory->setImplementation(Impl);
3501 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3502 ObjCProtocolDecl *To,
3503 ImportDefinitionKind Kind) {
3504 if (To->getDefinition()) {
3505 if (shouldForceImportDeclContext(Kind))
3506 ImportDeclContext(From);
3510 // Start the protocol definition
3511 To->startDefinition();
3514 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3515 SmallVector<SourceLocation, 4> ProtocolLocs;
3516 ObjCProtocolDecl::protocol_loc_iterator
3517 FromProtoLoc = From->protocol_loc_begin();
3518 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3519 FromProtoEnd = From->protocol_end();
3520 FromProto != FromProtoEnd;
3521 ++FromProto, ++FromProtoLoc) {
3522 ObjCProtocolDecl *ToProto
3523 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3526 Protocols.push_back(ToProto);
3527 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3530 // FIXME: If we're merging, make sure that the protocol list is the same.
3531 To->setProtocolList(Protocols.data(), Protocols.size(),
3532 ProtocolLocs.data(), Importer.getToContext());
3534 if (shouldForceImportDeclContext(Kind)) {
3535 // Import all of the members of this protocol.
3536 ImportDeclContext(From, /*ForceImport=*/true);
3541 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3542 // If this protocol has a definition in the translation unit we're coming
3543 // from, but this particular declaration is not that definition, import the
3544 // definition and map to that.
3545 ObjCProtocolDecl *Definition = D->getDefinition();
3546 if (Definition && Definition != D) {
3547 Decl *ImportedDef = Importer.Import(Definition);
3551 return Importer.Imported(D, ImportedDef);
3554 // Import the major distinguishing characteristics of a protocol.
3555 DeclContext *DC, *LexicalDC;
3556 DeclarationName Name;
3559 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3564 ObjCProtocolDecl *MergeWithProtocol = nullptr;
3565 SmallVector<NamedDecl *, 2> FoundDecls;
3566 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3567 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3568 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3571 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3575 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3577 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3578 Name.getAsIdentifierInfo(), Loc,
3579 Importer.Import(D->getAtStartLoc()),
3580 /*PrevDecl=*/nullptr);
3581 ToProto->setLexicalDeclContext(LexicalDC);
3582 LexicalDC->addDeclInternal(ToProto);
3585 Importer.Imported(D, ToProto);
3587 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3593 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3594 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3595 DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3597 SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3598 SourceLocation LangLoc = Importer.Import(D->getLocation());
3600 bool HasBraces = D->hasBraces();
3602 LinkageSpecDecl *ToLinkageSpec =
3603 LinkageSpecDecl::Create(Importer.getToContext(),
3611 SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3612 ToLinkageSpec->setRBraceLoc(RBraceLoc);
3615 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3616 LexicalDC->addDeclInternal(ToLinkageSpec);
3618 Importer.Imported(D, ToLinkageSpec);
3620 return ToLinkageSpec;
3623 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3624 ObjCInterfaceDecl *To,
3625 ImportDefinitionKind Kind) {
3626 if (To->getDefinition()) {
3627 // Check consistency of superclass.
3628 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3630 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3635 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3636 if ((bool)FromSuper != (bool)ToSuper ||
3637 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3638 Importer.ToDiag(To->getLocation(),
3639 diag::err_odr_objc_superclass_inconsistent)
3640 << To->getDeclName();
3642 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3643 << To->getSuperClass()->getDeclName();
3645 Importer.ToDiag(To->getLocation(),
3646 diag::note_odr_objc_missing_superclass);
3647 if (From->getSuperClass())
3648 Importer.FromDiag(From->getSuperClassLoc(),
3649 diag::note_odr_objc_superclass)
3650 << From->getSuperClass()->getDeclName();
3652 Importer.FromDiag(From->getLocation(),
3653 diag::note_odr_objc_missing_superclass);
3656 if (shouldForceImportDeclContext(Kind))
3657 ImportDeclContext(From);
3661 // Start the definition.
3662 To->startDefinition();
3664 // If this class has a superclass, import it.
3665 if (From->getSuperClass()) {
3666 ObjCInterfaceDecl *Super = cast_or_null<ObjCInterfaceDecl>(
3667 Importer.Import(From->getSuperClass()));
3671 To->setSuperClass(Super);
3672 To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
3676 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3677 SmallVector<SourceLocation, 4> ProtocolLocs;
3678 ObjCInterfaceDecl::protocol_loc_iterator
3679 FromProtoLoc = From->protocol_loc_begin();
3681 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3682 FromProtoEnd = From->protocol_end();
3683 FromProto != FromProtoEnd;
3684 ++FromProto, ++FromProtoLoc) {
3685 ObjCProtocolDecl *ToProto
3686 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3689 Protocols.push_back(ToProto);
3690 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3693 // FIXME: If we're merging, make sure that the protocol list is the same.
3694 To->setProtocolList(Protocols.data(), Protocols.size(),
3695 ProtocolLocs.data(), Importer.getToContext());
3697 // Import categories. When the categories themselves are imported, they'll
3698 // hook themselves into this interface.
3699 for (auto *Cat : From->known_categories())
3700 Importer.Import(Cat);
3702 // If we have an @implementation, import it as well.
3703 if (From->getImplementation()) {
3704 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3705 Importer.Import(From->getImplementation()));
3709 To->setImplementation(Impl);
3712 if (shouldForceImportDeclContext(Kind)) {
3713 // Import all of the members of this class.
3714 ImportDeclContext(From, /*ForceImport=*/true);
3719 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3720 // If this class has a definition in the translation unit we're coming from,
3721 // but this particular declaration is not that definition, import the
3722 // definition and map to that.
3723 ObjCInterfaceDecl *Definition = D->getDefinition();
3724 if (Definition && Definition != D) {
3725 Decl *ImportedDef = Importer.Import(Definition);
3729 return Importer.Imported(D, ImportedDef);
3732 // Import the major distinguishing characteristics of an @interface.
3733 DeclContext *DC, *LexicalDC;
3734 DeclarationName Name;
3737 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3742 // Look for an existing interface with the same name.
3743 ObjCInterfaceDecl *MergeWithIface = nullptr;
3744 SmallVector<NamedDecl *, 2> FoundDecls;
3745 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3746 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3747 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3750 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3754 // Create an interface declaration, if one does not already exist.
3755 ObjCInterfaceDecl *ToIface = MergeWithIface;
3757 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3758 Importer.Import(D->getAtStartLoc()),
3759 Name.getAsIdentifierInfo(),
3760 /*PrevDecl=*/nullptr, Loc,
3761 D->isImplicitInterfaceDecl());
3762 ToIface->setLexicalDeclContext(LexicalDC);
3763 LexicalDC->addDeclInternal(ToIface);
3765 Importer.Imported(D, ToIface);
3767 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3773 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3774 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3775 Importer.Import(D->getCategoryDecl()));
3779 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3781 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3785 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3786 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3787 Importer.Import(D->getIdentifier()),
3788 Category->getClassInterface(),
3789 Importer.Import(D->getLocation()),
3790 Importer.Import(D->getAtStartLoc()),
3793 DeclContext *LexicalDC = DC;
3794 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3795 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3799 ToImpl->setLexicalDeclContext(LexicalDC);
3802 LexicalDC->addDeclInternal(ToImpl);
3803 Category->setImplementation(ToImpl);
3806 Importer.Imported(D, ToImpl);
3807 ImportDeclContext(D);
3811 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3812 // Find the corresponding interface.
3813 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3814 Importer.Import(D->getClassInterface()));
3818 // Import the superclass, if any.
3819 ObjCInterfaceDecl *Super = nullptr;
3820 if (D->getSuperClass()) {
3821 Super = cast_or_null<ObjCInterfaceDecl>(
3822 Importer.Import(D->getSuperClass()));
3827 ObjCImplementationDecl *Impl = Iface->getImplementation();
3829 // We haven't imported an implementation yet. Create a new @implementation
3831 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3832 Importer.ImportContext(D->getDeclContext()),
3834 Importer.Import(D->getLocation()),
3835 Importer.Import(D->getAtStartLoc()),
3836 Importer.Import(D->getSuperClassLoc()),
3837 Importer.Import(D->getIvarLBraceLoc()),
3838 Importer.Import(D->getIvarRBraceLoc()));
3840 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3841 DeclContext *LexicalDC
3842 = Importer.ImportContext(D->getLexicalDeclContext());
3845 Impl->setLexicalDeclContext(LexicalDC);
3848 // Associate the implementation with the class it implements.
3849 Iface->setImplementation(Impl);
3850 Importer.Imported(D, Iface->getImplementation());
3852 Importer.Imported(D, Iface->getImplementation());
3854 // Verify that the existing @implementation has the same superclass.
3855 if ((Super && !Impl->getSuperClass()) ||
3856 (!Super && Impl->getSuperClass()) ||
3857 (Super && Impl->getSuperClass() &&
3858 !declaresSameEntity(Super->getCanonicalDecl(),
3859 Impl->getSuperClass()))) {
3860 Importer.ToDiag(Impl->getLocation(),
3861 diag::err_odr_objc_superclass_inconsistent)
3862 << Iface->getDeclName();
3863 // FIXME: It would be nice to have the location of the superclass
3865 if (Impl->getSuperClass())
3866 Importer.ToDiag(Impl->getLocation(),
3867 diag::note_odr_objc_superclass)
3868 << Impl->getSuperClass()->getDeclName();
3870 Importer.ToDiag(Impl->getLocation(),
3871 diag::note_odr_objc_missing_superclass);
3872 if (D->getSuperClass())
3873 Importer.FromDiag(D->getLocation(),
3874 diag::note_odr_objc_superclass)
3875 << D->getSuperClass()->getDeclName();
3877 Importer.FromDiag(D->getLocation(),
3878 diag::note_odr_objc_missing_superclass);
3883 // Import all of the members of this @implementation.
3884 ImportDeclContext(D);
3889 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3890 // Import the major distinguishing characteristics of an @property.
3891 DeclContext *DC, *LexicalDC;
3892 DeclarationName Name;
3895 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3900 // Check whether we have already imported this property.
3901 SmallVector<NamedDecl *, 2> FoundDecls;
3902 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3903 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3904 if (ObjCPropertyDecl *FoundProp
3905 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3906 // Check property types.
3907 if (!Importer.IsStructurallyEquivalent(D->getType(),
3908 FoundProp->getType())) {
3909 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3910 << Name << D->getType() << FoundProp->getType();
3911 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3912 << FoundProp->getType();
3916 // FIXME: Check property attributes, getters, setters, etc.?
3918 // Consider these properties to be equivalent.
3919 Importer.Imported(D, FoundProp);
3925 TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
3929 // Create the new property.
3930 ObjCPropertyDecl *ToProperty
3931 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3932 Name.getAsIdentifierInfo(),
3933 Importer.Import(D->getAtLoc()),
3934 Importer.Import(D->getLParenLoc()),
3935 Importer.Import(D->getType()),
3937 D->getPropertyImplementation());
3938 Importer.Imported(D, ToProperty);
3939 ToProperty->setLexicalDeclContext(LexicalDC);
3940 LexicalDC->addDeclInternal(ToProperty);
3942 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3943 ToProperty->setPropertyAttributesAsWritten(
3944 D->getPropertyAttributesAsWritten());
3945 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
3946 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
3947 ToProperty->setGetterMethodDecl(
3948 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3949 ToProperty->setSetterMethodDecl(
3950 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3951 ToProperty->setPropertyIvarDecl(
3952 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3956 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3957 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3958 Importer.Import(D->getPropertyDecl()));
3962 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3966 // Import the lexical declaration context.
3967 DeclContext *LexicalDC = DC;
3968 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3969 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3974 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3978 // Import the ivar (for an @synthesize).
3979 ObjCIvarDecl *Ivar = nullptr;
3980 if (D->getPropertyIvarDecl()) {
3981 Ivar = cast_or_null<ObjCIvarDecl>(
3982 Importer.Import(D->getPropertyIvarDecl()));
3987 ObjCPropertyImplDecl *ToImpl
3988 = InImpl->FindPropertyImplDecl(Property->getIdentifier());
3990 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3991 Importer.Import(D->getLocStart()),
3992 Importer.Import(D->getLocation()),
3994 D->getPropertyImplementation(),
3996 Importer.Import(D->getPropertyIvarDeclLoc()));
3997 ToImpl->setLexicalDeclContext(LexicalDC);
3998 Importer.Imported(D, ToImpl);
3999 LexicalDC->addDeclInternal(ToImpl);
4001 // Check that we have the same kind of property implementation (@synthesize
4003 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4004 Importer.ToDiag(ToImpl->getLocation(),
4005 diag::err_odr_objc_property_impl_kind_inconsistent)
4006 << Property->getDeclName()
4007 << (ToImpl->getPropertyImplementation()
4008 == ObjCPropertyImplDecl::Dynamic);
4009 Importer.FromDiag(D->getLocation(),
4010 diag::note_odr_objc_property_impl_kind)
4011 << D->getPropertyDecl()->getDeclName()
4012 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4016 // For @synthesize, check that we have the same
4017 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4018 Ivar != ToImpl->getPropertyIvarDecl()) {
4019 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4020 diag::err_odr_objc_synthesize_ivar_inconsistent)
4021 << Property->getDeclName()
4022 << ToImpl->getPropertyIvarDecl()->getDeclName()
4023 << Ivar->getDeclName();
4024 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4025 diag::note_odr_objc_synthesize_ivar_here)
4026 << D->getPropertyIvarDecl()->getDeclName();
4030 // Merge the existing implementation with the new implementation.
4031 Importer.Imported(D, ToImpl);
4037 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4038 // For template arguments, we adopt the translation unit as our declaration
4039 // context. This context will be fixed when the actual template declaration
4042 // FIXME: Import default argument.
4043 return TemplateTypeParmDecl::Create(Importer.getToContext(),
4044 Importer.getToContext().getTranslationUnitDecl(),
4045 Importer.Import(D->getLocStart()),
4046 Importer.Import(D->getLocation()),
4049 Importer.Import(D->getIdentifier()),
4050 D->wasDeclaredWithTypename(),
4051 D->isParameterPack());
4055 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4056 // Import the name of this declaration.
4057 DeclarationName Name = Importer.Import(D->getDeclName());
4058 if (D->getDeclName() && !Name)
4061 // Import the location of this declaration.
4062 SourceLocation Loc = Importer.Import(D->getLocation());
4064 // Import the type of this declaration.
4065 QualType T = Importer.Import(D->getType());
4069 // Import type-source information.
4070 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4071 if (D->getTypeSourceInfo() && !TInfo)
4074 // FIXME: Import default argument.
4076 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4077 Importer.getToContext().getTranslationUnitDecl(),
4078 Importer.Import(D->getInnerLocStart()),
4079 Loc, D->getDepth(), D->getPosition(),
4080 Name.getAsIdentifierInfo(),
4081 T, D->isParameterPack(), TInfo);
4085 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4086 // Import the name of this declaration.
4087 DeclarationName Name = Importer.Import(D->getDeclName());
4088 if (D->getDeclName() && !Name)
4091 // Import the location of this declaration.
4092 SourceLocation Loc = Importer.Import(D->getLocation());
4094 // Import template parameters.
4095 TemplateParameterList *TemplateParams
4096 = ImportTemplateParameterList(D->getTemplateParameters());
4097 if (!TemplateParams)
4100 // FIXME: Import default argument.
4102 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
4103 Importer.getToContext().getTranslationUnitDecl(),
4104 Loc, D->getDepth(), D->getPosition(),
4105 D->isParameterPack(),
4106 Name.getAsIdentifierInfo(),
4110 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4111 // If this record has a definition in the translation unit we're coming from,
4112 // but this particular declaration is not that definition, import the
4113 // definition and map to that.
4114 CXXRecordDecl *Definition
4115 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4116 if (Definition && Definition != D->getTemplatedDecl()) {
4118 = Importer.Import(Definition->getDescribedClassTemplate());
4122 return Importer.Imported(D, ImportedDef);
4125 // Import the major distinguishing characteristics of this class template.
4126 DeclContext *DC, *LexicalDC;
4127 DeclarationName Name;
4130 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4135 // We may already have a template of the same name; try to find and match it.
4136 if (!DC->isFunctionOrMethod()) {
4137 SmallVector<NamedDecl *, 4> ConflictingDecls;
4138 SmallVector<NamedDecl *, 2> FoundDecls;
4139 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4140 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4141 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4144 Decl *Found = FoundDecls[I];
4145 if (ClassTemplateDecl *FoundTemplate
4146 = dyn_cast<ClassTemplateDecl>(Found)) {
4147 if (IsStructuralMatch(D, FoundTemplate)) {
4148 // The class templates structurally match; call it the same template.
4149 // FIXME: We may be filling in a forward declaration here. Handle
4151 Importer.Imported(D->getTemplatedDecl(),
4152 FoundTemplate->getTemplatedDecl());
4153 return Importer.Imported(D, FoundTemplate);
4157 ConflictingDecls.push_back(FoundDecls[I]);
4160 if (!ConflictingDecls.empty()) {
4161 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4162 ConflictingDecls.data(),
4163 ConflictingDecls.size());
4170 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4172 // Create the declaration that is being templated.
4173 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4174 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4175 CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4176 DTemplated->getTagKind(),
4177 DC, StartLoc, IdLoc,
4178 Name.getAsIdentifierInfo());
4179 D2Templated->setAccess(DTemplated->getAccess());
4180 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4181 D2Templated->setLexicalDeclContext(LexicalDC);
4183 // Create the class template declaration itself.
4184 TemplateParameterList *TemplateParams
4185 = ImportTemplateParameterList(D->getTemplateParameters());
4186 if (!TemplateParams)
4189 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4190 Loc, Name, TemplateParams,
4192 /*PrevDecl=*/nullptr);
4193 D2Templated->setDescribedClassTemplate(D2);
4195 D2->setAccess(D->getAccess());
4196 D2->setLexicalDeclContext(LexicalDC);
4197 LexicalDC->addDeclInternal(D2);
4199 // Note the relationship between the class templates.
4200 Importer.Imported(D, D2);
4201 Importer.Imported(DTemplated, D2Templated);
4203 if (DTemplated->isCompleteDefinition() &&
4204 !D2Templated->isCompleteDefinition()) {
4205 // FIXME: Import definition!
4211 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4212 ClassTemplateSpecializationDecl *D) {
4213 // If this record has a definition in the translation unit we're coming from,
4214 // but this particular declaration is not that definition, import the
4215 // definition and map to that.
4216 TagDecl *Definition = D->getDefinition();
4217 if (Definition && Definition != D) {
4218 Decl *ImportedDef = Importer.Import(Definition);
4222 return Importer.Imported(D, ImportedDef);
4225 ClassTemplateDecl *ClassTemplate
4226 = cast_or_null<ClassTemplateDecl>(Importer.Import(
4227 D->getSpecializedTemplate()));
4231 // Import the context of this declaration.
4232 DeclContext *DC = ClassTemplate->getDeclContext();
4236 DeclContext *LexicalDC = DC;
4237 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4238 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4243 // Import the location of this declaration.
4244 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4245 SourceLocation IdLoc = Importer.Import(D->getLocation());
4247 // Import template arguments.
4248 SmallVector<TemplateArgument, 2> TemplateArgs;
4249 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4250 D->getTemplateArgs().size(),
4254 // Try to find an existing specialization with these template arguments.
4255 void *InsertPos = nullptr;
4256 ClassTemplateSpecializationDecl *D2
4257 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4259 // We already have a class template specialization with these template
4262 // FIXME: Check for specialization vs. instantiation errors.
4264 if (RecordDecl *FoundDef = D2->getDefinition()) {
4265 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4266 // The record types structurally match, or the "from" translation
4267 // unit only had a forward declaration anyway; call it the same
4269 return Importer.Imported(D, FoundDef);
4273 // Create a new specialization.
4274 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4275 D->getTagKind(), DC,
4278 TemplateArgs.data(),
4279 TemplateArgs.size(),
4280 /*PrevDecl=*/nullptr);
4281 D2->setSpecializationKind(D->getSpecializationKind());
4283 // Add this specialization to the class template.
4284 ClassTemplate->AddSpecialization(D2, InsertPos);
4286 // Import the qualifier, if any.
4287 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4289 // Add the specialization to this context.
4290 D2->setLexicalDeclContext(LexicalDC);
4291 LexicalDC->addDeclInternal(D2);
4293 Importer.Imported(D, D2);
4295 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4301 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4302 // If this variable has a definition in the translation unit we're coming
4304 // but this particular declaration is not that definition, import the
4305 // definition and map to that.
4306 VarDecl *Definition =
4307 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4308 if (Definition && Definition != D->getTemplatedDecl()) {
4309 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4313 return Importer.Imported(D, ImportedDef);
4316 // Import the major distinguishing characteristics of this variable template.
4317 DeclContext *DC, *LexicalDC;
4318 DeclarationName Name;
4321 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4326 // We may already have a template of the same name; try to find and match it.
4327 assert(!DC->isFunctionOrMethod() &&
4328 "Variable templates cannot be declared at function scope");
4329 SmallVector<NamedDecl *, 4> ConflictingDecls;
4330 SmallVector<NamedDecl *, 2> FoundDecls;
4331 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4332 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4333 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4336 Decl *Found = FoundDecls[I];
4337 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4338 if (IsStructuralMatch(D, FoundTemplate)) {
4339 // The variable templates structurally match; call it the same template.
4340 Importer.Imported(D->getTemplatedDecl(),
4341 FoundTemplate->getTemplatedDecl());
4342 return Importer.Imported(D, FoundTemplate);
4346 ConflictingDecls.push_back(FoundDecls[I]);
4349 if (!ConflictingDecls.empty()) {
4350 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4351 ConflictingDecls.data(),
4352 ConflictingDecls.size());
4358 VarDecl *DTemplated = D->getTemplatedDecl();
4361 QualType T = Importer.Import(DTemplated->getType());
4365 // Create the declaration that is being templated.
4366 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4367 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4368 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4369 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4370 IdLoc, Name.getAsIdentifierInfo(), T,
4371 TInfo, DTemplated->getStorageClass());
4372 D2Templated->setAccess(DTemplated->getAccess());
4373 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4374 D2Templated->setLexicalDeclContext(LexicalDC);
4376 // Importer.Imported(DTemplated, D2Templated);
4377 // LexicalDC->addDeclInternal(D2Templated);
4379 // Merge the initializer.
4380 if (ImportDefinition(DTemplated, D2Templated))
4383 // Create the variable template declaration itself.
4384 TemplateParameterList *TemplateParams =
4385 ImportTemplateParameterList(D->getTemplateParameters());
4386 if (!TemplateParams)
4389 VarTemplateDecl *D2 = VarTemplateDecl::Create(
4390 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4391 D2Templated->setDescribedVarTemplate(D2);
4393 D2->setAccess(D->getAccess());
4394 D2->setLexicalDeclContext(LexicalDC);
4395 LexicalDC->addDeclInternal(D2);
4397 // Note the relationship between the variable templates.
4398 Importer.Imported(D, D2);
4399 Importer.Imported(DTemplated, D2Templated);
4401 if (DTemplated->isThisDeclarationADefinition() &&
4402 !D2Templated->isThisDeclarationADefinition()) {
4403 // FIXME: Import definition!
4409 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4410 VarTemplateSpecializationDecl *D) {
4411 // If this record has a definition in the translation unit we're coming from,
4412 // but this particular declaration is not that definition, import the
4413 // definition and map to that.
4414 VarDecl *Definition = D->getDefinition();
4415 if (Definition && Definition != D) {
4416 Decl *ImportedDef = Importer.Import(Definition);
4420 return Importer.Imported(D, ImportedDef);
4423 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4424 Importer.Import(D->getSpecializedTemplate()));
4428 // Import the context of this declaration.
4429 DeclContext *DC = VarTemplate->getDeclContext();
4433 DeclContext *LexicalDC = DC;
4434 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4435 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4440 // Import the location of this declaration.
4441 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4442 SourceLocation IdLoc = Importer.Import(D->getLocation());
4444 // Import template arguments.
4445 SmallVector<TemplateArgument, 2> TemplateArgs;
4446 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4447 D->getTemplateArgs().size(), TemplateArgs))
4450 // Try to find an existing specialization with these template arguments.
4451 void *InsertPos = nullptr;
4452 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4453 TemplateArgs, InsertPos);
4455 // We already have a variable template specialization with these template
4458 // FIXME: Check for specialization vs. instantiation errors.
4460 if (VarDecl *FoundDef = D2->getDefinition()) {
4461 if (!D->isThisDeclarationADefinition() ||
4462 IsStructuralMatch(D, FoundDef)) {
4463 // The record types structurally match, or the "from" translation
4464 // unit only had a forward declaration anyway; call it the same
4466 return Importer.Imported(D, FoundDef);
4472 QualType T = Importer.Import(D->getType());
4475 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4477 // Create a new specialization.
4478 D2 = VarTemplateSpecializationDecl::Create(
4479 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4480 D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4481 D2->setSpecializationKind(D->getSpecializationKind());
4482 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4484 // Add this specialization to the class template.
4485 VarTemplate->AddSpecialization(D2, InsertPos);
4487 // Import the qualifier, if any.
4488 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4490 // Add the specialization to this context.
4491 D2->setLexicalDeclContext(LexicalDC);
4492 LexicalDC->addDeclInternal(D2);
4494 Importer.Imported(D, D2);
4496 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4502 //----------------------------------------------------------------------------
4503 // Import Statements
4504 //----------------------------------------------------------------------------
4506 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4508 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4509 size_t NumDecls = DG.end() - DG.begin();
4510 SmallVector<Decl *, 1> ToDecls(NumDecls);
4511 auto &_Importer = this->Importer;
4512 std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4513 [&_Importer](Decl *D) -> Decl * {
4514 return _Importer.Import(D);
4516 return DeclGroupRef::Create(Importer.getToContext(),
4521 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4522 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4523 << S->getStmtClassName();
4527 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4528 DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4529 for (Decl *ToD : ToDG) {
4533 SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4534 SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4535 return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4538 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4539 SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4540 return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4541 S->hasLeadingEmptyMacro());
4544 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4545 SmallVector<Stmt *, 4> ToStmts(S->size());
4546 auto &_Importer = this->Importer;
4547 std::transform(S->body_begin(), S->body_end(), ToStmts.begin(),
4548 [&_Importer](Stmt *CS) -> Stmt * {
4549 return _Importer.Import(CS);
4551 for (Stmt *ToS : ToStmts) {
4555 SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4556 SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4557 return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
4559 ToLBraceLoc, ToRBraceLoc);
4562 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4563 Expr *ToLHS = Importer.Import(S->getLHS());
4566 Expr *ToRHS = Importer.Import(S->getRHS());
4567 if (!ToRHS && S->getRHS())
4569 SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4570 SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4571 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4572 return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
4573 ToCaseLoc, ToEllipsisLoc,
4577 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4578 SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4579 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4580 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4581 if (!ToSubStmt && S->getSubStmt())
4583 return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4587 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4588 SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4589 LabelDecl *ToLabelDecl =
4590 cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4591 if (!ToLabelDecl && S->getDecl())
4593 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4594 if (!ToSubStmt && S->getSubStmt())
4596 return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4600 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4601 SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4602 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4603 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4604 ASTContext &_ToContext = Importer.getToContext();
4605 std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4606 [&_ToContext](const Attr *A) -> const Attr * {
4607 return A->clone(_ToContext);
4609 for (const Attr *ToA : ToAttrs) {
4613 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4614 if (!ToSubStmt && S->getSubStmt())
4616 return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4617 ToAttrs, ToSubStmt);
4620 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4621 SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4622 VarDecl *ToConditionVariable = nullptr;
4623 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4624 ToConditionVariable =
4625 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4626 if (!ToConditionVariable)
4629 Expr *ToCondition = Importer.Import(S->getCond());
4630 if (!ToCondition && S->getCond())
4632 Stmt *ToThenStmt = Importer.Import(S->getThen());
4633 if (!ToThenStmt && S->getThen())
4635 SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4636 Stmt *ToElseStmt = Importer.Import(S->getElse());
4637 if (!ToElseStmt && S->getElse())
4639 return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4640 ToIfLoc, ToConditionVariable,
4641 ToCondition, ToThenStmt,
4642 ToElseLoc, ToElseStmt);
4645 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4646 VarDecl *ToConditionVariable = nullptr;
4647 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4648 ToConditionVariable =
4649 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4650 if (!ToConditionVariable)
4653 Expr *ToCondition = Importer.Import(S->getCond());
4654 if (!ToCondition && S->getCond())
4656 SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
4657 Importer.getToContext(), ToConditionVariable,
4659 Stmt *ToBody = Importer.Import(S->getBody());
4660 if (!ToBody && S->getBody())
4662 ToStmt->setBody(ToBody);
4663 ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
4664 // Now we have to re-chain the cases.
4665 SwitchCase *LastChainedSwitchCase = nullptr;
4666 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
4667 SC = SC->getNextSwitchCase()) {
4668 SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
4671 if (LastChainedSwitchCase)
4672 LastChainedSwitchCase->setNextSwitchCase(ToSC);
4674 ToStmt->setSwitchCaseList(ToSC);
4675 LastChainedSwitchCase = ToSC;
4680 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
4681 VarDecl *ToConditionVariable = nullptr;
4682 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4683 ToConditionVariable =
4684 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4685 if (!ToConditionVariable)
4688 Expr *ToCondition = Importer.Import(S->getCond());
4689 if (!ToCondition && S->getCond())
4691 Stmt *ToBody = Importer.Import(S->getBody());
4692 if (!ToBody && S->getBody())
4694 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4695 return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
4696 ToConditionVariable,
4697 ToCondition, ToBody,
4701 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
4702 Stmt *ToBody = Importer.Import(S->getBody());
4703 if (!ToBody && S->getBody())
4705 Expr *ToCondition = Importer.Import(S->getCond());
4706 if (!ToCondition && S->getCond())
4708 SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
4709 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4710 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4711 return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
4712 ToDoLoc, ToWhileLoc,
4716 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
4717 Stmt *ToInit = Importer.Import(S->getInit());
4718 if (!ToInit && S->getInit())
4720 Expr *ToCondition = Importer.Import(S->getCond());
4721 if (!ToCondition && S->getCond())
4723 VarDecl *ToConditionVariable = nullptr;
4724 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4725 ToConditionVariable =
4726 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4727 if (!ToConditionVariable)
4730 Expr *ToInc = Importer.Import(S->getInc());
4731 if (!ToInc && S->getInc())
4733 Stmt *ToBody = Importer.Import(S->getBody());
4734 if (!ToBody && S->getBody())
4736 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4737 SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
4738 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4739 return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
4740 ToInit, ToCondition,
4741 ToConditionVariable,
4743 ToForLoc, ToLParenLoc,
4747 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
4748 LabelDecl *ToLabel = nullptr;
4749 if (LabelDecl *FromLabel = S->getLabel()) {
4750 ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
4754 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4755 SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
4756 return new (Importer.getToContext()) GotoStmt(ToLabel,
4757 ToGotoLoc, ToLabelLoc);
4760 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
4761 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4762 SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
4763 Expr *ToTarget = Importer.Import(S->getTarget());
4764 if (!ToTarget && S->getTarget())
4766 return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
4770 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
4771 SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
4772 return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
4775 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
4776 SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
4777 return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
4780 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
4781 SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
4782 Expr *ToRetExpr = Importer.Import(S->getRetValue());
4783 if (!ToRetExpr && S->getRetValue())
4785 VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
4786 VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
4787 if (!ToNRVOCandidate && NRVOCandidate)
4789 return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
4793 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
4794 SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
4795 VarDecl *ToExceptionDecl = nullptr;
4796 if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
4798 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4799 if (!ToExceptionDecl)
4802 Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
4803 if (!ToHandlerBlock && S->getHandlerBlock())
4805 return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
4810 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
4811 SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
4812 Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
4813 if (!ToTryBlock && S->getTryBlock())
4815 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
4816 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
4817 CXXCatchStmt *FromHandler = S->getHandler(HI);
4818 if (Stmt *ToHandler = Importer.Import(FromHandler))
4819 ToHandlers[HI] = ToHandler;
4823 return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
4827 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4829 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
4830 if (!ToRange && S->getRangeStmt())
4832 DeclStmt *ToBeginEnd =
4833 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginEndStmt()));
4834 if (!ToBeginEnd && S->getBeginEndStmt())
4836 Expr *ToCond = Importer.Import(S->getCond());
4837 if (!ToCond && S->getCond())
4839 Expr *ToInc = Importer.Import(S->getInc());
4840 if (!ToInc && S->getInc())
4842 DeclStmt *ToLoopVar =
4843 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
4844 if (!ToLoopVar && S->getLoopVarStmt())
4846 Stmt *ToBody = Importer.Import(S->getBody());
4847 if (!ToBody && S->getBody())
4849 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4850 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4851 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4852 return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBeginEnd,
4855 ToForLoc, ToColonLoc,
4859 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
4860 Stmt *ToElem = Importer.Import(S->getElement());
4861 if (!ToElem && S->getElement())
4863 Expr *ToCollect = Importer.Import(S->getCollection());
4864 if (!ToCollect && S->getCollection())
4866 Stmt *ToBody = Importer.Import(S->getBody());
4867 if (!ToBody && S->getBody())
4869 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4870 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4871 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
4877 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4878 SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
4879 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4880 VarDecl *ToExceptionDecl = nullptr;
4881 if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
4883 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4884 if (!ToExceptionDecl)
4887 Stmt *ToBody = Importer.Import(S->getCatchBody());
4888 if (!ToBody && S->getCatchBody())
4890 return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
4896 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
4897 SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
4898 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
4899 if (!ToAtFinallyStmt && S->getFinallyBody())
4901 return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
4905 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
4906 SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
4907 Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
4908 if (!ToAtTryStmt && S->getTryBody())
4910 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
4911 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
4912 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
4913 if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
4914 ToCatchStmts[CI] = ToCatchStmt;
4918 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
4919 if (!ToAtFinallyStmt && S->getFinallyStmt())
4921 return ObjCAtTryStmt::Create(Importer.getToContext(),
4922 ToAtTryLoc, ToAtTryStmt,
4923 ToCatchStmts.begin(), ToCatchStmts.size(),
4927 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
4928 (ObjCAtSynchronizedStmt *S) {
4929 SourceLocation ToAtSynchronizedLoc =
4930 Importer.Import(S->getAtSynchronizedLoc());
4931 Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
4932 if (!ToSynchExpr && S->getSynchExpr())
4934 Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
4935 if (!ToSynchBody && S->getSynchBody())
4937 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
4938 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
4941 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
4942 SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
4943 Expr *ToThrow = Importer.Import(S->getThrowExpr());
4944 if (!ToThrow && S->getThrowExpr())
4946 return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
4949 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
4950 (ObjCAutoreleasePoolStmt *S) {
4951 SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
4952 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4953 if (!ToSubStmt && S->getSubStmt())
4955 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
4959 //----------------------------------------------------------------------------
4960 // Import Expressions
4961 //----------------------------------------------------------------------------
4962 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
4963 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
4964 << E->getStmtClassName();
4968 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
4969 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
4973 NamedDecl *FoundD = nullptr;
4974 if (E->getDecl() != E->getFoundDecl()) {
4975 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
4980 QualType T = Importer.Import(E->getType());
4984 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
4985 Importer.Import(E->getQualifierLoc()),
4986 Importer.Import(E->getTemplateKeywordLoc()),
4988 E->refersToEnclosingVariableOrCapture(),
4989 Importer.Import(E->getLocation()),
4990 T, E->getValueKind(),
4992 /*FIXME:TemplateArgs=*/nullptr);
4993 if (E->hadMultipleCandidates())
4994 DRE->setHadMultipleCandidates(true);
4998 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
4999 QualType T = Importer.Import(E->getType());
5003 return IntegerLiteral::Create(Importer.getToContext(),
5005 Importer.Import(E->getLocation()));
5008 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5009 QualType T = Importer.Import(E->getType());
5013 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5015 Importer.Import(E->getLocation()));
5018 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5019 Expr *SubExpr = Importer.Import(E->getSubExpr());
5023 return new (Importer.getToContext())
5024 ParenExpr(Importer.Import(E->getLParen()),
5025 Importer.Import(E->getRParen()),
5029 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5030 QualType T = Importer.Import(E->getType());
5034 Expr *SubExpr = Importer.Import(E->getSubExpr());
5038 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5039 T, E->getValueKind(),
5041 Importer.Import(E->getOperatorLoc()));
5044 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5045 UnaryExprOrTypeTraitExpr *E) {
5046 QualType ResultType = Importer.Import(E->getType());
5048 if (E->isArgumentType()) {
5049 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5053 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5055 Importer.Import(E->getOperatorLoc()),
5056 Importer.Import(E->getRParenLoc()));
5059 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5063 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5064 SubExpr, ResultType,
5065 Importer.Import(E->getOperatorLoc()),
5066 Importer.Import(E->getRParenLoc()));
5069 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5070 QualType T = Importer.Import(E->getType());
5074 Expr *LHS = Importer.Import(E->getLHS());
5078 Expr *RHS = Importer.Import(E->getRHS());
5082 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5083 T, E->getValueKind(),
5085 Importer.Import(E->getOperatorLoc()),
5086 E->isFPContractable());
5089 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5090 QualType T = Importer.Import(E->getType());
5094 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5095 if (CompLHSType.isNull())
5098 QualType CompResultType = Importer.Import(E->getComputationResultType());
5099 if (CompResultType.isNull())
5102 Expr *LHS = Importer.Import(E->getLHS());
5106 Expr *RHS = Importer.Import(E->getRHS());
5110 return new (Importer.getToContext())
5111 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5112 T, E->getValueKind(),
5114 CompLHSType, CompResultType,
5115 Importer.Import(E->getOperatorLoc()),
5116 E->isFPContractable());
5119 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
5120 if (E->path_empty()) return false;
5122 // TODO: import cast paths
5126 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5127 QualType T = Importer.Import(E->getType());
5131 Expr *SubExpr = Importer.Import(E->getSubExpr());
5135 CXXCastPath BasePath;
5136 if (ImportCastPath(E, BasePath))
5139 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5140 SubExpr, &BasePath, E->getValueKind());
5143 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
5144 QualType T = Importer.Import(E->getType());
5148 Expr *SubExpr = Importer.Import(E->getSubExpr());
5152 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5153 if (!TInfo && E->getTypeInfoAsWritten())
5156 CXXCastPath BasePath;
5157 if (ImportCastPath(E, BasePath))
5160 return CStyleCastExpr::Create(Importer.getToContext(), T,
5161 E->getValueKind(), E->getCastKind(),
5162 SubExpr, &BasePath, TInfo,
5163 Importer.Import(E->getLParenLoc()),
5164 Importer.Import(E->getRParenLoc()));
5167 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5168 QualType T = Importer.Import(E->getType());
5172 CXXConstructorDecl *ToCCD =
5173 dyn_cast<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5174 if (!ToCCD && E->getConstructor())
5177 size_t NumArgs = E->getNumArgs();
5178 SmallVector<Expr *, 1> ToArgs(NumArgs);
5179 ASTImporter &_Importer = Importer;
5180 std::transform(E->arg_begin(), E->arg_end(), ToArgs.begin(),
5181 [&_Importer](Expr *AE) -> Expr * {
5182 return _Importer.Import(AE);
5184 for (Expr *ToA : ToArgs) {
5189 return CXXConstructExpr::Create(Importer.getToContext(), T,
5190 Importer.Import(E->getLocation()),
5191 ToCCD, E->isElidable(),
5192 ToArgs, E->hadMultipleCandidates(),
5193 E->isListInitialization(),
5194 E->isStdInitListInitialization(),
5195 E->requiresZeroInitialization(),
5196 E->getConstructionKind(),
5197 Importer.Import(E->getParenOrBraceRange()));
5200 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5201 QualType T = Importer.Import(E->getType());
5205 Expr *ToBase = Importer.Import(E->getBase());
5206 if (!ToBase && E->getBase())
5209 ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5210 if (!ToMember && E->getMemberDecl())
5213 DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5214 dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5215 E->getFoundDecl().getAccess());
5217 DeclarationNameInfo ToMemberNameInfo(
5218 Importer.Import(E->getMemberNameInfo().getName()),
5219 Importer.Import(E->getMemberNameInfo().getLoc()));
5221 if (E->hasExplicitTemplateArgs()) {
5222 return nullptr; // FIXME: handle template arguments
5225 return MemberExpr::Create(Importer.getToContext(), ToBase,
5227 Importer.Import(E->getOperatorLoc()),
5228 Importer.Import(E->getQualifierLoc()),
5229 Importer.Import(E->getTemplateKeywordLoc()),
5230 ToMember, ToFoundDecl, ToMemberNameInfo,
5231 nullptr, T, E->getValueKind(),
5232 E->getObjectKind());
5235 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5236 QualType T = Importer.Import(E->getType());
5240 Expr *ToCallee = Importer.Import(E->getCallee());
5241 if (!ToCallee && E->getCallee())
5244 unsigned NumArgs = E->getNumArgs();
5246 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5248 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5249 Expr *FromArg = E->getArg(ai);
5250 Expr *ToArg = Importer.Import(FromArg);
5256 Expr **ToArgs_Copied = new (Importer.getToContext())
5259 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5260 ToArgs_Copied[ai] = ToArgs[ai];
5262 return new (Importer.getToContext())
5263 CallExpr(Importer.getToContext(), ToCallee,
5264 ArrayRef<Expr*>(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5265 Importer.Import(E->getRParenLoc()));
5268 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
5269 ASTContext &FromContext, FileManager &FromFileManager,
5271 : ToContext(ToContext), FromContext(FromContext),
5272 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
5273 Minimal(MinimalImport), LastDiagFromFrom(false)
5275 ImportedDecls[FromContext.getTranslationUnitDecl()]
5276 = ToContext.getTranslationUnitDecl();
5279 ASTImporter::~ASTImporter() { }
5281 QualType ASTImporter::Import(QualType FromT) {
5285 const Type *fromTy = FromT.getTypePtr();
5287 // Check whether we've already imported this type.
5288 llvm::DenseMap<const Type *, const Type *>::iterator Pos
5289 = ImportedTypes.find(fromTy);
5290 if (Pos != ImportedTypes.end())
5291 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
5294 ASTNodeImporter Importer(*this);
5295 QualType ToT = Importer.Visit(fromTy);
5299 // Record the imported type.
5300 ImportedTypes[fromTy] = ToT.getTypePtr();
5302 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
5305 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
5309 // FIXME: For now we just create a "trivial" type source info based
5310 // on the type and a single location. Implement a real version of this.
5311 QualType T = Import(FromTSI->getType());
5315 return ToContext.getTrivialTypeSourceInfo(T,
5316 FromTSI->getTypeLoc().getLocStart());
5319 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
5320 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5321 if (Pos != ImportedDecls.end()) {
5322 Decl *ToD = Pos->second;
5323 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
5330 Decl *ASTImporter::Import(Decl *FromD) {
5334 ASTNodeImporter Importer(*this);
5336 // Check whether we've already imported this declaration.
5337 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5338 if (Pos != ImportedDecls.end()) {
5339 Decl *ToD = Pos->second;
5340 Importer.ImportDefinitionIfNeeded(FromD, ToD);
5345 Decl *ToD = Importer.Visit(FromD);
5349 // Record the imported declaration.
5350 ImportedDecls[FromD] = ToD;
5352 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
5353 // Keep track of anonymous tags that have an associated typedef.
5354 if (FromTag->getTypedefNameForAnonDecl())
5355 AnonTagsWithPendingTypedefs.push_back(FromTag);
5356 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
5357 // When we've finished transforming a typedef, see whether it was the
5358 // typedef for an anonymous tag.
5359 for (SmallVectorImpl<TagDecl *>::iterator
5360 FromTag = AnonTagsWithPendingTypedefs.begin(),
5361 FromTagEnd = AnonTagsWithPendingTypedefs.end();
5362 FromTag != FromTagEnd; ++FromTag) {
5363 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
5364 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
5365 // We found the typedef for an anonymous tag; link them.
5366 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
5367 AnonTagsWithPendingTypedefs.erase(FromTag);
5377 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
5381 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
5385 // When we're using a record/enum/Objective-C class/protocol as a context, we
5386 // need it to have a definition.
5387 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
5388 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
5389 if (ToRecord->isCompleteDefinition()) {
5391 } else if (FromRecord->isCompleteDefinition()) {
5392 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
5393 ASTNodeImporter::IDK_Basic);
5395 CompleteDecl(ToRecord);
5397 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
5398 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
5399 if (ToEnum->isCompleteDefinition()) {
5401 } else if (FromEnum->isCompleteDefinition()) {
5402 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
5403 ASTNodeImporter::IDK_Basic);
5405 CompleteDecl(ToEnum);
5407 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
5408 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
5409 if (ToClass->getDefinition()) {
5411 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
5412 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
5413 ASTNodeImporter::IDK_Basic);
5415 CompleteDecl(ToClass);
5417 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
5418 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
5419 if (ToProto->getDefinition()) {
5421 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
5422 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
5423 ASTNodeImporter::IDK_Basic);
5425 CompleteDecl(ToProto);
5432 Expr *ASTImporter::Import(Expr *FromE) {
5436 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
5439 Stmt *ASTImporter::Import(Stmt *FromS) {
5443 // Check whether we've already imported this declaration.
5444 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
5445 if (Pos != ImportedStmts.end())
5449 ASTNodeImporter Importer(*this);
5450 Stmt *ToS = Importer.Visit(FromS);
5454 // Record the imported declaration.
5455 ImportedStmts[FromS] = ToS;
5459 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
5463 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
5465 switch (FromNNS->getKind()) {
5466 case NestedNameSpecifier::Identifier:
5467 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
5468 return NestedNameSpecifier::Create(ToContext, prefix, II);
5472 case NestedNameSpecifier::Namespace:
5473 if (NamespaceDecl *NS =
5474 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
5475 return NestedNameSpecifier::Create(ToContext, prefix, NS);
5479 case NestedNameSpecifier::NamespaceAlias:
5480 if (NamespaceAliasDecl *NSAD =
5481 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
5482 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
5486 case NestedNameSpecifier::Global:
5487 return NestedNameSpecifier::GlobalSpecifier(ToContext);
5489 case NestedNameSpecifier::Super:
5490 if (CXXRecordDecl *RD =
5491 cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
5492 return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
5496 case NestedNameSpecifier::TypeSpec:
5497 case NestedNameSpecifier::TypeSpecWithTemplate: {
5498 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
5500 bool bTemplate = FromNNS->getKind() ==
5501 NestedNameSpecifier::TypeSpecWithTemplate;
5502 return NestedNameSpecifier::Create(ToContext, prefix,
5503 bTemplate, T.getTypePtr());
5509 llvm_unreachable("Invalid nested name specifier kind");
5512 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
5513 // FIXME: Implement!
5514 return NestedNameSpecifierLoc();
5517 TemplateName ASTImporter::Import(TemplateName From) {
5518 switch (From.getKind()) {
5519 case TemplateName::Template:
5520 if (TemplateDecl *ToTemplate
5521 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5522 return TemplateName(ToTemplate);
5524 return TemplateName();
5526 case TemplateName::OverloadedTemplate: {
5527 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
5528 UnresolvedSet<2> ToTemplates;
5529 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
5530 E = FromStorage->end();
5532 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
5533 ToTemplates.addDecl(To);
5535 return TemplateName();
5537 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
5541 case TemplateName::QualifiedTemplate: {
5542 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
5543 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
5545 return TemplateName();
5547 if (TemplateDecl *ToTemplate
5548 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5549 return ToContext.getQualifiedTemplateName(Qualifier,
5550 QTN->hasTemplateKeyword(),
5553 return TemplateName();
5556 case TemplateName::DependentTemplate: {
5557 DependentTemplateName *DTN = From.getAsDependentTemplateName();
5558 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
5560 return TemplateName();
5562 if (DTN->isIdentifier()) {
5563 return ToContext.getDependentTemplateName(Qualifier,
5564 Import(DTN->getIdentifier()));
5567 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
5570 case TemplateName::SubstTemplateTemplateParm: {
5571 SubstTemplateTemplateParmStorage *subst
5572 = From.getAsSubstTemplateTemplateParm();
5573 TemplateTemplateParmDecl *param
5574 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
5576 return TemplateName();
5578 TemplateName replacement = Import(subst->getReplacement());
5579 if (replacement.isNull()) return TemplateName();
5581 return ToContext.getSubstTemplateTemplateParm(param, replacement);
5584 case TemplateName::SubstTemplateTemplateParmPack: {
5585 SubstTemplateTemplateParmPackStorage *SubstPack
5586 = From.getAsSubstTemplateTemplateParmPack();
5587 TemplateTemplateParmDecl *Param
5588 = cast_or_null<TemplateTemplateParmDecl>(
5589 Import(SubstPack->getParameterPack()));
5591 return TemplateName();
5593 ASTNodeImporter Importer(*this);
5594 TemplateArgument ArgPack
5595 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
5596 if (ArgPack.isNull())
5597 return TemplateName();
5599 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
5603 llvm_unreachable("Invalid template name kind");
5606 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
5607 if (FromLoc.isInvalid())
5608 return SourceLocation();
5610 SourceManager &FromSM = FromContext.getSourceManager();
5612 // For now, map everything down to its spelling location, so that we
5613 // don't have to import macro expansions.
5614 // FIXME: Import macro expansions!
5615 FromLoc = FromSM.getSpellingLoc(FromLoc);
5616 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
5617 SourceManager &ToSM = ToContext.getSourceManager();
5618 FileID ToFileID = Import(Decomposed.first);
5619 if (ToFileID.isInvalid())
5620 return SourceLocation();
5621 SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
5622 .getLocWithOffset(Decomposed.second);
5626 SourceRange ASTImporter::Import(SourceRange FromRange) {
5627 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
5630 FileID ASTImporter::Import(FileID FromID) {
5631 llvm::DenseMap<FileID, FileID>::iterator Pos
5632 = ImportedFileIDs.find(FromID);
5633 if (Pos != ImportedFileIDs.end())
5636 SourceManager &FromSM = FromContext.getSourceManager();
5637 SourceManager &ToSM = ToContext.getSourceManager();
5638 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
5639 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
5641 // Include location of this file.
5642 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
5644 // Map the FileID for to the "to" source manager.
5646 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
5647 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
5648 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
5650 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
5651 // than mmap the files several times.
5652 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
5655 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
5656 FromSLoc.getFile().getFileCharacteristic());
5658 // FIXME: We want to re-use the existing MemoryBuffer!
5659 const llvm::MemoryBuffer *
5660 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
5661 std::unique_ptr<llvm::MemoryBuffer> ToBuf
5662 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
5663 FromBuf->getBufferIdentifier());
5664 ToID = ToSM.createFileID(std::move(ToBuf),
5665 FromSLoc.getFile().getFileCharacteristic());
5669 ImportedFileIDs[FromID] = ToID;
5673 void ASTImporter::ImportDefinition(Decl *From) {
5674 Decl *To = Import(From);
5678 if (DeclContext *FromDC = cast<DeclContext>(From)) {
5679 ASTNodeImporter Importer(*this);
5681 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
5682 if (!ToRecord->getDefinition()) {
5683 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
5684 ASTNodeImporter::IDK_Everything);
5689 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
5690 if (!ToEnum->getDefinition()) {
5691 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
5692 ASTNodeImporter::IDK_Everything);
5697 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
5698 if (!ToIFace->getDefinition()) {
5699 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
5700 ASTNodeImporter::IDK_Everything);
5705 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
5706 if (!ToProto->getDefinition()) {
5707 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
5708 ASTNodeImporter::IDK_Everything);
5713 Importer.ImportDeclContext(FromDC, true);
5717 DeclarationName ASTImporter::Import(DeclarationName FromName) {
5719 return DeclarationName();
5721 switch (FromName.getNameKind()) {
5722 case DeclarationName::Identifier:
5723 return Import(FromName.getAsIdentifierInfo());
5725 case DeclarationName::ObjCZeroArgSelector:
5726 case DeclarationName::ObjCOneArgSelector:
5727 case DeclarationName::ObjCMultiArgSelector:
5728 return Import(FromName.getObjCSelector());
5730 case DeclarationName::CXXConstructorName: {
5731 QualType T = Import(FromName.getCXXNameType());
5733 return DeclarationName();
5735 return ToContext.DeclarationNames.getCXXConstructorName(
5736 ToContext.getCanonicalType(T));
5739 case DeclarationName::CXXDestructorName: {
5740 QualType T = Import(FromName.getCXXNameType());
5742 return DeclarationName();
5744 return ToContext.DeclarationNames.getCXXDestructorName(
5745 ToContext.getCanonicalType(T));
5748 case DeclarationName::CXXConversionFunctionName: {
5749 QualType T = Import(FromName.getCXXNameType());
5751 return DeclarationName();
5753 return ToContext.DeclarationNames.getCXXConversionFunctionName(
5754 ToContext.getCanonicalType(T));
5757 case DeclarationName::CXXOperatorName:
5758 return ToContext.DeclarationNames.getCXXOperatorName(
5759 FromName.getCXXOverloadedOperator());
5761 case DeclarationName::CXXLiteralOperatorName:
5762 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5763 Import(FromName.getCXXLiteralIdentifier()));
5765 case DeclarationName::CXXUsingDirective:
5767 return DeclarationName::getUsingDirectiveName();
5770 llvm_unreachable("Invalid DeclarationName Kind!");
5773 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5777 return &ToContext.Idents.get(FromId->getName());
5780 Selector ASTImporter::Import(Selector FromSel) {
5781 if (FromSel.isNull())
5784 SmallVector<IdentifierInfo *, 4> Idents;
5785 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5786 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5787 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5788 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5791 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5795 unsigned NumDecls) {
5799 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5800 if (LastDiagFromFrom)
5801 ToContext.getDiagnostics().notePriorDiagnosticFrom(
5802 FromContext.getDiagnostics());
5803 LastDiagFromFrom = false;
5804 return ToContext.getDiagnostics().Report(Loc, DiagID);
5807 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5808 if (!LastDiagFromFrom)
5809 FromContext.getDiagnostics().notePriorDiagnosticFrom(
5810 ToContext.getDiagnostics());
5811 LastDiagFromFrom = true;
5812 return FromContext.getDiagnostics().Report(Loc, DiagID);
5815 void ASTImporter::CompleteDecl (Decl *D) {
5816 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5817 if (!ID->getDefinition())
5818 ID->startDefinition();
5820 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5821 if (!PD->getDefinition())
5822 PD->startDefinition();
5824 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5825 if (!TD->getDefinition() && !TD->isBeingDefined()) {
5826 TD->startDefinition();
5827 TD->setCompleteDefinition(true);
5831 assert (0 && "CompleteDecl called on a Decl that can't be completed");
5835 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5836 ImportedDecls[From] = To;
5840 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5842 llvm::DenseMap<const Type *, const Type *>::iterator Pos
5843 = ImportedTypes.find(From.getTypePtr());
5844 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5847 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5849 return Ctx.IsStructurallyEquivalent(From, To);