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 QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
68 // FIXME: DependentDecltypeType
69 QualType VisitRecordType(const RecordType *T);
70 QualType VisitEnumType(const EnumType *T);
71 QualType VisitAttributedType(const AttributedType *T);
72 QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
73 // FIXME: SubstTemplateTypeParmType
74 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
75 QualType VisitElaboratedType(const ElaboratedType *T);
76 // FIXME: DependentNameType
77 // FIXME: DependentTemplateSpecializationType
78 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
79 QualType VisitObjCObjectType(const ObjCObjectType *T);
80 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
82 // Importing declarations
83 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
84 DeclContext *&LexicalDC, DeclarationName &Name,
85 NamedDecl *&ToD, SourceLocation &Loc);
86 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
87 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
88 DeclarationNameInfo& To);
89 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
91 typedef DesignatedInitExpr::Designator Designator;
92 Designator ImportDesignator(const Designator &D);
95 /// \brief What we should import from the definition.
96 enum ImportDefinitionKind {
97 /// \brief Import the default subset of the definition, which might be
98 /// nothing (if minimal import is set) or might be everything (if minimal
99 /// import is not set).
101 /// \brief Import everything.
103 /// \brief Import only the bare bones needed to establish a valid
108 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
109 return IDK == IDK_Everything ||
110 (IDK == IDK_Default && !Importer.isMinimalImport());
113 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
114 ImportDefinitionKind Kind = IDK_Default);
115 bool ImportDefinition(VarDecl *From, VarDecl *To,
116 ImportDefinitionKind Kind = IDK_Default);
117 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
118 ImportDefinitionKind Kind = IDK_Default);
119 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
120 ImportDefinitionKind Kind = IDK_Default);
121 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
122 ImportDefinitionKind Kind = IDK_Default);
123 TemplateParameterList *ImportTemplateParameterList(
124 TemplateParameterList *Params);
125 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
126 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
127 unsigned NumFromArgs,
128 SmallVectorImpl<TemplateArgument> &ToArgs);
129 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
130 bool Complain = true);
131 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
132 bool Complain = true);
133 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
134 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
135 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
136 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
137 Decl *VisitDecl(Decl *D);
138 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
139 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
140 Decl *VisitNamespaceDecl(NamespaceDecl *D);
141 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
142 Decl *VisitTypedefDecl(TypedefDecl *D);
143 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
144 Decl *VisitLabelDecl(LabelDecl *D);
145 Decl *VisitEnumDecl(EnumDecl *D);
146 Decl *VisitRecordDecl(RecordDecl *D);
147 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
148 Decl *VisitFunctionDecl(FunctionDecl *D);
149 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
150 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
151 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
152 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
153 Decl *VisitFieldDecl(FieldDecl *D);
154 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
155 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
156 Decl *VisitVarDecl(VarDecl *D);
157 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
158 Decl *VisitParmVarDecl(ParmVarDecl *D);
159 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
160 Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
161 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
162 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
163 Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
165 ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
166 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
167 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
168 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
169 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
170 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
171 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
172 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
173 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
174 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
175 Decl *VisitClassTemplateSpecializationDecl(
176 ClassTemplateSpecializationDecl *D);
177 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
178 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
180 // Importing statements
181 DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
183 Stmt *VisitStmt(Stmt *S);
184 Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
185 Stmt *VisitDeclStmt(DeclStmt *S);
186 Stmt *VisitNullStmt(NullStmt *S);
187 Stmt *VisitCompoundStmt(CompoundStmt *S);
188 Stmt *VisitCaseStmt(CaseStmt *S);
189 Stmt *VisitDefaultStmt(DefaultStmt *S);
190 Stmt *VisitLabelStmt(LabelStmt *S);
191 Stmt *VisitAttributedStmt(AttributedStmt *S);
192 Stmt *VisitIfStmt(IfStmt *S);
193 Stmt *VisitSwitchStmt(SwitchStmt *S);
194 Stmt *VisitWhileStmt(WhileStmt *S);
195 Stmt *VisitDoStmt(DoStmt *S);
196 Stmt *VisitForStmt(ForStmt *S);
197 Stmt *VisitGotoStmt(GotoStmt *S);
198 Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
199 Stmt *VisitContinueStmt(ContinueStmt *S);
200 Stmt *VisitBreakStmt(BreakStmt *S);
201 Stmt *VisitReturnStmt(ReturnStmt *S);
203 // FIXME: SEHExceptStmt
204 // FIXME: SEHFinallyStmt
206 // FIXME: SEHLeaveStmt
207 // FIXME: CapturedStmt
208 Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
209 Stmt *VisitCXXTryStmt(CXXTryStmt *S);
210 Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
211 // FIXME: MSDependentExistsStmt
212 Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
213 Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
214 Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
215 Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
216 Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
217 Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
218 Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
220 // Importing expressions
221 Expr *VisitExpr(Expr *E);
222 Expr *VisitVAArgExpr(VAArgExpr *E);
223 Expr *VisitGNUNullExpr(GNUNullExpr *E);
224 Expr *VisitPredefinedExpr(PredefinedExpr *E);
225 Expr *VisitDeclRefExpr(DeclRefExpr *E);
226 Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
227 Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
228 Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
229 Expr *VisitIntegerLiteral(IntegerLiteral *E);
230 Expr *VisitFloatingLiteral(FloatingLiteral *E);
231 Expr *VisitCharacterLiteral(CharacterLiteral *E);
232 Expr *VisitStringLiteral(StringLiteral *E);
233 Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
234 Expr *VisitAtomicExpr(AtomicExpr *E);
235 Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
236 Expr *VisitParenExpr(ParenExpr *E);
237 Expr *VisitParenListExpr(ParenListExpr *E);
238 Expr *VisitStmtExpr(StmtExpr *E);
239 Expr *VisitUnaryOperator(UnaryOperator *E);
240 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
241 Expr *VisitBinaryOperator(BinaryOperator *E);
242 Expr *VisitConditionalOperator(ConditionalOperator *E);
243 Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
244 Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
245 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
246 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
247 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
248 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
249 Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
250 Expr *VisitCXXThisExpr(CXXThisExpr *E);
251 Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
252 Expr *VisitMemberExpr(MemberExpr *E);
253 Expr *VisitCallExpr(CallExpr *E);
254 Expr *VisitInitListExpr(InitListExpr *E);
255 Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
256 Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
258 template<typename IIter, typename OIter>
259 void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
260 typedef typename std::remove_reference<decltype(*Obegin)>::type ItemT;
261 ASTImporter &ImporterRef = Importer;
262 std::transform(Ibegin, Iend, Obegin,
263 [&ImporterRef](ItemT From) -> ItemT {
264 return ImporterRef.Import(From);
268 template<typename IIter, typename OIter>
269 bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
270 typedef typename std::remove_reference<decltype(**Obegin)>::type ItemT;
271 ASTImporter &ImporterRef = Importer;
273 std::transform(Ibegin, Iend, Obegin,
274 [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
275 ItemT *To = ImporterRef.Import(From);
285 using namespace clang;
287 //----------------------------------------------------------------------------
288 // Structural Equivalence
289 //----------------------------------------------------------------------------
292 struct StructuralEquivalenceContext {
293 /// \brief AST contexts for which we are checking structural equivalence.
296 /// \brief The set of "tentative" equivalences between two canonical
297 /// declarations, mapping from a declaration in the first context to the
298 /// declaration in the second context that we believe to be equivalent.
299 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
301 /// \brief Queue of declarations in the first context whose equivalence
302 /// with a declaration in the second context still needs to be verified.
303 std::deque<Decl *> DeclsToCheck;
305 /// \brief Declaration (from, to) pairs that are known not to be equivalent
306 /// (which we have already complained about).
307 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
309 /// \brief Whether we're being strict about the spelling of types when
310 /// unifying two types.
311 bool StrictTypeSpelling;
313 /// \brief Whether to complain about failures.
316 /// \brief \c true if the last diagnostic came from C2.
319 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
320 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
321 bool StrictTypeSpelling = false,
322 bool Complain = true)
323 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
324 StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
325 LastDiagFromC2(false) {}
327 /// \brief Determine whether the two declarations are structurally
329 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
331 /// \brief Determine whether the two types are structurally equivalent.
332 bool IsStructurallyEquivalent(QualType T1, QualType T2);
335 /// \brief Finish checking all of the structural equivalences.
337 /// \returns true if an error occurred, false otherwise.
341 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
342 assert(Complain && "Not allowed to complain");
344 C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
345 LastDiagFromC2 = false;
346 return C1.getDiagnostics().Report(Loc, DiagID);
349 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
350 assert(Complain && "Not allowed to complain");
352 C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
353 LastDiagFromC2 = true;
354 return C2.getDiagnostics().Report(Loc, DiagID);
359 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
360 QualType T1, QualType T2);
361 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
364 /// \brief Determine structural equivalence of two expressions.
365 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
366 Expr *E1, Expr *E2) {
370 // FIXME: Actually perform a structural comparison!
374 /// \brief Determine whether two identifiers are equivalent.
375 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
376 const IdentifierInfo *Name2) {
377 if (!Name1 || !Name2)
378 return Name1 == Name2;
380 return Name1->getName() == Name2->getName();
383 /// \brief Determine whether two nested-name-specifiers are equivalent.
384 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
385 NestedNameSpecifier *NNS1,
386 NestedNameSpecifier *NNS2) {
391 /// \brief Determine whether two template arguments are equivalent.
392 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
393 const TemplateArgument &Arg1,
394 const TemplateArgument &Arg2) {
395 if (Arg1.getKind() != Arg2.getKind())
398 switch (Arg1.getKind()) {
399 case TemplateArgument::Null:
402 case TemplateArgument::Type:
403 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
405 case TemplateArgument::Integral:
406 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
407 Arg2.getIntegralType()))
410 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
412 case TemplateArgument::Declaration:
413 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
415 case TemplateArgument::NullPtr:
416 return true; // FIXME: Is this correct?
418 case TemplateArgument::Template:
419 return IsStructurallyEquivalent(Context,
420 Arg1.getAsTemplate(),
421 Arg2.getAsTemplate());
423 case TemplateArgument::TemplateExpansion:
424 return IsStructurallyEquivalent(Context,
425 Arg1.getAsTemplateOrTemplatePattern(),
426 Arg2.getAsTemplateOrTemplatePattern());
428 case TemplateArgument::Expression:
429 return IsStructurallyEquivalent(Context,
430 Arg1.getAsExpr(), Arg2.getAsExpr());
432 case TemplateArgument::Pack:
433 if (Arg1.pack_size() != Arg2.pack_size())
436 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
437 if (!IsStructurallyEquivalent(Context,
438 Arg1.pack_begin()[I],
439 Arg2.pack_begin()[I]))
445 llvm_unreachable("Invalid template argument kind");
448 /// \brief Determine structural equivalence for the common part of array
450 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
451 const ArrayType *Array1,
452 const ArrayType *Array2) {
453 if (!IsStructurallyEquivalent(Context,
454 Array1->getElementType(),
455 Array2->getElementType()))
457 if (Array1->getSizeModifier() != Array2->getSizeModifier())
459 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
465 /// \brief Determine structural equivalence of two types.
466 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
467 QualType T1, QualType T2) {
468 if (T1.isNull() || T2.isNull())
469 return T1.isNull() && T2.isNull();
471 if (!Context.StrictTypeSpelling) {
472 // We aren't being strict about token-to-token equivalence of types,
473 // so map down to the canonical type.
474 T1 = Context.C1.getCanonicalType(T1);
475 T2 = Context.C2.getCanonicalType(T2);
478 if (T1.getQualifiers() != T2.getQualifiers())
481 Type::TypeClass TC = T1->getTypeClass();
483 if (T1->getTypeClass() != T2->getTypeClass()) {
484 // Compare function types with prototypes vs. without prototypes as if
485 // both did not have prototypes.
486 if (T1->getTypeClass() == Type::FunctionProto &&
487 T2->getTypeClass() == Type::FunctionNoProto)
488 TC = Type::FunctionNoProto;
489 else if (T1->getTypeClass() == Type::FunctionNoProto &&
490 T2->getTypeClass() == Type::FunctionProto)
491 TC = Type::FunctionNoProto;
498 // FIXME: Deal with Char_S/Char_U.
499 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
504 if (!IsStructurallyEquivalent(Context,
505 cast<ComplexType>(T1)->getElementType(),
506 cast<ComplexType>(T2)->getElementType()))
512 if (!IsStructurallyEquivalent(Context,
513 cast<AdjustedType>(T1)->getOriginalType(),
514 cast<AdjustedType>(T2)->getOriginalType()))
519 if (!IsStructurallyEquivalent(Context,
520 cast<PointerType>(T1)->getPointeeType(),
521 cast<PointerType>(T2)->getPointeeType()))
525 case Type::BlockPointer:
526 if (!IsStructurallyEquivalent(Context,
527 cast<BlockPointerType>(T1)->getPointeeType(),
528 cast<BlockPointerType>(T2)->getPointeeType()))
532 case Type::LValueReference:
533 case Type::RValueReference: {
534 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
535 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
536 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
538 if (Ref1->isInnerRef() != Ref2->isInnerRef())
540 if (!IsStructurallyEquivalent(Context,
541 Ref1->getPointeeTypeAsWritten(),
542 Ref2->getPointeeTypeAsWritten()))
547 case Type::MemberPointer: {
548 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
549 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
550 if (!IsStructurallyEquivalent(Context,
551 MemPtr1->getPointeeType(),
552 MemPtr2->getPointeeType()))
554 if (!IsStructurallyEquivalent(Context,
555 QualType(MemPtr1->getClass(), 0),
556 QualType(MemPtr2->getClass(), 0)))
561 case Type::ConstantArray: {
562 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
563 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
564 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
567 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
572 case Type::IncompleteArray:
573 if (!IsArrayStructurallyEquivalent(Context,
575 cast<ArrayType>(T2)))
579 case Type::VariableArray: {
580 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
581 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
582 if (!IsStructurallyEquivalent(Context,
583 Array1->getSizeExpr(), Array2->getSizeExpr()))
586 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
592 case Type::DependentSizedArray: {
593 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
594 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
595 if (!IsStructurallyEquivalent(Context,
596 Array1->getSizeExpr(), Array2->getSizeExpr()))
599 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
605 case Type::DependentSizedExtVector: {
606 const DependentSizedExtVectorType *Vec1
607 = cast<DependentSizedExtVectorType>(T1);
608 const DependentSizedExtVectorType *Vec2
609 = cast<DependentSizedExtVectorType>(T2);
610 if (!IsStructurallyEquivalent(Context,
611 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
613 if (!IsStructurallyEquivalent(Context,
614 Vec1->getElementType(),
615 Vec2->getElementType()))
621 case Type::ExtVector: {
622 const VectorType *Vec1 = cast<VectorType>(T1);
623 const VectorType *Vec2 = cast<VectorType>(T2);
624 if (!IsStructurallyEquivalent(Context,
625 Vec1->getElementType(),
626 Vec2->getElementType()))
628 if (Vec1->getNumElements() != Vec2->getNumElements())
630 if (Vec1->getVectorKind() != Vec2->getVectorKind())
635 case Type::FunctionProto: {
636 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
637 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
638 if (Proto1->getNumParams() != Proto2->getNumParams())
640 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
641 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
642 Proto2->getParamType(I)))
645 if (Proto1->isVariadic() != Proto2->isVariadic())
647 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
649 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
650 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
652 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
653 if (!IsStructurallyEquivalent(Context,
654 Proto1->getExceptionType(I),
655 Proto2->getExceptionType(I)))
658 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
659 if (!IsStructurallyEquivalent(Context,
660 Proto1->getNoexceptExpr(),
661 Proto2->getNoexceptExpr()))
664 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
667 // Fall through to check the bits common with FunctionNoProtoType.
670 case Type::FunctionNoProto: {
671 const FunctionType *Function1 = cast<FunctionType>(T1);
672 const FunctionType *Function2 = cast<FunctionType>(T2);
673 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
674 Function2->getReturnType()))
676 if (Function1->getExtInfo() != Function2->getExtInfo())
681 case Type::UnresolvedUsing:
682 if (!IsStructurallyEquivalent(Context,
683 cast<UnresolvedUsingType>(T1)->getDecl(),
684 cast<UnresolvedUsingType>(T2)->getDecl()))
689 case Type::Attributed:
690 if (!IsStructurallyEquivalent(Context,
691 cast<AttributedType>(T1)->getModifiedType(),
692 cast<AttributedType>(T2)->getModifiedType()))
694 if (!IsStructurallyEquivalent(Context,
695 cast<AttributedType>(T1)->getEquivalentType(),
696 cast<AttributedType>(T2)->getEquivalentType()))
701 if (!IsStructurallyEquivalent(Context,
702 cast<ParenType>(T1)->getInnerType(),
703 cast<ParenType>(T2)->getInnerType()))
708 if (!IsStructurallyEquivalent(Context,
709 cast<TypedefType>(T1)->getDecl(),
710 cast<TypedefType>(T2)->getDecl()))
714 case Type::TypeOfExpr:
715 if (!IsStructurallyEquivalent(Context,
716 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
717 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
722 if (!IsStructurallyEquivalent(Context,
723 cast<TypeOfType>(T1)->getUnderlyingType(),
724 cast<TypeOfType>(T2)->getUnderlyingType()))
728 case Type::UnaryTransform:
729 if (!IsStructurallyEquivalent(Context,
730 cast<UnaryTransformType>(T1)->getUnderlyingType(),
731 cast<UnaryTransformType>(T1)->getUnderlyingType()))
736 if (!IsStructurallyEquivalent(Context,
737 cast<DecltypeType>(T1)->getUnderlyingExpr(),
738 cast<DecltypeType>(T2)->getUnderlyingExpr()))
743 if (!IsStructurallyEquivalent(Context,
744 cast<AutoType>(T1)->getDeducedType(),
745 cast<AutoType>(T2)->getDeducedType()))
751 if (!IsStructurallyEquivalent(Context,
752 cast<TagType>(T1)->getDecl(),
753 cast<TagType>(T2)->getDecl()))
757 case Type::TemplateTypeParm: {
758 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
759 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
760 if (Parm1->getDepth() != Parm2->getDepth())
762 if (Parm1->getIndex() != Parm2->getIndex())
764 if (Parm1->isParameterPack() != Parm2->isParameterPack())
767 // Names of template type parameters are never significant.
771 case Type::SubstTemplateTypeParm: {
772 const SubstTemplateTypeParmType *Subst1
773 = cast<SubstTemplateTypeParmType>(T1);
774 const SubstTemplateTypeParmType *Subst2
775 = cast<SubstTemplateTypeParmType>(T2);
776 if (!IsStructurallyEquivalent(Context,
777 QualType(Subst1->getReplacedParameter(), 0),
778 QualType(Subst2->getReplacedParameter(), 0)))
780 if (!IsStructurallyEquivalent(Context,
781 Subst1->getReplacementType(),
782 Subst2->getReplacementType()))
787 case Type::SubstTemplateTypeParmPack: {
788 const SubstTemplateTypeParmPackType *Subst1
789 = cast<SubstTemplateTypeParmPackType>(T1);
790 const SubstTemplateTypeParmPackType *Subst2
791 = cast<SubstTemplateTypeParmPackType>(T2);
792 if (!IsStructurallyEquivalent(Context,
793 QualType(Subst1->getReplacedParameter(), 0),
794 QualType(Subst2->getReplacedParameter(), 0)))
796 if (!IsStructurallyEquivalent(Context,
797 Subst1->getArgumentPack(),
798 Subst2->getArgumentPack()))
802 case Type::TemplateSpecialization: {
803 const TemplateSpecializationType *Spec1
804 = cast<TemplateSpecializationType>(T1);
805 const TemplateSpecializationType *Spec2
806 = cast<TemplateSpecializationType>(T2);
807 if (!IsStructurallyEquivalent(Context,
808 Spec1->getTemplateName(),
809 Spec2->getTemplateName()))
811 if (Spec1->getNumArgs() != Spec2->getNumArgs())
813 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
814 if (!IsStructurallyEquivalent(Context,
815 Spec1->getArg(I), Spec2->getArg(I)))
821 case Type::Elaborated: {
822 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
823 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
824 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
825 if (Elab1->getKeyword() != Elab2->getKeyword())
827 if (!IsStructurallyEquivalent(Context,
828 Elab1->getQualifier(),
829 Elab2->getQualifier()))
831 if (!IsStructurallyEquivalent(Context,
832 Elab1->getNamedType(),
833 Elab2->getNamedType()))
838 case Type::InjectedClassName: {
839 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
840 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
841 if (!IsStructurallyEquivalent(Context,
842 Inj1->getInjectedSpecializationType(),
843 Inj2->getInjectedSpecializationType()))
848 case Type::DependentName: {
849 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
850 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
851 if (!IsStructurallyEquivalent(Context,
852 Typename1->getQualifier(),
853 Typename2->getQualifier()))
855 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
856 Typename2->getIdentifier()))
862 case Type::DependentTemplateSpecialization: {
863 const DependentTemplateSpecializationType *Spec1 =
864 cast<DependentTemplateSpecializationType>(T1);
865 const DependentTemplateSpecializationType *Spec2 =
866 cast<DependentTemplateSpecializationType>(T2);
867 if (!IsStructurallyEquivalent(Context,
868 Spec1->getQualifier(),
869 Spec2->getQualifier()))
871 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
872 Spec2->getIdentifier()))
874 if (Spec1->getNumArgs() != Spec2->getNumArgs())
876 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
877 if (!IsStructurallyEquivalent(Context,
878 Spec1->getArg(I), Spec2->getArg(I)))
884 case Type::PackExpansion:
885 if (!IsStructurallyEquivalent(Context,
886 cast<PackExpansionType>(T1)->getPattern(),
887 cast<PackExpansionType>(T2)->getPattern()))
891 case Type::ObjCInterface: {
892 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
893 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
894 if (!IsStructurallyEquivalent(Context,
895 Iface1->getDecl(), Iface2->getDecl()))
900 case Type::ObjCObject: {
901 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
902 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
903 if (!IsStructurallyEquivalent(Context,
905 Obj2->getBaseType()))
907 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
909 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
910 if (!IsStructurallyEquivalent(Context,
911 Obj1->getProtocol(I),
912 Obj2->getProtocol(I)))
918 case Type::ObjCObjectPointer: {
919 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
920 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
921 if (!IsStructurallyEquivalent(Context,
922 Ptr1->getPointeeType(),
923 Ptr2->getPointeeType()))
929 if (!IsStructurallyEquivalent(Context,
930 cast<AtomicType>(T1)->getValueType(),
931 cast<AtomicType>(T2)->getValueType()))
937 if (!IsStructurallyEquivalent(Context,
938 cast<PipeType>(T1)->getElementType(),
939 cast<PipeType>(T2)->getElementType()))
949 /// \brief Determine structural equivalence of two fields.
950 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
951 FieldDecl *Field1, FieldDecl *Field2) {
952 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
954 // For anonymous structs/unions, match up the anonymous struct/union type
955 // declarations directly, so that we don't go off searching for anonymous
957 if (Field1->isAnonymousStructOrUnion() &&
958 Field2->isAnonymousStructOrUnion()) {
959 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
960 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
961 return IsStructurallyEquivalent(Context, D1, D2);
964 // Check for equivalent field names.
965 IdentifierInfo *Name1 = Field1->getIdentifier();
966 IdentifierInfo *Name2 = Field2->getIdentifier();
967 if (!::IsStructurallyEquivalent(Name1, Name2))
970 if (!IsStructurallyEquivalent(Context,
971 Field1->getType(), Field2->getType())) {
972 if (Context.Complain) {
973 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
974 << Context.C2.getTypeDeclType(Owner2);
975 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
976 << Field2->getDeclName() << Field2->getType();
977 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
978 << Field1->getDeclName() << Field1->getType();
983 if (Field1->isBitField() != Field2->isBitField()) {
984 if (Context.Complain) {
985 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
986 << Context.C2.getTypeDeclType(Owner2);
987 if (Field1->isBitField()) {
988 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
989 << Field1->getDeclName() << Field1->getType()
990 << Field1->getBitWidthValue(Context.C1);
991 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
992 << Field2->getDeclName();
994 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
995 << Field2->getDeclName() << Field2->getType()
996 << Field2->getBitWidthValue(Context.C2);
997 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
998 << Field1->getDeclName();
1004 if (Field1->isBitField()) {
1005 // Make sure that the bit-fields are the same length.
1006 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
1007 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
1009 if (Bits1 != Bits2) {
1010 if (Context.Complain) {
1011 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1012 << Context.C2.getTypeDeclType(Owner2);
1013 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
1014 << Field2->getDeclName() << Field2->getType() << Bits2;
1015 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
1016 << Field1->getDeclName() << Field1->getType() << Bits1;
1025 /// \brief Find the index of the given anonymous struct/union within its
1028 /// \returns Returns the index of this anonymous struct/union in its context,
1029 /// including the next assigned index (if none of them match). Returns an
1030 /// empty option if the context is not a record, i.e.. if the anonymous
1031 /// struct/union is at namespace or block scope.
1032 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
1033 ASTContext &Context = Anon->getASTContext();
1034 QualType AnonTy = Context.getRecordType(Anon);
1036 RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
1041 for (const auto *D : Owner->noload_decls()) {
1042 const auto *F = dyn_cast<FieldDecl>(D);
1043 if (!F || !F->isAnonymousStructOrUnion())
1046 if (Context.hasSameType(F->getType(), AnonTy))
1055 /// \brief Determine structural equivalence of two records.
1056 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1057 RecordDecl *D1, RecordDecl *D2) {
1058 if (D1->isUnion() != D2->isUnion()) {
1059 if (Context.Complain) {
1060 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1061 << Context.C2.getTypeDeclType(D2);
1062 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1063 << D1->getDeclName() << (unsigned)D1->getTagKind();
1068 if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1069 // If both anonymous structs/unions are in a record context, make sure
1070 // they occur in the same location in the context records.
1071 if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
1072 if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
1073 if (*Index1 != *Index2)
1079 // If both declarations are class template specializations, we know
1080 // the ODR applies, so check the template and template arguments.
1081 ClassTemplateSpecializationDecl *Spec1
1082 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1083 ClassTemplateSpecializationDecl *Spec2
1084 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1085 if (Spec1 && Spec2) {
1086 // Check that the specialized templates are the same.
1087 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1088 Spec2->getSpecializedTemplate()))
1091 // Check that the template arguments are the same.
1092 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1095 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1096 if (!IsStructurallyEquivalent(Context,
1097 Spec1->getTemplateArgs().get(I),
1098 Spec2->getTemplateArgs().get(I)))
1101 // If one is a class template specialization and the other is not, these
1102 // structures are different.
1103 else if (Spec1 || Spec2)
1106 // Compare the definitions of these two records. If either or both are
1107 // incomplete, we assume that they are equivalent.
1108 D1 = D1->getDefinition();
1109 D2 = D2->getDefinition();
1113 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1114 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1115 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1116 if (Context.Complain) {
1117 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1118 << Context.C2.getTypeDeclType(D2);
1119 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1120 << D2CXX->getNumBases();
1121 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1122 << D1CXX->getNumBases();
1127 // Check the base classes.
1128 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1129 BaseEnd1 = D1CXX->bases_end(),
1130 Base2 = D2CXX->bases_begin();
1133 if (!IsStructurallyEquivalent(Context,
1134 Base1->getType(), Base2->getType())) {
1135 if (Context.Complain) {
1136 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1137 << Context.C2.getTypeDeclType(D2);
1138 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1140 << Base2->getSourceRange();
1141 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1143 << Base1->getSourceRange();
1148 // Check virtual vs. non-virtual inheritance mismatch.
1149 if (Base1->isVirtual() != Base2->isVirtual()) {
1150 if (Context.Complain) {
1151 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1152 << Context.C2.getTypeDeclType(D2);
1153 Context.Diag2(Base2->getLocStart(),
1154 diag::note_odr_virtual_base)
1155 << Base2->isVirtual() << Base2->getSourceRange();
1156 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1157 << Base1->isVirtual()
1158 << Base1->getSourceRange();
1163 } else if (D1CXX->getNumBases() > 0) {
1164 if (Context.Complain) {
1165 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1166 << Context.C2.getTypeDeclType(D2);
1167 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1168 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1170 << Base1->getSourceRange();
1171 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1177 // Check the fields for consistency.
1178 RecordDecl::field_iterator Field2 = D2->field_begin(),
1179 Field2End = D2->field_end();
1180 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1181 Field1End = D1->field_end();
1182 Field1 != Field1End;
1183 ++Field1, ++Field2) {
1184 if (Field2 == Field2End) {
1185 if (Context.Complain) {
1186 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1187 << Context.C2.getTypeDeclType(D2);
1188 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1189 << Field1->getDeclName() << Field1->getType();
1190 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1195 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1199 if (Field2 != Field2End) {
1200 if (Context.Complain) {
1201 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1202 << Context.C2.getTypeDeclType(D2);
1203 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1204 << Field2->getDeclName() << Field2->getType();
1205 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1213 /// \brief Determine structural equivalence of two enums.
1214 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1215 EnumDecl *D1, EnumDecl *D2) {
1216 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1217 EC2End = D2->enumerator_end();
1218 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1219 EC1End = D1->enumerator_end();
1220 EC1 != EC1End; ++EC1, ++EC2) {
1221 if (EC2 == EC2End) {
1222 if (Context.Complain) {
1223 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1224 << Context.C2.getTypeDeclType(D2);
1225 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1226 << EC1->getDeclName()
1227 << EC1->getInitVal().toString(10);
1228 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1233 llvm::APSInt Val1 = EC1->getInitVal();
1234 llvm::APSInt Val2 = EC2->getInitVal();
1235 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1236 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1237 if (Context.Complain) {
1238 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1239 << Context.C2.getTypeDeclType(D2);
1240 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1241 << EC2->getDeclName()
1242 << EC2->getInitVal().toString(10);
1243 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1244 << EC1->getDeclName()
1245 << EC1->getInitVal().toString(10);
1251 if (EC2 != EC2End) {
1252 if (Context.Complain) {
1253 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1254 << Context.C2.getTypeDeclType(D2);
1255 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1256 << EC2->getDeclName()
1257 << EC2->getInitVal().toString(10);
1258 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1266 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1267 TemplateParameterList *Params1,
1268 TemplateParameterList *Params2) {
1269 if (Params1->size() != Params2->size()) {
1270 if (Context.Complain) {
1271 Context.Diag2(Params2->getTemplateLoc(),
1272 diag::err_odr_different_num_template_parameters)
1273 << Params1->size() << Params2->size();
1274 Context.Diag1(Params1->getTemplateLoc(),
1275 diag::note_odr_template_parameter_list);
1280 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1281 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1282 if (Context.Complain) {
1283 Context.Diag2(Params2->getParam(I)->getLocation(),
1284 diag::err_odr_different_template_parameter_kind);
1285 Context.Diag1(Params1->getParam(I)->getLocation(),
1286 diag::note_odr_template_parameter_here);
1291 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1292 Params2->getParam(I))) {
1301 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1302 TemplateTypeParmDecl *D1,
1303 TemplateTypeParmDecl *D2) {
1304 if (D1->isParameterPack() != D2->isParameterPack()) {
1305 if (Context.Complain) {
1306 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1307 << D2->isParameterPack();
1308 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1309 << D1->isParameterPack();
1317 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1318 NonTypeTemplateParmDecl *D1,
1319 NonTypeTemplateParmDecl *D2) {
1320 if (D1->isParameterPack() != D2->isParameterPack()) {
1321 if (Context.Complain) {
1322 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1323 << D2->isParameterPack();
1324 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1325 << D1->isParameterPack();
1331 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1332 if (Context.Complain) {
1333 Context.Diag2(D2->getLocation(),
1334 diag::err_odr_non_type_parameter_type_inconsistent)
1335 << D2->getType() << D1->getType();
1336 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1345 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1346 TemplateTemplateParmDecl *D1,
1347 TemplateTemplateParmDecl *D2) {
1348 if (D1->isParameterPack() != D2->isParameterPack()) {
1349 if (Context.Complain) {
1350 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1351 << D2->isParameterPack();
1352 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1353 << D1->isParameterPack();
1358 // Check template parameter lists.
1359 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1360 D2->getTemplateParameters());
1363 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1364 ClassTemplateDecl *D1,
1365 ClassTemplateDecl *D2) {
1366 // Check template parameters.
1367 if (!IsStructurallyEquivalent(Context,
1368 D1->getTemplateParameters(),
1369 D2->getTemplateParameters()))
1372 // Check the templated declaration.
1373 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1374 D2->getTemplatedDecl());
1377 /// \brief Determine structural equivalence of two declarations.
1378 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1379 Decl *D1, Decl *D2) {
1380 // FIXME: Check for known structural equivalences via a callback of some sort.
1382 // Check whether we already know that these two declarations are not
1383 // structurally equivalent.
1384 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1385 D2->getCanonicalDecl())))
1388 // Determine whether we've already produced a tentative equivalence for D1.
1389 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1391 return EquivToD1 == D2->getCanonicalDecl();
1393 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1394 EquivToD1 = D2->getCanonicalDecl();
1395 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1399 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1401 if (!::IsStructurallyEquivalent(*this, D1, D2))
1407 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1409 if (!::IsStructurallyEquivalent(*this, T1, T2))
1415 bool StructuralEquivalenceContext::Finish() {
1416 while (!DeclsToCheck.empty()) {
1417 // Check the next declaration.
1418 Decl *D1 = DeclsToCheck.front();
1419 DeclsToCheck.pop_front();
1421 Decl *D2 = TentativeEquivalences[D1];
1422 assert(D2 && "Unrecorded tentative equivalence?");
1424 bool Equivalent = true;
1426 // FIXME: Switch on all declaration kinds. For now, we're just going to
1427 // check the obvious ones.
1428 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1429 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1430 // Check for equivalent structure names.
1431 IdentifierInfo *Name1 = Record1->getIdentifier();
1432 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1433 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1434 IdentifierInfo *Name2 = Record2->getIdentifier();
1435 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1436 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1437 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1438 !::IsStructurallyEquivalent(*this, Record1, Record2))
1441 // Record/non-record mismatch.
1444 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1445 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1446 // Check for equivalent enum names.
1447 IdentifierInfo *Name1 = Enum1->getIdentifier();
1448 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1449 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1450 IdentifierInfo *Name2 = Enum2->getIdentifier();
1451 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1452 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1453 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1454 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1457 // Enum/non-enum mismatch
1460 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1461 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1462 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1463 Typedef2->getIdentifier()) ||
1464 !::IsStructurallyEquivalent(*this,
1465 Typedef1->getUnderlyingType(),
1466 Typedef2->getUnderlyingType()))
1469 // Typedef/non-typedef mismatch.
1472 } else if (ClassTemplateDecl *ClassTemplate1
1473 = dyn_cast<ClassTemplateDecl>(D1)) {
1474 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1475 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1476 ClassTemplate2->getIdentifier()) ||
1477 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1480 // Class template/non-class-template mismatch.
1483 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1484 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1485 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1491 } else if (NonTypeTemplateParmDecl *NTTP1
1492 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1493 if (NonTypeTemplateParmDecl *NTTP2
1494 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1495 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1501 } else if (TemplateTemplateParmDecl *TTP1
1502 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1503 if (TemplateTemplateParmDecl *TTP2
1504 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1505 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1514 // Note that these two declarations are not equivalent (and we already
1516 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1517 D2->getCanonicalDecl()));
1520 // FIXME: Check other declaration kinds!
1526 //----------------------------------------------------------------------------
1528 //----------------------------------------------------------------------------
1530 QualType ASTNodeImporter::VisitType(const Type *T) {
1531 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1532 << T->getTypeClassName();
1536 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1537 switch (T->getKind()) {
1538 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1539 case BuiltinType::Id: \
1540 return Importer.getToContext().SingletonId;
1541 #include "clang/Basic/OpenCLImageTypes.def"
1542 #define SHARED_SINGLETON_TYPE(Expansion)
1543 #define BUILTIN_TYPE(Id, SingletonId) \
1544 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1545 #include "clang/AST/BuiltinTypes.def"
1547 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1548 // context supports C++.
1550 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1551 // context supports ObjC.
1553 case BuiltinType::Char_U:
1554 // The context we're importing from has an unsigned 'char'. If we're
1555 // importing into a context with a signed 'char', translate to
1556 // 'unsigned char' instead.
1557 if (Importer.getToContext().getLangOpts().CharIsSigned)
1558 return Importer.getToContext().UnsignedCharTy;
1560 return Importer.getToContext().CharTy;
1562 case BuiltinType::Char_S:
1563 // The context we're importing from has an unsigned 'char'. If we're
1564 // importing into a context with a signed 'char', translate to
1565 // 'unsigned char' instead.
1566 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1567 return Importer.getToContext().SignedCharTy;
1569 return Importer.getToContext().CharTy;
1571 case BuiltinType::WChar_S:
1572 case BuiltinType::WChar_U:
1573 // FIXME: If not in C++, shall we translate to the C equivalent of
1575 return Importer.getToContext().WCharTy;
1578 llvm_unreachable("Invalid BuiltinType Kind!");
1581 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1582 QualType ToElementType = Importer.Import(T->getElementType());
1583 if (ToElementType.isNull())
1586 return Importer.getToContext().getComplexType(ToElementType);
1589 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1590 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1591 if (ToPointeeType.isNull())
1594 return Importer.getToContext().getPointerType(ToPointeeType);
1597 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1598 // FIXME: Check for blocks support in "to" context.
1599 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1600 if (ToPointeeType.isNull())
1603 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1607 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1608 // FIXME: Check for C++ support in "to" context.
1609 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1610 if (ToPointeeType.isNull())
1613 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1617 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1618 // FIXME: Check for C++0x support in "to" context.
1619 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1620 if (ToPointeeType.isNull())
1623 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1626 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1627 // FIXME: Check for C++ support in "to" context.
1628 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1629 if (ToPointeeType.isNull())
1632 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1633 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1634 ClassType.getTypePtr());
1637 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1638 QualType ToElementType = Importer.Import(T->getElementType());
1639 if (ToElementType.isNull())
1642 return Importer.getToContext().getConstantArrayType(ToElementType,
1644 T->getSizeModifier(),
1645 T->getIndexTypeCVRQualifiers());
1649 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1650 QualType ToElementType = Importer.Import(T->getElementType());
1651 if (ToElementType.isNull())
1654 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1655 T->getSizeModifier(),
1656 T->getIndexTypeCVRQualifiers());
1659 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1660 QualType ToElementType = Importer.Import(T->getElementType());
1661 if (ToElementType.isNull())
1664 Expr *Size = Importer.Import(T->getSizeExpr());
1668 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1669 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1670 T->getSizeModifier(),
1671 T->getIndexTypeCVRQualifiers(),
1675 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1676 QualType ToElementType = Importer.Import(T->getElementType());
1677 if (ToElementType.isNull())
1680 return Importer.getToContext().getVectorType(ToElementType,
1681 T->getNumElements(),
1682 T->getVectorKind());
1685 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1686 QualType ToElementType = Importer.Import(T->getElementType());
1687 if (ToElementType.isNull())
1690 return Importer.getToContext().getExtVectorType(ToElementType,
1691 T->getNumElements());
1695 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1696 // FIXME: What happens if we're importing a function without a prototype
1697 // into C++? Should we make it variadic?
1698 QualType ToResultType = Importer.Import(T->getReturnType());
1699 if (ToResultType.isNull())
1702 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1706 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1707 QualType ToResultType = Importer.Import(T->getReturnType());
1708 if (ToResultType.isNull())
1711 // Import argument types
1712 SmallVector<QualType, 4> ArgTypes;
1713 for (const auto &A : T->param_types()) {
1714 QualType ArgType = Importer.Import(A);
1715 if (ArgType.isNull())
1717 ArgTypes.push_back(ArgType);
1720 // Import exception types
1721 SmallVector<QualType, 4> ExceptionTypes;
1722 for (const auto &E : T->exceptions()) {
1723 QualType ExceptionType = Importer.Import(E);
1724 if (ExceptionType.isNull())
1726 ExceptionTypes.push_back(ExceptionType);
1729 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1730 FunctionProtoType::ExtProtoInfo ToEPI;
1732 ToEPI.ExtInfo = FromEPI.ExtInfo;
1733 ToEPI.Variadic = FromEPI.Variadic;
1734 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1735 ToEPI.TypeQuals = FromEPI.TypeQuals;
1736 ToEPI.RefQualifier = FromEPI.RefQualifier;
1737 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1738 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1739 ToEPI.ExceptionSpec.NoexceptExpr =
1740 Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1741 ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1742 Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1743 ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1744 Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1746 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1749 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1750 QualType ToInnerType = Importer.Import(T->getInnerType());
1751 if (ToInnerType.isNull())
1754 return Importer.getToContext().getParenType(ToInnerType);
1757 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1758 TypedefNameDecl *ToDecl
1759 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1763 return Importer.getToContext().getTypeDeclType(ToDecl);
1766 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1767 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1771 return Importer.getToContext().getTypeOfExprType(ToExpr);
1774 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1775 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1776 if (ToUnderlyingType.isNull())
1779 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1782 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1783 // FIXME: Make sure that the "to" context supports C++0x!
1784 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1788 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1789 if (UnderlyingType.isNull())
1792 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1795 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1796 QualType ToBaseType = Importer.Import(T->getBaseType());
1797 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1798 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1801 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1806 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1807 // FIXME: Make sure that the "to" context supports C++11!
1808 QualType FromDeduced = T->getDeducedType();
1810 if (!FromDeduced.isNull()) {
1811 ToDeduced = Importer.Import(FromDeduced);
1812 if (ToDeduced.isNull())
1816 return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
1817 /*IsDependent*/false);
1820 QualType ASTNodeImporter::VisitInjectedClassNameType(
1821 const InjectedClassNameType *T) {
1822 CXXRecordDecl *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
1826 QualType InjType = Importer.Import(T->getInjectedSpecializationType());
1827 if (InjType.isNull())
1830 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1831 // See comments in InjectedClassNameType definition for details
1832 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1834 TypeAlignmentInBits = 4,
1835 TypeAlignment = 1 << TypeAlignmentInBits
1838 return QualType(new (Importer.getToContext(), TypeAlignment)
1839 InjectedClassNameType(D, InjType), 0);
1842 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1844 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1848 return Importer.getToContext().getTagDeclType(ToDecl);
1851 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1853 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1857 return Importer.getToContext().getTagDeclType(ToDecl);
1860 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1861 QualType FromModifiedType = T->getModifiedType();
1862 QualType FromEquivalentType = T->getEquivalentType();
1863 QualType ToModifiedType;
1864 QualType ToEquivalentType;
1866 if (!FromModifiedType.isNull()) {
1867 ToModifiedType = Importer.Import(FromModifiedType);
1868 if (ToModifiedType.isNull())
1871 if (!FromEquivalentType.isNull()) {
1872 ToEquivalentType = Importer.Import(FromEquivalentType);
1873 if (ToEquivalentType.isNull())
1877 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1878 ToModifiedType, ToEquivalentType);
1882 QualType ASTNodeImporter::VisitTemplateTypeParmType(
1883 const TemplateTypeParmType *T) {
1884 TemplateTypeParmDecl *ParmDecl =
1885 cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
1886 if (!ParmDecl && T->getDecl())
1889 return Importer.getToContext().getTemplateTypeParmType(
1890 T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
1893 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1894 const TemplateSpecializationType *T) {
1895 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1896 if (ToTemplate.isNull())
1899 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1900 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1903 QualType ToCanonType;
1904 if (!QualType(T, 0).isCanonical()) {
1905 QualType FromCanonType
1906 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1907 ToCanonType =Importer.Import(FromCanonType);
1908 if (ToCanonType.isNull())
1911 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1912 ToTemplateArgs.data(),
1913 ToTemplateArgs.size(),
1917 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1918 NestedNameSpecifier *ToQualifier = nullptr;
1919 // Note: the qualifier in an ElaboratedType is optional.
1920 if (T->getQualifier()) {
1921 ToQualifier = Importer.Import(T->getQualifier());
1926 QualType ToNamedType = Importer.Import(T->getNamedType());
1927 if (ToNamedType.isNull())
1930 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1931 ToQualifier, ToNamedType);
1934 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1935 ObjCInterfaceDecl *Class
1936 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1940 return Importer.getToContext().getObjCInterfaceType(Class);
1943 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1944 QualType ToBaseType = Importer.Import(T->getBaseType());
1945 if (ToBaseType.isNull())
1948 SmallVector<QualType, 4> TypeArgs;
1949 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1950 QualType ImportedTypeArg = Importer.Import(TypeArg);
1951 if (ImportedTypeArg.isNull())
1954 TypeArgs.push_back(ImportedTypeArg);
1957 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1958 for (auto *P : T->quals()) {
1959 ObjCProtocolDecl *Protocol
1960 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1963 Protocols.push_back(Protocol);
1966 return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1968 T->isKindOfTypeAsWritten());
1972 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1973 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1974 if (ToPointeeType.isNull())
1977 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1980 //----------------------------------------------------------------------------
1981 // Import Declarations
1982 //----------------------------------------------------------------------------
1983 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1984 DeclContext *&LexicalDC,
1985 DeclarationName &Name,
1987 SourceLocation &Loc) {
1988 // Import the context of this declaration.
1989 DC = Importer.ImportContext(D->getDeclContext());
1994 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1995 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2000 // Import the name of this declaration.
2001 Name = Importer.Import(D->getDeclName());
2002 if (D->getDeclName() && !Name)
2005 // Import the location of this declaration.
2006 Loc = Importer.Import(D->getLocation());
2007 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
2011 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
2016 ToD = Importer.Import(FromD);
2021 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
2022 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
2023 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
2024 ImportDefinition(FromRecord, ToRecord);
2030 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
2031 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
2032 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
2033 ImportDefinition(FromEnum, ToEnum);
2041 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
2042 DeclarationNameInfo& To) {
2043 // NOTE: To.Name and To.Loc are already imported.
2044 // We only have to import To.LocInfo.
2045 switch (To.getName().getNameKind()) {
2046 case DeclarationName::Identifier:
2047 case DeclarationName::ObjCZeroArgSelector:
2048 case DeclarationName::ObjCOneArgSelector:
2049 case DeclarationName::ObjCMultiArgSelector:
2050 case DeclarationName::CXXUsingDirective:
2053 case DeclarationName::CXXOperatorName: {
2054 SourceRange Range = From.getCXXOperatorNameRange();
2055 To.setCXXOperatorNameRange(Importer.Import(Range));
2058 case DeclarationName::CXXLiteralOperatorName: {
2059 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
2060 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
2063 case DeclarationName::CXXConstructorName:
2064 case DeclarationName::CXXDestructorName:
2065 case DeclarationName::CXXConversionFunctionName: {
2066 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
2067 To.setNamedTypeInfo(Importer.Import(FromTInfo));
2071 llvm_unreachable("Unknown name kind.");
2074 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
2075 if (Importer.isMinimalImport() && !ForceImport) {
2076 Importer.ImportContext(FromDC);
2080 for (auto *From : FromDC->decls())
2081 Importer.Import(From);
2084 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
2085 ImportDefinitionKind Kind) {
2086 if (To->getDefinition() || To->isBeingDefined()) {
2087 if (Kind == IDK_Everything)
2088 ImportDeclContext(From, /*ForceImport=*/true);
2093 To->startDefinition();
2095 // Add base classes.
2096 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
2097 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
2099 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2100 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2101 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
2102 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
2103 ToData.Aggregate = FromData.Aggregate;
2104 ToData.PlainOldData = FromData.PlainOldData;
2105 ToData.Empty = FromData.Empty;
2106 ToData.Polymorphic = FromData.Polymorphic;
2107 ToData.Abstract = FromData.Abstract;
2108 ToData.IsStandardLayout = FromData.IsStandardLayout;
2109 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
2110 ToData.HasPrivateFields = FromData.HasPrivateFields;
2111 ToData.HasProtectedFields = FromData.HasProtectedFields;
2112 ToData.HasPublicFields = FromData.HasPublicFields;
2113 ToData.HasMutableFields = FromData.HasMutableFields;
2114 ToData.HasVariantMembers = FromData.HasVariantMembers;
2115 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2116 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2117 ToData.HasUninitializedReferenceMember
2118 = FromData.HasUninitializedReferenceMember;
2119 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
2120 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
2121 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
2122 ToData.NeedOverloadResolutionForMoveConstructor
2123 = FromData.NeedOverloadResolutionForMoveConstructor;
2124 ToData.NeedOverloadResolutionForMoveAssignment
2125 = FromData.NeedOverloadResolutionForMoveAssignment;
2126 ToData.NeedOverloadResolutionForDestructor
2127 = FromData.NeedOverloadResolutionForDestructor;
2128 ToData.DefaultedMoveConstructorIsDeleted
2129 = FromData.DefaultedMoveConstructorIsDeleted;
2130 ToData.DefaultedMoveAssignmentIsDeleted
2131 = FromData.DefaultedMoveAssignmentIsDeleted;
2132 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2133 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2134 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2135 ToData.HasConstexprNonCopyMoveConstructor
2136 = FromData.HasConstexprNonCopyMoveConstructor;
2137 ToData.HasDefaultedDefaultConstructor
2138 = FromData.HasDefaultedDefaultConstructor;
2139 ToData.DefaultedDefaultConstructorIsConstexpr
2140 = FromData.DefaultedDefaultConstructorIsConstexpr;
2141 ToData.HasConstexprDefaultConstructor
2142 = FromData.HasConstexprDefaultConstructor;
2143 ToData.HasNonLiteralTypeFieldsOrBases
2144 = FromData.HasNonLiteralTypeFieldsOrBases;
2145 // ComputedVisibleConversions not imported.
2146 ToData.UserProvidedDefaultConstructor
2147 = FromData.UserProvidedDefaultConstructor;
2148 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2149 ToData.ImplicitCopyConstructorHasConstParam
2150 = FromData.ImplicitCopyConstructorHasConstParam;
2151 ToData.ImplicitCopyAssignmentHasConstParam
2152 = FromData.ImplicitCopyAssignmentHasConstParam;
2153 ToData.HasDeclaredCopyConstructorWithConstParam
2154 = FromData.HasDeclaredCopyConstructorWithConstParam;
2155 ToData.HasDeclaredCopyAssignmentWithConstParam
2156 = FromData.HasDeclaredCopyAssignmentWithConstParam;
2157 ToData.IsLambda = FromData.IsLambda;
2159 SmallVector<CXXBaseSpecifier *, 4> Bases;
2160 for (const auto &Base1 : FromCXX->bases()) {
2161 QualType T = Importer.Import(Base1.getType());
2165 SourceLocation EllipsisLoc;
2166 if (Base1.isPackExpansion())
2167 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2169 // Ensure that we have a definition for the base.
2170 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2173 new (Importer.getToContext())
2174 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2176 Base1.isBaseOfClass(),
2177 Base1.getAccessSpecifierAsWritten(),
2178 Importer.Import(Base1.getTypeSourceInfo()),
2182 ToCXX->setBases(Bases.data(), Bases.size());
2185 if (shouldForceImportDeclContext(Kind))
2186 ImportDeclContext(From, /*ForceImport=*/true);
2188 To->completeDefinition();
2192 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2193 ImportDefinitionKind Kind) {
2194 if (To->getAnyInitializer())
2197 // FIXME: Can we really import any initializer? Alternatively, we could force
2198 // ourselves to import every declaration of a variable and then only use
2200 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2202 // FIXME: Other bits to merge?
2207 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2208 ImportDefinitionKind Kind) {
2209 if (To->getDefinition() || To->isBeingDefined()) {
2210 if (Kind == IDK_Everything)
2211 ImportDeclContext(From, /*ForceImport=*/true);
2215 To->startDefinition();
2217 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2221 QualType ToPromotionType = Importer.Import(From->getPromotionType());
2222 if (ToPromotionType.isNull())
2225 if (shouldForceImportDeclContext(Kind))
2226 ImportDeclContext(From, /*ForceImport=*/true);
2228 // FIXME: we might need to merge the number of positive or negative bits
2229 // if the enumerator lists don't match.
2230 To->completeDefinition(T, ToPromotionType,
2231 From->getNumPositiveBits(),
2232 From->getNumNegativeBits());
2236 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2237 TemplateParameterList *Params) {
2238 SmallVector<NamedDecl *, 4> ToParams;
2239 ToParams.reserve(Params->size());
2240 for (TemplateParameterList::iterator P = Params->begin(),
2241 PEnd = Params->end();
2243 Decl *To = Importer.Import(*P);
2247 ToParams.push_back(cast<NamedDecl>(To));
2250 return TemplateParameterList::Create(Importer.getToContext(),
2251 Importer.Import(Params->getTemplateLoc()),
2252 Importer.Import(Params->getLAngleLoc()),
2254 Importer.Import(Params->getRAngleLoc()));
2258 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2259 switch (From.getKind()) {
2260 case TemplateArgument::Null:
2261 return TemplateArgument();
2263 case TemplateArgument::Type: {
2264 QualType ToType = Importer.Import(From.getAsType());
2265 if (ToType.isNull())
2266 return TemplateArgument();
2267 return TemplateArgument(ToType);
2270 case TemplateArgument::Integral: {
2271 QualType ToType = Importer.Import(From.getIntegralType());
2272 if (ToType.isNull())
2273 return TemplateArgument();
2274 return TemplateArgument(From, ToType);
2277 case TemplateArgument::Declaration: {
2278 ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2279 QualType ToType = Importer.Import(From.getParamTypeForDecl());
2280 if (!To || ToType.isNull())
2281 return TemplateArgument();
2282 return TemplateArgument(To, ToType);
2285 case TemplateArgument::NullPtr: {
2286 QualType ToType = Importer.Import(From.getNullPtrType());
2287 if (ToType.isNull())
2288 return TemplateArgument();
2289 return TemplateArgument(ToType, /*isNullPtr*/true);
2292 case TemplateArgument::Template: {
2293 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2294 if (ToTemplate.isNull())
2295 return TemplateArgument();
2297 return TemplateArgument(ToTemplate);
2300 case TemplateArgument::TemplateExpansion: {
2301 TemplateName ToTemplate
2302 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2303 if (ToTemplate.isNull())
2304 return TemplateArgument();
2306 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2309 case TemplateArgument::Expression:
2310 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2311 return TemplateArgument(ToExpr);
2312 return TemplateArgument();
2314 case TemplateArgument::Pack: {
2315 SmallVector<TemplateArgument, 2> ToPack;
2316 ToPack.reserve(From.pack_size());
2317 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2318 return TemplateArgument();
2320 return TemplateArgument(
2321 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
2325 llvm_unreachable("Invalid template argument kind");
2328 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2329 unsigned NumFromArgs,
2330 SmallVectorImpl<TemplateArgument> &ToArgs) {
2331 for (unsigned I = 0; I != NumFromArgs; ++I) {
2332 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2333 if (To.isNull() && !FromArgs[I].isNull())
2336 ToArgs.push_back(To);
2342 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2343 RecordDecl *ToRecord, bool Complain) {
2344 // Eliminate a potential failure point where we attempt to re-import
2345 // something we're trying to import while completing ToRecord.
2346 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2348 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2350 ToRecord = ToOriginRecord;
2353 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2354 ToRecord->getASTContext(),
2355 Importer.getNonEquivalentDecls(),
2357 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2360 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2362 StructuralEquivalenceContext Ctx(
2363 Importer.getFromContext(), Importer.getToContext(),
2364 Importer.getNonEquivalentDecls(), false, Complain);
2365 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2368 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2369 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2370 Importer.getToContext(),
2371 Importer.getNonEquivalentDecls());
2372 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2375 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2376 EnumConstantDecl *ToEC)
2378 const llvm::APSInt &FromVal = FromEC->getInitVal();
2379 const llvm::APSInt &ToVal = ToEC->getInitVal();
2381 return FromVal.isSigned() == ToVal.isSigned() &&
2382 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2386 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2387 ClassTemplateDecl *To) {
2388 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2389 Importer.getToContext(),
2390 Importer.getNonEquivalentDecls());
2391 return Ctx.IsStructurallyEquivalent(From, To);
2394 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2395 VarTemplateDecl *To) {
2396 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2397 Importer.getToContext(),
2398 Importer.getNonEquivalentDecls());
2399 return Ctx.IsStructurallyEquivalent(From, To);
2402 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2403 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2404 << D->getDeclKindName();
2408 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2409 TranslationUnitDecl *ToD =
2410 Importer.getToContext().getTranslationUnitDecl();
2412 Importer.Imported(D, ToD);
2417 Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2419 SourceLocation Loc = Importer.Import(D->getLocation());
2420 SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
2422 // Import the context of this declaration.
2423 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2427 AccessSpecDecl *accessSpecDecl
2428 = AccessSpecDecl::Create(Importer.getToContext(), D->getAccess(),
2431 if (!accessSpecDecl)
2434 // Lexical DeclContext and Semantic DeclContext
2435 // is always the same for the accessSpec.
2436 accessSpecDecl->setLexicalDeclContext(DC);
2437 DC->addDeclInternal(accessSpecDecl);
2439 return accessSpecDecl;
2442 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2443 // Import the major distinguishing characteristics of this namespace.
2444 DeclContext *DC, *LexicalDC;
2445 DeclarationName Name;
2448 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2453 NamespaceDecl *MergeWithNamespace = nullptr;
2455 // This is an anonymous namespace. Adopt an existing anonymous
2456 // namespace if we can.
2457 // FIXME: Not testable.
2458 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2459 MergeWithNamespace = TU->getAnonymousNamespace();
2461 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2463 SmallVector<NamedDecl *, 4> ConflictingDecls;
2464 SmallVector<NamedDecl *, 2> FoundDecls;
2465 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2466 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2467 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2470 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2471 MergeWithNamespace = FoundNS;
2472 ConflictingDecls.clear();
2476 ConflictingDecls.push_back(FoundDecls[I]);
2479 if (!ConflictingDecls.empty()) {
2480 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2481 ConflictingDecls.data(),
2482 ConflictingDecls.size());
2486 // Create the "to" namespace, if needed.
2487 NamespaceDecl *ToNamespace = MergeWithNamespace;
2489 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2491 Importer.Import(D->getLocStart()),
2492 Loc, Name.getAsIdentifierInfo(),
2493 /*PrevDecl=*/nullptr);
2494 ToNamespace->setLexicalDeclContext(LexicalDC);
2495 LexicalDC->addDeclInternal(ToNamespace);
2497 // If this is an anonymous namespace, register it as the anonymous
2498 // namespace within its context.
2500 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2501 TU->setAnonymousNamespace(ToNamespace);
2503 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2506 Importer.Imported(D, ToNamespace);
2508 ImportDeclContext(D);
2513 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2514 // Import the major distinguishing characteristics of this typedef.
2515 DeclContext *DC, *LexicalDC;
2516 DeclarationName Name;
2519 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2524 // If this typedef is not in block scope, determine whether we've
2525 // seen a typedef with the same name (that we can merge with) or any
2526 // other entity by that name (which name lookup could conflict with).
2527 if (!DC->isFunctionOrMethod()) {
2528 SmallVector<NamedDecl *, 4> ConflictingDecls;
2529 unsigned IDNS = Decl::IDNS_Ordinary;
2530 SmallVector<NamedDecl *, 2> FoundDecls;
2531 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2532 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2533 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2535 if (TypedefNameDecl *FoundTypedef =
2536 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2537 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2538 FoundTypedef->getUnderlyingType()))
2539 return Importer.Imported(D, FoundTypedef);
2542 ConflictingDecls.push_back(FoundDecls[I]);
2545 if (!ConflictingDecls.empty()) {
2546 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2547 ConflictingDecls.data(),
2548 ConflictingDecls.size());
2554 // Import the underlying type of this typedef;
2555 QualType T = Importer.Import(D->getUnderlyingType());
2559 // Create the new typedef node.
2560 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2561 SourceLocation StartL = Importer.Import(D->getLocStart());
2562 TypedefNameDecl *ToTypedef;
2564 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2566 Name.getAsIdentifierInfo(),
2569 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2571 Name.getAsIdentifierInfo(),
2574 ToTypedef->setAccess(D->getAccess());
2575 ToTypedef->setLexicalDeclContext(LexicalDC);
2576 Importer.Imported(D, ToTypedef);
2577 LexicalDC->addDeclInternal(ToTypedef);
2582 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2583 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2586 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2587 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2590 Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2591 // Import the major distinguishing characteristics of this label.
2592 DeclContext *DC, *LexicalDC;
2593 DeclarationName Name;
2596 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2601 assert(LexicalDC->isFunctionOrMethod());
2603 LabelDecl *ToLabel = D->isGnuLocal()
2604 ? LabelDecl::Create(Importer.getToContext(),
2605 DC, Importer.Import(D->getLocation()),
2606 Name.getAsIdentifierInfo(),
2607 Importer.Import(D->getLocStart()))
2608 : LabelDecl::Create(Importer.getToContext(),
2609 DC, Importer.Import(D->getLocation()),
2610 Name.getAsIdentifierInfo());
2611 Importer.Imported(D, ToLabel);
2613 LabelStmt *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
2617 ToLabel->setStmt(Label);
2618 ToLabel->setLexicalDeclContext(LexicalDC);
2619 LexicalDC->addDeclInternal(ToLabel);
2623 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2624 // Import the major distinguishing characteristics of this enum.
2625 DeclContext *DC, *LexicalDC;
2626 DeclarationName Name;
2629 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2634 // Figure out what enum name we're looking for.
2635 unsigned IDNS = Decl::IDNS_Tag;
2636 DeclarationName SearchName = Name;
2637 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2638 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2639 IDNS = Decl::IDNS_Ordinary;
2640 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2641 IDNS |= Decl::IDNS_Ordinary;
2643 // We may already have an enum of the same name; try to find and match it.
2644 if (!DC->isFunctionOrMethod() && SearchName) {
2645 SmallVector<NamedDecl *, 4> ConflictingDecls;
2646 SmallVector<NamedDecl *, 2> FoundDecls;
2647 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2648 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2649 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2652 Decl *Found = FoundDecls[I];
2653 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2654 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2655 Found = Tag->getDecl();
2658 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2659 if (IsStructuralMatch(D, FoundEnum))
2660 return Importer.Imported(D, FoundEnum);
2663 ConflictingDecls.push_back(FoundDecls[I]);
2666 if (!ConflictingDecls.empty()) {
2667 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2668 ConflictingDecls.data(),
2669 ConflictingDecls.size());
2673 // Create the enum declaration.
2674 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2675 Importer.Import(D->getLocStart()),
2676 Loc, Name.getAsIdentifierInfo(), nullptr,
2677 D->isScoped(), D->isScopedUsingClassTag(),
2679 // Import the qualifier, if any.
2680 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2681 D2->setAccess(D->getAccess());
2682 D2->setLexicalDeclContext(LexicalDC);
2683 Importer.Imported(D, D2);
2684 LexicalDC->addDeclInternal(D2);
2686 // Import the integer type.
2687 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2688 if (ToIntegerType.isNull())
2690 D2->setIntegerType(ToIntegerType);
2692 // Import the definition
2693 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2699 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2700 // If this record has a definition in the translation unit we're coming from,
2701 // but this particular declaration is not that definition, import the
2702 // definition and map to that.
2703 TagDecl *Definition = D->getDefinition();
2704 if (Definition && Definition != D) {
2705 Decl *ImportedDef = Importer.Import(Definition);
2709 return Importer.Imported(D, ImportedDef);
2712 // Import the major distinguishing characteristics of this record.
2713 DeclContext *DC, *LexicalDC;
2714 DeclarationName Name;
2717 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2722 // Figure out what structure name we're looking for.
2723 unsigned IDNS = Decl::IDNS_Tag;
2724 DeclarationName SearchName = Name;
2725 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2726 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2727 IDNS = Decl::IDNS_Ordinary;
2728 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2729 IDNS |= Decl::IDNS_Ordinary;
2731 // We may already have a record of the same name; try to find and match it.
2732 RecordDecl *AdoptDecl = nullptr;
2733 if (!DC->isFunctionOrMethod()) {
2734 SmallVector<NamedDecl *, 4> ConflictingDecls;
2735 SmallVector<NamedDecl *, 2> FoundDecls;
2736 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2737 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2738 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2741 Decl *Found = FoundDecls[I];
2742 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2743 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2744 Found = Tag->getDecl();
2747 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2748 if (D->isAnonymousStructOrUnion() &&
2749 FoundRecord->isAnonymousStructOrUnion()) {
2750 // If both anonymous structs/unions are in a record context, make sure
2751 // they occur in the same location in the context records.
2752 if (Optional<unsigned> Index1
2753 = findAnonymousStructOrUnionIndex(D)) {
2754 if (Optional<unsigned> Index2 =
2755 findAnonymousStructOrUnionIndex(FoundRecord)) {
2756 if (*Index1 != *Index2)
2762 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2763 if ((SearchName && !D->isCompleteDefinition())
2764 || (D->isCompleteDefinition() &&
2765 D->isAnonymousStructOrUnion()
2766 == FoundDef->isAnonymousStructOrUnion() &&
2767 IsStructuralMatch(D, FoundDef))) {
2768 // The record types structurally match, or the "from" translation
2769 // unit only had a forward declaration anyway; call it the same
2771 // FIXME: For C++, we should also merge methods here.
2772 return Importer.Imported(D, FoundDef);
2774 } else if (!D->isCompleteDefinition()) {
2775 // We have a forward declaration of this type, so adopt that forward
2776 // declaration rather than building a new one.
2778 // If one or both can be completed from external storage then try one
2779 // last time to complete and compare them before doing this.
2781 if (FoundRecord->hasExternalLexicalStorage() &&
2782 !FoundRecord->isCompleteDefinition())
2783 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2784 if (D->hasExternalLexicalStorage())
2785 D->getASTContext().getExternalSource()->CompleteType(D);
2787 if (FoundRecord->isCompleteDefinition() &&
2788 D->isCompleteDefinition() &&
2789 !IsStructuralMatch(D, FoundRecord))
2792 AdoptDecl = FoundRecord;
2794 } else if (!SearchName) {
2799 ConflictingDecls.push_back(FoundDecls[I]);
2802 if (!ConflictingDecls.empty() && SearchName) {
2803 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2804 ConflictingDecls.data(),
2805 ConflictingDecls.size());
2809 // Create the record declaration.
2810 RecordDecl *D2 = AdoptDecl;
2811 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2813 CXXRecordDecl *D2CXX = nullptr;
2814 if (CXXRecordDecl *DCXX = llvm::dyn_cast<CXXRecordDecl>(D)) {
2815 if (DCXX->isLambda()) {
2816 TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
2817 D2CXX = CXXRecordDecl::CreateLambda(Importer.getToContext(),
2819 DCXX->isDependentLambda(),
2820 DCXX->isGenericLambda(),
2821 DCXX->getLambdaCaptureDefault());
2822 Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
2823 if (DCXX->getLambdaContextDecl() && !CDecl)
2825 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
2826 } else if (DCXX->isInjectedClassName()) {
2827 // We have to be careful to do a similar dance to the one in
2828 // Sema::ActOnStartCXXMemberDeclarations
2829 CXXRecordDecl *const PrevDecl = nullptr;
2830 const bool DelayTypeCreation = true;
2831 D2CXX = CXXRecordDecl::Create(
2832 Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc,
2833 Name.getAsIdentifierInfo(), PrevDecl, DelayTypeCreation);
2834 Importer.getToContext().getTypeDeclType(
2835 D2CXX, llvm::dyn_cast<CXXRecordDecl>(DC));
2837 D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2840 Name.getAsIdentifierInfo());
2843 D2->setAccess(D->getAccess());
2845 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2846 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2849 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2850 D2->setLexicalDeclContext(LexicalDC);
2851 LexicalDC->addDeclInternal(D2);
2852 if (D->isAnonymousStructOrUnion())
2853 D2->setAnonymousStructOrUnion(true);
2856 Importer.Imported(D, D2);
2858 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2864 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2865 // Import the major distinguishing characteristics of this enumerator.
2866 DeclContext *DC, *LexicalDC;
2867 DeclarationName Name;
2870 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2875 QualType T = Importer.Import(D->getType());
2879 // Determine whether there are any other declarations with the same name and
2880 // in the same context.
2881 if (!LexicalDC->isFunctionOrMethod()) {
2882 SmallVector<NamedDecl *, 4> ConflictingDecls;
2883 unsigned IDNS = Decl::IDNS_Ordinary;
2884 SmallVector<NamedDecl *, 2> FoundDecls;
2885 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2886 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2887 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2890 if (EnumConstantDecl *FoundEnumConstant
2891 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2892 if (IsStructuralMatch(D, FoundEnumConstant))
2893 return Importer.Imported(D, FoundEnumConstant);
2896 ConflictingDecls.push_back(FoundDecls[I]);
2899 if (!ConflictingDecls.empty()) {
2900 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2901 ConflictingDecls.data(),
2902 ConflictingDecls.size());
2908 Expr *Init = Importer.Import(D->getInitExpr());
2909 if (D->getInitExpr() && !Init)
2912 EnumConstantDecl *ToEnumerator
2913 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2914 Name.getAsIdentifierInfo(), T,
2915 Init, D->getInitVal());
2916 ToEnumerator->setAccess(D->getAccess());
2917 ToEnumerator->setLexicalDeclContext(LexicalDC);
2918 Importer.Imported(D, ToEnumerator);
2919 LexicalDC->addDeclInternal(ToEnumerator);
2920 return ToEnumerator;
2923 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2924 // Import the major distinguishing characteristics of this function.
2925 DeclContext *DC, *LexicalDC;
2926 DeclarationName Name;
2929 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2934 // Try to find a function in our own ("to") context with the same name, same
2935 // type, and in the same context as the function we're importing.
2936 if (!LexicalDC->isFunctionOrMethod()) {
2937 SmallVector<NamedDecl *, 4> ConflictingDecls;
2938 unsigned IDNS = Decl::IDNS_Ordinary;
2939 SmallVector<NamedDecl *, 2> FoundDecls;
2940 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2941 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2942 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2945 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2946 if (FoundFunction->hasExternalFormalLinkage() &&
2947 D->hasExternalFormalLinkage()) {
2948 if (Importer.IsStructurallyEquivalent(D->getType(),
2949 FoundFunction->getType())) {
2950 // FIXME: Actually try to merge the body and other attributes.
2951 return Importer.Imported(D, FoundFunction);
2954 // FIXME: Check for overloading more carefully, e.g., by boosting
2955 // Sema::IsOverload out to the AST library.
2957 // Function overloading is okay in C++.
2958 if (Importer.getToContext().getLangOpts().CPlusPlus)
2961 // Complain about inconsistent function types.
2962 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2963 << Name << D->getType() << FoundFunction->getType();
2964 Importer.ToDiag(FoundFunction->getLocation(),
2965 diag::note_odr_value_here)
2966 << FoundFunction->getType();
2970 ConflictingDecls.push_back(FoundDecls[I]);
2973 if (!ConflictingDecls.empty()) {
2974 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2975 ConflictingDecls.data(),
2976 ConflictingDecls.size());
2982 DeclarationNameInfo NameInfo(Name, Loc);
2983 // Import additional name location/type info.
2984 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2986 QualType FromTy = D->getType();
2987 bool usedDifferentExceptionSpec = false;
2989 if (const FunctionProtoType *
2990 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2991 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2992 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2993 // FunctionDecl that we are importing the FunctionProtoType for.
2994 // To avoid an infinite recursion when importing, create the FunctionDecl
2995 // with a simplified function type and update it afterwards.
2996 if (FromEPI.ExceptionSpec.SourceDecl ||
2997 FromEPI.ExceptionSpec.SourceTemplate ||
2998 FromEPI.ExceptionSpec.NoexceptExpr) {
2999 FunctionProtoType::ExtProtoInfo DefaultEPI;
3000 FromTy = Importer.getFromContext().getFunctionType(
3001 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3002 usedDifferentExceptionSpec = true;
3007 QualType T = Importer.Import(FromTy);
3011 // Import the function parameters.
3012 SmallVector<ParmVarDecl *, 8> Parameters;
3013 for (auto P : D->parameters()) {
3014 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
3018 Parameters.push_back(ToP);
3021 // Create the imported function.
3022 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3023 FunctionDecl *ToFunction = nullptr;
3024 SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
3025 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3026 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
3027 cast<CXXRecordDecl>(DC),
3030 FromConstructor->isExplicit(),
3031 D->isInlineSpecified(),
3034 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3035 SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
3036 for (CXXCtorInitializer *I : FromConstructor->inits()) {
3037 CXXCtorInitializer *ToI =
3038 cast_or_null<CXXCtorInitializer>(Importer.Import(I));
3041 CtorInitializers.push_back(ToI);
3043 CXXCtorInitializer **Memory =
3044 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3045 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3046 CXXConstructorDecl *ToCtor = llvm::cast<CXXConstructorDecl>(ToFunction);
3047 ToCtor->setCtorInitializers(Memory);
3048 ToCtor->setNumCtorInitializers(NumInitializers);
3050 } else if (isa<CXXDestructorDecl>(D)) {
3051 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
3052 cast<CXXRecordDecl>(DC),
3055 D->isInlineSpecified(),
3057 } else if (CXXConversionDecl *FromConversion
3058 = dyn_cast<CXXConversionDecl>(D)) {
3059 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
3060 cast<CXXRecordDecl>(DC),
3063 D->isInlineSpecified(),
3064 FromConversion->isExplicit(),
3066 Importer.Import(D->getLocEnd()));
3067 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3068 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
3069 cast<CXXRecordDecl>(DC),
3072 Method->getStorageClass(),
3073 Method->isInlineSpecified(),
3075 Importer.Import(D->getLocEnd()));
3077 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
3079 NameInfo, T, TInfo, D->getStorageClass(),
3080 D->isInlineSpecified(),
3081 D->hasWrittenPrototype(),
3085 // Import the qualifier, if any.
3086 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3087 ToFunction->setAccess(D->getAccess());
3088 ToFunction->setLexicalDeclContext(LexicalDC);
3089 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3090 ToFunction->setTrivial(D->isTrivial());
3091 ToFunction->setPure(D->isPure());
3092 Importer.Imported(D, ToFunction);
3094 // Set the parameters.
3095 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
3096 Parameters[I]->setOwningFunction(ToFunction);
3097 ToFunction->addDeclInternal(Parameters[I]);
3099 ToFunction->setParams(Parameters);
3101 if (usedDifferentExceptionSpec) {
3102 // Update FunctionProtoType::ExtProtoInfo.
3103 QualType T = Importer.Import(D->getType());
3106 ToFunction->setType(T);
3109 // Import the body, if any.
3110 if (Stmt *FromBody = D->getBody()) {
3111 if (Stmt *ToBody = Importer.Import(FromBody)) {
3112 ToFunction->setBody(ToBody);
3116 // FIXME: Other bits to merge?
3118 // Add this function to the lexical context.
3119 LexicalDC->addDeclInternal(ToFunction);
3124 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3125 return VisitFunctionDecl(D);
3128 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3129 return VisitCXXMethodDecl(D);
3132 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3133 return VisitCXXMethodDecl(D);
3136 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3137 return VisitCXXMethodDecl(D);
3140 static unsigned getFieldIndex(Decl *F) {
3141 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
3146 for (const auto *D : Owner->noload_decls()) {
3150 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
3157 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3158 // Import the major distinguishing characteristics of a variable.
3159 DeclContext *DC, *LexicalDC;
3160 DeclarationName Name;
3163 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3168 // Determine whether we've already imported this field.
3169 SmallVector<NamedDecl *, 2> FoundDecls;
3170 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3171 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3172 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
3173 // For anonymous fields, match up by index.
3174 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3177 if (Importer.IsStructurallyEquivalent(D->getType(),
3178 FoundField->getType())) {
3179 Importer.Imported(D, FoundField);
3183 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3184 << Name << D->getType() << FoundField->getType();
3185 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3186 << FoundField->getType();
3192 QualType T = Importer.Import(D->getType());
3196 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3197 Expr *BitWidth = Importer.Import(D->getBitWidth());
3198 if (!BitWidth && D->getBitWidth())
3201 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
3202 Importer.Import(D->getInnerLocStart()),
3203 Loc, Name.getAsIdentifierInfo(),
3204 T, TInfo, BitWidth, D->isMutable(),
3205 D->getInClassInitStyle());
3206 ToField->setAccess(D->getAccess());
3207 ToField->setLexicalDeclContext(LexicalDC);
3208 if (Expr *FromInitializer = D->getInClassInitializer()) {
3209 Expr *ToInitializer = Importer.Import(FromInitializer);
3211 ToField->setInClassInitializer(ToInitializer);
3215 ToField->setImplicit(D->isImplicit());
3216 Importer.Imported(D, ToField);
3217 LexicalDC->addDeclInternal(ToField);
3221 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3222 // Import the major distinguishing characteristics of a variable.
3223 DeclContext *DC, *LexicalDC;
3224 DeclarationName Name;
3227 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3232 // Determine whether we've already imported this field.
3233 SmallVector<NamedDecl *, 2> FoundDecls;
3234 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3235 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3236 if (IndirectFieldDecl *FoundField
3237 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3238 // For anonymous indirect fields, match up by index.
3239 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3242 if (Importer.IsStructurallyEquivalent(D->getType(),
3243 FoundField->getType(),
3245 Importer.Imported(D, FoundField);
3249 // If there are more anonymous fields to check, continue.
3250 if (!Name && I < N-1)
3253 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3254 << Name << D->getType() << FoundField->getType();
3255 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3256 << FoundField->getType();
3262 QualType T = Importer.Import(D->getType());
3266 NamedDecl **NamedChain =
3267 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3270 for (auto *PI : D->chain()) {
3271 Decl *D = Importer.Import(PI);
3274 NamedChain[i++] = cast<NamedDecl>(D);
3277 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3278 Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3279 {NamedChain, D->getChainingSize()});
3281 for (const auto *Attr : D->attrs())
3282 ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3284 ToIndirectField->setAccess(D->getAccess());
3285 ToIndirectField->setLexicalDeclContext(LexicalDC);
3286 Importer.Imported(D, ToIndirectField);
3287 LexicalDC->addDeclInternal(ToIndirectField);
3288 return ToIndirectField;
3291 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3292 // Import the major distinguishing characteristics of an ivar.
3293 DeclContext *DC, *LexicalDC;
3294 DeclarationName Name;
3297 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3302 // Determine whether we've already imported this ivar
3303 SmallVector<NamedDecl *, 2> FoundDecls;
3304 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3305 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3306 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3307 if (Importer.IsStructurallyEquivalent(D->getType(),
3308 FoundIvar->getType())) {
3309 Importer.Imported(D, FoundIvar);
3313 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3314 << Name << D->getType() << FoundIvar->getType();
3315 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3316 << FoundIvar->getType();
3322 QualType T = Importer.Import(D->getType());
3326 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3327 Expr *BitWidth = Importer.Import(D->getBitWidth());
3328 if (!BitWidth && D->getBitWidth())
3331 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3332 cast<ObjCContainerDecl>(DC),
3333 Importer.Import(D->getInnerLocStart()),
3334 Loc, Name.getAsIdentifierInfo(),
3335 T, TInfo, D->getAccessControl(),
3336 BitWidth, D->getSynthesize());
3337 ToIvar->setLexicalDeclContext(LexicalDC);
3338 Importer.Imported(D, ToIvar);
3339 LexicalDC->addDeclInternal(ToIvar);
3344 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3345 // Import the major distinguishing characteristics of a variable.
3346 DeclContext *DC, *LexicalDC;
3347 DeclarationName Name;
3350 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3355 // Try to find a variable in our own ("to") context with the same name and
3356 // in the same context as the variable we're importing.
3357 if (D->isFileVarDecl()) {
3358 VarDecl *MergeWithVar = nullptr;
3359 SmallVector<NamedDecl *, 4> ConflictingDecls;
3360 unsigned IDNS = Decl::IDNS_Ordinary;
3361 SmallVector<NamedDecl *, 2> FoundDecls;
3362 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3363 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3364 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3367 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3368 // We have found a variable that we may need to merge with. Check it.
3369 if (FoundVar->hasExternalFormalLinkage() &&
3370 D->hasExternalFormalLinkage()) {
3371 if (Importer.IsStructurallyEquivalent(D->getType(),
3372 FoundVar->getType())) {
3373 MergeWithVar = FoundVar;
3377 const ArrayType *FoundArray
3378 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3379 const ArrayType *TArray
3380 = Importer.getToContext().getAsArrayType(D->getType());
3381 if (FoundArray && TArray) {
3382 if (isa<IncompleteArrayType>(FoundArray) &&
3383 isa<ConstantArrayType>(TArray)) {
3385 QualType T = Importer.Import(D->getType());
3389 FoundVar->setType(T);
3390 MergeWithVar = FoundVar;
3392 } else if (isa<IncompleteArrayType>(TArray) &&
3393 isa<ConstantArrayType>(FoundArray)) {
3394 MergeWithVar = FoundVar;
3399 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3400 << Name << D->getType() << FoundVar->getType();
3401 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3402 << FoundVar->getType();
3406 ConflictingDecls.push_back(FoundDecls[I]);
3410 // An equivalent variable with external linkage has been found. Link
3411 // the two declarations, then merge them.
3412 Importer.Imported(D, MergeWithVar);
3414 if (VarDecl *DDef = D->getDefinition()) {
3415 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3416 Importer.ToDiag(ExistingDef->getLocation(),
3417 diag::err_odr_variable_multiple_def)
3419 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3421 Expr *Init = Importer.Import(DDef->getInit());
3422 MergeWithVar->setInit(Init);
3423 if (DDef->isInitKnownICE()) {
3424 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3425 Eval->CheckedICE = true;
3426 Eval->IsICE = DDef->isInitICE();
3431 return MergeWithVar;
3434 if (!ConflictingDecls.empty()) {
3435 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3436 ConflictingDecls.data(),
3437 ConflictingDecls.size());
3444 QualType T = Importer.Import(D->getType());
3448 // Create the imported variable.
3449 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3450 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3451 Importer.Import(D->getInnerLocStart()),
3452 Loc, Name.getAsIdentifierInfo(),
3454 D->getStorageClass());
3455 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3456 ToVar->setAccess(D->getAccess());
3457 ToVar->setLexicalDeclContext(LexicalDC);
3458 Importer.Imported(D, ToVar);
3459 LexicalDC->addDeclInternal(ToVar);
3461 if (!D->isFileVarDecl() &&
3465 // Merge the initializer.
3466 if (ImportDefinition(D, ToVar))
3472 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3473 // Parameters are created in the translation unit's context, then moved
3474 // into the function declaration's context afterward.
3475 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3477 // Import the name of this declaration.
3478 DeclarationName Name = Importer.Import(D->getDeclName());
3479 if (D->getDeclName() && !Name)
3482 // Import the location of this declaration.
3483 SourceLocation Loc = Importer.Import(D->getLocation());
3485 // Import the parameter's type.
3486 QualType T = Importer.Import(D->getType());
3490 // Create the imported parameter.
3491 ImplicitParamDecl *ToParm
3492 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3493 Loc, Name.getAsIdentifierInfo(),
3495 return Importer.Imported(D, ToParm);
3498 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3499 // Parameters are created in the translation unit's context, then moved
3500 // into the function declaration's context afterward.
3501 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3503 // Import the name of this declaration.
3504 DeclarationName Name = Importer.Import(D->getDeclName());
3505 if (D->getDeclName() && !Name)
3508 // Import the location of this declaration.
3509 SourceLocation Loc = Importer.Import(D->getLocation());
3511 // Import the parameter's type.
3512 QualType T = Importer.Import(D->getType());
3516 // Create the imported parameter.
3517 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3518 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3519 Importer.Import(D->getInnerLocStart()),
3520 Loc, Name.getAsIdentifierInfo(),
3521 T, TInfo, D->getStorageClass(),
3522 /*FIXME: Default argument*/nullptr);
3523 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3526 ToParm->setIsUsed();
3528 return Importer.Imported(D, ToParm);
3531 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3532 // Import the major distinguishing characteristics of a method.
3533 DeclContext *DC, *LexicalDC;
3534 DeclarationName Name;
3537 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3542 SmallVector<NamedDecl *, 2> FoundDecls;
3543 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3544 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3545 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3546 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3549 // Check return types.
3550 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3551 FoundMethod->getReturnType())) {
3552 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3553 << D->isInstanceMethod() << Name << D->getReturnType()
3554 << FoundMethod->getReturnType();
3555 Importer.ToDiag(FoundMethod->getLocation(),
3556 diag::note_odr_objc_method_here)
3557 << D->isInstanceMethod() << Name;
3561 // Check the number of parameters.
3562 if (D->param_size() != FoundMethod->param_size()) {
3563 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3564 << D->isInstanceMethod() << Name
3565 << D->param_size() << FoundMethod->param_size();
3566 Importer.ToDiag(FoundMethod->getLocation(),
3567 diag::note_odr_objc_method_here)
3568 << D->isInstanceMethod() << Name;
3572 // Check parameter types.
3573 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3574 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3575 P != PEnd; ++P, ++FoundP) {
3576 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3577 (*FoundP)->getType())) {
3578 Importer.FromDiag((*P)->getLocation(),
3579 diag::err_odr_objc_method_param_type_inconsistent)
3580 << D->isInstanceMethod() << Name
3581 << (*P)->getType() << (*FoundP)->getType();
3582 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3583 << (*FoundP)->getType();
3588 // Check variadic/non-variadic.
3589 // Check the number of parameters.
3590 if (D->isVariadic() != FoundMethod->isVariadic()) {
3591 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3592 << D->isInstanceMethod() << Name;
3593 Importer.ToDiag(FoundMethod->getLocation(),
3594 diag::note_odr_objc_method_here)
3595 << D->isInstanceMethod() << Name;
3599 // FIXME: Any other bits we need to merge?
3600 return Importer.Imported(D, FoundMethod);
3604 // Import the result type.
3605 QualType ResultTy = Importer.Import(D->getReturnType());
3606 if (ResultTy.isNull())
3609 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3611 ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3612 Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3613 Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3614 D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3615 D->getImplementationControl(), D->hasRelatedResultType());
3617 // FIXME: When we decide to merge method definitions, we'll need to
3618 // deal with implicit parameters.
3620 // Import the parameters
3621 SmallVector<ParmVarDecl *, 5> ToParams;
3622 for (auto *FromP : D->parameters()) {
3623 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3627 ToParams.push_back(ToP);
3630 // Set the parameters.
3631 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3632 ToParams[I]->setOwningFunction(ToMethod);
3633 ToMethod->addDeclInternal(ToParams[I]);
3635 SmallVector<SourceLocation, 12> SelLocs;
3636 D->getSelectorLocs(SelLocs);
3637 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3639 ToMethod->setLexicalDeclContext(LexicalDC);
3640 Importer.Imported(D, ToMethod);
3641 LexicalDC->addDeclInternal(ToMethod);
3645 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3646 // Import the major distinguishing characteristics of a category.
3647 DeclContext *DC, *LexicalDC;
3648 DeclarationName Name;
3651 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3656 TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3660 ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3661 Importer.getToContext(), DC,
3663 Importer.Import(D->getVarianceLoc()),
3665 Importer.Import(D->getLocation()),
3666 Name.getAsIdentifierInfo(),
3667 Importer.Import(D->getColonLoc()),
3669 Importer.Imported(D, Result);
3670 Result->setLexicalDeclContext(LexicalDC);
3674 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3675 // Import the major distinguishing characteristics of a category.
3676 DeclContext *DC, *LexicalDC;
3677 DeclarationName Name;
3680 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3685 ObjCInterfaceDecl *ToInterface
3686 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3690 // Determine if we've already encountered this category.
3691 ObjCCategoryDecl *MergeWithCategory
3692 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3693 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3695 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3696 Importer.Import(D->getAtStartLoc()),
3698 Importer.Import(D->getCategoryNameLoc()),
3699 Name.getAsIdentifierInfo(),
3701 /*TypeParamList=*/nullptr,
3702 Importer.Import(D->getIvarLBraceLoc()),
3703 Importer.Import(D->getIvarRBraceLoc()));
3704 ToCategory->setLexicalDeclContext(LexicalDC);
3705 LexicalDC->addDeclInternal(ToCategory);
3706 Importer.Imported(D, ToCategory);
3707 // Import the type parameter list after calling Imported, to avoid
3708 // loops when bringing in their DeclContext.
3709 ToCategory->setTypeParamList(ImportObjCTypeParamList(
3710 D->getTypeParamList()));
3713 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3714 SmallVector<SourceLocation, 4> ProtocolLocs;
3715 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3716 = D->protocol_loc_begin();
3717 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3718 FromProtoEnd = D->protocol_end();
3719 FromProto != FromProtoEnd;
3720 ++FromProto, ++FromProtoLoc) {
3721 ObjCProtocolDecl *ToProto
3722 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3725 Protocols.push_back(ToProto);
3726 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3729 // FIXME: If we're merging, make sure that the protocol list is the same.
3730 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3731 ProtocolLocs.data(), Importer.getToContext());
3734 Importer.Imported(D, ToCategory);
3737 // Import all of the members of this category.
3738 ImportDeclContext(D);
3740 // If we have an implementation, import it as well.
3741 if (D->getImplementation()) {
3742 ObjCCategoryImplDecl *Impl
3743 = cast_or_null<ObjCCategoryImplDecl>(
3744 Importer.Import(D->getImplementation()));
3748 ToCategory->setImplementation(Impl);
3754 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3755 ObjCProtocolDecl *To,
3756 ImportDefinitionKind Kind) {
3757 if (To->getDefinition()) {
3758 if (shouldForceImportDeclContext(Kind))
3759 ImportDeclContext(From);
3763 // Start the protocol definition
3764 To->startDefinition();
3767 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3768 SmallVector<SourceLocation, 4> ProtocolLocs;
3769 ObjCProtocolDecl::protocol_loc_iterator
3770 FromProtoLoc = From->protocol_loc_begin();
3771 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3772 FromProtoEnd = From->protocol_end();
3773 FromProto != FromProtoEnd;
3774 ++FromProto, ++FromProtoLoc) {
3775 ObjCProtocolDecl *ToProto
3776 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3779 Protocols.push_back(ToProto);
3780 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3783 // FIXME: If we're merging, make sure that the protocol list is the same.
3784 To->setProtocolList(Protocols.data(), Protocols.size(),
3785 ProtocolLocs.data(), Importer.getToContext());
3787 if (shouldForceImportDeclContext(Kind)) {
3788 // Import all of the members of this protocol.
3789 ImportDeclContext(From, /*ForceImport=*/true);
3794 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3795 // If this protocol has a definition in the translation unit we're coming
3796 // from, but this particular declaration is not that definition, import the
3797 // definition and map to that.
3798 ObjCProtocolDecl *Definition = D->getDefinition();
3799 if (Definition && Definition != D) {
3800 Decl *ImportedDef = Importer.Import(Definition);
3804 return Importer.Imported(D, ImportedDef);
3807 // Import the major distinguishing characteristics of a protocol.
3808 DeclContext *DC, *LexicalDC;
3809 DeclarationName Name;
3812 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3817 ObjCProtocolDecl *MergeWithProtocol = nullptr;
3818 SmallVector<NamedDecl *, 2> FoundDecls;
3819 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3820 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3821 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3824 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3828 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3830 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3831 Name.getAsIdentifierInfo(), Loc,
3832 Importer.Import(D->getAtStartLoc()),
3833 /*PrevDecl=*/nullptr);
3834 ToProto->setLexicalDeclContext(LexicalDC);
3835 LexicalDC->addDeclInternal(ToProto);
3838 Importer.Imported(D, ToProto);
3840 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3846 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3847 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3848 DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3850 SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3851 SourceLocation LangLoc = Importer.Import(D->getLocation());
3853 bool HasBraces = D->hasBraces();
3855 LinkageSpecDecl *ToLinkageSpec =
3856 LinkageSpecDecl::Create(Importer.getToContext(),
3864 SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3865 ToLinkageSpec->setRBraceLoc(RBraceLoc);
3868 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3869 LexicalDC->addDeclInternal(ToLinkageSpec);
3871 Importer.Imported(D, ToLinkageSpec);
3873 return ToLinkageSpec;
3876 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3877 ObjCInterfaceDecl *To,
3878 ImportDefinitionKind Kind) {
3879 if (To->getDefinition()) {
3880 // Check consistency of superclass.
3881 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3883 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3888 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3889 if ((bool)FromSuper != (bool)ToSuper ||
3890 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3891 Importer.ToDiag(To->getLocation(),
3892 diag::err_odr_objc_superclass_inconsistent)
3893 << To->getDeclName();
3895 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3896 << To->getSuperClass()->getDeclName();
3898 Importer.ToDiag(To->getLocation(),
3899 diag::note_odr_objc_missing_superclass);
3900 if (From->getSuperClass())
3901 Importer.FromDiag(From->getSuperClassLoc(),
3902 diag::note_odr_objc_superclass)
3903 << From->getSuperClass()->getDeclName();
3905 Importer.FromDiag(From->getLocation(),
3906 diag::note_odr_objc_missing_superclass);
3909 if (shouldForceImportDeclContext(Kind))
3910 ImportDeclContext(From);
3914 // Start the definition.
3915 To->startDefinition();
3917 // If this class has a superclass, import it.
3918 if (From->getSuperClass()) {
3919 TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3923 To->setSuperClass(SuperTInfo);
3927 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3928 SmallVector<SourceLocation, 4> ProtocolLocs;
3929 ObjCInterfaceDecl::protocol_loc_iterator
3930 FromProtoLoc = From->protocol_loc_begin();
3932 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3933 FromProtoEnd = From->protocol_end();
3934 FromProto != FromProtoEnd;
3935 ++FromProto, ++FromProtoLoc) {
3936 ObjCProtocolDecl *ToProto
3937 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3940 Protocols.push_back(ToProto);
3941 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3944 // FIXME: If we're merging, make sure that the protocol list is the same.
3945 To->setProtocolList(Protocols.data(), Protocols.size(),
3946 ProtocolLocs.data(), Importer.getToContext());
3948 // Import categories. When the categories themselves are imported, they'll
3949 // hook themselves into this interface.
3950 for (auto *Cat : From->known_categories())
3951 Importer.Import(Cat);
3953 // If we have an @implementation, import it as well.
3954 if (From->getImplementation()) {
3955 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3956 Importer.Import(From->getImplementation()));
3960 To->setImplementation(Impl);
3963 if (shouldForceImportDeclContext(Kind)) {
3964 // Import all of the members of this class.
3965 ImportDeclContext(From, /*ForceImport=*/true);
3971 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
3975 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
3976 for (auto fromTypeParam : *list) {
3977 auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3978 Importer.Import(fromTypeParam));
3982 toTypeParams.push_back(toTypeParam);
3985 return ObjCTypeParamList::create(Importer.getToContext(),
3986 Importer.Import(list->getLAngleLoc()),
3988 Importer.Import(list->getRAngleLoc()));
3991 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3992 // If this class has a definition in the translation unit we're coming from,
3993 // but this particular declaration is not that definition, import the
3994 // definition and map to that.
3995 ObjCInterfaceDecl *Definition = D->getDefinition();
3996 if (Definition && Definition != D) {
3997 Decl *ImportedDef = Importer.Import(Definition);
4001 return Importer.Imported(D, ImportedDef);
4004 // Import the major distinguishing characteristics of an @interface.
4005 DeclContext *DC, *LexicalDC;
4006 DeclarationName Name;
4009 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4014 // Look for an existing interface with the same name.
4015 ObjCInterfaceDecl *MergeWithIface = nullptr;
4016 SmallVector<NamedDecl *, 2> FoundDecls;
4017 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4018 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4019 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4022 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
4026 // Create an interface declaration, if one does not already exist.
4027 ObjCInterfaceDecl *ToIface = MergeWithIface;
4029 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
4030 Importer.Import(D->getAtStartLoc()),
4031 Name.getAsIdentifierInfo(),
4032 /*TypeParamList=*/nullptr,
4033 /*PrevDecl=*/nullptr, Loc,
4034 D->isImplicitInterfaceDecl());
4035 ToIface->setLexicalDeclContext(LexicalDC);
4036 LexicalDC->addDeclInternal(ToIface);
4038 Importer.Imported(D, ToIface);
4039 // Import the type parameter list after calling Imported, to avoid
4040 // loops when bringing in their DeclContext.
4041 ToIface->setTypeParamList(ImportObjCTypeParamList(
4042 D->getTypeParamListAsWritten()));
4044 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
4050 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4051 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
4052 Importer.Import(D->getCategoryDecl()));
4056 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4058 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4062 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
4063 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
4064 Importer.Import(D->getIdentifier()),
4065 Category->getClassInterface(),
4066 Importer.Import(D->getLocation()),
4067 Importer.Import(D->getAtStartLoc()),
4070 DeclContext *LexicalDC = DC;
4071 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4072 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4076 ToImpl->setLexicalDeclContext(LexicalDC);
4079 LexicalDC->addDeclInternal(ToImpl);
4080 Category->setImplementation(ToImpl);
4083 Importer.Imported(D, ToImpl);
4084 ImportDeclContext(D);
4088 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4089 // Find the corresponding interface.
4090 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
4091 Importer.Import(D->getClassInterface()));
4095 // Import the superclass, if any.
4096 ObjCInterfaceDecl *Super = nullptr;
4097 if (D->getSuperClass()) {
4098 Super = cast_or_null<ObjCInterfaceDecl>(
4099 Importer.Import(D->getSuperClass()));
4104 ObjCImplementationDecl *Impl = Iface->getImplementation();
4106 // We haven't imported an implementation yet. Create a new @implementation
4108 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
4109 Importer.ImportContext(D->getDeclContext()),
4111 Importer.Import(D->getLocation()),
4112 Importer.Import(D->getAtStartLoc()),
4113 Importer.Import(D->getSuperClassLoc()),
4114 Importer.Import(D->getIvarLBraceLoc()),
4115 Importer.Import(D->getIvarRBraceLoc()));
4117 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4118 DeclContext *LexicalDC
4119 = Importer.ImportContext(D->getLexicalDeclContext());
4122 Impl->setLexicalDeclContext(LexicalDC);
4125 // Associate the implementation with the class it implements.
4126 Iface->setImplementation(Impl);
4127 Importer.Imported(D, Iface->getImplementation());
4129 Importer.Imported(D, Iface->getImplementation());
4131 // Verify that the existing @implementation has the same superclass.
4132 if ((Super && !Impl->getSuperClass()) ||
4133 (!Super && Impl->getSuperClass()) ||
4134 (Super && Impl->getSuperClass() &&
4135 !declaresSameEntity(Super->getCanonicalDecl(),
4136 Impl->getSuperClass()))) {
4137 Importer.ToDiag(Impl->getLocation(),
4138 diag::err_odr_objc_superclass_inconsistent)
4139 << Iface->getDeclName();
4140 // FIXME: It would be nice to have the location of the superclass
4142 if (Impl->getSuperClass())
4143 Importer.ToDiag(Impl->getLocation(),
4144 diag::note_odr_objc_superclass)
4145 << Impl->getSuperClass()->getDeclName();
4147 Importer.ToDiag(Impl->getLocation(),
4148 diag::note_odr_objc_missing_superclass);
4149 if (D->getSuperClass())
4150 Importer.FromDiag(D->getLocation(),
4151 diag::note_odr_objc_superclass)
4152 << D->getSuperClass()->getDeclName();
4154 Importer.FromDiag(D->getLocation(),
4155 diag::note_odr_objc_missing_superclass);
4160 // Import all of the members of this @implementation.
4161 ImportDeclContext(D);
4166 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
4167 // Import the major distinguishing characteristics of an @property.
4168 DeclContext *DC, *LexicalDC;
4169 DeclarationName Name;
4172 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4177 // Check whether we have already imported this property.
4178 SmallVector<NamedDecl *, 2> FoundDecls;
4179 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4180 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4181 if (ObjCPropertyDecl *FoundProp
4182 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
4183 // Check property types.
4184 if (!Importer.IsStructurallyEquivalent(D->getType(),
4185 FoundProp->getType())) {
4186 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
4187 << Name << D->getType() << FoundProp->getType();
4188 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4189 << FoundProp->getType();
4193 // FIXME: Check property attributes, getters, setters, etc.?
4195 // Consider these properties to be equivalent.
4196 Importer.Imported(D, FoundProp);
4202 TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4206 // Create the new property.
4207 ObjCPropertyDecl *ToProperty
4208 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
4209 Name.getAsIdentifierInfo(),
4210 Importer.Import(D->getAtLoc()),
4211 Importer.Import(D->getLParenLoc()),
4212 Importer.Import(D->getType()),
4214 D->getPropertyImplementation());
4215 Importer.Imported(D, ToProperty);
4216 ToProperty->setLexicalDeclContext(LexicalDC);
4217 LexicalDC->addDeclInternal(ToProperty);
4219 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4220 ToProperty->setPropertyAttributesAsWritten(
4221 D->getPropertyAttributesAsWritten());
4222 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
4223 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
4224 ToProperty->setGetterMethodDecl(
4225 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4226 ToProperty->setSetterMethodDecl(
4227 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4228 ToProperty->setPropertyIvarDecl(
4229 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4233 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4234 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
4235 Importer.Import(D->getPropertyDecl()));
4239 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4243 // Import the lexical declaration context.
4244 DeclContext *LexicalDC = DC;
4245 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4246 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4251 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4255 // Import the ivar (for an @synthesize).
4256 ObjCIvarDecl *Ivar = nullptr;
4257 if (D->getPropertyIvarDecl()) {
4258 Ivar = cast_or_null<ObjCIvarDecl>(
4259 Importer.Import(D->getPropertyIvarDecl()));
4264 ObjCPropertyImplDecl *ToImpl
4265 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4266 Property->getQueryKind());
4268 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
4269 Importer.Import(D->getLocStart()),
4270 Importer.Import(D->getLocation()),
4272 D->getPropertyImplementation(),
4274 Importer.Import(D->getPropertyIvarDeclLoc()));
4275 ToImpl->setLexicalDeclContext(LexicalDC);
4276 Importer.Imported(D, ToImpl);
4277 LexicalDC->addDeclInternal(ToImpl);
4279 // Check that we have the same kind of property implementation (@synthesize
4281 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4282 Importer.ToDiag(ToImpl->getLocation(),
4283 diag::err_odr_objc_property_impl_kind_inconsistent)
4284 << Property->getDeclName()
4285 << (ToImpl->getPropertyImplementation()
4286 == ObjCPropertyImplDecl::Dynamic);
4287 Importer.FromDiag(D->getLocation(),
4288 diag::note_odr_objc_property_impl_kind)
4289 << D->getPropertyDecl()->getDeclName()
4290 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4294 // For @synthesize, check that we have the same
4295 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4296 Ivar != ToImpl->getPropertyIvarDecl()) {
4297 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4298 diag::err_odr_objc_synthesize_ivar_inconsistent)
4299 << Property->getDeclName()
4300 << ToImpl->getPropertyIvarDecl()->getDeclName()
4301 << Ivar->getDeclName();
4302 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4303 diag::note_odr_objc_synthesize_ivar_here)
4304 << D->getPropertyIvarDecl()->getDeclName();
4308 // Merge the existing implementation with the new implementation.
4309 Importer.Imported(D, ToImpl);
4315 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4316 // For template arguments, we adopt the translation unit as our declaration
4317 // context. This context will be fixed when the actual template declaration
4320 // FIXME: Import default argument.
4321 return TemplateTypeParmDecl::Create(Importer.getToContext(),
4322 Importer.getToContext().getTranslationUnitDecl(),
4323 Importer.Import(D->getLocStart()),
4324 Importer.Import(D->getLocation()),
4327 Importer.Import(D->getIdentifier()),
4328 D->wasDeclaredWithTypename(),
4329 D->isParameterPack());
4333 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4334 // Import the name of this declaration.
4335 DeclarationName Name = Importer.Import(D->getDeclName());
4336 if (D->getDeclName() && !Name)
4339 // Import the location of this declaration.
4340 SourceLocation Loc = Importer.Import(D->getLocation());
4342 // Import the type of this declaration.
4343 QualType T = Importer.Import(D->getType());
4347 // Import type-source information.
4348 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4349 if (D->getTypeSourceInfo() && !TInfo)
4352 // FIXME: Import default argument.
4354 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4355 Importer.getToContext().getTranslationUnitDecl(),
4356 Importer.Import(D->getInnerLocStart()),
4357 Loc, D->getDepth(), D->getPosition(),
4358 Name.getAsIdentifierInfo(),
4359 T, D->isParameterPack(), TInfo);
4363 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4364 // Import the name of this declaration.
4365 DeclarationName Name = Importer.Import(D->getDeclName());
4366 if (D->getDeclName() && !Name)
4369 // Import the location of this declaration.
4370 SourceLocation Loc = Importer.Import(D->getLocation());
4372 // Import template parameters.
4373 TemplateParameterList *TemplateParams
4374 = ImportTemplateParameterList(D->getTemplateParameters());
4375 if (!TemplateParams)
4378 // FIXME: Import default argument.
4380 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
4381 Importer.getToContext().getTranslationUnitDecl(),
4382 Loc, D->getDepth(), D->getPosition(),
4383 D->isParameterPack(),
4384 Name.getAsIdentifierInfo(),
4388 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4389 // If this record has a definition in the translation unit we're coming from,
4390 // but this particular declaration is not that definition, import the
4391 // definition and map to that.
4392 CXXRecordDecl *Definition
4393 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4394 if (Definition && Definition != D->getTemplatedDecl()) {
4396 = Importer.Import(Definition->getDescribedClassTemplate());
4400 return Importer.Imported(D, ImportedDef);
4403 // Import the major distinguishing characteristics of this class template.
4404 DeclContext *DC, *LexicalDC;
4405 DeclarationName Name;
4408 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4413 // We may already have a template of the same name; try to find and match it.
4414 if (!DC->isFunctionOrMethod()) {
4415 SmallVector<NamedDecl *, 4> ConflictingDecls;
4416 SmallVector<NamedDecl *, 2> FoundDecls;
4417 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4418 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4419 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4422 Decl *Found = FoundDecls[I];
4423 if (ClassTemplateDecl *FoundTemplate
4424 = dyn_cast<ClassTemplateDecl>(Found)) {
4425 if (IsStructuralMatch(D, FoundTemplate)) {
4426 // The class templates structurally match; call it the same template.
4427 // FIXME: We may be filling in a forward declaration here. Handle
4429 Importer.Imported(D->getTemplatedDecl(),
4430 FoundTemplate->getTemplatedDecl());
4431 return Importer.Imported(D, FoundTemplate);
4435 ConflictingDecls.push_back(FoundDecls[I]);
4438 if (!ConflictingDecls.empty()) {
4439 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4440 ConflictingDecls.data(),
4441 ConflictingDecls.size());
4448 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4450 // Create the declaration that is being templated.
4451 // Create the declaration that is being templated.
4452 CXXRecordDecl *D2Templated = cast_or_null<CXXRecordDecl>(
4453 Importer.Import(DTemplated));
4457 // Resolve possible cyclic import.
4458 if (Decl *AlreadyImported = Importer.GetAlreadyImportedOrNull(D))
4459 return AlreadyImported;
4461 // Create the class template declaration itself.
4462 TemplateParameterList *TemplateParams
4463 = ImportTemplateParameterList(D->getTemplateParameters());
4464 if (!TemplateParams)
4467 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4468 Loc, Name, TemplateParams,
4470 /*PrevDecl=*/nullptr);
4471 D2Templated->setDescribedClassTemplate(D2);
4473 D2->setAccess(D->getAccess());
4474 D2->setLexicalDeclContext(LexicalDC);
4475 LexicalDC->addDeclInternal(D2);
4477 // Note the relationship between the class templates.
4478 Importer.Imported(D, D2);
4479 Importer.Imported(DTemplated, D2Templated);
4481 if (DTemplated->isCompleteDefinition() &&
4482 !D2Templated->isCompleteDefinition()) {
4483 // FIXME: Import definition!
4489 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4490 ClassTemplateSpecializationDecl *D) {
4491 // If this record has a definition in the translation unit we're coming from,
4492 // but this particular declaration is not that definition, import the
4493 // definition and map to that.
4494 TagDecl *Definition = D->getDefinition();
4495 if (Definition && Definition != D) {
4496 Decl *ImportedDef = Importer.Import(Definition);
4500 return Importer.Imported(D, ImportedDef);
4503 ClassTemplateDecl *ClassTemplate
4504 = cast_or_null<ClassTemplateDecl>(Importer.Import(
4505 D->getSpecializedTemplate()));
4509 // Import the context of this declaration.
4510 DeclContext *DC = ClassTemplate->getDeclContext();
4514 DeclContext *LexicalDC = DC;
4515 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4516 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4521 // Import the location of this declaration.
4522 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4523 SourceLocation IdLoc = Importer.Import(D->getLocation());
4525 // Import template arguments.
4526 SmallVector<TemplateArgument, 2> TemplateArgs;
4527 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4528 D->getTemplateArgs().size(),
4532 // Try to find an existing specialization with these template arguments.
4533 void *InsertPos = nullptr;
4534 ClassTemplateSpecializationDecl *D2
4535 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4537 // We already have a class template specialization with these template
4540 // FIXME: Check for specialization vs. instantiation errors.
4542 if (RecordDecl *FoundDef = D2->getDefinition()) {
4543 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4544 // The record types structurally match, or the "from" translation
4545 // unit only had a forward declaration anyway; call it the same
4547 return Importer.Imported(D, FoundDef);
4551 // Create a new specialization.
4552 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4553 D->getTagKind(), DC,
4556 TemplateArgs.data(),
4557 TemplateArgs.size(),
4558 /*PrevDecl=*/nullptr);
4559 D2->setSpecializationKind(D->getSpecializationKind());
4561 // Add this specialization to the class template.
4562 ClassTemplate->AddSpecialization(D2, InsertPos);
4564 // Import the qualifier, if any.
4565 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4567 // Add the specialization to this context.
4568 D2->setLexicalDeclContext(LexicalDC);
4569 LexicalDC->addDeclInternal(D2);
4571 Importer.Imported(D, D2);
4573 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4579 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4580 // If this variable has a definition in the translation unit we're coming
4582 // but this particular declaration is not that definition, import the
4583 // definition and map to that.
4584 VarDecl *Definition =
4585 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4586 if (Definition && Definition != D->getTemplatedDecl()) {
4587 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4591 return Importer.Imported(D, ImportedDef);
4594 // Import the major distinguishing characteristics of this variable template.
4595 DeclContext *DC, *LexicalDC;
4596 DeclarationName Name;
4599 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4604 // We may already have a template of the same name; try to find and match it.
4605 assert(!DC->isFunctionOrMethod() &&
4606 "Variable templates cannot be declared at function scope");
4607 SmallVector<NamedDecl *, 4> ConflictingDecls;
4608 SmallVector<NamedDecl *, 2> FoundDecls;
4609 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4610 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4611 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4614 Decl *Found = FoundDecls[I];
4615 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4616 if (IsStructuralMatch(D, FoundTemplate)) {
4617 // The variable templates structurally match; call it the same template.
4618 Importer.Imported(D->getTemplatedDecl(),
4619 FoundTemplate->getTemplatedDecl());
4620 return Importer.Imported(D, FoundTemplate);
4624 ConflictingDecls.push_back(FoundDecls[I]);
4627 if (!ConflictingDecls.empty()) {
4628 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4629 ConflictingDecls.data(),
4630 ConflictingDecls.size());
4636 VarDecl *DTemplated = D->getTemplatedDecl();
4639 QualType T = Importer.Import(DTemplated->getType());
4643 // Create the declaration that is being templated.
4644 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4645 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4646 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4647 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4648 IdLoc, Name.getAsIdentifierInfo(), T,
4649 TInfo, DTemplated->getStorageClass());
4650 D2Templated->setAccess(DTemplated->getAccess());
4651 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4652 D2Templated->setLexicalDeclContext(LexicalDC);
4654 // Importer.Imported(DTemplated, D2Templated);
4655 // LexicalDC->addDeclInternal(D2Templated);
4657 // Merge the initializer.
4658 if (ImportDefinition(DTemplated, D2Templated))
4661 // Create the variable template declaration itself.
4662 TemplateParameterList *TemplateParams =
4663 ImportTemplateParameterList(D->getTemplateParameters());
4664 if (!TemplateParams)
4667 VarTemplateDecl *D2 = VarTemplateDecl::Create(
4668 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4669 D2Templated->setDescribedVarTemplate(D2);
4671 D2->setAccess(D->getAccess());
4672 D2->setLexicalDeclContext(LexicalDC);
4673 LexicalDC->addDeclInternal(D2);
4675 // Note the relationship between the variable templates.
4676 Importer.Imported(D, D2);
4677 Importer.Imported(DTemplated, D2Templated);
4679 if (DTemplated->isThisDeclarationADefinition() &&
4680 !D2Templated->isThisDeclarationADefinition()) {
4681 // FIXME: Import definition!
4687 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4688 VarTemplateSpecializationDecl *D) {
4689 // If this record has a definition in the translation unit we're coming from,
4690 // but this particular declaration is not that definition, import the
4691 // definition and map to that.
4692 VarDecl *Definition = D->getDefinition();
4693 if (Definition && Definition != D) {
4694 Decl *ImportedDef = Importer.Import(Definition);
4698 return Importer.Imported(D, ImportedDef);
4701 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4702 Importer.Import(D->getSpecializedTemplate()));
4706 // Import the context of this declaration.
4707 DeclContext *DC = VarTemplate->getDeclContext();
4711 DeclContext *LexicalDC = DC;
4712 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4713 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4718 // Import the location of this declaration.
4719 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4720 SourceLocation IdLoc = Importer.Import(D->getLocation());
4722 // Import template arguments.
4723 SmallVector<TemplateArgument, 2> TemplateArgs;
4724 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4725 D->getTemplateArgs().size(), TemplateArgs))
4728 // Try to find an existing specialization with these template arguments.
4729 void *InsertPos = nullptr;
4730 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4731 TemplateArgs, InsertPos);
4733 // We already have a variable template specialization with these template
4736 // FIXME: Check for specialization vs. instantiation errors.
4738 if (VarDecl *FoundDef = D2->getDefinition()) {
4739 if (!D->isThisDeclarationADefinition() ||
4740 IsStructuralMatch(D, FoundDef)) {
4741 // The record types structurally match, or the "from" translation
4742 // unit only had a forward declaration anyway; call it the same
4744 return Importer.Imported(D, FoundDef);
4750 QualType T = Importer.Import(D->getType());
4753 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4755 // Create a new specialization.
4756 D2 = VarTemplateSpecializationDecl::Create(
4757 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4758 D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4759 D2->setSpecializationKind(D->getSpecializationKind());
4760 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4762 // Add this specialization to the class template.
4763 VarTemplate->AddSpecialization(D2, InsertPos);
4765 // Import the qualifier, if any.
4766 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4768 // Add the specialization to this context.
4769 D2->setLexicalDeclContext(LexicalDC);
4770 LexicalDC->addDeclInternal(D2);
4772 Importer.Imported(D, D2);
4774 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4780 //----------------------------------------------------------------------------
4781 // Import Statements
4782 //----------------------------------------------------------------------------
4784 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4786 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4787 size_t NumDecls = DG.end() - DG.begin();
4788 SmallVector<Decl *, 1> ToDecls(NumDecls);
4789 auto &_Importer = this->Importer;
4790 std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4791 [&_Importer](Decl *D) -> Decl * {
4792 return _Importer.Import(D);
4794 return DeclGroupRef::Create(Importer.getToContext(),
4799 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4800 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4801 << S->getStmtClassName();
4806 Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
4807 SmallVector<IdentifierInfo *, 4> Names;
4808 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4809 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
4812 Names.push_back(ToII);
4814 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4815 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
4818 Names.push_back(ToII);
4821 SmallVector<StringLiteral *, 4> Clobbers;
4822 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
4823 StringLiteral *Clobber = cast_or_null<StringLiteral>(
4824 Importer.Import(S->getClobberStringLiteral(I)));
4827 Clobbers.push_back(Clobber);
4830 SmallVector<StringLiteral *, 4> Constraints;
4831 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4832 StringLiteral *Output = cast_or_null<StringLiteral>(
4833 Importer.Import(S->getOutputConstraintLiteral(I)));
4836 Constraints.push_back(Output);
4839 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4840 StringLiteral *Input = cast_or_null<StringLiteral>(
4841 Importer.Import(S->getInputConstraintLiteral(I)));
4844 Constraints.push_back(Input);
4847 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs());
4848 if (ImportArrayChecked(S->begin_outputs(), S->end_outputs(), Exprs.begin()))
4851 if (ImportArrayChecked(S->begin_inputs(), S->end_inputs(),
4852 Exprs.begin() + S->getNumOutputs()))
4855 StringLiteral *AsmStr = cast_or_null<StringLiteral>(
4856 Importer.Import(S->getAsmString()));
4860 return new (Importer.getToContext()) GCCAsmStmt(
4861 Importer.getToContext(),
4862 Importer.Import(S->getAsmLoc()),
4871 S->getNumClobbers(),
4873 Importer.Import(S->getRParenLoc()));
4876 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4877 DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4878 for (Decl *ToD : ToDG) {
4882 SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4883 SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4884 return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4887 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4888 SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4889 return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4890 S->hasLeadingEmptyMacro());
4893 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4894 llvm::SmallVector<Stmt *, 8> ToStmts(S->size());
4896 if (ImportArrayChecked(S->body_begin(), S->body_end(), ToStmts.begin()))
4899 SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4900 SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4901 return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
4903 ToLBraceLoc, ToRBraceLoc);
4906 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4907 Expr *ToLHS = Importer.Import(S->getLHS());
4910 Expr *ToRHS = Importer.Import(S->getRHS());
4911 if (!ToRHS && S->getRHS())
4913 SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4914 SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4915 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4916 return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
4917 ToCaseLoc, ToEllipsisLoc,
4921 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4922 SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4923 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4924 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4925 if (!ToSubStmt && S->getSubStmt())
4927 return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4931 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4932 SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4933 LabelDecl *ToLabelDecl =
4934 cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4935 if (!ToLabelDecl && S->getDecl())
4937 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4938 if (!ToSubStmt && S->getSubStmt())
4940 return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4944 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4945 SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4946 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4947 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4948 ASTContext &_ToContext = Importer.getToContext();
4949 std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4950 [&_ToContext](const Attr *A) -> const Attr * {
4951 return A->clone(_ToContext);
4953 for (const Attr *ToA : ToAttrs) {
4957 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4958 if (!ToSubStmt && S->getSubStmt())
4960 return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4961 ToAttrs, ToSubStmt);
4964 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4965 SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4966 VarDecl *ToConditionVariable = nullptr;
4967 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4968 ToConditionVariable =
4969 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4970 if (!ToConditionVariable)
4973 Expr *ToCondition = Importer.Import(S->getCond());
4974 if (!ToCondition && S->getCond())
4976 Stmt *ToThenStmt = Importer.Import(S->getThen());
4977 if (!ToThenStmt && S->getThen())
4979 SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4980 Stmt *ToElseStmt = Importer.Import(S->getElse());
4981 if (!ToElseStmt && S->getElse())
4983 return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4984 ToIfLoc, S->isConstexpr(),
4985 ToConditionVariable,
4986 ToCondition, ToThenStmt,
4987 ToElseLoc, ToElseStmt);
4990 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4991 VarDecl *ToConditionVariable = nullptr;
4992 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4993 ToConditionVariable =
4994 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4995 if (!ToConditionVariable)
4998 Expr *ToCondition = Importer.Import(S->getCond());
4999 if (!ToCondition && S->getCond())
5001 SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
5002 Importer.getToContext(), ToConditionVariable,
5004 Stmt *ToBody = Importer.Import(S->getBody());
5005 if (!ToBody && S->getBody())
5007 ToStmt->setBody(ToBody);
5008 ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
5009 // Now we have to re-chain the cases.
5010 SwitchCase *LastChainedSwitchCase = nullptr;
5011 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5012 SC = SC->getNextSwitchCase()) {
5013 SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
5016 if (LastChainedSwitchCase)
5017 LastChainedSwitchCase->setNextSwitchCase(ToSC);
5019 ToStmt->setSwitchCaseList(ToSC);
5020 LastChainedSwitchCase = ToSC;
5025 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
5026 VarDecl *ToConditionVariable = nullptr;
5027 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5028 ToConditionVariable =
5029 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5030 if (!ToConditionVariable)
5033 Expr *ToCondition = Importer.Import(S->getCond());
5034 if (!ToCondition && S->getCond())
5036 Stmt *ToBody = Importer.Import(S->getBody());
5037 if (!ToBody && S->getBody())
5039 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5040 return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
5041 ToConditionVariable,
5042 ToCondition, ToBody,
5046 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
5047 Stmt *ToBody = Importer.Import(S->getBody());
5048 if (!ToBody && S->getBody())
5050 Expr *ToCondition = Importer.Import(S->getCond());
5051 if (!ToCondition && S->getCond())
5053 SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
5054 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5055 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5056 return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
5057 ToDoLoc, ToWhileLoc,
5061 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
5062 Stmt *ToInit = Importer.Import(S->getInit());
5063 if (!ToInit && S->getInit())
5065 Expr *ToCondition = Importer.Import(S->getCond());
5066 if (!ToCondition && S->getCond())
5068 VarDecl *ToConditionVariable = nullptr;
5069 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5070 ToConditionVariable =
5071 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5072 if (!ToConditionVariable)
5075 Expr *ToInc = Importer.Import(S->getInc());
5076 if (!ToInc && S->getInc())
5078 Stmt *ToBody = Importer.Import(S->getBody());
5079 if (!ToBody && S->getBody())
5081 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5082 SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
5083 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5084 return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
5085 ToInit, ToCondition,
5086 ToConditionVariable,
5088 ToForLoc, ToLParenLoc,
5092 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
5093 LabelDecl *ToLabel = nullptr;
5094 if (LabelDecl *FromLabel = S->getLabel()) {
5095 ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
5099 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5100 SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
5101 return new (Importer.getToContext()) GotoStmt(ToLabel,
5102 ToGotoLoc, ToLabelLoc);
5105 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
5106 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5107 SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
5108 Expr *ToTarget = Importer.Import(S->getTarget());
5109 if (!ToTarget && S->getTarget())
5111 return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
5115 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
5116 SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
5117 return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
5120 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
5121 SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
5122 return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
5125 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
5126 SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
5127 Expr *ToRetExpr = Importer.Import(S->getRetValue());
5128 if (!ToRetExpr && S->getRetValue())
5130 VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
5131 VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
5132 if (!ToNRVOCandidate && NRVOCandidate)
5134 return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
5138 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
5139 SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
5140 VarDecl *ToExceptionDecl = nullptr;
5141 if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
5143 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5144 if (!ToExceptionDecl)
5147 Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
5148 if (!ToHandlerBlock && S->getHandlerBlock())
5150 return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
5155 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
5156 SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
5157 Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
5158 if (!ToTryBlock && S->getTryBlock())
5160 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5161 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5162 CXXCatchStmt *FromHandler = S->getHandler(HI);
5163 if (Stmt *ToHandler = Importer.Import(FromHandler))
5164 ToHandlers[HI] = ToHandler;
5168 return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
5172 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
5174 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
5175 if (!ToRange && S->getRangeStmt())
5178 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
5179 if (!ToBegin && S->getBeginStmt())
5182 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
5183 if (!ToEnd && S->getEndStmt())
5185 Expr *ToCond = Importer.Import(S->getCond());
5186 if (!ToCond && S->getCond())
5188 Expr *ToInc = Importer.Import(S->getInc());
5189 if (!ToInc && S->getInc())
5191 DeclStmt *ToLoopVar =
5192 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
5193 if (!ToLoopVar && S->getLoopVarStmt())
5195 Stmt *ToBody = Importer.Import(S->getBody());
5196 if (!ToBody && S->getBody())
5198 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5199 SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
5200 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5201 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5202 return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBegin, ToEnd,
5205 ToForLoc, ToCoawaitLoc,
5206 ToColonLoc, ToRParenLoc);
5209 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
5210 Stmt *ToElem = Importer.Import(S->getElement());
5211 if (!ToElem && S->getElement())
5213 Expr *ToCollect = Importer.Import(S->getCollection());
5214 if (!ToCollect && S->getCollection())
5216 Stmt *ToBody = Importer.Import(S->getBody());
5217 if (!ToBody && S->getBody())
5219 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5220 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5221 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
5227 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5228 SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
5229 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5230 VarDecl *ToExceptionDecl = nullptr;
5231 if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
5233 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5234 if (!ToExceptionDecl)
5237 Stmt *ToBody = Importer.Import(S->getCatchBody());
5238 if (!ToBody && S->getCatchBody())
5240 return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
5246 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5247 SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
5248 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
5249 if (!ToAtFinallyStmt && S->getFinallyBody())
5251 return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
5255 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
5256 SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
5257 Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
5258 if (!ToAtTryStmt && S->getTryBody())
5260 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
5261 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
5262 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
5263 if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
5264 ToCatchStmts[CI] = ToCatchStmt;
5268 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
5269 if (!ToAtFinallyStmt && S->getFinallyStmt())
5271 return ObjCAtTryStmt::Create(Importer.getToContext(),
5272 ToAtTryLoc, ToAtTryStmt,
5273 ToCatchStmts.begin(), ToCatchStmts.size(),
5277 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5278 (ObjCAtSynchronizedStmt *S) {
5279 SourceLocation ToAtSynchronizedLoc =
5280 Importer.Import(S->getAtSynchronizedLoc());
5281 Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5282 if (!ToSynchExpr && S->getSynchExpr())
5284 Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5285 if (!ToSynchBody && S->getSynchBody())
5287 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5288 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5291 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5292 SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5293 Expr *ToThrow = Importer.Import(S->getThrowExpr());
5294 if (!ToThrow && S->getThrowExpr())
5296 return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5299 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5300 (ObjCAutoreleasePoolStmt *S) {
5301 SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5302 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5303 if (!ToSubStmt && S->getSubStmt())
5305 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5309 //----------------------------------------------------------------------------
5310 // Import Expressions
5311 //----------------------------------------------------------------------------
5312 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5313 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5314 << E->getStmtClassName();
5318 Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
5319 QualType T = Importer.Import(E->getType());
5323 Expr *SubExpr = Importer.Import(E->getSubExpr());
5324 if (!SubExpr && E->getSubExpr())
5327 TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
5331 return new (Importer.getToContext()) VAArgExpr(
5332 Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
5333 Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
5337 Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
5338 QualType T = Importer.Import(E->getType());
5342 return new (Importer.getToContext()) GNUNullExpr(
5343 T, Importer.Import(E->getExprLoc()));
5346 Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
5347 QualType T = Importer.Import(E->getType());
5351 StringLiteral *SL = cast_or_null<StringLiteral>(
5352 Importer.Import(E->getFunctionName()));
5353 if (!SL && E->getFunctionName())
5356 return new (Importer.getToContext()) PredefinedExpr(
5357 Importer.Import(E->getExprLoc()), T, E->getIdentType(), SL);
5360 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5361 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5365 NamedDecl *FoundD = nullptr;
5366 if (E->getDecl() != E->getFoundDecl()) {
5367 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5372 QualType T = Importer.Import(E->getType());
5376 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5377 Importer.Import(E->getQualifierLoc()),
5378 Importer.Import(E->getTemplateKeywordLoc()),
5380 E->refersToEnclosingVariableOrCapture(),
5381 Importer.Import(E->getLocation()),
5382 T, E->getValueKind(),
5384 /*FIXME:TemplateArgs=*/nullptr);
5385 if (E->hadMultipleCandidates())
5386 DRE->setHadMultipleCandidates(true);
5390 Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5391 QualType T = Importer.Import(E->getType());
5395 return new (Importer.getToContext()) ImplicitValueInitExpr(T);
5398 ASTNodeImporter::Designator
5399 ASTNodeImporter::ImportDesignator(const Designator &D) {
5400 if (D.isFieldDesignator()) {
5401 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
5402 // Caller checks for import error
5403 return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
5404 Importer.Import(D.getFieldLoc()));
5406 if (D.isArrayDesignator())
5407 return Designator(D.getFirstExprIndex(),
5408 Importer.Import(D.getLBracketLoc()),
5409 Importer.Import(D.getRBracketLoc()));
5411 assert(D.isArrayRangeDesignator());
5412 return Designator(D.getFirstExprIndex(),
5413 Importer.Import(D.getLBracketLoc()),
5414 Importer.Import(D.getEllipsisLoc()),
5415 Importer.Import(D.getRBracketLoc()));
5419 Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
5420 Expr *Init = cast_or_null<Expr>(Importer.Import(DIE->getInit()));
5424 SmallVector<Expr *, 4> IndexExprs(DIE->getNumSubExprs() - 1);
5425 // List elements from the second, the first is Init itself
5426 for (unsigned I = 1, E = DIE->getNumSubExprs(); I < E; I++) {
5427 if (Expr *Arg = cast_or_null<Expr>(Importer.Import(DIE->getSubExpr(I))))
5428 IndexExprs[I - 1] = Arg;
5433 SmallVector<Designator, 4> Designators(DIE->size());
5434 llvm::transform(DIE->designators(), Designators.begin(),
5435 [this](const Designator &D) -> Designator {
5436 return ImportDesignator(D);
5439 for (const Designator &D : DIE->designators())
5440 if (D.isFieldDesignator() && !D.getFieldName())
5443 return DesignatedInitExpr::Create(
5444 Importer.getToContext(), Designators,
5445 IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()),
5446 DIE->usesGNUSyntax(), Init);
5449 Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
5450 QualType T = Importer.Import(E->getType());
5454 return new (Importer.getToContext())
5455 CXXNullPtrLiteralExpr(T, Importer.Import(E->getLocation()));
5458 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5459 QualType T = Importer.Import(E->getType());
5463 return IntegerLiteral::Create(Importer.getToContext(),
5465 Importer.Import(E->getLocation()));
5468 Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
5469 QualType T = Importer.Import(E->getType());
5473 return FloatingLiteral::Create(Importer.getToContext(),
5474 E->getValue(), E->isExact(), T,
5475 Importer.Import(E->getLocation()));
5478 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5479 QualType T = Importer.Import(E->getType());
5483 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5485 Importer.Import(E->getLocation()));
5488 Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
5489 QualType T = Importer.Import(E->getType());
5493 SmallVector<SourceLocation, 4> Locations(E->getNumConcatenated());
5494 ImportArray(E->tokloc_begin(), E->tokloc_end(), Locations.begin());
5496 return StringLiteral::Create(Importer.getToContext(), E->getBytes(),
5497 E->getKind(), E->isPascal(), T,
5498 Locations.data(), Locations.size());
5501 Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
5502 QualType T = Importer.Import(E->getType());
5506 TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo());
5510 Expr *Init = Importer.Import(E->getInitializer());
5514 return new (Importer.getToContext()) CompoundLiteralExpr(
5515 Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(),
5516 Init, E->isFileScope());
5519 Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
5520 QualType T = Importer.Import(E->getType());
5524 SmallVector<Expr *, 6> Exprs(E->getNumSubExprs());
5525 if (ImportArrayChecked(
5526 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
5530 return new (Importer.getToContext()) AtomicExpr(
5531 Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(),
5532 Importer.Import(E->getRParenLoc()));
5535 Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
5536 QualType T = Importer.Import(E->getType());
5540 LabelDecl *ToLabel = cast_or_null<LabelDecl>(Importer.Import(E->getLabel()));
5544 return new (Importer.getToContext()) AddrLabelExpr(
5545 Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()),
5549 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5550 Expr *SubExpr = Importer.Import(E->getSubExpr());
5554 return new (Importer.getToContext())
5555 ParenExpr(Importer.Import(E->getLParen()),
5556 Importer.Import(E->getRParen()),
5560 Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
5561 SmallVector<Expr *, 4> Exprs(E->getNumExprs());
5562 if (ImportArrayChecked(
5563 E->getExprs(), E->getExprs() + E->getNumExprs(), Exprs.begin()))
5566 return new (Importer.getToContext()) ParenListExpr(
5567 Importer.getToContext(), Importer.Import(E->getLParenLoc()),
5568 Exprs, Importer.Import(E->getLParenLoc()));
5571 Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
5572 QualType T = Importer.Import(E->getType());
5576 CompoundStmt *ToSubStmt = cast_or_null<CompoundStmt>(
5577 Importer.Import(E->getSubStmt()));
5578 if (!ToSubStmt && E->getSubStmt())
5581 return new (Importer.getToContext()) StmtExpr(ToSubStmt, T,
5582 Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc()));
5585 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5586 QualType T = Importer.Import(E->getType());
5590 Expr *SubExpr = Importer.Import(E->getSubExpr());
5594 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5595 T, E->getValueKind(),
5597 Importer.Import(E->getOperatorLoc()));
5600 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5601 UnaryExprOrTypeTraitExpr *E) {
5602 QualType ResultType = Importer.Import(E->getType());
5604 if (E->isArgumentType()) {
5605 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5609 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5611 Importer.Import(E->getOperatorLoc()),
5612 Importer.Import(E->getRParenLoc()));
5615 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5619 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5620 SubExpr, ResultType,
5621 Importer.Import(E->getOperatorLoc()),
5622 Importer.Import(E->getRParenLoc()));
5625 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5626 QualType T = Importer.Import(E->getType());
5630 Expr *LHS = Importer.Import(E->getLHS());
5634 Expr *RHS = Importer.Import(E->getRHS());
5638 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5639 T, E->getValueKind(),
5641 Importer.Import(E->getOperatorLoc()),
5642 E->isFPContractable());
5645 Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
5646 QualType T = Importer.Import(E->getType());
5650 Expr *ToLHS = Importer.Import(E->getLHS());
5654 Expr *ToRHS = Importer.Import(E->getRHS());
5658 Expr *ToCond = Importer.Import(E->getCond());
5662 return new (Importer.getToContext()) ConditionalOperator(
5663 ToCond, Importer.Import(E->getQuestionLoc()),
5664 ToLHS, Importer.Import(E->getColonLoc()),
5665 ToRHS, T, E->getValueKind(), E->getObjectKind());
5668 Expr *ASTNodeImporter::VisitBinaryConditionalOperator(
5669 BinaryConditionalOperator *E) {
5670 QualType T = Importer.Import(E->getType());
5674 Expr *Common = Importer.Import(E->getCommon());
5678 Expr *Cond = Importer.Import(E->getCond());
5682 OpaqueValueExpr *OpaqueValue = cast_or_null<OpaqueValueExpr>(
5683 Importer.Import(E->getOpaqueValue()));
5687 Expr *TrueExpr = Importer.Import(E->getTrueExpr());
5691 Expr *FalseExpr = Importer.Import(E->getFalseExpr());
5695 return new (Importer.getToContext()) BinaryConditionalOperator(
5696 Common, OpaqueValue, Cond, TrueExpr, FalseExpr,
5697 Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()),
5698 T, E->getValueKind(), E->getObjectKind());
5701 Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
5702 QualType T = Importer.Import(E->getType());
5706 Expr *SourceExpr = Importer.Import(E->getSourceExpr());
5707 if (!SourceExpr && E->getSourceExpr())
5710 return new (Importer.getToContext()) OpaqueValueExpr(
5711 Importer.Import(E->getExprLoc()), T, E->getValueKind(),
5712 E->getObjectKind(), SourceExpr);
5715 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5716 QualType T = Importer.Import(E->getType());
5720 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5721 if (CompLHSType.isNull())
5724 QualType CompResultType = Importer.Import(E->getComputationResultType());
5725 if (CompResultType.isNull())
5728 Expr *LHS = Importer.Import(E->getLHS());
5732 Expr *RHS = Importer.Import(E->getRHS());
5736 return new (Importer.getToContext())
5737 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5738 T, E->getValueKind(),
5740 CompLHSType, CompResultType,
5741 Importer.Import(E->getOperatorLoc()),
5742 E->isFPContractable());
5745 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
5746 if (E->path_empty()) return false;
5748 // TODO: import cast paths
5752 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5753 QualType T = Importer.Import(E->getType());
5757 Expr *SubExpr = Importer.Import(E->getSubExpr());
5761 CXXCastPath BasePath;
5762 if (ImportCastPath(E, BasePath))
5765 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5766 SubExpr, &BasePath, E->getValueKind());
5769 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
5770 QualType T = Importer.Import(E->getType());
5774 Expr *SubExpr = Importer.Import(E->getSubExpr());
5778 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5779 if (!TInfo && E->getTypeInfoAsWritten())
5782 CXXCastPath BasePath;
5783 if (ImportCastPath(E, BasePath))
5786 return CStyleCastExpr::Create(Importer.getToContext(), T,
5787 E->getValueKind(), E->getCastKind(),
5788 SubExpr, &BasePath, TInfo,
5789 Importer.Import(E->getLParenLoc()),
5790 Importer.Import(E->getRParenLoc()));
5793 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5794 QualType T = Importer.Import(E->getType());
5798 CXXConstructorDecl *ToCCD =
5799 dyn_cast_or_null<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5803 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
5804 if (ImportArrayChecked(E->getArgs(), E->getArgs() + E->getNumArgs(),
5808 return CXXConstructExpr::Create(Importer.getToContext(), T,
5809 Importer.Import(E->getLocation()),
5810 ToCCD, E->isElidable(),
5811 ToArgs, E->hadMultipleCandidates(),
5812 E->isListInitialization(),
5813 E->isStdInitListInitialization(),
5814 E->requiresZeroInitialization(),
5815 E->getConstructionKind(),
5816 Importer.Import(E->getParenOrBraceRange()));
5819 Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
5820 QualType T = Importer.Import(E->getType());
5824 Expr *ToFn = Importer.Import(E->getCallee());
5828 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
5830 if (ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
5833 return new (Importer.getToContext()) CXXMemberCallExpr(
5834 Importer.getToContext(), ToFn, ToArgs, T, E->getValueKind(),
5835 Importer.Import(E->getRParenLoc()));
5838 Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
5839 QualType T = Importer.Import(E->getType());
5843 return new (Importer.getToContext())
5844 CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit());
5847 Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
5848 QualType T = Importer.Import(E->getType());
5852 return new (Importer.getToContext())
5853 CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation()));
5857 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5858 QualType T = Importer.Import(E->getType());
5862 Expr *ToBase = Importer.Import(E->getBase());
5863 if (!ToBase && E->getBase())
5866 ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5867 if (!ToMember && E->getMemberDecl())
5870 DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5871 dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5872 E->getFoundDecl().getAccess());
5874 DeclarationNameInfo ToMemberNameInfo(
5875 Importer.Import(E->getMemberNameInfo().getName()),
5876 Importer.Import(E->getMemberNameInfo().getLoc()));
5878 if (E->hasExplicitTemplateArgs()) {
5879 return nullptr; // FIXME: handle template arguments
5882 return MemberExpr::Create(Importer.getToContext(), ToBase,
5884 Importer.Import(E->getOperatorLoc()),
5885 Importer.Import(E->getQualifierLoc()),
5886 Importer.Import(E->getTemplateKeywordLoc()),
5887 ToMember, ToFoundDecl, ToMemberNameInfo,
5888 nullptr, T, E->getValueKind(),
5889 E->getObjectKind());
5892 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5893 QualType T = Importer.Import(E->getType());
5897 Expr *ToCallee = Importer.Import(E->getCallee());
5898 if (!ToCallee && E->getCallee())
5901 unsigned NumArgs = E->getNumArgs();
5903 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5905 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5906 Expr *FromArg = E->getArg(ai);
5907 Expr *ToArg = Importer.Import(FromArg);
5913 Expr **ToArgs_Copied = new (Importer.getToContext())
5916 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5917 ToArgs_Copied[ai] = ToArgs[ai];
5919 return new (Importer.getToContext())
5920 CallExpr(Importer.getToContext(), ToCallee,
5921 llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5922 Importer.Import(E->getRParenLoc()));
5925 Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) {
5926 QualType T = Importer.Import(ILE->getType());
5930 llvm::SmallVector<Expr *, 4> Exprs(ILE->getNumInits());
5931 if (ImportArrayChecked(
5932 ILE->getInits(), ILE->getInits() + ILE->getNumInits(), Exprs.begin()))
5935 ASTContext &ToCtx = Importer.getToContext();
5936 InitListExpr *To = new (ToCtx) InitListExpr(
5937 ToCtx, Importer.Import(ILE->getLBraceLoc()),
5938 Exprs, Importer.Import(ILE->getLBraceLoc()));
5941 if (ILE->hasArrayFiller()) {
5942 Expr *Filler = Importer.Import(ILE->getArrayFiller());
5945 To->setArrayFiller(Filler);
5948 if (FieldDecl *FromFD = ILE->getInitializedFieldInUnion()) {
5949 FieldDecl *ToFD = cast_or_null<FieldDecl>(Importer.Import(FromFD));
5952 To->setInitializedFieldInUnion(ToFD);
5955 if (InitListExpr *SyntForm = ILE->getSyntacticForm()) {
5956 InitListExpr *ToSyntForm = cast_or_null<InitListExpr>(
5957 Importer.Import(SyntForm));
5960 To->setSyntacticForm(ToSyntForm);
5963 To->sawArrayRangeDesignator(ILE->hadArrayRangeDesignator());
5964 To->setValueDependent(ILE->isValueDependent());
5965 To->setInstantiationDependent(ILE->isInstantiationDependent());
5970 Expr *ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
5971 FieldDecl *ToField = llvm::dyn_cast_or_null<FieldDecl>(
5972 Importer.Import(DIE->getField()));
5973 if (!ToField && DIE->getField())
5976 return CXXDefaultInitExpr::Create(
5977 Importer.getToContext(), Importer.Import(DIE->getLocStart()), ToField);
5980 Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
5981 QualType ToType = Importer.Import(E->getType());
5982 if (ToType.isNull() && !E->getType().isNull())
5984 ExprValueKind VK = E->getValueKind();
5985 CastKind CK = E->getCastKind();
5986 Expr *ToOp = Importer.Import(E->getSubExpr());
5987 if (!ToOp && E->getSubExpr())
5989 CXXCastPath BasePath;
5990 if (ImportCastPath(E, BasePath))
5992 TypeSourceInfo *ToWritten = Importer.Import(E->getTypeInfoAsWritten());
5993 SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc());
5994 SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc());
5995 SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets());
5997 if (isa<CXXStaticCastExpr>(E)) {
5998 return CXXStaticCastExpr::Create(
5999 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6000 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6001 } else if (isa<CXXDynamicCastExpr>(E)) {
6002 return CXXDynamicCastExpr::Create(
6003 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6004 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6005 } else if (isa<CXXReinterpretCastExpr>(E)) {
6006 return CXXReinterpretCastExpr::Create(
6007 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6008 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6014 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
6015 ASTContext &FromContext, FileManager &FromFileManager,
6017 : ToContext(ToContext), FromContext(FromContext),
6018 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
6019 Minimal(MinimalImport), LastDiagFromFrom(false)
6021 ImportedDecls[FromContext.getTranslationUnitDecl()]
6022 = ToContext.getTranslationUnitDecl();
6025 ASTImporter::~ASTImporter() { }
6027 QualType ASTImporter::Import(QualType FromT) {
6031 const Type *fromTy = FromT.getTypePtr();
6033 // Check whether we've already imported this type.
6034 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6035 = ImportedTypes.find(fromTy);
6036 if (Pos != ImportedTypes.end())
6037 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
6040 ASTNodeImporter Importer(*this);
6041 QualType ToT = Importer.Visit(fromTy);
6045 // Record the imported type.
6046 ImportedTypes[fromTy] = ToT.getTypePtr();
6048 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
6051 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
6055 // FIXME: For now we just create a "trivial" type source info based
6056 // on the type and a single location. Implement a real version of this.
6057 QualType T = Import(FromTSI->getType());
6061 return ToContext.getTrivialTypeSourceInfo(T,
6062 Import(FromTSI->getTypeLoc().getLocStart()));
6065 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
6066 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6067 if (Pos != ImportedDecls.end()) {
6068 Decl *ToD = Pos->second;
6069 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
6076 Decl *ASTImporter::Import(Decl *FromD) {
6080 ASTNodeImporter Importer(*this);
6082 // Check whether we've already imported this declaration.
6083 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6084 if (Pos != ImportedDecls.end()) {
6085 Decl *ToD = Pos->second;
6086 Importer.ImportDefinitionIfNeeded(FromD, ToD);
6091 Decl *ToD = Importer.Visit(FromD);
6095 // Record the imported declaration.
6096 ImportedDecls[FromD] = ToD;
6098 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
6099 // Keep track of anonymous tags that have an associated typedef.
6100 if (FromTag->getTypedefNameForAnonDecl())
6101 AnonTagsWithPendingTypedefs.push_back(FromTag);
6102 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
6103 // When we've finished transforming a typedef, see whether it was the
6104 // typedef for an anonymous tag.
6105 for (SmallVectorImpl<TagDecl *>::iterator
6106 FromTag = AnonTagsWithPendingTypedefs.begin(),
6107 FromTagEnd = AnonTagsWithPendingTypedefs.end();
6108 FromTag != FromTagEnd; ++FromTag) {
6109 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
6110 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
6111 // We found the typedef for an anonymous tag; link them.
6112 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
6113 AnonTagsWithPendingTypedefs.erase(FromTag);
6123 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
6127 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
6131 // When we're using a record/enum/Objective-C class/protocol as a context, we
6132 // need it to have a definition.
6133 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
6134 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
6135 if (ToRecord->isCompleteDefinition()) {
6137 } else if (FromRecord->isCompleteDefinition()) {
6138 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
6139 ASTNodeImporter::IDK_Basic);
6141 CompleteDecl(ToRecord);
6143 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
6144 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
6145 if (ToEnum->isCompleteDefinition()) {
6147 } else if (FromEnum->isCompleteDefinition()) {
6148 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
6149 ASTNodeImporter::IDK_Basic);
6151 CompleteDecl(ToEnum);
6153 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
6154 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
6155 if (ToClass->getDefinition()) {
6157 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
6158 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
6159 ASTNodeImporter::IDK_Basic);
6161 CompleteDecl(ToClass);
6163 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
6164 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
6165 if (ToProto->getDefinition()) {
6167 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
6168 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
6169 ASTNodeImporter::IDK_Basic);
6171 CompleteDecl(ToProto);
6178 Expr *ASTImporter::Import(Expr *FromE) {
6182 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
6185 Stmt *ASTImporter::Import(Stmt *FromS) {
6189 // Check whether we've already imported this declaration.
6190 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
6191 if (Pos != ImportedStmts.end())
6195 ASTNodeImporter Importer(*this);
6196 Stmt *ToS = Importer.Visit(FromS);
6200 // Record the imported declaration.
6201 ImportedStmts[FromS] = ToS;
6205 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
6209 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
6211 switch (FromNNS->getKind()) {
6212 case NestedNameSpecifier::Identifier:
6213 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
6214 return NestedNameSpecifier::Create(ToContext, prefix, II);
6218 case NestedNameSpecifier::Namespace:
6219 if (NamespaceDecl *NS =
6220 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
6221 return NestedNameSpecifier::Create(ToContext, prefix, NS);
6225 case NestedNameSpecifier::NamespaceAlias:
6226 if (NamespaceAliasDecl *NSAD =
6227 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
6228 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
6232 case NestedNameSpecifier::Global:
6233 return NestedNameSpecifier::GlobalSpecifier(ToContext);
6235 case NestedNameSpecifier::Super:
6236 if (CXXRecordDecl *RD =
6237 cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
6238 return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
6242 case NestedNameSpecifier::TypeSpec:
6243 case NestedNameSpecifier::TypeSpecWithTemplate: {
6244 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
6246 bool bTemplate = FromNNS->getKind() ==
6247 NestedNameSpecifier::TypeSpecWithTemplate;
6248 return NestedNameSpecifier::Create(ToContext, prefix,
6249 bTemplate, T.getTypePtr());
6255 llvm_unreachable("Invalid nested name specifier kind");
6258 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
6259 // FIXME: Implement!
6260 return NestedNameSpecifierLoc();
6263 TemplateName ASTImporter::Import(TemplateName From) {
6264 switch (From.getKind()) {
6265 case TemplateName::Template:
6266 if (TemplateDecl *ToTemplate
6267 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6268 return TemplateName(ToTemplate);
6270 return TemplateName();
6272 case TemplateName::OverloadedTemplate: {
6273 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
6274 UnresolvedSet<2> ToTemplates;
6275 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
6276 E = FromStorage->end();
6278 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
6279 ToTemplates.addDecl(To);
6281 return TemplateName();
6283 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
6287 case TemplateName::QualifiedTemplate: {
6288 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
6289 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
6291 return TemplateName();
6293 if (TemplateDecl *ToTemplate
6294 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6295 return ToContext.getQualifiedTemplateName(Qualifier,
6296 QTN->hasTemplateKeyword(),
6299 return TemplateName();
6302 case TemplateName::DependentTemplate: {
6303 DependentTemplateName *DTN = From.getAsDependentTemplateName();
6304 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
6306 return TemplateName();
6308 if (DTN->isIdentifier()) {
6309 return ToContext.getDependentTemplateName(Qualifier,
6310 Import(DTN->getIdentifier()));
6313 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
6316 case TemplateName::SubstTemplateTemplateParm: {
6317 SubstTemplateTemplateParmStorage *subst
6318 = From.getAsSubstTemplateTemplateParm();
6319 TemplateTemplateParmDecl *param
6320 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
6322 return TemplateName();
6324 TemplateName replacement = Import(subst->getReplacement());
6325 if (replacement.isNull()) return TemplateName();
6327 return ToContext.getSubstTemplateTemplateParm(param, replacement);
6330 case TemplateName::SubstTemplateTemplateParmPack: {
6331 SubstTemplateTemplateParmPackStorage *SubstPack
6332 = From.getAsSubstTemplateTemplateParmPack();
6333 TemplateTemplateParmDecl *Param
6334 = cast_or_null<TemplateTemplateParmDecl>(
6335 Import(SubstPack->getParameterPack()));
6337 return TemplateName();
6339 ASTNodeImporter Importer(*this);
6340 TemplateArgument ArgPack
6341 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
6342 if (ArgPack.isNull())
6343 return TemplateName();
6345 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
6349 llvm_unreachable("Invalid template name kind");
6352 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
6353 if (FromLoc.isInvalid())
6354 return SourceLocation();
6356 SourceManager &FromSM = FromContext.getSourceManager();
6358 // For now, map everything down to its spelling location, so that we
6359 // don't have to import macro expansions.
6360 // FIXME: Import macro expansions!
6361 FromLoc = FromSM.getSpellingLoc(FromLoc);
6362 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
6363 SourceManager &ToSM = ToContext.getSourceManager();
6364 FileID ToFileID = Import(Decomposed.first);
6365 if (ToFileID.isInvalid())
6366 return SourceLocation();
6367 SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
6368 .getLocWithOffset(Decomposed.second);
6372 SourceRange ASTImporter::Import(SourceRange FromRange) {
6373 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
6376 FileID ASTImporter::Import(FileID FromID) {
6377 llvm::DenseMap<FileID, FileID>::iterator Pos
6378 = ImportedFileIDs.find(FromID);
6379 if (Pos != ImportedFileIDs.end())
6382 SourceManager &FromSM = FromContext.getSourceManager();
6383 SourceManager &ToSM = ToContext.getSourceManager();
6384 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
6385 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
6387 // Include location of this file.
6388 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
6390 // Map the FileID for to the "to" source manager.
6392 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
6393 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
6394 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
6396 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
6397 // than mmap the files several times.
6398 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
6401 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
6402 FromSLoc.getFile().getFileCharacteristic());
6404 // FIXME: We want to re-use the existing MemoryBuffer!
6405 const llvm::MemoryBuffer *
6406 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
6407 std::unique_ptr<llvm::MemoryBuffer> ToBuf
6408 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
6409 FromBuf->getBufferIdentifier());
6410 ToID = ToSM.createFileID(std::move(ToBuf),
6411 FromSLoc.getFile().getFileCharacteristic());
6415 ImportedFileIDs[FromID] = ToID;
6419 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
6420 Expr *ToExpr = Import(From->getInit());
6421 if (!ToExpr && From->getInit())
6424 if (From->isBaseInitializer()) {
6425 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6426 if (!ToTInfo && From->getTypeSourceInfo())
6429 return new (ToContext) CXXCtorInitializer(
6430 ToContext, ToTInfo, From->isBaseVirtual(), Import(From->getLParenLoc()),
6431 ToExpr, Import(From->getRParenLoc()),
6432 From->isPackExpansion() ? Import(From->getEllipsisLoc())
6433 : SourceLocation());
6434 } else if (From->isMemberInitializer()) {
6435 FieldDecl *ToField =
6436 llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
6437 if (!ToField && From->getMember())
6440 return new (ToContext) CXXCtorInitializer(
6441 ToContext, ToField, Import(From->getMemberLocation()),
6442 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6443 } else if (From->isIndirectMemberInitializer()) {
6444 IndirectFieldDecl *ToIField = llvm::cast_or_null<IndirectFieldDecl>(
6445 Import(From->getIndirectMember()));
6446 if (!ToIField && From->getIndirectMember())
6449 return new (ToContext) CXXCtorInitializer(
6450 ToContext, ToIField, Import(From->getMemberLocation()),
6451 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6452 } else if (From->isDelegatingInitializer()) {
6453 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6454 if (!ToTInfo && From->getTypeSourceInfo())
6457 return new (ToContext)
6458 CXXCtorInitializer(ToContext, ToTInfo, Import(From->getLParenLoc()),
6459 ToExpr, Import(From->getRParenLoc()));
6460 } else if (unsigned NumArrayIndices = From->getNumArrayIndices()) {
6461 FieldDecl *ToField =
6462 llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
6463 if (!ToField && From->getMember())
6466 SmallVector<VarDecl *, 4> ToAIs(NumArrayIndices);
6468 for (unsigned AII = 0; AII < NumArrayIndices; ++AII) {
6469 VarDecl *ToArrayIndex =
6470 dyn_cast_or_null<VarDecl>(Import(From->getArrayIndex(AII)));
6471 if (!ToArrayIndex && From->getArrayIndex(AII))
6475 return CXXCtorInitializer::Create(
6476 ToContext, ToField, Import(From->getMemberLocation()),
6477 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()),
6478 ToAIs.data(), NumArrayIndices);
6485 void ASTImporter::ImportDefinition(Decl *From) {
6486 Decl *To = Import(From);
6490 if (DeclContext *FromDC = cast<DeclContext>(From)) {
6491 ASTNodeImporter Importer(*this);
6493 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
6494 if (!ToRecord->getDefinition()) {
6495 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
6496 ASTNodeImporter::IDK_Everything);
6501 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
6502 if (!ToEnum->getDefinition()) {
6503 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
6504 ASTNodeImporter::IDK_Everything);
6509 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
6510 if (!ToIFace->getDefinition()) {
6511 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
6512 ASTNodeImporter::IDK_Everything);
6517 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
6518 if (!ToProto->getDefinition()) {
6519 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
6520 ASTNodeImporter::IDK_Everything);
6525 Importer.ImportDeclContext(FromDC, true);
6529 DeclarationName ASTImporter::Import(DeclarationName FromName) {
6531 return DeclarationName();
6533 switch (FromName.getNameKind()) {
6534 case DeclarationName::Identifier:
6535 return Import(FromName.getAsIdentifierInfo());
6537 case DeclarationName::ObjCZeroArgSelector:
6538 case DeclarationName::ObjCOneArgSelector:
6539 case DeclarationName::ObjCMultiArgSelector:
6540 return Import(FromName.getObjCSelector());
6542 case DeclarationName::CXXConstructorName: {
6543 QualType T = Import(FromName.getCXXNameType());
6545 return DeclarationName();
6547 return ToContext.DeclarationNames.getCXXConstructorName(
6548 ToContext.getCanonicalType(T));
6551 case DeclarationName::CXXDestructorName: {
6552 QualType T = Import(FromName.getCXXNameType());
6554 return DeclarationName();
6556 return ToContext.DeclarationNames.getCXXDestructorName(
6557 ToContext.getCanonicalType(T));
6560 case DeclarationName::CXXConversionFunctionName: {
6561 QualType T = Import(FromName.getCXXNameType());
6563 return DeclarationName();
6565 return ToContext.DeclarationNames.getCXXConversionFunctionName(
6566 ToContext.getCanonicalType(T));
6569 case DeclarationName::CXXOperatorName:
6570 return ToContext.DeclarationNames.getCXXOperatorName(
6571 FromName.getCXXOverloadedOperator());
6573 case DeclarationName::CXXLiteralOperatorName:
6574 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
6575 Import(FromName.getCXXLiteralIdentifier()));
6577 case DeclarationName::CXXUsingDirective:
6579 return DeclarationName::getUsingDirectiveName();
6582 llvm_unreachable("Invalid DeclarationName Kind!");
6585 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
6589 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
6591 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
6592 ToId->setBuiltinID(FromId->getBuiltinID());
6597 Selector ASTImporter::Import(Selector FromSel) {
6598 if (FromSel.isNull())
6601 SmallVector<IdentifierInfo *, 4> Idents;
6602 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
6603 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
6604 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
6605 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
6608 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
6612 unsigned NumDecls) {
6616 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
6617 if (LastDiagFromFrom)
6618 ToContext.getDiagnostics().notePriorDiagnosticFrom(
6619 FromContext.getDiagnostics());
6620 LastDiagFromFrom = false;
6621 return ToContext.getDiagnostics().Report(Loc, DiagID);
6624 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
6625 if (!LastDiagFromFrom)
6626 FromContext.getDiagnostics().notePriorDiagnosticFrom(
6627 ToContext.getDiagnostics());
6628 LastDiagFromFrom = true;
6629 return FromContext.getDiagnostics().Report(Loc, DiagID);
6632 void ASTImporter::CompleteDecl (Decl *D) {
6633 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
6634 if (!ID->getDefinition())
6635 ID->startDefinition();
6637 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
6638 if (!PD->getDefinition())
6639 PD->startDefinition();
6641 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6642 if (!TD->getDefinition() && !TD->isBeingDefined()) {
6643 TD->startDefinition();
6644 TD->setCompleteDefinition(true);
6648 assert (0 && "CompleteDecl called on a Decl that can't be completed");
6652 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
6653 if (From->hasAttrs()) {
6654 for (Attr *FromAttr : From->getAttrs())
6655 To->addAttr(FromAttr->clone(To->getASTContext()));
6657 if (From->isUsed()) {
6660 if (From->isImplicit()) {
6663 ImportedDecls[From] = To;
6667 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
6669 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6670 = ImportedTypes.find(From.getTypePtr());
6671 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
6674 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
6676 return Ctx.IsStructurallyEquivalent(From, To);