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 VisitAtomicType(const AtomicType *T);
43 QualType VisitBuiltinType(const BuiltinType *T);
44 QualType VisitDecayedType(const DecayedType *T);
45 QualType VisitComplexType(const ComplexType *T);
46 QualType VisitPointerType(const PointerType *T);
47 QualType VisitBlockPointerType(const BlockPointerType *T);
48 QualType VisitLValueReferenceType(const LValueReferenceType *T);
49 QualType VisitRValueReferenceType(const RValueReferenceType *T);
50 QualType VisitMemberPointerType(const MemberPointerType *T);
51 QualType VisitConstantArrayType(const ConstantArrayType *T);
52 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
53 QualType VisitVariableArrayType(const VariableArrayType *T);
54 // FIXME: DependentSizedArrayType
55 // FIXME: DependentSizedExtVectorType
56 QualType VisitVectorType(const VectorType *T);
57 QualType VisitExtVectorType(const ExtVectorType *T);
58 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
59 QualType VisitFunctionProtoType(const FunctionProtoType *T);
60 // FIXME: UnresolvedUsingType
61 QualType VisitParenType(const ParenType *T);
62 QualType VisitTypedefType(const TypedefType *T);
63 QualType VisitTypeOfExprType(const TypeOfExprType *T);
64 // FIXME: DependentTypeOfExprType
65 QualType VisitTypeOfType(const TypeOfType *T);
66 QualType VisitDecltypeType(const DecltypeType *T);
67 QualType VisitUnaryTransformType(const UnaryTransformType *T);
68 QualType VisitAutoType(const AutoType *T);
69 QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
70 // FIXME: DependentDecltypeType
71 QualType VisitRecordType(const RecordType *T);
72 QualType VisitEnumType(const EnumType *T);
73 QualType VisitAttributedType(const AttributedType *T);
74 QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
75 // FIXME: SubstTemplateTypeParmType
76 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
77 QualType VisitElaboratedType(const ElaboratedType *T);
78 // FIXME: DependentNameType
79 // FIXME: DependentTemplateSpecializationType
80 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
81 QualType VisitObjCObjectType(const ObjCObjectType *T);
82 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
84 // Importing declarations
85 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
86 DeclContext *&LexicalDC, DeclarationName &Name,
87 NamedDecl *&ToD, SourceLocation &Loc);
88 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
89 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
90 DeclarationNameInfo& To);
91 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
93 bool ImportCastPath(CastExpr *E, CXXCastPath &Path);
95 typedef DesignatedInitExpr::Designator Designator;
96 Designator ImportDesignator(const Designator &D);
99 /// \brief What we should import from the definition.
100 enum ImportDefinitionKind {
101 /// \brief Import the default subset of the definition, which might be
102 /// nothing (if minimal import is set) or might be everything (if minimal
103 /// import is not set).
105 /// \brief Import everything.
107 /// \brief Import only the bare bones needed to establish a valid
112 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
113 return IDK == IDK_Everything ||
114 (IDK == IDK_Default && !Importer.isMinimalImport());
117 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
118 ImportDefinitionKind Kind = IDK_Default);
119 bool ImportDefinition(VarDecl *From, VarDecl *To,
120 ImportDefinitionKind Kind = IDK_Default);
121 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
122 ImportDefinitionKind Kind = IDK_Default);
123 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
124 ImportDefinitionKind Kind = IDK_Default);
125 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
126 ImportDefinitionKind Kind = IDK_Default);
127 TemplateParameterList *ImportTemplateParameterList(
128 TemplateParameterList *Params);
129 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
130 TemplateArgumentLoc ImportTemplateArgumentLoc(
131 const TemplateArgumentLoc &TALoc, bool &Error);
132 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
133 unsigned NumFromArgs,
134 SmallVectorImpl<TemplateArgument> &ToArgs);
135 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
136 bool Complain = true);
137 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
138 bool Complain = true);
139 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
140 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
141 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
142 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
143 Decl *VisitDecl(Decl *D);
144 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
145 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
146 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
147 Decl *VisitNamespaceDecl(NamespaceDecl *D);
148 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
149 Decl *VisitTypedefDecl(TypedefDecl *D);
150 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
151 Decl *VisitLabelDecl(LabelDecl *D);
152 Decl *VisitEnumDecl(EnumDecl *D);
153 Decl *VisitRecordDecl(RecordDecl *D);
154 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
155 Decl *VisitFunctionDecl(FunctionDecl *D);
156 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
157 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
158 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
159 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
160 Decl *VisitFieldDecl(FieldDecl *D);
161 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
162 Decl *VisitFriendDecl(FriendDecl *D);
163 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
164 Decl *VisitVarDecl(VarDecl *D);
165 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
166 Decl *VisitParmVarDecl(ParmVarDecl *D);
167 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
168 Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
169 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
170 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
171 Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
173 ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
174 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
175 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
176 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
177 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
178 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
179 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
180 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
181 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
182 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
183 Decl *VisitClassTemplateSpecializationDecl(
184 ClassTemplateSpecializationDecl *D);
185 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
186 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
188 // Importing statements
189 DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
191 Stmt *VisitStmt(Stmt *S);
192 Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
193 Stmt *VisitDeclStmt(DeclStmt *S);
194 Stmt *VisitNullStmt(NullStmt *S);
195 Stmt *VisitCompoundStmt(CompoundStmt *S);
196 Stmt *VisitCaseStmt(CaseStmt *S);
197 Stmt *VisitDefaultStmt(DefaultStmt *S);
198 Stmt *VisitLabelStmt(LabelStmt *S);
199 Stmt *VisitAttributedStmt(AttributedStmt *S);
200 Stmt *VisitIfStmt(IfStmt *S);
201 Stmt *VisitSwitchStmt(SwitchStmt *S);
202 Stmt *VisitWhileStmt(WhileStmt *S);
203 Stmt *VisitDoStmt(DoStmt *S);
204 Stmt *VisitForStmt(ForStmt *S);
205 Stmt *VisitGotoStmt(GotoStmt *S);
206 Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
207 Stmt *VisitContinueStmt(ContinueStmt *S);
208 Stmt *VisitBreakStmt(BreakStmt *S);
209 Stmt *VisitReturnStmt(ReturnStmt *S);
211 // FIXME: SEHExceptStmt
212 // FIXME: SEHFinallyStmt
214 // FIXME: SEHLeaveStmt
215 // FIXME: CapturedStmt
216 Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
217 Stmt *VisitCXXTryStmt(CXXTryStmt *S);
218 Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
219 // FIXME: MSDependentExistsStmt
220 Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
221 Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
222 Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
223 Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
224 Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
225 Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
226 Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
228 // Importing expressions
229 Expr *VisitExpr(Expr *E);
230 Expr *VisitVAArgExpr(VAArgExpr *E);
231 Expr *VisitGNUNullExpr(GNUNullExpr *E);
232 Expr *VisitPredefinedExpr(PredefinedExpr *E);
233 Expr *VisitDeclRefExpr(DeclRefExpr *E);
234 Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
235 Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
236 Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
237 Expr *VisitIntegerLiteral(IntegerLiteral *E);
238 Expr *VisitFloatingLiteral(FloatingLiteral *E);
239 Expr *VisitCharacterLiteral(CharacterLiteral *E);
240 Expr *VisitStringLiteral(StringLiteral *E);
241 Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
242 Expr *VisitAtomicExpr(AtomicExpr *E);
243 Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
244 Expr *VisitParenExpr(ParenExpr *E);
245 Expr *VisitParenListExpr(ParenListExpr *E);
246 Expr *VisitStmtExpr(StmtExpr *E);
247 Expr *VisitUnaryOperator(UnaryOperator *E);
248 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
249 Expr *VisitBinaryOperator(BinaryOperator *E);
250 Expr *VisitConditionalOperator(ConditionalOperator *E);
251 Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
252 Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
253 Expr *VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
254 Expr *VisitExpressionTraitExpr(ExpressionTraitExpr *E);
255 Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
256 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
257 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
258 Expr *VisitExplicitCastExpr(ExplicitCastExpr *E);
259 Expr *VisitOffsetOfExpr(OffsetOfExpr *OE);
260 Expr *VisitCXXThrowExpr(CXXThrowExpr *E);
261 Expr *VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
262 Expr *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
263 Expr *VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
264 Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
265 Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
266 Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
267 Expr *VisitCXXNewExpr(CXXNewExpr *CE);
268 Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
269 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
270 Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
271 Expr *VisitExprWithCleanups(ExprWithCleanups *EWC);
272 Expr *VisitCXXThisExpr(CXXThisExpr *E);
273 Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
274 Expr *VisitMemberExpr(MemberExpr *E);
275 Expr *VisitCallExpr(CallExpr *E);
276 Expr *VisitInitListExpr(InitListExpr *E);
277 Expr *VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
278 Expr *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
279 Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
280 Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
282 template<typename IIter, typename OIter>
283 void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
284 typedef typename std::remove_reference<decltype(*Obegin)>::type ItemT;
285 ASTImporter &ImporterRef = Importer;
286 std::transform(Ibegin, Iend, Obegin,
287 [&ImporterRef](ItemT From) -> ItemT {
288 return ImporterRef.Import(From);
292 template<typename IIter, typename OIter>
293 bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
294 typedef typename std::remove_reference<decltype(**Obegin)>::type ItemT;
295 ASTImporter &ImporterRef = Importer;
297 std::transform(Ibegin, Iend, Obegin,
298 [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
299 ItemT *To = cast_or_null<ItemT>(
300 ImporterRef.Import(From));
308 template<typename InContainerTy, typename OutContainerTy>
309 bool ImportContainerChecked(const InContainerTy &InContainer,
310 OutContainerTy &OutContainer) {
311 return ImportArrayChecked(InContainer.begin(), InContainer.end(),
312 OutContainer.begin());
315 template<typename InContainerTy, typename OIter>
316 bool ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
317 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
322 using namespace clang;
324 //----------------------------------------------------------------------------
325 // Structural Equivalence
326 //----------------------------------------------------------------------------
329 struct StructuralEquivalenceContext {
330 /// \brief AST contexts for which we are checking structural equivalence.
333 /// \brief The set of "tentative" equivalences between two canonical
334 /// declarations, mapping from a declaration in the first context to the
335 /// declaration in the second context that we believe to be equivalent.
336 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
338 /// \brief Queue of declarations in the first context whose equivalence
339 /// with a declaration in the second context still needs to be verified.
340 std::deque<Decl *> DeclsToCheck;
342 /// \brief Declaration (from, to) pairs that are known not to be equivalent
343 /// (which we have already complained about).
344 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
346 /// \brief Whether we're being strict about the spelling of types when
347 /// unifying two types.
348 bool StrictTypeSpelling;
350 /// \brief Whether to complain about failures.
353 /// \brief \c true if the last diagnostic came from C2.
356 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
357 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
358 bool StrictTypeSpelling = false,
359 bool Complain = true)
360 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
361 StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
362 LastDiagFromC2(false) {}
364 /// \brief Determine whether the two declarations are structurally
366 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
368 /// \brief Determine whether the two types are structurally equivalent.
369 bool IsStructurallyEquivalent(QualType T1, QualType T2);
372 /// \brief Finish checking all of the structural equivalences.
374 /// \returns true if an error occurred, false otherwise.
378 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
379 assert(Complain && "Not allowed to complain");
381 C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
382 LastDiagFromC2 = false;
383 return C1.getDiagnostics().Report(Loc, DiagID);
386 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
387 assert(Complain && "Not allowed to complain");
389 C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
390 LastDiagFromC2 = true;
391 return C2.getDiagnostics().Report(Loc, DiagID);
396 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
397 QualType T1, QualType T2);
398 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
401 /// \brief Determine structural equivalence of two expressions.
402 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
403 Expr *E1, Expr *E2) {
407 // FIXME: Actually perform a structural comparison!
411 /// \brief Determine whether two identifiers are equivalent.
412 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
413 const IdentifierInfo *Name2) {
414 if (!Name1 || !Name2)
415 return Name1 == Name2;
417 return Name1->getName() == Name2->getName();
420 /// \brief Determine whether two nested-name-specifiers are equivalent.
421 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
422 NestedNameSpecifier *NNS1,
423 NestedNameSpecifier *NNS2) {
428 /// \brief Determine whether two template arguments are equivalent.
429 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
430 const TemplateArgument &Arg1,
431 const TemplateArgument &Arg2) {
432 if (Arg1.getKind() != Arg2.getKind())
435 switch (Arg1.getKind()) {
436 case TemplateArgument::Null:
439 case TemplateArgument::Type:
440 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
442 case TemplateArgument::Integral:
443 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
444 Arg2.getIntegralType()))
447 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
449 case TemplateArgument::Declaration:
450 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
452 case TemplateArgument::NullPtr:
453 return true; // FIXME: Is this correct?
455 case TemplateArgument::Template:
456 return IsStructurallyEquivalent(Context,
457 Arg1.getAsTemplate(),
458 Arg2.getAsTemplate());
460 case TemplateArgument::TemplateExpansion:
461 return IsStructurallyEquivalent(Context,
462 Arg1.getAsTemplateOrTemplatePattern(),
463 Arg2.getAsTemplateOrTemplatePattern());
465 case TemplateArgument::Expression:
466 return IsStructurallyEquivalent(Context,
467 Arg1.getAsExpr(), Arg2.getAsExpr());
469 case TemplateArgument::Pack:
470 if (Arg1.pack_size() != Arg2.pack_size())
473 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
474 if (!IsStructurallyEquivalent(Context,
475 Arg1.pack_begin()[I],
476 Arg2.pack_begin()[I]))
482 llvm_unreachable("Invalid template argument kind");
485 /// \brief Determine structural equivalence for the common part of array
487 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
488 const ArrayType *Array1,
489 const ArrayType *Array2) {
490 if (!IsStructurallyEquivalent(Context,
491 Array1->getElementType(),
492 Array2->getElementType()))
494 if (Array1->getSizeModifier() != Array2->getSizeModifier())
496 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
502 /// \brief Determine structural equivalence of two types.
503 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
504 QualType T1, QualType T2) {
505 if (T1.isNull() || T2.isNull())
506 return T1.isNull() && T2.isNull();
508 if (!Context.StrictTypeSpelling) {
509 // We aren't being strict about token-to-token equivalence of types,
510 // so map down to the canonical type.
511 T1 = Context.C1.getCanonicalType(T1);
512 T2 = Context.C2.getCanonicalType(T2);
515 if (T1.getQualifiers() != T2.getQualifiers())
518 Type::TypeClass TC = T1->getTypeClass();
520 if (T1->getTypeClass() != T2->getTypeClass()) {
521 // Compare function types with prototypes vs. without prototypes as if
522 // both did not have prototypes.
523 if (T1->getTypeClass() == Type::FunctionProto &&
524 T2->getTypeClass() == Type::FunctionNoProto)
525 TC = Type::FunctionNoProto;
526 else if (T1->getTypeClass() == Type::FunctionNoProto &&
527 T2->getTypeClass() == Type::FunctionProto)
528 TC = Type::FunctionNoProto;
535 // FIXME: Deal with Char_S/Char_U.
536 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
541 if (!IsStructurallyEquivalent(Context,
542 cast<ComplexType>(T1)->getElementType(),
543 cast<ComplexType>(T2)->getElementType()))
549 if (!IsStructurallyEquivalent(Context,
550 cast<AdjustedType>(T1)->getOriginalType(),
551 cast<AdjustedType>(T2)->getOriginalType()))
556 if (!IsStructurallyEquivalent(Context,
557 cast<PointerType>(T1)->getPointeeType(),
558 cast<PointerType>(T2)->getPointeeType()))
562 case Type::BlockPointer:
563 if (!IsStructurallyEquivalent(Context,
564 cast<BlockPointerType>(T1)->getPointeeType(),
565 cast<BlockPointerType>(T2)->getPointeeType()))
569 case Type::LValueReference:
570 case Type::RValueReference: {
571 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
572 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
573 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
575 if (Ref1->isInnerRef() != Ref2->isInnerRef())
577 if (!IsStructurallyEquivalent(Context,
578 Ref1->getPointeeTypeAsWritten(),
579 Ref2->getPointeeTypeAsWritten()))
584 case Type::MemberPointer: {
585 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
586 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
587 if (!IsStructurallyEquivalent(Context,
588 MemPtr1->getPointeeType(),
589 MemPtr2->getPointeeType()))
591 if (!IsStructurallyEquivalent(Context,
592 QualType(MemPtr1->getClass(), 0),
593 QualType(MemPtr2->getClass(), 0)))
598 case Type::ConstantArray: {
599 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
600 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
601 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
604 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
609 case Type::IncompleteArray:
610 if (!IsArrayStructurallyEquivalent(Context,
612 cast<ArrayType>(T2)))
616 case Type::VariableArray: {
617 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
618 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
619 if (!IsStructurallyEquivalent(Context,
620 Array1->getSizeExpr(), Array2->getSizeExpr()))
623 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
629 case Type::DependentSizedArray: {
630 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
631 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
632 if (!IsStructurallyEquivalent(Context,
633 Array1->getSizeExpr(), Array2->getSizeExpr()))
636 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
642 case Type::DependentSizedExtVector: {
643 const DependentSizedExtVectorType *Vec1
644 = cast<DependentSizedExtVectorType>(T1);
645 const DependentSizedExtVectorType *Vec2
646 = cast<DependentSizedExtVectorType>(T2);
647 if (!IsStructurallyEquivalent(Context,
648 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
650 if (!IsStructurallyEquivalent(Context,
651 Vec1->getElementType(),
652 Vec2->getElementType()))
658 case Type::ExtVector: {
659 const VectorType *Vec1 = cast<VectorType>(T1);
660 const VectorType *Vec2 = cast<VectorType>(T2);
661 if (!IsStructurallyEquivalent(Context,
662 Vec1->getElementType(),
663 Vec2->getElementType()))
665 if (Vec1->getNumElements() != Vec2->getNumElements())
667 if (Vec1->getVectorKind() != Vec2->getVectorKind())
672 case Type::FunctionProto: {
673 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
674 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
675 if (Proto1->getNumParams() != Proto2->getNumParams())
677 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
678 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
679 Proto2->getParamType(I)))
682 if (Proto1->isVariadic() != Proto2->isVariadic())
684 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
686 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
687 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
689 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
690 if (!IsStructurallyEquivalent(Context,
691 Proto1->getExceptionType(I),
692 Proto2->getExceptionType(I)))
695 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
696 if (!IsStructurallyEquivalent(Context,
697 Proto1->getNoexceptExpr(),
698 Proto2->getNoexceptExpr()))
701 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
704 // Fall through to check the bits common with FunctionNoProtoType.
707 case Type::FunctionNoProto: {
708 const FunctionType *Function1 = cast<FunctionType>(T1);
709 const FunctionType *Function2 = cast<FunctionType>(T2);
710 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
711 Function2->getReturnType()))
713 if (Function1->getExtInfo() != Function2->getExtInfo())
718 case Type::UnresolvedUsing:
719 if (!IsStructurallyEquivalent(Context,
720 cast<UnresolvedUsingType>(T1)->getDecl(),
721 cast<UnresolvedUsingType>(T2)->getDecl()))
726 case Type::Attributed:
727 if (!IsStructurallyEquivalent(Context,
728 cast<AttributedType>(T1)->getModifiedType(),
729 cast<AttributedType>(T2)->getModifiedType()))
731 if (!IsStructurallyEquivalent(Context,
732 cast<AttributedType>(T1)->getEquivalentType(),
733 cast<AttributedType>(T2)->getEquivalentType()))
738 if (!IsStructurallyEquivalent(Context,
739 cast<ParenType>(T1)->getInnerType(),
740 cast<ParenType>(T2)->getInnerType()))
745 if (!IsStructurallyEquivalent(Context,
746 cast<TypedefType>(T1)->getDecl(),
747 cast<TypedefType>(T2)->getDecl()))
751 case Type::TypeOfExpr:
752 if (!IsStructurallyEquivalent(Context,
753 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
754 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
759 if (!IsStructurallyEquivalent(Context,
760 cast<TypeOfType>(T1)->getUnderlyingType(),
761 cast<TypeOfType>(T2)->getUnderlyingType()))
765 case Type::UnaryTransform:
766 if (!IsStructurallyEquivalent(Context,
767 cast<UnaryTransformType>(T1)->getUnderlyingType(),
768 cast<UnaryTransformType>(T1)->getUnderlyingType()))
773 if (!IsStructurallyEquivalent(Context,
774 cast<DecltypeType>(T1)->getUnderlyingExpr(),
775 cast<DecltypeType>(T2)->getUnderlyingExpr()))
780 if (!IsStructurallyEquivalent(Context,
781 cast<AutoType>(T1)->getDeducedType(),
782 cast<AutoType>(T2)->getDeducedType()))
788 if (!IsStructurallyEquivalent(Context,
789 cast<TagType>(T1)->getDecl(),
790 cast<TagType>(T2)->getDecl()))
794 case Type::TemplateTypeParm: {
795 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
796 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
797 if (Parm1->getDepth() != Parm2->getDepth())
799 if (Parm1->getIndex() != Parm2->getIndex())
801 if (Parm1->isParameterPack() != Parm2->isParameterPack())
804 // Names of template type parameters are never significant.
808 case Type::SubstTemplateTypeParm: {
809 const SubstTemplateTypeParmType *Subst1
810 = cast<SubstTemplateTypeParmType>(T1);
811 const SubstTemplateTypeParmType *Subst2
812 = cast<SubstTemplateTypeParmType>(T2);
813 if (!IsStructurallyEquivalent(Context,
814 QualType(Subst1->getReplacedParameter(), 0),
815 QualType(Subst2->getReplacedParameter(), 0)))
817 if (!IsStructurallyEquivalent(Context,
818 Subst1->getReplacementType(),
819 Subst2->getReplacementType()))
824 case Type::SubstTemplateTypeParmPack: {
825 const SubstTemplateTypeParmPackType *Subst1
826 = cast<SubstTemplateTypeParmPackType>(T1);
827 const SubstTemplateTypeParmPackType *Subst2
828 = cast<SubstTemplateTypeParmPackType>(T2);
829 if (!IsStructurallyEquivalent(Context,
830 QualType(Subst1->getReplacedParameter(), 0),
831 QualType(Subst2->getReplacedParameter(), 0)))
833 if (!IsStructurallyEquivalent(Context,
834 Subst1->getArgumentPack(),
835 Subst2->getArgumentPack()))
839 case Type::TemplateSpecialization: {
840 const TemplateSpecializationType *Spec1
841 = cast<TemplateSpecializationType>(T1);
842 const TemplateSpecializationType *Spec2
843 = cast<TemplateSpecializationType>(T2);
844 if (!IsStructurallyEquivalent(Context,
845 Spec1->getTemplateName(),
846 Spec2->getTemplateName()))
848 if (Spec1->getNumArgs() != Spec2->getNumArgs())
850 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
851 if (!IsStructurallyEquivalent(Context,
852 Spec1->getArg(I), Spec2->getArg(I)))
858 case Type::Elaborated: {
859 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
860 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
861 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
862 if (Elab1->getKeyword() != Elab2->getKeyword())
864 if (!IsStructurallyEquivalent(Context,
865 Elab1->getQualifier(),
866 Elab2->getQualifier()))
868 if (!IsStructurallyEquivalent(Context,
869 Elab1->getNamedType(),
870 Elab2->getNamedType()))
875 case Type::InjectedClassName: {
876 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
877 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
878 if (!IsStructurallyEquivalent(Context,
879 Inj1->getInjectedSpecializationType(),
880 Inj2->getInjectedSpecializationType()))
885 case Type::DependentName: {
886 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
887 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
888 if (!IsStructurallyEquivalent(Context,
889 Typename1->getQualifier(),
890 Typename2->getQualifier()))
892 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
893 Typename2->getIdentifier()))
899 case Type::DependentTemplateSpecialization: {
900 const DependentTemplateSpecializationType *Spec1 =
901 cast<DependentTemplateSpecializationType>(T1);
902 const DependentTemplateSpecializationType *Spec2 =
903 cast<DependentTemplateSpecializationType>(T2);
904 if (!IsStructurallyEquivalent(Context,
905 Spec1->getQualifier(),
906 Spec2->getQualifier()))
908 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
909 Spec2->getIdentifier()))
911 if (Spec1->getNumArgs() != Spec2->getNumArgs())
913 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
914 if (!IsStructurallyEquivalent(Context,
915 Spec1->getArg(I), Spec2->getArg(I)))
921 case Type::PackExpansion:
922 if (!IsStructurallyEquivalent(Context,
923 cast<PackExpansionType>(T1)->getPattern(),
924 cast<PackExpansionType>(T2)->getPattern()))
928 case Type::ObjCInterface: {
929 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
930 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
931 if (!IsStructurallyEquivalent(Context,
932 Iface1->getDecl(), Iface2->getDecl()))
937 case Type::ObjCTypeParam: {
938 const ObjCTypeParamType *Obj1 = cast<ObjCTypeParamType>(T1);
939 const ObjCTypeParamType *Obj2 = cast<ObjCTypeParamType>(T2);
940 if (!IsStructurallyEquivalent(Context, Obj1->getDecl(),
944 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
946 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
947 if (!IsStructurallyEquivalent(Context,
948 Obj1->getProtocol(I),
949 Obj2->getProtocol(I)))
954 case Type::ObjCObject: {
955 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
956 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
957 if (!IsStructurallyEquivalent(Context,
959 Obj2->getBaseType()))
961 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
963 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
964 if (!IsStructurallyEquivalent(Context,
965 Obj1->getProtocol(I),
966 Obj2->getProtocol(I)))
972 case Type::ObjCObjectPointer: {
973 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
974 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
975 if (!IsStructurallyEquivalent(Context,
976 Ptr1->getPointeeType(),
977 Ptr2->getPointeeType()))
983 if (!IsStructurallyEquivalent(Context,
984 cast<AtomicType>(T1)->getValueType(),
985 cast<AtomicType>(T2)->getValueType()))
991 if (!IsStructurallyEquivalent(Context,
992 cast<PipeType>(T1)->getElementType(),
993 cast<PipeType>(T2)->getElementType()))
1003 /// \brief Determine structural equivalence of two fields.
1004 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1005 FieldDecl *Field1, FieldDecl *Field2) {
1006 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
1008 // For anonymous structs/unions, match up the anonymous struct/union type
1009 // declarations directly, so that we don't go off searching for anonymous
1011 if (Field1->isAnonymousStructOrUnion() &&
1012 Field2->isAnonymousStructOrUnion()) {
1013 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
1014 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
1015 return IsStructurallyEquivalent(Context, D1, D2);
1018 // Check for equivalent field names.
1019 IdentifierInfo *Name1 = Field1->getIdentifier();
1020 IdentifierInfo *Name2 = Field2->getIdentifier();
1021 if (!::IsStructurallyEquivalent(Name1, Name2))
1024 if (!IsStructurallyEquivalent(Context,
1025 Field1->getType(), Field2->getType())) {
1026 if (Context.Complain) {
1027 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1028 << Context.C2.getTypeDeclType(Owner2);
1029 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1030 << Field2->getDeclName() << Field2->getType();
1031 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1032 << Field1->getDeclName() << Field1->getType();
1037 if (Field1->isBitField() != Field2->isBitField()) {
1038 if (Context.Complain) {
1039 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1040 << Context.C2.getTypeDeclType(Owner2);
1041 if (Field1->isBitField()) {
1042 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
1043 << Field1->getDeclName() << Field1->getType()
1044 << Field1->getBitWidthValue(Context.C1);
1045 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
1046 << Field2->getDeclName();
1048 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
1049 << Field2->getDeclName() << Field2->getType()
1050 << Field2->getBitWidthValue(Context.C2);
1051 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
1052 << Field1->getDeclName();
1058 if (Field1->isBitField()) {
1059 // Make sure that the bit-fields are the same length.
1060 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
1061 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
1063 if (Bits1 != Bits2) {
1064 if (Context.Complain) {
1065 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1066 << Context.C2.getTypeDeclType(Owner2);
1067 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
1068 << Field2->getDeclName() << Field2->getType() << Bits2;
1069 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
1070 << Field1->getDeclName() << Field1->getType() << Bits1;
1079 /// \brief Find the index of the given anonymous struct/union within its
1082 /// \returns Returns the index of this anonymous struct/union in its context,
1083 /// including the next assigned index (if none of them match). Returns an
1084 /// empty option if the context is not a record, i.e.. if the anonymous
1085 /// struct/union is at namespace or block scope.
1086 static Optional<unsigned> findUntaggedStructOrUnionIndex(RecordDecl *Anon) {
1087 ASTContext &Context = Anon->getASTContext();
1088 QualType AnonTy = Context.getRecordType(Anon);
1090 RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
1095 for (const auto *D : Owner->noload_decls()) {
1096 const auto *F = dyn_cast<FieldDecl>(D);
1100 if (F->isAnonymousStructOrUnion()) {
1101 if (Context.hasSameType(F->getType(), AnonTy))
1107 // If the field looks like this:
1108 // struct { ... } A;
1109 QualType FieldType = F->getType();
1110 if (const auto *RecType = dyn_cast<RecordType>(FieldType)) {
1111 const RecordDecl *RecDecl = RecType->getDecl();
1112 if (RecDecl->getDeclContext() == Owner &&
1113 !RecDecl->getIdentifier()) {
1114 if (Context.hasSameType(FieldType, AnonTy))
1125 /// \brief Determine structural equivalence of two records.
1126 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1127 RecordDecl *D1, RecordDecl *D2) {
1128 if (D1->isUnion() != D2->isUnion()) {
1129 if (Context.Complain) {
1130 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1131 << Context.C2.getTypeDeclType(D2);
1132 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1133 << D1->getDeclName() << (unsigned)D1->getTagKind();
1138 if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1139 // If both anonymous structs/unions are in a record context, make sure
1140 // they occur in the same location in the context records.
1141 if (Optional<unsigned> Index1 = findUntaggedStructOrUnionIndex(D1)) {
1142 if (Optional<unsigned> Index2 = findUntaggedStructOrUnionIndex(D2)) {
1143 if (*Index1 != *Index2)
1149 // If both declarations are class template specializations, we know
1150 // the ODR applies, so check the template and template arguments.
1151 ClassTemplateSpecializationDecl *Spec1
1152 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1153 ClassTemplateSpecializationDecl *Spec2
1154 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1155 if (Spec1 && Spec2) {
1156 // Check that the specialized templates are the same.
1157 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1158 Spec2->getSpecializedTemplate()))
1161 // Check that the template arguments are the same.
1162 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1165 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1166 if (!IsStructurallyEquivalent(Context,
1167 Spec1->getTemplateArgs().get(I),
1168 Spec2->getTemplateArgs().get(I)))
1171 // If one is a class template specialization and the other is not, these
1172 // structures are different.
1173 else if (Spec1 || Spec2)
1176 // Compare the definitions of these two records. If either or both are
1177 // incomplete, we assume that they are equivalent.
1178 D1 = D1->getDefinition();
1179 D2 = D2->getDefinition();
1183 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1184 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1185 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1186 if (Context.Complain) {
1187 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1188 << Context.C2.getTypeDeclType(D2);
1189 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1190 << D2CXX->getNumBases();
1191 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1192 << D1CXX->getNumBases();
1197 // Check the base classes.
1198 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1199 BaseEnd1 = D1CXX->bases_end(),
1200 Base2 = D2CXX->bases_begin();
1203 if (!IsStructurallyEquivalent(Context,
1204 Base1->getType(), Base2->getType())) {
1205 if (Context.Complain) {
1206 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1207 << Context.C2.getTypeDeclType(D2);
1208 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1210 << Base2->getSourceRange();
1211 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1213 << Base1->getSourceRange();
1218 // Check virtual vs. non-virtual inheritance mismatch.
1219 if (Base1->isVirtual() != Base2->isVirtual()) {
1220 if (Context.Complain) {
1221 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1222 << Context.C2.getTypeDeclType(D2);
1223 Context.Diag2(Base2->getLocStart(),
1224 diag::note_odr_virtual_base)
1225 << Base2->isVirtual() << Base2->getSourceRange();
1226 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1227 << Base1->isVirtual()
1228 << Base1->getSourceRange();
1233 } else if (D1CXX->getNumBases() > 0) {
1234 if (Context.Complain) {
1235 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1236 << Context.C2.getTypeDeclType(D2);
1237 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1238 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1240 << Base1->getSourceRange();
1241 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1247 // Check the fields for consistency.
1248 RecordDecl::field_iterator Field2 = D2->field_begin(),
1249 Field2End = D2->field_end();
1250 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1251 Field1End = D1->field_end();
1252 Field1 != Field1End;
1253 ++Field1, ++Field2) {
1254 if (Field2 == Field2End) {
1255 if (Context.Complain) {
1256 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1257 << Context.C2.getTypeDeclType(D2);
1258 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1259 << Field1->getDeclName() << Field1->getType();
1260 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1265 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1269 if (Field2 != Field2End) {
1270 if (Context.Complain) {
1271 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1272 << Context.C2.getTypeDeclType(D2);
1273 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1274 << Field2->getDeclName() << Field2->getType();
1275 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1283 /// \brief Determine structural equivalence of two enums.
1284 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1285 EnumDecl *D1, EnumDecl *D2) {
1286 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1287 EC2End = D2->enumerator_end();
1288 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1289 EC1End = D1->enumerator_end();
1290 EC1 != EC1End; ++EC1, ++EC2) {
1291 if (EC2 == EC2End) {
1292 if (Context.Complain) {
1293 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1294 << Context.C2.getTypeDeclType(D2);
1295 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1296 << EC1->getDeclName()
1297 << EC1->getInitVal().toString(10);
1298 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1303 llvm::APSInt Val1 = EC1->getInitVal();
1304 llvm::APSInt Val2 = EC2->getInitVal();
1305 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1306 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1307 if (Context.Complain) {
1308 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1309 << Context.C2.getTypeDeclType(D2);
1310 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1311 << EC2->getDeclName()
1312 << EC2->getInitVal().toString(10);
1313 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1314 << EC1->getDeclName()
1315 << EC1->getInitVal().toString(10);
1321 if (EC2 != EC2End) {
1322 if (Context.Complain) {
1323 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1324 << Context.C2.getTypeDeclType(D2);
1325 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1326 << EC2->getDeclName()
1327 << EC2->getInitVal().toString(10);
1328 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1336 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1337 TemplateParameterList *Params1,
1338 TemplateParameterList *Params2) {
1339 if (Params1->size() != Params2->size()) {
1340 if (Context.Complain) {
1341 Context.Diag2(Params2->getTemplateLoc(),
1342 diag::err_odr_different_num_template_parameters)
1343 << Params1->size() << Params2->size();
1344 Context.Diag1(Params1->getTemplateLoc(),
1345 diag::note_odr_template_parameter_list);
1350 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1351 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1352 if (Context.Complain) {
1353 Context.Diag2(Params2->getParam(I)->getLocation(),
1354 diag::err_odr_different_template_parameter_kind);
1355 Context.Diag1(Params1->getParam(I)->getLocation(),
1356 diag::note_odr_template_parameter_here);
1361 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1362 Params2->getParam(I))) {
1371 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1372 TemplateTypeParmDecl *D1,
1373 TemplateTypeParmDecl *D2) {
1374 if (D1->isParameterPack() != D2->isParameterPack()) {
1375 if (Context.Complain) {
1376 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1377 << D2->isParameterPack();
1378 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1379 << D1->isParameterPack();
1387 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1388 NonTypeTemplateParmDecl *D1,
1389 NonTypeTemplateParmDecl *D2) {
1390 if (D1->isParameterPack() != D2->isParameterPack()) {
1391 if (Context.Complain) {
1392 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1393 << D2->isParameterPack();
1394 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1395 << D1->isParameterPack();
1401 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1402 if (Context.Complain) {
1403 Context.Diag2(D2->getLocation(),
1404 diag::err_odr_non_type_parameter_type_inconsistent)
1405 << D2->getType() << D1->getType();
1406 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1415 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1416 TemplateTemplateParmDecl *D1,
1417 TemplateTemplateParmDecl *D2) {
1418 if (D1->isParameterPack() != D2->isParameterPack()) {
1419 if (Context.Complain) {
1420 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1421 << D2->isParameterPack();
1422 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1423 << D1->isParameterPack();
1428 // Check template parameter lists.
1429 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1430 D2->getTemplateParameters());
1433 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1434 ClassTemplateDecl *D1,
1435 ClassTemplateDecl *D2) {
1436 // Check template parameters.
1437 if (!IsStructurallyEquivalent(Context,
1438 D1->getTemplateParameters(),
1439 D2->getTemplateParameters()))
1442 // Check the templated declaration.
1443 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1444 D2->getTemplatedDecl());
1447 /// \brief Determine structural equivalence of two declarations.
1448 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1449 Decl *D1, Decl *D2) {
1450 // FIXME: Check for known structural equivalences via a callback of some sort.
1452 // Check whether we already know that these two declarations are not
1453 // structurally equivalent.
1454 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1455 D2->getCanonicalDecl())))
1458 // Determine whether we've already produced a tentative equivalence for D1.
1459 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1461 return EquivToD1 == D2->getCanonicalDecl();
1463 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1464 EquivToD1 = D2->getCanonicalDecl();
1465 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1469 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1471 if (!::IsStructurallyEquivalent(*this, D1, D2))
1477 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1479 if (!::IsStructurallyEquivalent(*this, T1, T2))
1485 bool StructuralEquivalenceContext::Finish() {
1486 while (!DeclsToCheck.empty()) {
1487 // Check the next declaration.
1488 Decl *D1 = DeclsToCheck.front();
1489 DeclsToCheck.pop_front();
1491 Decl *D2 = TentativeEquivalences[D1];
1492 assert(D2 && "Unrecorded tentative equivalence?");
1494 bool Equivalent = true;
1496 // FIXME: Switch on all declaration kinds. For now, we're just going to
1497 // check the obvious ones.
1498 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1499 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1500 // Check for equivalent structure names.
1501 IdentifierInfo *Name1 = Record1->getIdentifier();
1502 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1503 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1504 IdentifierInfo *Name2 = Record2->getIdentifier();
1505 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1506 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1507 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1508 !::IsStructurallyEquivalent(*this, Record1, Record2))
1511 // Record/non-record mismatch.
1514 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1515 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1516 // Check for equivalent enum names.
1517 IdentifierInfo *Name1 = Enum1->getIdentifier();
1518 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1519 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1520 IdentifierInfo *Name2 = Enum2->getIdentifier();
1521 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1522 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1523 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1524 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1527 // Enum/non-enum mismatch
1530 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1531 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1532 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1533 Typedef2->getIdentifier()) ||
1534 !::IsStructurallyEquivalent(*this,
1535 Typedef1->getUnderlyingType(),
1536 Typedef2->getUnderlyingType()))
1539 // Typedef/non-typedef mismatch.
1542 } else if (ClassTemplateDecl *ClassTemplate1
1543 = dyn_cast<ClassTemplateDecl>(D1)) {
1544 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1545 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1546 ClassTemplate2->getIdentifier()) ||
1547 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1550 // Class template/non-class-template mismatch.
1553 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1554 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1555 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1561 } else if (NonTypeTemplateParmDecl *NTTP1
1562 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1563 if (NonTypeTemplateParmDecl *NTTP2
1564 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1565 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1571 } else if (TemplateTemplateParmDecl *TTP1
1572 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1573 if (TemplateTemplateParmDecl *TTP2
1574 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1575 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1584 // Note that these two declarations are not equivalent (and we already
1586 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1587 D2->getCanonicalDecl()));
1590 // FIXME: Check other declaration kinds!
1596 //----------------------------------------------------------------------------
1598 //----------------------------------------------------------------------------
1600 QualType ASTNodeImporter::VisitType(const Type *T) {
1601 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1602 << T->getTypeClassName();
1606 QualType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1607 QualType UnderlyingType = Importer.Import(T->getValueType());
1608 if(UnderlyingType.isNull())
1611 return Importer.getToContext().getAtomicType(UnderlyingType);
1614 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1615 switch (T->getKind()) {
1616 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1617 case BuiltinType::Id: \
1618 return Importer.getToContext().SingletonId;
1619 #include "clang/Basic/OpenCLImageTypes.def"
1620 #define SHARED_SINGLETON_TYPE(Expansion)
1621 #define BUILTIN_TYPE(Id, SingletonId) \
1622 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1623 #include "clang/AST/BuiltinTypes.def"
1625 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1626 // context supports C++.
1628 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1629 // context supports ObjC.
1631 case BuiltinType::Char_U:
1632 // The context we're importing from has an unsigned 'char'. If we're
1633 // importing into a context with a signed 'char', translate to
1634 // 'unsigned char' instead.
1635 if (Importer.getToContext().getLangOpts().CharIsSigned)
1636 return Importer.getToContext().UnsignedCharTy;
1638 return Importer.getToContext().CharTy;
1640 case BuiltinType::Char_S:
1641 // The context we're importing from has an unsigned 'char'. If we're
1642 // importing into a context with a signed 'char', translate to
1643 // 'unsigned char' instead.
1644 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1645 return Importer.getToContext().SignedCharTy;
1647 return Importer.getToContext().CharTy;
1649 case BuiltinType::WChar_S:
1650 case BuiltinType::WChar_U:
1651 // FIXME: If not in C++, shall we translate to the C equivalent of
1653 return Importer.getToContext().WCharTy;
1656 llvm_unreachable("Invalid BuiltinType Kind!");
1659 QualType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1660 QualType OrigT = Importer.Import(T->getOriginalType());
1664 return Importer.getToContext().getDecayedType(OrigT);
1667 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1668 QualType ToElementType = Importer.Import(T->getElementType());
1669 if (ToElementType.isNull())
1672 return Importer.getToContext().getComplexType(ToElementType);
1675 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1676 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1677 if (ToPointeeType.isNull())
1680 return Importer.getToContext().getPointerType(ToPointeeType);
1683 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1684 // FIXME: Check for blocks support in "to" context.
1685 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1686 if (ToPointeeType.isNull())
1689 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1693 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1694 // FIXME: Check for C++ support in "to" context.
1695 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1696 if (ToPointeeType.isNull())
1699 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1703 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1704 // FIXME: Check for C++0x support in "to" context.
1705 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1706 if (ToPointeeType.isNull())
1709 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1712 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1713 // FIXME: Check for C++ support in "to" context.
1714 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1715 if (ToPointeeType.isNull())
1718 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1719 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1720 ClassType.getTypePtr());
1723 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1724 QualType ToElementType = Importer.Import(T->getElementType());
1725 if (ToElementType.isNull())
1728 return Importer.getToContext().getConstantArrayType(ToElementType,
1730 T->getSizeModifier(),
1731 T->getIndexTypeCVRQualifiers());
1735 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1736 QualType ToElementType = Importer.Import(T->getElementType());
1737 if (ToElementType.isNull())
1740 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1741 T->getSizeModifier(),
1742 T->getIndexTypeCVRQualifiers());
1745 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1746 QualType ToElementType = Importer.Import(T->getElementType());
1747 if (ToElementType.isNull())
1750 Expr *Size = Importer.Import(T->getSizeExpr());
1754 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1755 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1756 T->getSizeModifier(),
1757 T->getIndexTypeCVRQualifiers(),
1761 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1762 QualType ToElementType = Importer.Import(T->getElementType());
1763 if (ToElementType.isNull())
1766 return Importer.getToContext().getVectorType(ToElementType,
1767 T->getNumElements(),
1768 T->getVectorKind());
1771 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1772 QualType ToElementType = Importer.Import(T->getElementType());
1773 if (ToElementType.isNull())
1776 return Importer.getToContext().getExtVectorType(ToElementType,
1777 T->getNumElements());
1781 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1782 // FIXME: What happens if we're importing a function without a prototype
1783 // into C++? Should we make it variadic?
1784 QualType ToResultType = Importer.Import(T->getReturnType());
1785 if (ToResultType.isNull())
1788 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1792 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1793 QualType ToResultType = Importer.Import(T->getReturnType());
1794 if (ToResultType.isNull())
1797 // Import argument types
1798 SmallVector<QualType, 4> ArgTypes;
1799 for (const auto &A : T->param_types()) {
1800 QualType ArgType = Importer.Import(A);
1801 if (ArgType.isNull())
1803 ArgTypes.push_back(ArgType);
1806 // Import exception types
1807 SmallVector<QualType, 4> ExceptionTypes;
1808 for (const auto &E : T->exceptions()) {
1809 QualType ExceptionType = Importer.Import(E);
1810 if (ExceptionType.isNull())
1812 ExceptionTypes.push_back(ExceptionType);
1815 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1816 FunctionProtoType::ExtProtoInfo ToEPI;
1818 ToEPI.ExtInfo = FromEPI.ExtInfo;
1819 ToEPI.Variadic = FromEPI.Variadic;
1820 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1821 ToEPI.TypeQuals = FromEPI.TypeQuals;
1822 ToEPI.RefQualifier = FromEPI.RefQualifier;
1823 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1824 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1825 ToEPI.ExceptionSpec.NoexceptExpr =
1826 Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1827 ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1828 Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1829 ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1830 Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1832 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1835 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1836 QualType ToInnerType = Importer.Import(T->getInnerType());
1837 if (ToInnerType.isNull())
1840 return Importer.getToContext().getParenType(ToInnerType);
1843 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1844 TypedefNameDecl *ToDecl
1845 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1849 return Importer.getToContext().getTypeDeclType(ToDecl);
1852 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1853 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1857 return Importer.getToContext().getTypeOfExprType(ToExpr);
1860 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1861 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1862 if (ToUnderlyingType.isNull())
1865 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1868 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1869 // FIXME: Make sure that the "to" context supports C++0x!
1870 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1874 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1875 if (UnderlyingType.isNull())
1878 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1881 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1882 QualType ToBaseType = Importer.Import(T->getBaseType());
1883 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1884 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1887 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1892 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1893 // FIXME: Make sure that the "to" context supports C++11!
1894 QualType FromDeduced = T->getDeducedType();
1896 if (!FromDeduced.isNull()) {
1897 ToDeduced = Importer.Import(FromDeduced);
1898 if (ToDeduced.isNull())
1902 return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
1903 /*IsDependent*/false);
1906 QualType ASTNodeImporter::VisitInjectedClassNameType(
1907 const InjectedClassNameType *T) {
1908 CXXRecordDecl *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
1912 QualType InjType = Importer.Import(T->getInjectedSpecializationType());
1913 if (InjType.isNull())
1916 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1917 // See comments in InjectedClassNameType definition for details
1918 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1920 TypeAlignmentInBits = 4,
1921 TypeAlignment = 1 << TypeAlignmentInBits
1924 return QualType(new (Importer.getToContext(), TypeAlignment)
1925 InjectedClassNameType(D, InjType), 0);
1928 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1930 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1934 return Importer.getToContext().getTagDeclType(ToDecl);
1937 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1939 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1943 return Importer.getToContext().getTagDeclType(ToDecl);
1946 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1947 QualType FromModifiedType = T->getModifiedType();
1948 QualType FromEquivalentType = T->getEquivalentType();
1949 QualType ToModifiedType;
1950 QualType ToEquivalentType;
1952 if (!FromModifiedType.isNull()) {
1953 ToModifiedType = Importer.Import(FromModifiedType);
1954 if (ToModifiedType.isNull())
1957 if (!FromEquivalentType.isNull()) {
1958 ToEquivalentType = Importer.Import(FromEquivalentType);
1959 if (ToEquivalentType.isNull())
1963 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1964 ToModifiedType, ToEquivalentType);
1968 QualType ASTNodeImporter::VisitTemplateTypeParmType(
1969 const TemplateTypeParmType *T) {
1970 TemplateTypeParmDecl *ParmDecl =
1971 cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
1972 if (!ParmDecl && T->getDecl())
1975 return Importer.getToContext().getTemplateTypeParmType(
1976 T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
1979 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1980 const TemplateSpecializationType *T) {
1981 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1982 if (ToTemplate.isNull())
1985 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1986 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1989 QualType ToCanonType;
1990 if (!QualType(T, 0).isCanonical()) {
1991 QualType FromCanonType
1992 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1993 ToCanonType =Importer.Import(FromCanonType);
1994 if (ToCanonType.isNull())
1997 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
2002 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
2003 NestedNameSpecifier *ToQualifier = nullptr;
2004 // Note: the qualifier in an ElaboratedType is optional.
2005 if (T->getQualifier()) {
2006 ToQualifier = Importer.Import(T->getQualifier());
2011 QualType ToNamedType = Importer.Import(T->getNamedType());
2012 if (ToNamedType.isNull())
2015 return Importer.getToContext().getElaboratedType(T->getKeyword(),
2016 ToQualifier, ToNamedType);
2019 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
2020 ObjCInterfaceDecl *Class
2021 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
2025 return Importer.getToContext().getObjCInterfaceType(Class);
2028 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
2029 QualType ToBaseType = Importer.Import(T->getBaseType());
2030 if (ToBaseType.isNull())
2033 SmallVector<QualType, 4> TypeArgs;
2034 for (auto TypeArg : T->getTypeArgsAsWritten()) {
2035 QualType ImportedTypeArg = Importer.Import(TypeArg);
2036 if (ImportedTypeArg.isNull())
2039 TypeArgs.push_back(ImportedTypeArg);
2042 SmallVector<ObjCProtocolDecl *, 4> Protocols;
2043 for (auto *P : T->quals()) {
2044 ObjCProtocolDecl *Protocol
2045 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
2048 Protocols.push_back(Protocol);
2051 return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
2053 T->isKindOfTypeAsWritten());
2057 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
2058 QualType ToPointeeType = Importer.Import(T->getPointeeType());
2059 if (ToPointeeType.isNull())
2062 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
2065 //----------------------------------------------------------------------------
2066 // Import Declarations
2067 //----------------------------------------------------------------------------
2068 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
2069 DeclContext *&LexicalDC,
2070 DeclarationName &Name,
2072 SourceLocation &Loc) {
2073 // Import the context of this declaration.
2074 DC = Importer.ImportContext(D->getDeclContext());
2079 if (D->getDeclContext() != D->getLexicalDeclContext()) {
2080 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2085 // Import the name of this declaration.
2086 Name = Importer.Import(D->getDeclName());
2087 if (D->getDeclName() && !Name)
2090 // Import the location of this declaration.
2091 Loc = Importer.Import(D->getLocation());
2092 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
2096 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
2101 ToD = Importer.Import(FromD);
2106 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
2107 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
2108 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
2109 ImportDefinition(FromRecord, ToRecord);
2115 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
2116 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
2117 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
2118 ImportDefinition(FromEnum, ToEnum);
2126 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
2127 DeclarationNameInfo& To) {
2128 // NOTE: To.Name and To.Loc are already imported.
2129 // We only have to import To.LocInfo.
2130 switch (To.getName().getNameKind()) {
2131 case DeclarationName::Identifier:
2132 case DeclarationName::ObjCZeroArgSelector:
2133 case DeclarationName::ObjCOneArgSelector:
2134 case DeclarationName::ObjCMultiArgSelector:
2135 case DeclarationName::CXXUsingDirective:
2138 case DeclarationName::CXXOperatorName: {
2139 SourceRange Range = From.getCXXOperatorNameRange();
2140 To.setCXXOperatorNameRange(Importer.Import(Range));
2143 case DeclarationName::CXXLiteralOperatorName: {
2144 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
2145 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
2148 case DeclarationName::CXXConstructorName:
2149 case DeclarationName::CXXDestructorName:
2150 case DeclarationName::CXXConversionFunctionName: {
2151 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
2152 To.setNamedTypeInfo(Importer.Import(FromTInfo));
2156 llvm_unreachable("Unknown name kind.");
2159 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
2160 if (Importer.isMinimalImport() && !ForceImport) {
2161 Importer.ImportContext(FromDC);
2165 for (auto *From : FromDC->decls())
2166 Importer.Import(From);
2169 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
2170 ImportDefinitionKind Kind) {
2171 if (To->getDefinition() || To->isBeingDefined()) {
2172 if (Kind == IDK_Everything)
2173 ImportDeclContext(From, /*ForceImport=*/true);
2178 To->startDefinition();
2180 // Add base classes.
2181 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
2182 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
2184 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2185 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2186 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
2187 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
2188 ToData.Aggregate = FromData.Aggregate;
2189 ToData.PlainOldData = FromData.PlainOldData;
2190 ToData.Empty = FromData.Empty;
2191 ToData.Polymorphic = FromData.Polymorphic;
2192 ToData.Abstract = FromData.Abstract;
2193 ToData.IsStandardLayout = FromData.IsStandardLayout;
2194 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
2195 ToData.HasPrivateFields = FromData.HasPrivateFields;
2196 ToData.HasProtectedFields = FromData.HasProtectedFields;
2197 ToData.HasPublicFields = FromData.HasPublicFields;
2198 ToData.HasMutableFields = FromData.HasMutableFields;
2199 ToData.HasVariantMembers = FromData.HasVariantMembers;
2200 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2201 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2202 ToData.HasUninitializedReferenceMember
2203 = FromData.HasUninitializedReferenceMember;
2204 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
2205 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
2206 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
2207 ToData.NeedOverloadResolutionForMoveConstructor
2208 = FromData.NeedOverloadResolutionForMoveConstructor;
2209 ToData.NeedOverloadResolutionForMoveAssignment
2210 = FromData.NeedOverloadResolutionForMoveAssignment;
2211 ToData.NeedOverloadResolutionForDestructor
2212 = FromData.NeedOverloadResolutionForDestructor;
2213 ToData.DefaultedMoveConstructorIsDeleted
2214 = FromData.DefaultedMoveConstructorIsDeleted;
2215 ToData.DefaultedMoveAssignmentIsDeleted
2216 = FromData.DefaultedMoveAssignmentIsDeleted;
2217 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2218 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2219 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2220 ToData.HasConstexprNonCopyMoveConstructor
2221 = FromData.HasConstexprNonCopyMoveConstructor;
2222 ToData.HasDefaultedDefaultConstructor
2223 = FromData.HasDefaultedDefaultConstructor;
2224 ToData.DefaultedDefaultConstructorIsConstexpr
2225 = FromData.DefaultedDefaultConstructorIsConstexpr;
2226 ToData.HasConstexprDefaultConstructor
2227 = FromData.HasConstexprDefaultConstructor;
2228 ToData.HasNonLiteralTypeFieldsOrBases
2229 = FromData.HasNonLiteralTypeFieldsOrBases;
2230 // ComputedVisibleConversions not imported.
2231 ToData.UserProvidedDefaultConstructor
2232 = FromData.UserProvidedDefaultConstructor;
2233 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2234 ToData.ImplicitCopyConstructorHasConstParam
2235 = FromData.ImplicitCopyConstructorHasConstParam;
2236 ToData.ImplicitCopyAssignmentHasConstParam
2237 = FromData.ImplicitCopyAssignmentHasConstParam;
2238 ToData.HasDeclaredCopyConstructorWithConstParam
2239 = FromData.HasDeclaredCopyConstructorWithConstParam;
2240 ToData.HasDeclaredCopyAssignmentWithConstParam
2241 = FromData.HasDeclaredCopyAssignmentWithConstParam;
2242 ToData.IsLambda = FromData.IsLambda;
2244 SmallVector<CXXBaseSpecifier *, 4> Bases;
2245 for (const auto &Base1 : FromCXX->bases()) {
2246 QualType T = Importer.Import(Base1.getType());
2250 SourceLocation EllipsisLoc;
2251 if (Base1.isPackExpansion())
2252 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2254 // Ensure that we have a definition for the base.
2255 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2258 new (Importer.getToContext())
2259 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2261 Base1.isBaseOfClass(),
2262 Base1.getAccessSpecifierAsWritten(),
2263 Importer.Import(Base1.getTypeSourceInfo()),
2267 ToCXX->setBases(Bases.data(), Bases.size());
2270 if (shouldForceImportDeclContext(Kind))
2271 ImportDeclContext(From, /*ForceImport=*/true);
2273 To->completeDefinition();
2277 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2278 ImportDefinitionKind Kind) {
2279 if (To->getAnyInitializer())
2282 // FIXME: Can we really import any initializer? Alternatively, we could force
2283 // ourselves to import every declaration of a variable and then only use
2285 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2287 // FIXME: Other bits to merge?
2292 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2293 ImportDefinitionKind Kind) {
2294 if (To->getDefinition() || To->isBeingDefined()) {
2295 if (Kind == IDK_Everything)
2296 ImportDeclContext(From, /*ForceImport=*/true);
2300 To->startDefinition();
2302 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2306 QualType ToPromotionType = Importer.Import(From->getPromotionType());
2307 if (ToPromotionType.isNull())
2310 if (shouldForceImportDeclContext(Kind))
2311 ImportDeclContext(From, /*ForceImport=*/true);
2313 // FIXME: we might need to merge the number of positive or negative bits
2314 // if the enumerator lists don't match.
2315 To->completeDefinition(T, ToPromotionType,
2316 From->getNumPositiveBits(),
2317 From->getNumNegativeBits());
2321 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2322 TemplateParameterList *Params) {
2323 SmallVector<NamedDecl *, 4> ToParams(Params->size());
2324 if (ImportContainerChecked(*Params, ToParams))
2327 Expr *ToRequiresClause;
2328 if (Expr *const R = Params->getRequiresClause()) {
2329 ToRequiresClause = Importer.Import(R);
2330 if (!ToRequiresClause)
2333 ToRequiresClause = nullptr;
2336 return TemplateParameterList::Create(Importer.getToContext(),
2337 Importer.Import(Params->getTemplateLoc()),
2338 Importer.Import(Params->getLAngleLoc()),
2340 Importer.Import(Params->getRAngleLoc()),
2345 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2346 switch (From.getKind()) {
2347 case TemplateArgument::Null:
2348 return TemplateArgument();
2350 case TemplateArgument::Type: {
2351 QualType ToType = Importer.Import(From.getAsType());
2352 if (ToType.isNull())
2353 return TemplateArgument();
2354 return TemplateArgument(ToType);
2357 case TemplateArgument::Integral: {
2358 QualType ToType = Importer.Import(From.getIntegralType());
2359 if (ToType.isNull())
2360 return TemplateArgument();
2361 return TemplateArgument(From, ToType);
2364 case TemplateArgument::Declaration: {
2365 ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2366 QualType ToType = Importer.Import(From.getParamTypeForDecl());
2367 if (!To || ToType.isNull())
2368 return TemplateArgument();
2369 return TemplateArgument(To, ToType);
2372 case TemplateArgument::NullPtr: {
2373 QualType ToType = Importer.Import(From.getNullPtrType());
2374 if (ToType.isNull())
2375 return TemplateArgument();
2376 return TemplateArgument(ToType, /*isNullPtr*/true);
2379 case TemplateArgument::Template: {
2380 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2381 if (ToTemplate.isNull())
2382 return TemplateArgument();
2384 return TemplateArgument(ToTemplate);
2387 case TemplateArgument::TemplateExpansion: {
2388 TemplateName ToTemplate
2389 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2390 if (ToTemplate.isNull())
2391 return TemplateArgument();
2393 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2396 case TemplateArgument::Expression:
2397 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2398 return TemplateArgument(ToExpr);
2399 return TemplateArgument();
2401 case TemplateArgument::Pack: {
2402 SmallVector<TemplateArgument, 2> ToPack;
2403 ToPack.reserve(From.pack_size());
2404 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2405 return TemplateArgument();
2407 return TemplateArgument(
2408 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
2412 llvm_unreachable("Invalid template argument kind");
2415 TemplateArgumentLoc ASTNodeImporter::ImportTemplateArgumentLoc(
2416 const TemplateArgumentLoc &TALoc, bool &Error) {
2418 TemplateArgument Arg = ImportTemplateArgument(TALoc.getArgument());
2419 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
2420 TemplateArgumentLocInfo ToInfo;
2421 if (Arg.getKind() == TemplateArgument::Expression) {
2422 Expr *E = Importer.Import(FromInfo.getAsExpr());
2423 ToInfo = TemplateArgumentLocInfo(E);
2426 } else if (Arg.getKind() == TemplateArgument::Type) {
2427 if (TypeSourceInfo *TSI = Importer.Import(FromInfo.getAsTypeSourceInfo()))
2428 ToInfo = TemplateArgumentLocInfo(TSI);
2432 ToInfo = TemplateArgumentLocInfo(
2433 Importer.Import(FromInfo.getTemplateQualifierLoc()),
2434 Importer.Import(FromInfo.getTemplateNameLoc()),
2435 Importer.Import(FromInfo.getTemplateEllipsisLoc()));
2437 return TemplateArgumentLoc(Arg, ToInfo);
2440 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2441 unsigned NumFromArgs,
2442 SmallVectorImpl<TemplateArgument> &ToArgs) {
2443 for (unsigned I = 0; I != NumFromArgs; ++I) {
2444 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2445 if (To.isNull() && !FromArgs[I].isNull())
2448 ToArgs.push_back(To);
2454 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2455 RecordDecl *ToRecord, bool Complain) {
2456 // Eliminate a potential failure point where we attempt to re-import
2457 // something we're trying to import while completing ToRecord.
2458 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2460 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2462 ToRecord = ToOriginRecord;
2465 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2466 ToRecord->getASTContext(),
2467 Importer.getNonEquivalentDecls(),
2469 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2472 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2474 StructuralEquivalenceContext Ctx(
2475 Importer.getFromContext(), Importer.getToContext(),
2476 Importer.getNonEquivalentDecls(), false, Complain);
2477 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2480 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2481 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2482 Importer.getToContext(),
2483 Importer.getNonEquivalentDecls());
2484 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2487 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2488 EnumConstantDecl *ToEC)
2490 const llvm::APSInt &FromVal = FromEC->getInitVal();
2491 const llvm::APSInt &ToVal = ToEC->getInitVal();
2493 return FromVal.isSigned() == ToVal.isSigned() &&
2494 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2498 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2499 ClassTemplateDecl *To) {
2500 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2501 Importer.getToContext(),
2502 Importer.getNonEquivalentDecls());
2503 return Ctx.IsStructurallyEquivalent(From, To);
2506 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2507 VarTemplateDecl *To) {
2508 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2509 Importer.getToContext(),
2510 Importer.getNonEquivalentDecls());
2511 return Ctx.IsStructurallyEquivalent(From, To);
2514 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2515 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2516 << D->getDeclKindName();
2520 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2521 TranslationUnitDecl *ToD =
2522 Importer.getToContext().getTranslationUnitDecl();
2524 Importer.Imported(D, ToD);
2529 Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2531 SourceLocation Loc = Importer.Import(D->getLocation());
2532 SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
2534 // Import the context of this declaration.
2535 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2539 AccessSpecDecl *accessSpecDecl
2540 = AccessSpecDecl::Create(Importer.getToContext(), D->getAccess(),
2543 if (!accessSpecDecl)
2546 // Lexical DeclContext and Semantic DeclContext
2547 // is always the same for the accessSpec.
2548 accessSpecDecl->setLexicalDeclContext(DC);
2549 DC->addDeclInternal(accessSpecDecl);
2551 return accessSpecDecl;
2554 Decl *ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2555 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2559 DeclContext *LexicalDC = DC;
2561 // Import the location of this declaration.
2562 SourceLocation Loc = Importer.Import(D->getLocation());
2564 Expr *AssertExpr = Importer.Import(D->getAssertExpr());
2568 StringLiteral *FromMsg = D->getMessage();
2569 StringLiteral *ToMsg = cast_or_null<StringLiteral>(Importer.Import(FromMsg));
2570 if (!ToMsg && FromMsg)
2573 StaticAssertDecl *ToD = StaticAssertDecl::Create(
2574 Importer.getToContext(), DC, Loc, AssertExpr, ToMsg,
2575 Importer.Import(D->getRParenLoc()), D->isFailed());
2577 ToD->setLexicalDeclContext(LexicalDC);
2578 LexicalDC->addDeclInternal(ToD);
2579 Importer.Imported(D, ToD);
2583 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2584 // Import the major distinguishing characteristics of this namespace.
2585 DeclContext *DC, *LexicalDC;
2586 DeclarationName Name;
2589 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2594 NamespaceDecl *MergeWithNamespace = nullptr;
2596 // This is an anonymous namespace. Adopt an existing anonymous
2597 // namespace if we can.
2598 // FIXME: Not testable.
2599 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2600 MergeWithNamespace = TU->getAnonymousNamespace();
2602 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2604 SmallVector<NamedDecl *, 4> ConflictingDecls;
2605 SmallVector<NamedDecl *, 2> FoundDecls;
2606 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2607 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2608 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2611 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2612 MergeWithNamespace = FoundNS;
2613 ConflictingDecls.clear();
2617 ConflictingDecls.push_back(FoundDecls[I]);
2620 if (!ConflictingDecls.empty()) {
2621 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2622 ConflictingDecls.data(),
2623 ConflictingDecls.size());
2627 // Create the "to" namespace, if needed.
2628 NamespaceDecl *ToNamespace = MergeWithNamespace;
2630 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2632 Importer.Import(D->getLocStart()),
2633 Loc, Name.getAsIdentifierInfo(),
2634 /*PrevDecl=*/nullptr);
2635 ToNamespace->setLexicalDeclContext(LexicalDC);
2636 LexicalDC->addDeclInternal(ToNamespace);
2638 // If this is an anonymous namespace, register it as the anonymous
2639 // namespace within its context.
2641 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2642 TU->setAnonymousNamespace(ToNamespace);
2644 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2647 Importer.Imported(D, ToNamespace);
2649 ImportDeclContext(D);
2654 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2655 // Import the major distinguishing characteristics of this typedef.
2656 DeclContext *DC, *LexicalDC;
2657 DeclarationName Name;
2660 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2665 // If this typedef is not in block scope, determine whether we've
2666 // seen a typedef with the same name (that we can merge with) or any
2667 // other entity by that name (which name lookup could conflict with).
2668 if (!DC->isFunctionOrMethod()) {
2669 SmallVector<NamedDecl *, 4> ConflictingDecls;
2670 unsigned IDNS = Decl::IDNS_Ordinary;
2671 SmallVector<NamedDecl *, 2> FoundDecls;
2672 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2673 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2674 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2676 if (TypedefNameDecl *FoundTypedef =
2677 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2678 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2679 FoundTypedef->getUnderlyingType()))
2680 return Importer.Imported(D, FoundTypedef);
2683 ConflictingDecls.push_back(FoundDecls[I]);
2686 if (!ConflictingDecls.empty()) {
2687 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2688 ConflictingDecls.data(),
2689 ConflictingDecls.size());
2695 // Import the underlying type of this typedef;
2696 QualType T = Importer.Import(D->getUnderlyingType());
2700 // Create the new typedef node.
2701 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2702 SourceLocation StartL = Importer.Import(D->getLocStart());
2703 TypedefNameDecl *ToTypedef;
2705 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2707 Name.getAsIdentifierInfo(),
2710 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2712 Name.getAsIdentifierInfo(),
2715 ToTypedef->setAccess(D->getAccess());
2716 ToTypedef->setLexicalDeclContext(LexicalDC);
2717 Importer.Imported(D, ToTypedef);
2718 LexicalDC->addDeclInternal(ToTypedef);
2723 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2724 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2727 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2728 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2731 Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2732 // Import the major distinguishing characteristics of this label.
2733 DeclContext *DC, *LexicalDC;
2734 DeclarationName Name;
2737 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2742 assert(LexicalDC->isFunctionOrMethod());
2744 LabelDecl *ToLabel = D->isGnuLocal()
2745 ? LabelDecl::Create(Importer.getToContext(),
2746 DC, Importer.Import(D->getLocation()),
2747 Name.getAsIdentifierInfo(),
2748 Importer.Import(D->getLocStart()))
2749 : LabelDecl::Create(Importer.getToContext(),
2750 DC, Importer.Import(D->getLocation()),
2751 Name.getAsIdentifierInfo());
2752 Importer.Imported(D, ToLabel);
2754 LabelStmt *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
2758 ToLabel->setStmt(Label);
2759 ToLabel->setLexicalDeclContext(LexicalDC);
2760 LexicalDC->addDeclInternal(ToLabel);
2764 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2765 // Import the major distinguishing characteristics of this enum.
2766 DeclContext *DC, *LexicalDC;
2767 DeclarationName Name;
2770 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2775 // Figure out what enum name we're looking for.
2776 unsigned IDNS = Decl::IDNS_Tag;
2777 DeclarationName SearchName = Name;
2778 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2779 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2780 IDNS = Decl::IDNS_Ordinary;
2781 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2782 IDNS |= Decl::IDNS_Ordinary;
2784 // We may already have an enum of the same name; try to find and match it.
2785 if (!DC->isFunctionOrMethod() && SearchName) {
2786 SmallVector<NamedDecl *, 4> ConflictingDecls;
2787 SmallVector<NamedDecl *, 2> FoundDecls;
2788 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2789 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2790 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2793 Decl *Found = FoundDecls[I];
2794 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2795 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2796 Found = Tag->getDecl();
2799 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2800 if (IsStructuralMatch(D, FoundEnum))
2801 return Importer.Imported(D, FoundEnum);
2804 ConflictingDecls.push_back(FoundDecls[I]);
2807 if (!ConflictingDecls.empty()) {
2808 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2809 ConflictingDecls.data(),
2810 ConflictingDecls.size());
2814 // Create the enum declaration.
2815 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2816 Importer.Import(D->getLocStart()),
2817 Loc, Name.getAsIdentifierInfo(), nullptr,
2818 D->isScoped(), D->isScopedUsingClassTag(),
2820 // Import the qualifier, if any.
2821 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2822 D2->setAccess(D->getAccess());
2823 D2->setLexicalDeclContext(LexicalDC);
2824 Importer.Imported(D, D2);
2825 LexicalDC->addDeclInternal(D2);
2827 // Import the integer type.
2828 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2829 if (ToIntegerType.isNull())
2831 D2->setIntegerType(ToIntegerType);
2833 // Import the definition
2834 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2840 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2841 // If this record has a definition in the translation unit we're coming from,
2842 // but this particular declaration is not that definition, import the
2843 // definition and map to that.
2844 TagDecl *Definition = D->getDefinition();
2845 if (Definition && Definition != D) {
2846 Decl *ImportedDef = Importer.Import(Definition);
2850 return Importer.Imported(D, ImportedDef);
2853 // Import the major distinguishing characteristics of this record.
2854 DeclContext *DC, *LexicalDC;
2855 DeclarationName Name;
2858 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2863 // Figure out what structure name we're looking for.
2864 unsigned IDNS = Decl::IDNS_Tag;
2865 DeclarationName SearchName = Name;
2866 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2867 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2868 IDNS = Decl::IDNS_Ordinary;
2869 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2870 IDNS |= Decl::IDNS_Ordinary;
2872 // We may already have a record of the same name; try to find and match it.
2873 RecordDecl *AdoptDecl = nullptr;
2874 if (!DC->isFunctionOrMethod()) {
2875 SmallVector<NamedDecl *, 4> ConflictingDecls;
2876 SmallVector<NamedDecl *, 2> FoundDecls;
2877 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2878 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2879 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2882 Decl *Found = FoundDecls[I];
2883 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2884 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2885 Found = Tag->getDecl();
2888 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2889 if (D->isAnonymousStructOrUnion() &&
2890 FoundRecord->isAnonymousStructOrUnion()) {
2891 // If both anonymous structs/unions are in a record context, make sure
2892 // they occur in the same location in the context records.
2893 if (Optional<unsigned> Index1
2894 = findUntaggedStructOrUnionIndex(D)) {
2895 if (Optional<unsigned> Index2 =
2896 findUntaggedStructOrUnionIndex(FoundRecord)) {
2897 if (*Index1 != *Index2)
2903 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2904 if ((SearchName && !D->isCompleteDefinition())
2905 || (D->isCompleteDefinition() &&
2906 D->isAnonymousStructOrUnion()
2907 == FoundDef->isAnonymousStructOrUnion() &&
2908 IsStructuralMatch(D, FoundDef))) {
2909 // The record types structurally match, or the "from" translation
2910 // unit only had a forward declaration anyway; call it the same
2912 // FIXME: For C++, we should also merge methods here.
2913 return Importer.Imported(D, FoundDef);
2915 } else if (!D->isCompleteDefinition()) {
2916 // We have a forward declaration of this type, so adopt that forward
2917 // declaration rather than building a new one.
2919 // If one or both can be completed from external storage then try one
2920 // last time to complete and compare them before doing this.
2922 if (FoundRecord->hasExternalLexicalStorage() &&
2923 !FoundRecord->isCompleteDefinition())
2924 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2925 if (D->hasExternalLexicalStorage())
2926 D->getASTContext().getExternalSource()->CompleteType(D);
2928 if (FoundRecord->isCompleteDefinition() &&
2929 D->isCompleteDefinition() &&
2930 !IsStructuralMatch(D, FoundRecord))
2933 AdoptDecl = FoundRecord;
2935 } else if (!SearchName) {
2940 ConflictingDecls.push_back(FoundDecls[I]);
2943 if (!ConflictingDecls.empty() && SearchName) {
2944 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2945 ConflictingDecls.data(),
2946 ConflictingDecls.size());
2950 // Create the record declaration.
2951 RecordDecl *D2 = AdoptDecl;
2952 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2954 CXXRecordDecl *D2CXX = nullptr;
2955 if (CXXRecordDecl *DCXX = llvm::dyn_cast<CXXRecordDecl>(D)) {
2956 if (DCXX->isLambda()) {
2957 TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
2958 D2CXX = CXXRecordDecl::CreateLambda(Importer.getToContext(),
2960 DCXX->isDependentLambda(),
2961 DCXX->isGenericLambda(),
2962 DCXX->getLambdaCaptureDefault());
2963 Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
2964 if (DCXX->getLambdaContextDecl() && !CDecl)
2966 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
2967 } else if (DCXX->isInjectedClassName()) {
2968 // We have to be careful to do a similar dance to the one in
2969 // Sema::ActOnStartCXXMemberDeclarations
2970 CXXRecordDecl *const PrevDecl = nullptr;
2971 const bool DelayTypeCreation = true;
2972 D2CXX = CXXRecordDecl::Create(
2973 Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc,
2974 Name.getAsIdentifierInfo(), PrevDecl, DelayTypeCreation);
2975 Importer.getToContext().getTypeDeclType(
2976 D2CXX, llvm::dyn_cast<CXXRecordDecl>(DC));
2978 D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2981 Name.getAsIdentifierInfo());
2984 D2->setAccess(D->getAccess());
2986 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2987 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2990 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2991 D2->setLexicalDeclContext(LexicalDC);
2992 LexicalDC->addDeclInternal(D2);
2993 if (D->isAnonymousStructOrUnion())
2994 D2->setAnonymousStructOrUnion(true);
2997 Importer.Imported(D, D2);
2999 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
3005 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
3006 // Import the major distinguishing characteristics of this enumerator.
3007 DeclContext *DC, *LexicalDC;
3008 DeclarationName Name;
3011 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3016 QualType T = Importer.Import(D->getType());
3020 // Determine whether there are any other declarations with the same name and
3021 // in the same context.
3022 if (!LexicalDC->isFunctionOrMethod()) {
3023 SmallVector<NamedDecl *, 4> ConflictingDecls;
3024 unsigned IDNS = Decl::IDNS_Ordinary;
3025 SmallVector<NamedDecl *, 2> FoundDecls;
3026 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3027 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3028 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3031 if (EnumConstantDecl *FoundEnumConstant
3032 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
3033 if (IsStructuralMatch(D, FoundEnumConstant))
3034 return Importer.Imported(D, FoundEnumConstant);
3037 ConflictingDecls.push_back(FoundDecls[I]);
3040 if (!ConflictingDecls.empty()) {
3041 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3042 ConflictingDecls.data(),
3043 ConflictingDecls.size());
3049 Expr *Init = Importer.Import(D->getInitExpr());
3050 if (D->getInitExpr() && !Init)
3053 EnumConstantDecl *ToEnumerator
3054 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3055 Name.getAsIdentifierInfo(), T,
3056 Init, D->getInitVal());
3057 ToEnumerator->setAccess(D->getAccess());
3058 ToEnumerator->setLexicalDeclContext(LexicalDC);
3059 Importer.Imported(D, ToEnumerator);
3060 LexicalDC->addDeclInternal(ToEnumerator);
3061 return ToEnumerator;
3064 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3065 // Import the major distinguishing characteristics of this function.
3066 DeclContext *DC, *LexicalDC;
3067 DeclarationName Name;
3070 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3075 // Try to find a function in our own ("to") context with the same name, same
3076 // type, and in the same context as the function we're importing.
3077 if (!LexicalDC->isFunctionOrMethod()) {
3078 SmallVector<NamedDecl *, 4> ConflictingDecls;
3079 unsigned IDNS = Decl::IDNS_Ordinary;
3080 SmallVector<NamedDecl *, 2> FoundDecls;
3081 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3082 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3083 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3086 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
3087 if (FoundFunction->hasExternalFormalLinkage() &&
3088 D->hasExternalFormalLinkage()) {
3089 if (Importer.IsStructurallyEquivalent(D->getType(),
3090 FoundFunction->getType())) {
3091 // FIXME: Actually try to merge the body and other attributes.
3092 return Importer.Imported(D, FoundFunction);
3095 // FIXME: Check for overloading more carefully, e.g., by boosting
3096 // Sema::IsOverload out to the AST library.
3098 // Function overloading is okay in C++.
3099 if (Importer.getToContext().getLangOpts().CPlusPlus)
3102 // Complain about inconsistent function types.
3103 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
3104 << Name << D->getType() << FoundFunction->getType();
3105 Importer.ToDiag(FoundFunction->getLocation(),
3106 diag::note_odr_value_here)
3107 << FoundFunction->getType();
3111 ConflictingDecls.push_back(FoundDecls[I]);
3114 if (!ConflictingDecls.empty()) {
3115 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3116 ConflictingDecls.data(),
3117 ConflictingDecls.size());
3123 DeclarationNameInfo NameInfo(Name, Loc);
3124 // Import additional name location/type info.
3125 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3127 QualType FromTy = D->getType();
3128 bool usedDifferentExceptionSpec = false;
3130 if (const FunctionProtoType *
3131 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3132 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3133 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3134 // FunctionDecl that we are importing the FunctionProtoType for.
3135 // To avoid an infinite recursion when importing, create the FunctionDecl
3136 // with a simplified function type and update it afterwards.
3137 if (FromEPI.ExceptionSpec.SourceDecl ||
3138 FromEPI.ExceptionSpec.SourceTemplate ||
3139 FromEPI.ExceptionSpec.NoexceptExpr) {
3140 FunctionProtoType::ExtProtoInfo DefaultEPI;
3141 FromTy = Importer.getFromContext().getFunctionType(
3142 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3143 usedDifferentExceptionSpec = true;
3148 QualType T = Importer.Import(FromTy);
3152 // Import the function parameters.
3153 SmallVector<ParmVarDecl *, 8> Parameters;
3154 for (auto P : D->parameters()) {
3155 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
3159 Parameters.push_back(ToP);
3162 // Create the imported function.
3163 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3164 FunctionDecl *ToFunction = nullptr;
3165 SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
3166 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3167 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
3168 cast<CXXRecordDecl>(DC),
3171 FromConstructor->isExplicit(),
3172 D->isInlineSpecified(),
3175 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3176 SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
3177 for (CXXCtorInitializer *I : FromConstructor->inits()) {
3178 CXXCtorInitializer *ToI =
3179 cast_or_null<CXXCtorInitializer>(Importer.Import(I));
3182 CtorInitializers.push_back(ToI);
3184 CXXCtorInitializer **Memory =
3185 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3186 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3187 CXXConstructorDecl *ToCtor = llvm::cast<CXXConstructorDecl>(ToFunction);
3188 ToCtor->setCtorInitializers(Memory);
3189 ToCtor->setNumCtorInitializers(NumInitializers);
3191 } else if (isa<CXXDestructorDecl>(D)) {
3192 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
3193 cast<CXXRecordDecl>(DC),
3196 D->isInlineSpecified(),
3198 } else if (CXXConversionDecl *FromConversion
3199 = dyn_cast<CXXConversionDecl>(D)) {
3200 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
3201 cast<CXXRecordDecl>(DC),
3204 D->isInlineSpecified(),
3205 FromConversion->isExplicit(),
3207 Importer.Import(D->getLocEnd()));
3208 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3209 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
3210 cast<CXXRecordDecl>(DC),
3213 Method->getStorageClass(),
3214 Method->isInlineSpecified(),
3216 Importer.Import(D->getLocEnd()));
3218 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
3220 NameInfo, T, TInfo, D->getStorageClass(),
3221 D->isInlineSpecified(),
3222 D->hasWrittenPrototype(),
3226 // Import the qualifier, if any.
3227 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3228 ToFunction->setAccess(D->getAccess());
3229 ToFunction->setLexicalDeclContext(LexicalDC);
3230 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3231 ToFunction->setTrivial(D->isTrivial());
3232 ToFunction->setPure(D->isPure());
3233 Importer.Imported(D, ToFunction);
3235 // Set the parameters.
3236 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
3237 Parameters[I]->setOwningFunction(ToFunction);
3238 ToFunction->addDeclInternal(Parameters[I]);
3240 ToFunction->setParams(Parameters);
3242 if (usedDifferentExceptionSpec) {
3243 // Update FunctionProtoType::ExtProtoInfo.
3244 QualType T = Importer.Import(D->getType());
3247 ToFunction->setType(T);
3250 // Import the body, if any.
3251 if (Stmt *FromBody = D->getBody()) {
3252 if (Stmt *ToBody = Importer.Import(FromBody)) {
3253 ToFunction->setBody(ToBody);
3257 // FIXME: Other bits to merge?
3259 // Add this function to the lexical context.
3260 LexicalDC->addDeclInternal(ToFunction);
3265 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3266 return VisitFunctionDecl(D);
3269 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3270 return VisitCXXMethodDecl(D);
3273 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3274 return VisitCXXMethodDecl(D);
3277 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3278 return VisitCXXMethodDecl(D);
3281 static unsigned getFieldIndex(Decl *F) {
3282 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
3287 for (const auto *D : Owner->noload_decls()) {
3291 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
3298 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3299 // Import the major distinguishing characteristics of a variable.
3300 DeclContext *DC, *LexicalDC;
3301 DeclarationName Name;
3304 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3309 // Determine whether we've already imported this field.
3310 SmallVector<NamedDecl *, 2> FoundDecls;
3311 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3312 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3313 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
3314 // For anonymous fields, match up by index.
3315 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3318 if (Importer.IsStructurallyEquivalent(D->getType(),
3319 FoundField->getType())) {
3320 Importer.Imported(D, FoundField);
3324 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3325 << Name << D->getType() << FoundField->getType();
3326 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3327 << FoundField->getType();
3333 QualType T = Importer.Import(D->getType());
3337 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3338 Expr *BitWidth = Importer.Import(D->getBitWidth());
3339 if (!BitWidth && D->getBitWidth())
3342 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
3343 Importer.Import(D->getInnerLocStart()),
3344 Loc, Name.getAsIdentifierInfo(),
3345 T, TInfo, BitWidth, D->isMutable(),
3346 D->getInClassInitStyle());
3347 ToField->setAccess(D->getAccess());
3348 ToField->setLexicalDeclContext(LexicalDC);
3349 if (Expr *FromInitializer = D->getInClassInitializer()) {
3350 Expr *ToInitializer = Importer.Import(FromInitializer);
3352 ToField->setInClassInitializer(ToInitializer);
3356 ToField->setImplicit(D->isImplicit());
3357 Importer.Imported(D, ToField);
3358 LexicalDC->addDeclInternal(ToField);
3362 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3363 // Import the major distinguishing characteristics of a variable.
3364 DeclContext *DC, *LexicalDC;
3365 DeclarationName Name;
3368 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3373 // Determine whether we've already imported this field.
3374 SmallVector<NamedDecl *, 2> FoundDecls;
3375 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3376 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3377 if (IndirectFieldDecl *FoundField
3378 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3379 // For anonymous indirect fields, match up by index.
3380 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3383 if (Importer.IsStructurallyEquivalent(D->getType(),
3384 FoundField->getType(),
3386 Importer.Imported(D, FoundField);
3390 // If there are more anonymous fields to check, continue.
3391 if (!Name && I < N-1)
3394 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3395 << Name << D->getType() << FoundField->getType();
3396 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3397 << FoundField->getType();
3403 QualType T = Importer.Import(D->getType());
3407 NamedDecl **NamedChain =
3408 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3411 for (auto *PI : D->chain()) {
3412 Decl *D = Importer.Import(PI);
3415 NamedChain[i++] = cast<NamedDecl>(D);
3418 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3419 Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3420 {NamedChain, D->getChainingSize()});
3422 for (const auto *Attr : D->attrs())
3423 ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3425 ToIndirectField->setAccess(D->getAccess());
3426 ToIndirectField->setLexicalDeclContext(LexicalDC);
3427 Importer.Imported(D, ToIndirectField);
3428 LexicalDC->addDeclInternal(ToIndirectField);
3429 return ToIndirectField;
3432 Decl *ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
3433 // Import the major distinguishing characteristics of a declaration.
3434 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3435 DeclContext *LexicalDC = D->getDeclContext() == D->getLexicalDeclContext()
3436 ? DC : Importer.ImportContext(D->getLexicalDeclContext());
3437 if (!DC || !LexicalDC)
3440 // Determine whether we've already imported this decl.
3441 // FriendDecl is not a NamedDecl so we cannot use localUncachedLookup.
3442 auto *RD = cast<CXXRecordDecl>(DC);
3443 FriendDecl *ImportedFriend = RD->getFirstFriend();
3444 StructuralEquivalenceContext Context(
3445 Importer.getFromContext(), Importer.getToContext(),
3446 Importer.getNonEquivalentDecls(), false, false);
3448 while (ImportedFriend) {
3449 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3450 if (Context.IsStructurallyEquivalent(D->getFriendDecl(),
3451 ImportedFriend->getFriendDecl()))
3452 return Importer.Imported(D, ImportedFriend);
3454 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3455 if (Importer.IsStructurallyEquivalent(
3456 D->getFriendType()->getType(),
3457 ImportedFriend->getFriendType()->getType(), true))
3458 return Importer.Imported(D, ImportedFriend);
3460 ImportedFriend = ImportedFriend->getNextFriend();
3463 // Not found. Create it.
3464 FriendDecl::FriendUnion ToFU;
3465 if (NamedDecl *FriendD = D->getFriendDecl())
3466 ToFU = cast_or_null<NamedDecl>(Importer.Import(FriendD));
3468 ToFU = Importer.Import(D->getFriendType());
3472 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3473 TemplateParameterList **FromTPLists =
3474 D->getTrailingObjects<TemplateParameterList *>();
3475 for (unsigned I = 0; I < D->NumTPLists; I++) {
3476 TemplateParameterList *List = ImportTemplateParameterList(FromTPLists[I]);
3479 ToTPLists[I] = List;
3482 FriendDecl *FrD = FriendDecl::Create(Importer.getToContext(), DC,
3483 Importer.Import(D->getLocation()),
3484 ToFU, Importer.Import(D->getFriendLoc()),
3487 Importer.Imported(D, FrD);
3488 RD->pushFriendDecl(FrD);
3490 FrD->setAccess(D->getAccess());
3491 FrD->setLexicalDeclContext(LexicalDC);
3492 LexicalDC->addDeclInternal(FrD);
3496 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3497 // Import the major distinguishing characteristics of an ivar.
3498 DeclContext *DC, *LexicalDC;
3499 DeclarationName Name;
3502 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3507 // Determine whether we've already imported this ivar
3508 SmallVector<NamedDecl *, 2> FoundDecls;
3509 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3510 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3511 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3512 if (Importer.IsStructurallyEquivalent(D->getType(),
3513 FoundIvar->getType())) {
3514 Importer.Imported(D, FoundIvar);
3518 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3519 << Name << D->getType() << FoundIvar->getType();
3520 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3521 << FoundIvar->getType();
3527 QualType T = Importer.Import(D->getType());
3531 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3532 Expr *BitWidth = Importer.Import(D->getBitWidth());
3533 if (!BitWidth && D->getBitWidth())
3536 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3537 cast<ObjCContainerDecl>(DC),
3538 Importer.Import(D->getInnerLocStart()),
3539 Loc, Name.getAsIdentifierInfo(),
3540 T, TInfo, D->getAccessControl(),
3541 BitWidth, D->getSynthesize());
3542 ToIvar->setLexicalDeclContext(LexicalDC);
3543 Importer.Imported(D, ToIvar);
3544 LexicalDC->addDeclInternal(ToIvar);
3549 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3550 // Import the major distinguishing characteristics of a variable.
3551 DeclContext *DC, *LexicalDC;
3552 DeclarationName Name;
3555 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3560 // Try to find a variable in our own ("to") context with the same name and
3561 // in the same context as the variable we're importing.
3562 if (D->isFileVarDecl()) {
3563 VarDecl *MergeWithVar = nullptr;
3564 SmallVector<NamedDecl *, 4> ConflictingDecls;
3565 unsigned IDNS = Decl::IDNS_Ordinary;
3566 SmallVector<NamedDecl *, 2> FoundDecls;
3567 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3568 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3569 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3572 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3573 // We have found a variable that we may need to merge with. Check it.
3574 if (FoundVar->hasExternalFormalLinkage() &&
3575 D->hasExternalFormalLinkage()) {
3576 if (Importer.IsStructurallyEquivalent(D->getType(),
3577 FoundVar->getType())) {
3578 MergeWithVar = FoundVar;
3582 const ArrayType *FoundArray
3583 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3584 const ArrayType *TArray
3585 = Importer.getToContext().getAsArrayType(D->getType());
3586 if (FoundArray && TArray) {
3587 if (isa<IncompleteArrayType>(FoundArray) &&
3588 isa<ConstantArrayType>(TArray)) {
3590 QualType T = Importer.Import(D->getType());
3594 FoundVar->setType(T);
3595 MergeWithVar = FoundVar;
3597 } else if (isa<IncompleteArrayType>(TArray) &&
3598 isa<ConstantArrayType>(FoundArray)) {
3599 MergeWithVar = FoundVar;
3604 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3605 << Name << D->getType() << FoundVar->getType();
3606 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3607 << FoundVar->getType();
3611 ConflictingDecls.push_back(FoundDecls[I]);
3615 // An equivalent variable with external linkage has been found. Link
3616 // the two declarations, then merge them.
3617 Importer.Imported(D, MergeWithVar);
3619 if (VarDecl *DDef = D->getDefinition()) {
3620 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3621 Importer.ToDiag(ExistingDef->getLocation(),
3622 diag::err_odr_variable_multiple_def)
3624 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3626 Expr *Init = Importer.Import(DDef->getInit());
3627 MergeWithVar->setInit(Init);
3628 if (DDef->isInitKnownICE()) {
3629 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3630 Eval->CheckedICE = true;
3631 Eval->IsICE = DDef->isInitICE();
3636 return MergeWithVar;
3639 if (!ConflictingDecls.empty()) {
3640 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3641 ConflictingDecls.data(),
3642 ConflictingDecls.size());
3649 QualType T = Importer.Import(D->getType());
3653 // Create the imported variable.
3654 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3655 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3656 Importer.Import(D->getInnerLocStart()),
3657 Loc, Name.getAsIdentifierInfo(),
3659 D->getStorageClass());
3660 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3661 ToVar->setAccess(D->getAccess());
3662 ToVar->setLexicalDeclContext(LexicalDC);
3663 Importer.Imported(D, ToVar);
3664 LexicalDC->addDeclInternal(ToVar);
3666 if (!D->isFileVarDecl() &&
3670 // Merge the initializer.
3671 if (ImportDefinition(D, ToVar))
3677 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3678 // Parameters are created in the translation unit's context, then moved
3679 // into the function declaration's context afterward.
3680 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3682 // Import the name of this declaration.
3683 DeclarationName Name = Importer.Import(D->getDeclName());
3684 if (D->getDeclName() && !Name)
3687 // Import the location of this declaration.
3688 SourceLocation Loc = Importer.Import(D->getLocation());
3690 // Import the parameter's type.
3691 QualType T = Importer.Import(D->getType());
3695 // Create the imported parameter.
3696 ImplicitParamDecl *ToParm
3697 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3698 Loc, Name.getAsIdentifierInfo(),
3700 return Importer.Imported(D, ToParm);
3703 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3704 // Parameters are created in the translation unit's context, then moved
3705 // into the function declaration's context afterward.
3706 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3708 // Import the name of this declaration.
3709 DeclarationName Name = Importer.Import(D->getDeclName());
3710 if (D->getDeclName() && !Name)
3713 // Import the location of this declaration.
3714 SourceLocation Loc = Importer.Import(D->getLocation());
3716 // Import the parameter's type.
3717 QualType T = Importer.Import(D->getType());
3721 // Create the imported parameter.
3722 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3723 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3724 Importer.Import(D->getInnerLocStart()),
3725 Loc, Name.getAsIdentifierInfo(),
3726 T, TInfo, D->getStorageClass(),
3727 /*FIXME: Default argument*/nullptr);
3728 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3731 ToParm->setIsUsed();
3733 return Importer.Imported(D, ToParm);
3736 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3737 // Import the major distinguishing characteristics of a method.
3738 DeclContext *DC, *LexicalDC;
3739 DeclarationName Name;
3742 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3747 SmallVector<NamedDecl *, 2> FoundDecls;
3748 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3749 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3750 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3751 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3754 // Check return types.
3755 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3756 FoundMethod->getReturnType())) {
3757 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3758 << D->isInstanceMethod() << Name << D->getReturnType()
3759 << FoundMethod->getReturnType();
3760 Importer.ToDiag(FoundMethod->getLocation(),
3761 diag::note_odr_objc_method_here)
3762 << D->isInstanceMethod() << Name;
3766 // Check the number of parameters.
3767 if (D->param_size() != FoundMethod->param_size()) {
3768 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3769 << D->isInstanceMethod() << Name
3770 << D->param_size() << FoundMethod->param_size();
3771 Importer.ToDiag(FoundMethod->getLocation(),
3772 diag::note_odr_objc_method_here)
3773 << D->isInstanceMethod() << Name;
3777 // Check parameter types.
3778 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3779 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3780 P != PEnd; ++P, ++FoundP) {
3781 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3782 (*FoundP)->getType())) {
3783 Importer.FromDiag((*P)->getLocation(),
3784 diag::err_odr_objc_method_param_type_inconsistent)
3785 << D->isInstanceMethod() << Name
3786 << (*P)->getType() << (*FoundP)->getType();
3787 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3788 << (*FoundP)->getType();
3793 // Check variadic/non-variadic.
3794 // Check the number of parameters.
3795 if (D->isVariadic() != FoundMethod->isVariadic()) {
3796 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3797 << D->isInstanceMethod() << Name;
3798 Importer.ToDiag(FoundMethod->getLocation(),
3799 diag::note_odr_objc_method_here)
3800 << D->isInstanceMethod() << Name;
3804 // FIXME: Any other bits we need to merge?
3805 return Importer.Imported(D, FoundMethod);
3809 // Import the result type.
3810 QualType ResultTy = Importer.Import(D->getReturnType());
3811 if (ResultTy.isNull())
3814 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3816 ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3817 Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3818 Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3819 D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3820 D->getImplementationControl(), D->hasRelatedResultType());
3822 // FIXME: When we decide to merge method definitions, we'll need to
3823 // deal with implicit parameters.
3825 // Import the parameters
3826 SmallVector<ParmVarDecl *, 5> ToParams;
3827 for (auto *FromP : D->parameters()) {
3828 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3832 ToParams.push_back(ToP);
3835 // Set the parameters.
3836 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3837 ToParams[I]->setOwningFunction(ToMethod);
3838 ToMethod->addDeclInternal(ToParams[I]);
3840 SmallVector<SourceLocation, 12> SelLocs;
3841 D->getSelectorLocs(SelLocs);
3842 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3844 ToMethod->setLexicalDeclContext(LexicalDC);
3845 Importer.Imported(D, ToMethod);
3846 LexicalDC->addDeclInternal(ToMethod);
3850 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3851 // Import the major distinguishing characteristics of a category.
3852 DeclContext *DC, *LexicalDC;
3853 DeclarationName Name;
3856 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3861 TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3865 ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3866 Importer.getToContext(), DC,
3868 Importer.Import(D->getVarianceLoc()),
3870 Importer.Import(D->getLocation()),
3871 Name.getAsIdentifierInfo(),
3872 Importer.Import(D->getColonLoc()),
3874 Importer.Imported(D, Result);
3875 Result->setLexicalDeclContext(LexicalDC);
3879 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3880 // Import the major distinguishing characteristics of a category.
3881 DeclContext *DC, *LexicalDC;
3882 DeclarationName Name;
3885 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3890 ObjCInterfaceDecl *ToInterface
3891 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3895 // Determine if we've already encountered this category.
3896 ObjCCategoryDecl *MergeWithCategory
3897 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3898 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3900 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3901 Importer.Import(D->getAtStartLoc()),
3903 Importer.Import(D->getCategoryNameLoc()),
3904 Name.getAsIdentifierInfo(),
3906 /*TypeParamList=*/nullptr,
3907 Importer.Import(D->getIvarLBraceLoc()),
3908 Importer.Import(D->getIvarRBraceLoc()));
3909 ToCategory->setLexicalDeclContext(LexicalDC);
3910 LexicalDC->addDeclInternal(ToCategory);
3911 Importer.Imported(D, ToCategory);
3912 // Import the type parameter list after calling Imported, to avoid
3913 // loops when bringing in their DeclContext.
3914 ToCategory->setTypeParamList(ImportObjCTypeParamList(
3915 D->getTypeParamList()));
3918 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3919 SmallVector<SourceLocation, 4> ProtocolLocs;
3920 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3921 = D->protocol_loc_begin();
3922 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3923 FromProtoEnd = D->protocol_end();
3924 FromProto != FromProtoEnd;
3925 ++FromProto, ++FromProtoLoc) {
3926 ObjCProtocolDecl *ToProto
3927 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3930 Protocols.push_back(ToProto);
3931 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3934 // FIXME: If we're merging, make sure that the protocol list is the same.
3935 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3936 ProtocolLocs.data(), Importer.getToContext());
3939 Importer.Imported(D, ToCategory);
3942 // Import all of the members of this category.
3943 ImportDeclContext(D);
3945 // If we have an implementation, import it as well.
3946 if (D->getImplementation()) {
3947 ObjCCategoryImplDecl *Impl
3948 = cast_or_null<ObjCCategoryImplDecl>(
3949 Importer.Import(D->getImplementation()));
3953 ToCategory->setImplementation(Impl);
3959 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3960 ObjCProtocolDecl *To,
3961 ImportDefinitionKind Kind) {
3962 if (To->getDefinition()) {
3963 if (shouldForceImportDeclContext(Kind))
3964 ImportDeclContext(From);
3968 // Start the protocol definition
3969 To->startDefinition();
3972 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3973 SmallVector<SourceLocation, 4> ProtocolLocs;
3974 ObjCProtocolDecl::protocol_loc_iterator
3975 FromProtoLoc = From->protocol_loc_begin();
3976 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3977 FromProtoEnd = From->protocol_end();
3978 FromProto != FromProtoEnd;
3979 ++FromProto, ++FromProtoLoc) {
3980 ObjCProtocolDecl *ToProto
3981 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3984 Protocols.push_back(ToProto);
3985 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3988 // FIXME: If we're merging, make sure that the protocol list is the same.
3989 To->setProtocolList(Protocols.data(), Protocols.size(),
3990 ProtocolLocs.data(), Importer.getToContext());
3992 if (shouldForceImportDeclContext(Kind)) {
3993 // Import all of the members of this protocol.
3994 ImportDeclContext(From, /*ForceImport=*/true);
3999 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4000 // If this protocol has a definition in the translation unit we're coming
4001 // from, but this particular declaration is not that definition, import the
4002 // definition and map to that.
4003 ObjCProtocolDecl *Definition = D->getDefinition();
4004 if (Definition && Definition != D) {
4005 Decl *ImportedDef = Importer.Import(Definition);
4009 return Importer.Imported(D, ImportedDef);
4012 // Import the major distinguishing characteristics of a protocol.
4013 DeclContext *DC, *LexicalDC;
4014 DeclarationName Name;
4017 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4022 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4023 SmallVector<NamedDecl *, 2> FoundDecls;
4024 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4025 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4026 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4029 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
4033 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4035 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
4036 Name.getAsIdentifierInfo(), Loc,
4037 Importer.Import(D->getAtStartLoc()),
4038 /*PrevDecl=*/nullptr);
4039 ToProto->setLexicalDeclContext(LexicalDC);
4040 LexicalDC->addDeclInternal(ToProto);
4043 Importer.Imported(D, ToProto);
4045 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
4051 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4052 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4053 DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4055 SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
4056 SourceLocation LangLoc = Importer.Import(D->getLocation());
4058 bool HasBraces = D->hasBraces();
4060 LinkageSpecDecl *ToLinkageSpec =
4061 LinkageSpecDecl::Create(Importer.getToContext(),
4069 SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
4070 ToLinkageSpec->setRBraceLoc(RBraceLoc);
4073 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4074 LexicalDC->addDeclInternal(ToLinkageSpec);
4076 Importer.Imported(D, ToLinkageSpec);
4078 return ToLinkageSpec;
4081 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
4082 ObjCInterfaceDecl *To,
4083 ImportDefinitionKind Kind) {
4084 if (To->getDefinition()) {
4085 // Check consistency of superclass.
4086 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4088 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
4093 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4094 if ((bool)FromSuper != (bool)ToSuper ||
4095 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4096 Importer.ToDiag(To->getLocation(),
4097 diag::err_odr_objc_superclass_inconsistent)
4098 << To->getDeclName();
4100 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4101 << To->getSuperClass()->getDeclName();
4103 Importer.ToDiag(To->getLocation(),
4104 diag::note_odr_objc_missing_superclass);
4105 if (From->getSuperClass())
4106 Importer.FromDiag(From->getSuperClassLoc(),
4107 diag::note_odr_objc_superclass)
4108 << From->getSuperClass()->getDeclName();
4110 Importer.FromDiag(From->getLocation(),
4111 diag::note_odr_objc_missing_superclass);
4114 if (shouldForceImportDeclContext(Kind))
4115 ImportDeclContext(From);
4119 // Start the definition.
4120 To->startDefinition();
4122 // If this class has a superclass, import it.
4123 if (From->getSuperClass()) {
4124 TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
4128 To->setSuperClass(SuperTInfo);
4132 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4133 SmallVector<SourceLocation, 4> ProtocolLocs;
4134 ObjCInterfaceDecl::protocol_loc_iterator
4135 FromProtoLoc = From->protocol_loc_begin();
4137 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4138 FromProtoEnd = From->protocol_end();
4139 FromProto != FromProtoEnd;
4140 ++FromProto, ++FromProtoLoc) {
4141 ObjCProtocolDecl *ToProto
4142 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
4145 Protocols.push_back(ToProto);
4146 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
4149 // FIXME: If we're merging, make sure that the protocol list is the same.
4150 To->setProtocolList(Protocols.data(), Protocols.size(),
4151 ProtocolLocs.data(), Importer.getToContext());
4153 // Import categories. When the categories themselves are imported, they'll
4154 // hook themselves into this interface.
4155 for (auto *Cat : From->known_categories())
4156 Importer.Import(Cat);
4158 // If we have an @implementation, import it as well.
4159 if (From->getImplementation()) {
4160 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
4161 Importer.Import(From->getImplementation()));
4165 To->setImplementation(Impl);
4168 if (shouldForceImportDeclContext(Kind)) {
4169 // Import all of the members of this class.
4170 ImportDeclContext(From, /*ForceImport=*/true);
4176 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4180 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4181 for (auto fromTypeParam : *list) {
4182 auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
4183 Importer.Import(fromTypeParam));
4187 toTypeParams.push_back(toTypeParam);
4190 return ObjCTypeParamList::create(Importer.getToContext(),
4191 Importer.Import(list->getLAngleLoc()),
4193 Importer.Import(list->getRAngleLoc()));
4196 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
4197 // If this class has a definition in the translation unit we're coming from,
4198 // but this particular declaration is not that definition, import the
4199 // definition and map to that.
4200 ObjCInterfaceDecl *Definition = D->getDefinition();
4201 if (Definition && Definition != D) {
4202 Decl *ImportedDef = Importer.Import(Definition);
4206 return Importer.Imported(D, ImportedDef);
4209 // Import the major distinguishing characteristics of an @interface.
4210 DeclContext *DC, *LexicalDC;
4211 DeclarationName Name;
4214 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4219 // Look for an existing interface with the same name.
4220 ObjCInterfaceDecl *MergeWithIface = nullptr;
4221 SmallVector<NamedDecl *, 2> FoundDecls;
4222 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4223 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4224 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4227 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
4231 // Create an interface declaration, if one does not already exist.
4232 ObjCInterfaceDecl *ToIface = MergeWithIface;
4234 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
4235 Importer.Import(D->getAtStartLoc()),
4236 Name.getAsIdentifierInfo(),
4237 /*TypeParamList=*/nullptr,
4238 /*PrevDecl=*/nullptr, Loc,
4239 D->isImplicitInterfaceDecl());
4240 ToIface->setLexicalDeclContext(LexicalDC);
4241 LexicalDC->addDeclInternal(ToIface);
4243 Importer.Imported(D, ToIface);
4244 // Import the type parameter list after calling Imported, to avoid
4245 // loops when bringing in their DeclContext.
4246 ToIface->setTypeParamList(ImportObjCTypeParamList(
4247 D->getTypeParamListAsWritten()));
4249 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
4255 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4256 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
4257 Importer.Import(D->getCategoryDecl()));
4261 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4263 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4267 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
4268 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
4269 Importer.Import(D->getIdentifier()),
4270 Category->getClassInterface(),
4271 Importer.Import(D->getLocation()),
4272 Importer.Import(D->getAtStartLoc()),
4275 DeclContext *LexicalDC = DC;
4276 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4277 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4281 ToImpl->setLexicalDeclContext(LexicalDC);
4284 LexicalDC->addDeclInternal(ToImpl);
4285 Category->setImplementation(ToImpl);
4288 Importer.Imported(D, ToImpl);
4289 ImportDeclContext(D);
4293 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4294 // Find the corresponding interface.
4295 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
4296 Importer.Import(D->getClassInterface()));
4300 // Import the superclass, if any.
4301 ObjCInterfaceDecl *Super = nullptr;
4302 if (D->getSuperClass()) {
4303 Super = cast_or_null<ObjCInterfaceDecl>(
4304 Importer.Import(D->getSuperClass()));
4309 ObjCImplementationDecl *Impl = Iface->getImplementation();
4311 // We haven't imported an implementation yet. Create a new @implementation
4313 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
4314 Importer.ImportContext(D->getDeclContext()),
4316 Importer.Import(D->getLocation()),
4317 Importer.Import(D->getAtStartLoc()),
4318 Importer.Import(D->getSuperClassLoc()),
4319 Importer.Import(D->getIvarLBraceLoc()),
4320 Importer.Import(D->getIvarRBraceLoc()));
4322 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4323 DeclContext *LexicalDC
4324 = Importer.ImportContext(D->getLexicalDeclContext());
4327 Impl->setLexicalDeclContext(LexicalDC);
4330 // Associate the implementation with the class it implements.
4331 Iface->setImplementation(Impl);
4332 Importer.Imported(D, Iface->getImplementation());
4334 Importer.Imported(D, Iface->getImplementation());
4336 // Verify that the existing @implementation has the same superclass.
4337 if ((Super && !Impl->getSuperClass()) ||
4338 (!Super && Impl->getSuperClass()) ||
4339 (Super && Impl->getSuperClass() &&
4340 !declaresSameEntity(Super->getCanonicalDecl(),
4341 Impl->getSuperClass()))) {
4342 Importer.ToDiag(Impl->getLocation(),
4343 diag::err_odr_objc_superclass_inconsistent)
4344 << Iface->getDeclName();
4345 // FIXME: It would be nice to have the location of the superclass
4347 if (Impl->getSuperClass())
4348 Importer.ToDiag(Impl->getLocation(),
4349 diag::note_odr_objc_superclass)
4350 << Impl->getSuperClass()->getDeclName();
4352 Importer.ToDiag(Impl->getLocation(),
4353 diag::note_odr_objc_missing_superclass);
4354 if (D->getSuperClass())
4355 Importer.FromDiag(D->getLocation(),
4356 diag::note_odr_objc_superclass)
4357 << D->getSuperClass()->getDeclName();
4359 Importer.FromDiag(D->getLocation(),
4360 diag::note_odr_objc_missing_superclass);
4365 // Import all of the members of this @implementation.
4366 ImportDeclContext(D);
4371 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
4372 // Import the major distinguishing characteristics of an @property.
4373 DeclContext *DC, *LexicalDC;
4374 DeclarationName Name;
4377 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4382 // Check whether we have already imported this property.
4383 SmallVector<NamedDecl *, 2> FoundDecls;
4384 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4385 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4386 if (ObjCPropertyDecl *FoundProp
4387 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
4388 // Check property types.
4389 if (!Importer.IsStructurallyEquivalent(D->getType(),
4390 FoundProp->getType())) {
4391 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
4392 << Name << D->getType() << FoundProp->getType();
4393 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4394 << FoundProp->getType();
4398 // FIXME: Check property attributes, getters, setters, etc.?
4400 // Consider these properties to be equivalent.
4401 Importer.Imported(D, FoundProp);
4407 TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4411 // Create the new property.
4412 ObjCPropertyDecl *ToProperty
4413 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
4414 Name.getAsIdentifierInfo(),
4415 Importer.Import(D->getAtLoc()),
4416 Importer.Import(D->getLParenLoc()),
4417 Importer.Import(D->getType()),
4419 D->getPropertyImplementation());
4420 Importer.Imported(D, ToProperty);
4421 ToProperty->setLexicalDeclContext(LexicalDC);
4422 LexicalDC->addDeclInternal(ToProperty);
4424 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4425 ToProperty->setPropertyAttributesAsWritten(
4426 D->getPropertyAttributesAsWritten());
4427 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
4428 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
4429 ToProperty->setGetterMethodDecl(
4430 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4431 ToProperty->setSetterMethodDecl(
4432 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4433 ToProperty->setPropertyIvarDecl(
4434 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4438 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4439 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
4440 Importer.Import(D->getPropertyDecl()));
4444 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4448 // Import the lexical declaration context.
4449 DeclContext *LexicalDC = DC;
4450 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4451 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4456 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4460 // Import the ivar (for an @synthesize).
4461 ObjCIvarDecl *Ivar = nullptr;
4462 if (D->getPropertyIvarDecl()) {
4463 Ivar = cast_or_null<ObjCIvarDecl>(
4464 Importer.Import(D->getPropertyIvarDecl()));
4469 ObjCPropertyImplDecl *ToImpl
4470 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4471 Property->getQueryKind());
4473 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
4474 Importer.Import(D->getLocStart()),
4475 Importer.Import(D->getLocation()),
4477 D->getPropertyImplementation(),
4479 Importer.Import(D->getPropertyIvarDeclLoc()));
4480 ToImpl->setLexicalDeclContext(LexicalDC);
4481 Importer.Imported(D, ToImpl);
4482 LexicalDC->addDeclInternal(ToImpl);
4484 // Check that we have the same kind of property implementation (@synthesize
4486 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4487 Importer.ToDiag(ToImpl->getLocation(),
4488 diag::err_odr_objc_property_impl_kind_inconsistent)
4489 << Property->getDeclName()
4490 << (ToImpl->getPropertyImplementation()
4491 == ObjCPropertyImplDecl::Dynamic);
4492 Importer.FromDiag(D->getLocation(),
4493 diag::note_odr_objc_property_impl_kind)
4494 << D->getPropertyDecl()->getDeclName()
4495 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4499 // For @synthesize, check that we have the same
4500 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4501 Ivar != ToImpl->getPropertyIvarDecl()) {
4502 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4503 diag::err_odr_objc_synthesize_ivar_inconsistent)
4504 << Property->getDeclName()
4505 << ToImpl->getPropertyIvarDecl()->getDeclName()
4506 << Ivar->getDeclName();
4507 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4508 diag::note_odr_objc_synthesize_ivar_here)
4509 << D->getPropertyIvarDecl()->getDeclName();
4513 // Merge the existing implementation with the new implementation.
4514 Importer.Imported(D, ToImpl);
4520 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4521 // For template arguments, we adopt the translation unit as our declaration
4522 // context. This context will be fixed when the actual template declaration
4525 // FIXME: Import default argument.
4526 return TemplateTypeParmDecl::Create(Importer.getToContext(),
4527 Importer.getToContext().getTranslationUnitDecl(),
4528 Importer.Import(D->getLocStart()),
4529 Importer.Import(D->getLocation()),
4532 Importer.Import(D->getIdentifier()),
4533 D->wasDeclaredWithTypename(),
4534 D->isParameterPack());
4538 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4539 // Import the name of this declaration.
4540 DeclarationName Name = Importer.Import(D->getDeclName());
4541 if (D->getDeclName() && !Name)
4544 // Import the location of this declaration.
4545 SourceLocation Loc = Importer.Import(D->getLocation());
4547 // Import the type of this declaration.
4548 QualType T = Importer.Import(D->getType());
4552 // Import type-source information.
4553 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4554 if (D->getTypeSourceInfo() && !TInfo)
4557 // FIXME: Import default argument.
4559 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4560 Importer.getToContext().getTranslationUnitDecl(),
4561 Importer.Import(D->getInnerLocStart()),
4562 Loc, D->getDepth(), D->getPosition(),
4563 Name.getAsIdentifierInfo(),
4564 T, D->isParameterPack(), TInfo);
4568 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4569 // Import the name of this declaration.
4570 DeclarationName Name = Importer.Import(D->getDeclName());
4571 if (D->getDeclName() && !Name)
4574 // Import the location of this declaration.
4575 SourceLocation Loc = Importer.Import(D->getLocation());
4577 // Import template parameters.
4578 TemplateParameterList *TemplateParams
4579 = ImportTemplateParameterList(D->getTemplateParameters());
4580 if (!TemplateParams)
4583 // FIXME: Import default argument.
4585 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
4586 Importer.getToContext().getTranslationUnitDecl(),
4587 Loc, D->getDepth(), D->getPosition(),
4588 D->isParameterPack(),
4589 Name.getAsIdentifierInfo(),
4593 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4594 // If this record has a definition in the translation unit we're coming from,
4595 // but this particular declaration is not that definition, import the
4596 // definition and map to that.
4597 CXXRecordDecl *Definition
4598 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4599 if (Definition && Definition != D->getTemplatedDecl()) {
4601 = Importer.Import(Definition->getDescribedClassTemplate());
4605 return Importer.Imported(D, ImportedDef);
4608 // Import the major distinguishing characteristics of this class template.
4609 DeclContext *DC, *LexicalDC;
4610 DeclarationName Name;
4613 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4618 // We may already have a template of the same name; try to find and match it.
4619 if (!DC->isFunctionOrMethod()) {
4620 SmallVector<NamedDecl *, 4> ConflictingDecls;
4621 SmallVector<NamedDecl *, 2> FoundDecls;
4622 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4623 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4624 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4627 Decl *Found = FoundDecls[I];
4628 if (ClassTemplateDecl *FoundTemplate
4629 = dyn_cast<ClassTemplateDecl>(Found)) {
4630 if (IsStructuralMatch(D, FoundTemplate)) {
4631 // The class templates structurally match; call it the same template.
4632 // FIXME: We may be filling in a forward declaration here. Handle
4634 Importer.Imported(D->getTemplatedDecl(),
4635 FoundTemplate->getTemplatedDecl());
4636 return Importer.Imported(D, FoundTemplate);
4640 ConflictingDecls.push_back(FoundDecls[I]);
4643 if (!ConflictingDecls.empty()) {
4644 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4645 ConflictingDecls.data(),
4646 ConflictingDecls.size());
4653 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4655 // Create the declaration that is being templated.
4656 // Create the declaration that is being templated.
4657 CXXRecordDecl *D2Templated = cast_or_null<CXXRecordDecl>(
4658 Importer.Import(DTemplated));
4662 // Resolve possible cyclic import.
4663 if (Decl *AlreadyImported = Importer.GetAlreadyImportedOrNull(D))
4664 return AlreadyImported;
4666 // Create the class template declaration itself.
4667 TemplateParameterList *TemplateParams
4668 = ImportTemplateParameterList(D->getTemplateParameters());
4669 if (!TemplateParams)
4672 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4673 Loc, Name, TemplateParams,
4675 D2Templated->setDescribedClassTemplate(D2);
4677 D2->setAccess(D->getAccess());
4678 D2->setLexicalDeclContext(LexicalDC);
4679 LexicalDC->addDeclInternal(D2);
4681 // Note the relationship between the class templates.
4682 Importer.Imported(D, D2);
4683 Importer.Imported(DTemplated, D2Templated);
4685 if (DTemplated->isCompleteDefinition() &&
4686 !D2Templated->isCompleteDefinition()) {
4687 // FIXME: Import definition!
4693 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4694 ClassTemplateSpecializationDecl *D) {
4695 // If this record has a definition in the translation unit we're coming from,
4696 // but this particular declaration is not that definition, import the
4697 // definition and map to that.
4698 TagDecl *Definition = D->getDefinition();
4699 if (Definition && Definition != D) {
4700 Decl *ImportedDef = Importer.Import(Definition);
4704 return Importer.Imported(D, ImportedDef);
4707 ClassTemplateDecl *ClassTemplate
4708 = cast_or_null<ClassTemplateDecl>(Importer.Import(
4709 D->getSpecializedTemplate()));
4713 // Import the context of this declaration.
4714 DeclContext *DC = ClassTemplate->getDeclContext();
4718 DeclContext *LexicalDC = DC;
4719 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4720 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4725 // Import the location of this declaration.
4726 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4727 SourceLocation IdLoc = Importer.Import(D->getLocation());
4729 // Import template arguments.
4730 SmallVector<TemplateArgument, 2> TemplateArgs;
4731 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4732 D->getTemplateArgs().size(),
4736 // Try to find an existing specialization with these template arguments.
4737 void *InsertPos = nullptr;
4738 ClassTemplateSpecializationDecl *D2
4739 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4741 // We already have a class template specialization with these template
4744 // FIXME: Check for specialization vs. instantiation errors.
4746 if (RecordDecl *FoundDef = D2->getDefinition()) {
4747 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4748 // The record types structurally match, or the "from" translation
4749 // unit only had a forward declaration anyway; call it the same
4751 return Importer.Imported(D, FoundDef);
4755 // Create a new specialization.
4756 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4757 D->getTagKind(), DC,
4761 /*PrevDecl=*/nullptr);
4762 D2->setSpecializationKind(D->getSpecializationKind());
4764 // Add this specialization to the class template.
4765 ClassTemplate->AddSpecialization(D2, InsertPos);
4767 // Import the qualifier, if any.
4768 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4770 // Add the specialization to this context.
4771 D2->setLexicalDeclContext(LexicalDC);
4772 LexicalDC->addDeclInternal(D2);
4774 Importer.Imported(D, D2);
4776 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4782 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4783 // If this variable has a definition in the translation unit we're coming
4785 // but this particular declaration is not that definition, import the
4786 // definition and map to that.
4787 VarDecl *Definition =
4788 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4789 if (Definition && Definition != D->getTemplatedDecl()) {
4790 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4794 return Importer.Imported(D, ImportedDef);
4797 // Import the major distinguishing characteristics of this variable template.
4798 DeclContext *DC, *LexicalDC;
4799 DeclarationName Name;
4802 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4807 // We may already have a template of the same name; try to find and match it.
4808 assert(!DC->isFunctionOrMethod() &&
4809 "Variable templates cannot be declared at function scope");
4810 SmallVector<NamedDecl *, 4> ConflictingDecls;
4811 SmallVector<NamedDecl *, 2> FoundDecls;
4812 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4813 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4814 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4817 Decl *Found = FoundDecls[I];
4818 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4819 if (IsStructuralMatch(D, FoundTemplate)) {
4820 // The variable templates structurally match; call it the same template.
4821 Importer.Imported(D->getTemplatedDecl(),
4822 FoundTemplate->getTemplatedDecl());
4823 return Importer.Imported(D, FoundTemplate);
4827 ConflictingDecls.push_back(FoundDecls[I]);
4830 if (!ConflictingDecls.empty()) {
4831 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4832 ConflictingDecls.data(),
4833 ConflictingDecls.size());
4839 VarDecl *DTemplated = D->getTemplatedDecl();
4842 QualType T = Importer.Import(DTemplated->getType());
4846 // Create the declaration that is being templated.
4847 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4848 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4849 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4850 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4851 IdLoc, Name.getAsIdentifierInfo(), T,
4852 TInfo, DTemplated->getStorageClass());
4853 D2Templated->setAccess(DTemplated->getAccess());
4854 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4855 D2Templated->setLexicalDeclContext(LexicalDC);
4857 // Importer.Imported(DTemplated, D2Templated);
4858 // LexicalDC->addDeclInternal(D2Templated);
4860 // Merge the initializer.
4861 if (ImportDefinition(DTemplated, D2Templated))
4864 // Create the variable template declaration itself.
4865 TemplateParameterList *TemplateParams =
4866 ImportTemplateParameterList(D->getTemplateParameters());
4867 if (!TemplateParams)
4870 VarTemplateDecl *D2 = VarTemplateDecl::Create(
4871 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4872 D2Templated->setDescribedVarTemplate(D2);
4874 D2->setAccess(D->getAccess());
4875 D2->setLexicalDeclContext(LexicalDC);
4876 LexicalDC->addDeclInternal(D2);
4878 // Note the relationship between the variable templates.
4879 Importer.Imported(D, D2);
4880 Importer.Imported(DTemplated, D2Templated);
4882 if (DTemplated->isThisDeclarationADefinition() &&
4883 !D2Templated->isThisDeclarationADefinition()) {
4884 // FIXME: Import definition!
4890 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4891 VarTemplateSpecializationDecl *D) {
4892 // If this record has a definition in the translation unit we're coming from,
4893 // but this particular declaration is not that definition, import the
4894 // definition and map to that.
4895 VarDecl *Definition = D->getDefinition();
4896 if (Definition && Definition != D) {
4897 Decl *ImportedDef = Importer.Import(Definition);
4901 return Importer.Imported(D, ImportedDef);
4904 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4905 Importer.Import(D->getSpecializedTemplate()));
4909 // Import the context of this declaration.
4910 DeclContext *DC = VarTemplate->getDeclContext();
4914 DeclContext *LexicalDC = DC;
4915 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4916 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4921 // Import the location of this declaration.
4922 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4923 SourceLocation IdLoc = Importer.Import(D->getLocation());
4925 // Import template arguments.
4926 SmallVector<TemplateArgument, 2> TemplateArgs;
4927 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4928 D->getTemplateArgs().size(), TemplateArgs))
4931 // Try to find an existing specialization with these template arguments.
4932 void *InsertPos = nullptr;
4933 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4934 TemplateArgs, InsertPos);
4936 // We already have a variable template specialization with these template
4939 // FIXME: Check for specialization vs. instantiation errors.
4941 if (VarDecl *FoundDef = D2->getDefinition()) {
4942 if (!D->isThisDeclarationADefinition() ||
4943 IsStructuralMatch(D, FoundDef)) {
4944 // The record types structurally match, or the "from" translation
4945 // unit only had a forward declaration anyway; call it the same
4947 return Importer.Imported(D, FoundDef);
4953 QualType T = Importer.Import(D->getType());
4956 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4958 // Create a new specialization.
4959 D2 = VarTemplateSpecializationDecl::Create(
4960 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4961 D->getStorageClass(), TemplateArgs);
4962 D2->setSpecializationKind(D->getSpecializationKind());
4963 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4965 // Add this specialization to the class template.
4966 VarTemplate->AddSpecialization(D2, InsertPos);
4968 // Import the qualifier, if any.
4969 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4971 // Add the specialization to this context.
4972 D2->setLexicalDeclContext(LexicalDC);
4973 LexicalDC->addDeclInternal(D2);
4975 Importer.Imported(D, D2);
4977 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4983 //----------------------------------------------------------------------------
4984 // Import Statements
4985 //----------------------------------------------------------------------------
4987 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4989 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4990 size_t NumDecls = DG.end() - DG.begin();
4991 SmallVector<Decl *, 1> ToDecls(NumDecls);
4992 auto &_Importer = this->Importer;
4993 std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4994 [&_Importer](Decl *D) -> Decl * {
4995 return _Importer.Import(D);
4997 return DeclGroupRef::Create(Importer.getToContext(),
5002 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
5003 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
5004 << S->getStmtClassName();
5009 Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
5010 SmallVector<IdentifierInfo *, 4> Names;
5011 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5012 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5015 Names.push_back(ToII);
5017 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5018 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5021 Names.push_back(ToII);
5024 SmallVector<StringLiteral *, 4> Clobbers;
5025 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5026 StringLiteral *Clobber = cast_or_null<StringLiteral>(
5027 Importer.Import(S->getClobberStringLiteral(I)));
5030 Clobbers.push_back(Clobber);
5033 SmallVector<StringLiteral *, 4> Constraints;
5034 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5035 StringLiteral *Output = cast_or_null<StringLiteral>(
5036 Importer.Import(S->getOutputConstraintLiteral(I)));
5039 Constraints.push_back(Output);
5042 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5043 StringLiteral *Input = cast_or_null<StringLiteral>(
5044 Importer.Import(S->getInputConstraintLiteral(I)));
5047 Constraints.push_back(Input);
5050 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs());
5051 if (ImportContainerChecked(S->outputs(), Exprs))
5054 if (ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
5057 StringLiteral *AsmStr = cast_or_null<StringLiteral>(
5058 Importer.Import(S->getAsmString()));
5062 return new (Importer.getToContext()) GCCAsmStmt(
5063 Importer.getToContext(),
5064 Importer.Import(S->getAsmLoc()),
5073 S->getNumClobbers(),
5075 Importer.Import(S->getRParenLoc()));
5078 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
5079 DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
5080 for (Decl *ToD : ToDG) {
5084 SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
5085 SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
5086 return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
5089 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
5090 SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
5091 return new (Importer.getToContext()) NullStmt(ToSemiLoc,
5092 S->hasLeadingEmptyMacro());
5095 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
5096 llvm::SmallVector<Stmt *, 8> ToStmts(S->size());
5098 if (ImportContainerChecked(S->body(), ToStmts))
5101 SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
5102 SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
5103 return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
5105 ToLBraceLoc, ToRBraceLoc);
5108 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
5109 Expr *ToLHS = Importer.Import(S->getLHS());
5112 Expr *ToRHS = Importer.Import(S->getRHS());
5113 if (!ToRHS && S->getRHS())
5115 SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
5116 SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
5117 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5118 return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
5119 ToCaseLoc, ToEllipsisLoc,
5123 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
5124 SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
5125 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5126 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5127 if (!ToSubStmt && S->getSubStmt())
5129 return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
5133 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
5134 SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
5135 LabelDecl *ToLabelDecl =
5136 cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
5137 if (!ToLabelDecl && S->getDecl())
5139 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5140 if (!ToSubStmt && S->getSubStmt())
5142 return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
5146 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
5147 SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
5148 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
5149 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
5150 ASTContext &_ToContext = Importer.getToContext();
5151 std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
5152 [&_ToContext](const Attr *A) -> const Attr * {
5153 return A->clone(_ToContext);
5155 for (const Attr *ToA : ToAttrs) {
5159 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5160 if (!ToSubStmt && S->getSubStmt())
5162 return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
5163 ToAttrs, ToSubStmt);
5166 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
5167 SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
5168 Stmt *ToInit = Importer.Import(S->getInit());
5169 if (!ToInit && S->getInit())
5171 VarDecl *ToConditionVariable = nullptr;
5172 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5173 ToConditionVariable =
5174 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5175 if (!ToConditionVariable)
5178 Expr *ToCondition = Importer.Import(S->getCond());
5179 if (!ToCondition && S->getCond())
5181 Stmt *ToThenStmt = Importer.Import(S->getThen());
5182 if (!ToThenStmt && S->getThen())
5184 SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
5185 Stmt *ToElseStmt = Importer.Import(S->getElse());
5186 if (!ToElseStmt && S->getElse())
5188 return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
5189 ToIfLoc, S->isConstexpr(),
5191 ToConditionVariable,
5192 ToCondition, ToThenStmt,
5193 ToElseLoc, ToElseStmt);
5196 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
5197 Stmt *ToInit = Importer.Import(S->getInit());
5198 if (!ToInit && S->getInit())
5200 VarDecl *ToConditionVariable = nullptr;
5201 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5202 ToConditionVariable =
5203 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5204 if (!ToConditionVariable)
5207 Expr *ToCondition = Importer.Import(S->getCond());
5208 if (!ToCondition && S->getCond())
5210 SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
5211 Importer.getToContext(), ToInit,
5212 ToConditionVariable, ToCondition);
5213 Stmt *ToBody = Importer.Import(S->getBody());
5214 if (!ToBody && S->getBody())
5216 ToStmt->setBody(ToBody);
5217 ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
5218 // Now we have to re-chain the cases.
5219 SwitchCase *LastChainedSwitchCase = nullptr;
5220 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5221 SC = SC->getNextSwitchCase()) {
5222 SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
5225 if (LastChainedSwitchCase)
5226 LastChainedSwitchCase->setNextSwitchCase(ToSC);
5228 ToStmt->setSwitchCaseList(ToSC);
5229 LastChainedSwitchCase = ToSC;
5234 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
5235 VarDecl *ToConditionVariable = nullptr;
5236 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5237 ToConditionVariable =
5238 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5239 if (!ToConditionVariable)
5242 Expr *ToCondition = Importer.Import(S->getCond());
5243 if (!ToCondition && S->getCond())
5245 Stmt *ToBody = Importer.Import(S->getBody());
5246 if (!ToBody && S->getBody())
5248 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5249 return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
5250 ToConditionVariable,
5251 ToCondition, ToBody,
5255 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
5256 Stmt *ToBody = Importer.Import(S->getBody());
5257 if (!ToBody && S->getBody())
5259 Expr *ToCondition = Importer.Import(S->getCond());
5260 if (!ToCondition && S->getCond())
5262 SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
5263 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5264 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5265 return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
5266 ToDoLoc, ToWhileLoc,
5270 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
5271 Stmt *ToInit = Importer.Import(S->getInit());
5272 if (!ToInit && S->getInit())
5274 Expr *ToCondition = Importer.Import(S->getCond());
5275 if (!ToCondition && S->getCond())
5277 VarDecl *ToConditionVariable = nullptr;
5278 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5279 ToConditionVariable =
5280 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5281 if (!ToConditionVariable)
5284 Expr *ToInc = Importer.Import(S->getInc());
5285 if (!ToInc && S->getInc())
5287 Stmt *ToBody = Importer.Import(S->getBody());
5288 if (!ToBody && S->getBody())
5290 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5291 SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
5292 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5293 return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
5294 ToInit, ToCondition,
5295 ToConditionVariable,
5297 ToForLoc, ToLParenLoc,
5301 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
5302 LabelDecl *ToLabel = nullptr;
5303 if (LabelDecl *FromLabel = S->getLabel()) {
5304 ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
5308 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5309 SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
5310 return new (Importer.getToContext()) GotoStmt(ToLabel,
5311 ToGotoLoc, ToLabelLoc);
5314 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
5315 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5316 SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
5317 Expr *ToTarget = Importer.Import(S->getTarget());
5318 if (!ToTarget && S->getTarget())
5320 return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
5324 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
5325 SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
5326 return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
5329 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
5330 SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
5331 return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
5334 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
5335 SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
5336 Expr *ToRetExpr = Importer.Import(S->getRetValue());
5337 if (!ToRetExpr && S->getRetValue())
5339 VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
5340 VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
5341 if (!ToNRVOCandidate && NRVOCandidate)
5343 return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
5347 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
5348 SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
5349 VarDecl *ToExceptionDecl = nullptr;
5350 if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
5352 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5353 if (!ToExceptionDecl)
5356 Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
5357 if (!ToHandlerBlock && S->getHandlerBlock())
5359 return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
5364 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
5365 SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
5366 Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
5367 if (!ToTryBlock && S->getTryBlock())
5369 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5370 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5371 CXXCatchStmt *FromHandler = S->getHandler(HI);
5372 if (Stmt *ToHandler = Importer.Import(FromHandler))
5373 ToHandlers[HI] = ToHandler;
5377 return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
5381 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
5383 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
5384 if (!ToRange && S->getRangeStmt())
5387 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
5388 if (!ToBegin && S->getBeginStmt())
5391 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
5392 if (!ToEnd && S->getEndStmt())
5394 Expr *ToCond = Importer.Import(S->getCond());
5395 if (!ToCond && S->getCond())
5397 Expr *ToInc = Importer.Import(S->getInc());
5398 if (!ToInc && S->getInc())
5400 DeclStmt *ToLoopVar =
5401 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
5402 if (!ToLoopVar && S->getLoopVarStmt())
5404 Stmt *ToBody = Importer.Import(S->getBody());
5405 if (!ToBody && S->getBody())
5407 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5408 SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
5409 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5410 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5411 return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBegin, ToEnd,
5414 ToForLoc, ToCoawaitLoc,
5415 ToColonLoc, ToRParenLoc);
5418 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
5419 Stmt *ToElem = Importer.Import(S->getElement());
5420 if (!ToElem && S->getElement())
5422 Expr *ToCollect = Importer.Import(S->getCollection());
5423 if (!ToCollect && S->getCollection())
5425 Stmt *ToBody = Importer.Import(S->getBody());
5426 if (!ToBody && S->getBody())
5428 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5429 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5430 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
5436 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5437 SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
5438 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5439 VarDecl *ToExceptionDecl = nullptr;
5440 if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
5442 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5443 if (!ToExceptionDecl)
5446 Stmt *ToBody = Importer.Import(S->getCatchBody());
5447 if (!ToBody && S->getCatchBody())
5449 return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
5455 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5456 SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
5457 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
5458 if (!ToAtFinallyStmt && S->getFinallyBody())
5460 return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
5464 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
5465 SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
5466 Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
5467 if (!ToAtTryStmt && S->getTryBody())
5469 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
5470 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
5471 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
5472 if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
5473 ToCatchStmts[CI] = ToCatchStmt;
5477 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
5478 if (!ToAtFinallyStmt && S->getFinallyStmt())
5480 return ObjCAtTryStmt::Create(Importer.getToContext(),
5481 ToAtTryLoc, ToAtTryStmt,
5482 ToCatchStmts.begin(), ToCatchStmts.size(),
5486 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5487 (ObjCAtSynchronizedStmt *S) {
5488 SourceLocation ToAtSynchronizedLoc =
5489 Importer.Import(S->getAtSynchronizedLoc());
5490 Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5491 if (!ToSynchExpr && S->getSynchExpr())
5493 Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5494 if (!ToSynchBody && S->getSynchBody())
5496 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5497 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5500 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5501 SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5502 Expr *ToThrow = Importer.Import(S->getThrowExpr());
5503 if (!ToThrow && S->getThrowExpr())
5505 return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5508 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5509 (ObjCAutoreleasePoolStmt *S) {
5510 SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5511 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5512 if (!ToSubStmt && S->getSubStmt())
5514 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5518 //----------------------------------------------------------------------------
5519 // Import Expressions
5520 //----------------------------------------------------------------------------
5521 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5522 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5523 << E->getStmtClassName();
5527 Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
5528 QualType T = Importer.Import(E->getType());
5532 Expr *SubExpr = Importer.Import(E->getSubExpr());
5533 if (!SubExpr && E->getSubExpr())
5536 TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
5540 return new (Importer.getToContext()) VAArgExpr(
5541 Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
5542 Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
5546 Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
5547 QualType T = Importer.Import(E->getType());
5551 return new (Importer.getToContext()) GNUNullExpr(
5552 T, Importer.Import(E->getLocStart()));
5555 Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
5556 QualType T = Importer.Import(E->getType());
5560 StringLiteral *SL = cast_or_null<StringLiteral>(
5561 Importer.Import(E->getFunctionName()));
5562 if (!SL && E->getFunctionName())
5565 return new (Importer.getToContext()) PredefinedExpr(
5566 Importer.Import(E->getLocStart()), T, E->getIdentType(), SL);
5569 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5570 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5574 NamedDecl *FoundD = nullptr;
5575 if (E->getDecl() != E->getFoundDecl()) {
5576 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5581 QualType T = Importer.Import(E->getType());
5586 TemplateArgumentListInfo ToTAInfo;
5587 TemplateArgumentListInfo *ResInfo = nullptr;
5588 if (E->hasExplicitTemplateArgs()) {
5589 for (const auto &FromLoc : E->template_arguments()) {
5591 TemplateArgumentLoc ToTALoc = ImportTemplateArgumentLoc(FromLoc, Error);
5594 ToTAInfo.addArgument(ToTALoc);
5596 ResInfo = &ToTAInfo;
5599 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5600 Importer.Import(E->getQualifierLoc()),
5601 Importer.Import(E->getTemplateKeywordLoc()),
5603 E->refersToEnclosingVariableOrCapture(),
5604 Importer.Import(E->getLocation()),
5605 T, E->getValueKind(),
5607 if (E->hadMultipleCandidates())
5608 DRE->setHadMultipleCandidates(true);
5612 Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5613 QualType T = Importer.Import(E->getType());
5617 return new (Importer.getToContext()) ImplicitValueInitExpr(T);
5620 ASTNodeImporter::Designator
5621 ASTNodeImporter::ImportDesignator(const Designator &D) {
5622 if (D.isFieldDesignator()) {
5623 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
5624 // Caller checks for import error
5625 return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
5626 Importer.Import(D.getFieldLoc()));
5628 if (D.isArrayDesignator())
5629 return Designator(D.getFirstExprIndex(),
5630 Importer.Import(D.getLBracketLoc()),
5631 Importer.Import(D.getRBracketLoc()));
5633 assert(D.isArrayRangeDesignator());
5634 return Designator(D.getFirstExprIndex(),
5635 Importer.Import(D.getLBracketLoc()),
5636 Importer.Import(D.getEllipsisLoc()),
5637 Importer.Import(D.getRBracketLoc()));
5641 Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
5642 Expr *Init = cast_or_null<Expr>(Importer.Import(DIE->getInit()));
5646 SmallVector<Expr *, 4> IndexExprs(DIE->getNumSubExprs() - 1);
5647 // List elements from the second, the first is Init itself
5648 for (unsigned I = 1, E = DIE->getNumSubExprs(); I < E; I++) {
5649 if (Expr *Arg = cast_or_null<Expr>(Importer.Import(DIE->getSubExpr(I))))
5650 IndexExprs[I - 1] = Arg;
5655 SmallVector<Designator, 4> Designators(DIE->size());
5656 llvm::transform(DIE->designators(), Designators.begin(),
5657 [this](const Designator &D) -> Designator {
5658 return ImportDesignator(D);
5661 for (const Designator &D : DIE->designators())
5662 if (D.isFieldDesignator() && !D.getFieldName())
5665 return DesignatedInitExpr::Create(
5666 Importer.getToContext(), Designators,
5667 IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()),
5668 DIE->usesGNUSyntax(), Init);
5671 Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
5672 QualType T = Importer.Import(E->getType());
5676 return new (Importer.getToContext())
5677 CXXNullPtrLiteralExpr(T, Importer.Import(E->getLocation()));
5680 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5681 QualType T = Importer.Import(E->getType());
5685 return IntegerLiteral::Create(Importer.getToContext(),
5687 Importer.Import(E->getLocation()));
5690 Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
5691 QualType T = Importer.Import(E->getType());
5695 return FloatingLiteral::Create(Importer.getToContext(),
5696 E->getValue(), E->isExact(), T,
5697 Importer.Import(E->getLocation()));
5700 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5701 QualType T = Importer.Import(E->getType());
5705 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5707 Importer.Import(E->getLocation()));
5710 Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
5711 QualType T = Importer.Import(E->getType());
5715 SmallVector<SourceLocation, 4> Locations(E->getNumConcatenated());
5716 ImportArray(E->tokloc_begin(), E->tokloc_end(), Locations.begin());
5718 return StringLiteral::Create(Importer.getToContext(), E->getBytes(),
5719 E->getKind(), E->isPascal(), T,
5720 Locations.data(), Locations.size());
5723 Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
5724 QualType T = Importer.Import(E->getType());
5728 TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo());
5732 Expr *Init = Importer.Import(E->getInitializer());
5736 return new (Importer.getToContext()) CompoundLiteralExpr(
5737 Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(),
5738 Init, E->isFileScope());
5741 Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
5742 QualType T = Importer.Import(E->getType());
5746 SmallVector<Expr *, 6> Exprs(E->getNumSubExprs());
5747 if (ImportArrayChecked(
5748 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
5752 return new (Importer.getToContext()) AtomicExpr(
5753 Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(),
5754 Importer.Import(E->getRParenLoc()));
5757 Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
5758 QualType T = Importer.Import(E->getType());
5762 LabelDecl *ToLabel = cast_or_null<LabelDecl>(Importer.Import(E->getLabel()));
5766 return new (Importer.getToContext()) AddrLabelExpr(
5767 Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()),
5771 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5772 Expr *SubExpr = Importer.Import(E->getSubExpr());
5776 return new (Importer.getToContext())
5777 ParenExpr(Importer.Import(E->getLParen()),
5778 Importer.Import(E->getRParen()),
5782 Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
5783 SmallVector<Expr *, 4> Exprs(E->getNumExprs());
5784 if (ImportContainerChecked(E->exprs(), Exprs))
5787 return new (Importer.getToContext()) ParenListExpr(
5788 Importer.getToContext(), Importer.Import(E->getLParenLoc()),
5789 Exprs, Importer.Import(E->getLParenLoc()));
5792 Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
5793 QualType T = Importer.Import(E->getType());
5797 CompoundStmt *ToSubStmt = cast_or_null<CompoundStmt>(
5798 Importer.Import(E->getSubStmt()));
5799 if (!ToSubStmt && E->getSubStmt())
5802 return new (Importer.getToContext()) StmtExpr(ToSubStmt, T,
5803 Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc()));
5806 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5807 QualType T = Importer.Import(E->getType());
5811 Expr *SubExpr = Importer.Import(E->getSubExpr());
5815 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5816 T, E->getValueKind(),
5818 Importer.Import(E->getOperatorLoc()));
5821 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5822 UnaryExprOrTypeTraitExpr *E) {
5823 QualType ResultType = Importer.Import(E->getType());
5825 if (E->isArgumentType()) {
5826 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5830 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5832 Importer.Import(E->getOperatorLoc()),
5833 Importer.Import(E->getRParenLoc()));
5836 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5840 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5841 SubExpr, ResultType,
5842 Importer.Import(E->getOperatorLoc()),
5843 Importer.Import(E->getRParenLoc()));
5846 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5847 QualType T = Importer.Import(E->getType());
5851 Expr *LHS = Importer.Import(E->getLHS());
5855 Expr *RHS = Importer.Import(E->getRHS());
5859 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5860 T, E->getValueKind(),
5862 Importer.Import(E->getOperatorLoc()),
5863 E->isFPContractable());
5866 Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
5867 QualType T = Importer.Import(E->getType());
5871 Expr *ToLHS = Importer.Import(E->getLHS());
5875 Expr *ToRHS = Importer.Import(E->getRHS());
5879 Expr *ToCond = Importer.Import(E->getCond());
5883 return new (Importer.getToContext()) ConditionalOperator(
5884 ToCond, Importer.Import(E->getQuestionLoc()),
5885 ToLHS, Importer.Import(E->getColonLoc()),
5886 ToRHS, T, E->getValueKind(), E->getObjectKind());
5889 Expr *ASTNodeImporter::VisitBinaryConditionalOperator(
5890 BinaryConditionalOperator *E) {
5891 QualType T = Importer.Import(E->getType());
5895 Expr *Common = Importer.Import(E->getCommon());
5899 Expr *Cond = Importer.Import(E->getCond());
5903 OpaqueValueExpr *OpaqueValue = cast_or_null<OpaqueValueExpr>(
5904 Importer.Import(E->getOpaqueValue()));
5908 Expr *TrueExpr = Importer.Import(E->getTrueExpr());
5912 Expr *FalseExpr = Importer.Import(E->getFalseExpr());
5916 return new (Importer.getToContext()) BinaryConditionalOperator(
5917 Common, OpaqueValue, Cond, TrueExpr, FalseExpr,
5918 Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()),
5919 T, E->getValueKind(), E->getObjectKind());
5922 Expr *ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
5923 QualType T = Importer.Import(E->getType());
5927 TypeSourceInfo *ToQueried = Importer.Import(E->getQueriedTypeSourceInfo());
5931 Expr *Dim = Importer.Import(E->getDimensionExpression());
5932 if (!Dim && E->getDimensionExpression())
5935 return new (Importer.getToContext()) ArrayTypeTraitExpr(
5936 Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
5937 E->getValue(), Dim, Importer.Import(E->getLocEnd()), T);
5940 Expr *ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
5941 QualType T = Importer.Import(E->getType());
5945 Expr *ToQueried = Importer.Import(E->getQueriedExpression());
5949 return new (Importer.getToContext()) ExpressionTraitExpr(
5950 Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
5951 E->getValue(), Importer.Import(E->getLocEnd()), T);
5954 Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
5955 QualType T = Importer.Import(E->getType());
5959 Expr *SourceExpr = Importer.Import(E->getSourceExpr());
5960 if (!SourceExpr && E->getSourceExpr())
5963 return new (Importer.getToContext()) OpaqueValueExpr(
5964 Importer.Import(E->getLocation()), T, E->getValueKind(),
5965 E->getObjectKind(), SourceExpr);
5968 Expr *ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
5969 QualType T = Importer.Import(E->getType());
5973 Expr *ToLHS = Importer.Import(E->getLHS());
5977 Expr *ToRHS = Importer.Import(E->getRHS());
5981 return new (Importer.getToContext()) ArraySubscriptExpr(
5982 ToLHS, ToRHS, T, E->getValueKind(), E->getObjectKind(),
5983 Importer.Import(E->getRBracketLoc()));
5986 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5987 QualType T = Importer.Import(E->getType());
5991 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5992 if (CompLHSType.isNull())
5995 QualType CompResultType = Importer.Import(E->getComputationResultType());
5996 if (CompResultType.isNull())
5999 Expr *LHS = Importer.Import(E->getLHS());
6003 Expr *RHS = Importer.Import(E->getRHS());
6007 return new (Importer.getToContext())
6008 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
6009 T, E->getValueKind(),
6011 CompLHSType, CompResultType,
6012 Importer.Import(E->getOperatorLoc()),
6013 E->isFPContractable());
6016 bool ASTNodeImporter::ImportCastPath(CastExpr *CE, CXXCastPath &Path) {
6017 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
6018 if (CXXBaseSpecifier *Spec = Importer.Import(*I))
6019 Path.push_back(Spec);
6026 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
6027 QualType T = Importer.Import(E->getType());
6031 Expr *SubExpr = Importer.Import(E->getSubExpr());
6035 CXXCastPath BasePath;
6036 if (ImportCastPath(E, BasePath))
6039 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
6040 SubExpr, &BasePath, E->getValueKind());
6043 Expr *ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
6044 QualType T = Importer.Import(E->getType());
6048 Expr *SubExpr = Importer.Import(E->getSubExpr());
6052 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
6053 if (!TInfo && E->getTypeInfoAsWritten())
6056 CXXCastPath BasePath;
6057 if (ImportCastPath(E, BasePath))
6060 switch (E->getStmtClass()) {
6061 case Stmt::CStyleCastExprClass: {
6062 CStyleCastExpr *CCE = cast<CStyleCastExpr>(E);
6063 return CStyleCastExpr::Create(Importer.getToContext(), T,
6064 E->getValueKind(), E->getCastKind(),
6065 SubExpr, &BasePath, TInfo,
6066 Importer.Import(CCE->getLParenLoc()),
6067 Importer.Import(CCE->getRParenLoc()));
6070 case Stmt::CXXFunctionalCastExprClass: {
6071 CXXFunctionalCastExpr *FCE = cast<CXXFunctionalCastExpr>(E);
6072 return CXXFunctionalCastExpr::Create(Importer.getToContext(), T,
6073 E->getValueKind(), TInfo,
6074 E->getCastKind(), SubExpr, &BasePath,
6075 Importer.Import(FCE->getLParenLoc()),
6076 Importer.Import(FCE->getRParenLoc()));
6079 case Stmt::ObjCBridgedCastExprClass: {
6080 ObjCBridgedCastExpr *OCE = cast<ObjCBridgedCastExpr>(E);
6081 return new (Importer.getToContext()) ObjCBridgedCastExpr(
6082 Importer.Import(OCE->getLParenLoc()), OCE->getBridgeKind(),
6083 E->getCastKind(), Importer.Import(OCE->getBridgeKeywordLoc()),
6087 break; // just fall through
6090 CXXNamedCastExpr *Named = cast<CXXNamedCastExpr>(E);
6091 SourceLocation ExprLoc = Importer.Import(Named->getOperatorLoc()),
6092 RParenLoc = Importer.Import(Named->getRParenLoc());
6093 SourceRange Brackets = Importer.Import(Named->getAngleBrackets());
6095 switch (E->getStmtClass()) {
6096 case Stmt::CXXStaticCastExprClass:
6097 return CXXStaticCastExpr::Create(Importer.getToContext(), T,
6098 E->getValueKind(), E->getCastKind(),
6099 SubExpr, &BasePath, TInfo,
6100 ExprLoc, RParenLoc, Brackets);
6102 case Stmt::CXXDynamicCastExprClass:
6103 return CXXDynamicCastExpr::Create(Importer.getToContext(), T,
6104 E->getValueKind(), E->getCastKind(),
6105 SubExpr, &BasePath, TInfo,
6106 ExprLoc, RParenLoc, Brackets);
6108 case Stmt::CXXReinterpretCastExprClass:
6109 return CXXReinterpretCastExpr::Create(Importer.getToContext(), T,
6110 E->getValueKind(), E->getCastKind(),
6111 SubExpr, &BasePath, TInfo,
6112 ExprLoc, RParenLoc, Brackets);
6114 case Stmt::CXXConstCastExprClass:
6115 return CXXConstCastExpr::Create(Importer.getToContext(), T,
6116 E->getValueKind(), SubExpr, TInfo, ExprLoc,
6117 RParenLoc, Brackets);
6119 llvm_unreachable("Cast expression of unsupported type!");
6124 Expr *ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *OE) {
6125 QualType T = Importer.Import(OE->getType());
6129 SmallVector<OffsetOfNode, 4> Nodes;
6130 for (int I = 0, E = OE->getNumComponents(); I < E; ++I) {
6131 const OffsetOfNode &Node = OE->getComponent(I);
6133 switch (Node.getKind()) {
6134 case OffsetOfNode::Array:
6135 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()),
6136 Node.getArrayExprIndex(),
6137 Importer.Import(Node.getLocEnd())));
6140 case OffsetOfNode::Base: {
6141 CXXBaseSpecifier *BS = Importer.Import(Node.getBase());
6142 if (!BS && Node.getBase())
6144 Nodes.push_back(OffsetOfNode(BS));
6147 case OffsetOfNode::Field: {
6148 FieldDecl *FD = cast_or_null<FieldDecl>(Importer.Import(Node.getField()));
6151 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), FD,
6152 Importer.Import(Node.getLocEnd())));
6155 case OffsetOfNode::Identifier: {
6156 IdentifierInfo *ToII = Importer.Import(Node.getFieldName());
6159 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), ToII,
6160 Importer.Import(Node.getLocEnd())));
6166 SmallVector<Expr *, 4> Exprs(OE->getNumExpressions());
6167 for (int I = 0, E = OE->getNumExpressions(); I < E; ++I) {
6168 Expr *ToIndexExpr = Importer.Import(OE->getIndexExpr(I));
6171 Exprs[I] = ToIndexExpr;
6174 TypeSourceInfo *TInfo = Importer.Import(OE->getTypeSourceInfo());
6175 if (!TInfo && OE->getTypeSourceInfo())
6178 return OffsetOfExpr::Create(Importer.getToContext(), T,
6179 Importer.Import(OE->getOperatorLoc()),
6180 TInfo, Nodes, Exprs,
6181 Importer.Import(OE->getRParenLoc()));
6184 Expr *ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
6185 QualType T = Importer.Import(E->getType());
6189 Expr *Operand = Importer.Import(E->getOperand());
6193 CanThrowResult CanThrow;
6194 if (E->isValueDependent())
6195 CanThrow = CT_Dependent;
6197 CanThrow = E->getValue() ? CT_Can : CT_Cannot;
6199 return new (Importer.getToContext()) CXXNoexceptExpr(
6200 T, Operand, CanThrow,
6201 Importer.Import(E->getLocStart()), Importer.Import(E->getLocEnd()));
6204 Expr *ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
6205 QualType T = Importer.Import(E->getType());
6209 Expr *SubExpr = Importer.Import(E->getSubExpr());
6210 if (!SubExpr && E->getSubExpr())
6213 return new (Importer.getToContext()) CXXThrowExpr(
6214 SubExpr, T, Importer.Import(E->getThrowLoc()),
6215 E->isThrownVariableInScope());
6218 Expr *ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6219 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
6220 Importer.Import(E->getParam()));
6224 return CXXDefaultArgExpr::Create(
6225 Importer.getToContext(), Importer.Import(E->getUsedLocation()), Param);
6228 Expr *ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
6229 QualType T = Importer.Import(E->getType());
6233 TypeSourceInfo *TypeInfo = Importer.Import(E->getTypeSourceInfo());
6237 return new (Importer.getToContext()) CXXScalarValueInitExpr(
6238 T, TypeInfo, Importer.Import(E->getRParenLoc()));
6241 Expr *ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
6242 Expr *SubExpr = Importer.Import(E->getSubExpr());
6246 auto *Dtor = cast_or_null<CXXDestructorDecl>(
6247 Importer.Import(const_cast<CXXDestructorDecl *>(
6248 E->getTemporary()->getDestructor())));
6252 ASTContext &ToCtx = Importer.getToContext();
6253 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, Dtor);
6254 return CXXBindTemporaryExpr::Create(ToCtx, Temp, SubExpr);
6257 Expr *ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE) {
6258 QualType T = Importer.Import(CE->getType());
6262 SmallVector<Expr *, 8> Args(CE->getNumArgs());
6263 if (ImportContainerChecked(CE->arguments(), Args))
6266 auto *Ctor = cast_or_null<CXXConstructorDecl>(
6267 Importer.Import(CE->getConstructor()));
6271 return CXXTemporaryObjectExpr::Create(
6272 Importer.getToContext(), T,
6273 Importer.Import(CE->getLocStart()),
6277 CE->hadMultipleCandidates(),
6278 CE->isListInitialization(),
6279 CE->isStdInitListInitialization(),
6280 CE->requiresZeroInitialization(),
6281 CE->getConstructionKind(),
6282 Importer.Import(CE->getParenOrBraceRange()));
6286 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
6287 QualType T = Importer.Import(E->getType());
6291 Expr *TempE = Importer.Import(E->GetTemporaryExpr());
6295 ValueDecl *ExtendedBy = cast_or_null<ValueDecl>(
6296 Importer.Import(const_cast<ValueDecl *>(E->getExtendingDecl())));
6297 if (!ExtendedBy && E->getExtendingDecl())
6300 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
6301 T, TempE, E->isBoundToLvalueReference());
6303 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
6304 ToMTE->setExtendingDecl(ExtendedBy, E->getManglingNumber());
6308 Expr *ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *CE) {
6309 QualType T = Importer.Import(CE->getType());
6313 SmallVector<Expr *, 4> PlacementArgs(CE->getNumPlacementArgs());
6314 if (ImportContainerChecked(CE->placement_arguments(), PlacementArgs))
6317 FunctionDecl *OperatorNewDecl = cast_or_null<FunctionDecl>(
6318 Importer.Import(CE->getOperatorNew()));
6319 if (!OperatorNewDecl && CE->getOperatorNew())
6322 FunctionDecl *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
6323 Importer.Import(CE->getOperatorDelete()));
6324 if (!OperatorDeleteDecl && CE->getOperatorDelete())
6327 Expr *ToInit = Importer.Import(CE->getInitializer());
6328 if (!ToInit && CE->getInitializer())
6331 TypeSourceInfo *TInfo = Importer.Import(CE->getAllocatedTypeSourceInfo());
6335 Expr *ToArrSize = Importer.Import(CE->getArraySize());
6336 if (!ToArrSize && CE->getArraySize())
6339 return new (Importer.getToContext()) CXXNewExpr(
6340 Importer.getToContext(),
6342 OperatorNewDecl, OperatorDeleteDecl,
6343 CE->passAlignment(),
6344 CE->doesUsualArrayDeleteWantSize(),
6346 Importer.Import(CE->getTypeIdParens()),
6347 ToArrSize, CE->getInitializationStyle(), ToInit, T, TInfo,
6348 Importer.Import(CE->getSourceRange()),
6349 Importer.Import(CE->getDirectInitRange()));
6352 Expr *ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
6353 QualType T = Importer.Import(E->getType());
6357 FunctionDecl *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
6358 Importer.Import(E->getOperatorDelete()));
6359 if (!OperatorDeleteDecl && E->getOperatorDelete())
6362 Expr *ToArg = Importer.Import(E->getArgument());
6363 if (!ToArg && E->getArgument())
6366 return new (Importer.getToContext()) CXXDeleteExpr(
6367 T, E->isGlobalDelete(),
6369 E->isArrayFormAsWritten(),
6370 E->doesUsualArrayDeleteWantSize(),
6373 Importer.Import(E->getLocStart()));
6376 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
6377 QualType T = Importer.Import(E->getType());
6381 CXXConstructorDecl *ToCCD =
6382 dyn_cast_or_null<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
6386 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
6387 if (ImportContainerChecked(E->arguments(), ToArgs))
6390 return CXXConstructExpr::Create(Importer.getToContext(), T,
6391 Importer.Import(E->getLocation()),
6392 ToCCD, E->isElidable(),
6393 ToArgs, E->hadMultipleCandidates(),
6394 E->isListInitialization(),
6395 E->isStdInitListInitialization(),
6396 E->requiresZeroInitialization(),
6397 E->getConstructionKind(),
6398 Importer.Import(E->getParenOrBraceRange()));
6401 Expr *ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *EWC) {
6402 Expr *SubExpr = Importer.Import(EWC->getSubExpr());
6403 if (!SubExpr && EWC->getSubExpr())
6406 SmallVector<ExprWithCleanups::CleanupObject, 8> Objs(EWC->getNumObjects());
6407 for (unsigned I = 0, E = EWC->getNumObjects(); I < E; I++)
6408 if (ExprWithCleanups::CleanupObject Obj =
6409 cast_or_null<BlockDecl>(Importer.Import(EWC->getObject(I))))
6414 return ExprWithCleanups::Create(Importer.getToContext(),
6415 SubExpr, EWC->cleanupsHaveSideEffects(),
6419 Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
6420 QualType T = Importer.Import(E->getType());
6424 Expr *ToFn = Importer.Import(E->getCallee());
6428 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
6429 if (ImportContainerChecked(E->arguments(), ToArgs))
6432 return new (Importer.getToContext()) CXXMemberCallExpr(
6433 Importer.getToContext(), ToFn, ToArgs, T, E->getValueKind(),
6434 Importer.Import(E->getRParenLoc()));
6437 Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
6438 QualType T = Importer.Import(E->getType());
6442 return new (Importer.getToContext())
6443 CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit());
6446 Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
6447 QualType T = Importer.Import(E->getType());
6451 return new (Importer.getToContext())
6452 CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation()));
6456 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
6457 QualType T = Importer.Import(E->getType());
6461 Expr *ToBase = Importer.Import(E->getBase());
6462 if (!ToBase && E->getBase())
6465 ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
6466 if (!ToMember && E->getMemberDecl())
6469 DeclAccessPair ToFoundDecl = DeclAccessPair::make(
6470 dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
6471 E->getFoundDecl().getAccess());
6473 DeclarationNameInfo ToMemberNameInfo(
6474 Importer.Import(E->getMemberNameInfo().getName()),
6475 Importer.Import(E->getMemberNameInfo().getLoc()));
6477 if (E->hasExplicitTemplateArgs()) {
6478 return nullptr; // FIXME: handle template arguments
6481 return MemberExpr::Create(Importer.getToContext(), ToBase,
6483 Importer.Import(E->getOperatorLoc()),
6484 Importer.Import(E->getQualifierLoc()),
6485 Importer.Import(E->getTemplateKeywordLoc()),
6486 ToMember, ToFoundDecl, ToMemberNameInfo,
6487 nullptr, T, E->getValueKind(),
6488 E->getObjectKind());
6491 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
6492 QualType T = Importer.Import(E->getType());
6496 Expr *ToCallee = Importer.Import(E->getCallee());
6497 if (!ToCallee && E->getCallee())
6500 unsigned NumArgs = E->getNumArgs();
6502 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
6504 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
6505 Expr *FromArg = E->getArg(ai);
6506 Expr *ToArg = Importer.Import(FromArg);
6512 Expr **ToArgs_Copied = new (Importer.getToContext())
6515 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
6516 ToArgs_Copied[ai] = ToArgs[ai];
6518 return new (Importer.getToContext())
6519 CallExpr(Importer.getToContext(), ToCallee,
6520 llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
6521 Importer.Import(E->getRParenLoc()));
6524 Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) {
6525 QualType T = Importer.Import(ILE->getType());
6529 llvm::SmallVector<Expr *, 4> Exprs(ILE->getNumInits());
6530 if (ImportContainerChecked(ILE->inits(), Exprs))
6533 ASTContext &ToCtx = Importer.getToContext();
6534 InitListExpr *To = new (ToCtx) InitListExpr(
6535 ToCtx, Importer.Import(ILE->getLBraceLoc()),
6536 Exprs, Importer.Import(ILE->getLBraceLoc()));
6539 if (ILE->hasArrayFiller()) {
6540 Expr *Filler = Importer.Import(ILE->getArrayFiller());
6543 To->setArrayFiller(Filler);
6546 if (FieldDecl *FromFD = ILE->getInitializedFieldInUnion()) {
6547 FieldDecl *ToFD = cast_or_null<FieldDecl>(Importer.Import(FromFD));
6550 To->setInitializedFieldInUnion(ToFD);
6553 if (InitListExpr *SyntForm = ILE->getSyntacticForm()) {
6554 InitListExpr *ToSyntForm = cast_or_null<InitListExpr>(
6555 Importer.Import(SyntForm));
6558 To->setSyntacticForm(ToSyntForm);
6561 To->sawArrayRangeDesignator(ILE->hadArrayRangeDesignator());
6562 To->setValueDependent(ILE->isValueDependent());
6563 To->setInstantiationDependent(ILE->isInstantiationDependent());
6568 Expr *ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
6569 QualType ToType = Importer.Import(E->getType());
6570 if (ToType.isNull())
6573 Expr *ToCommon = Importer.Import(E->getCommonExpr());
6574 if (!ToCommon && E->getCommonExpr())
6577 Expr *ToSubExpr = Importer.Import(E->getSubExpr());
6578 if (!ToSubExpr && E->getSubExpr())
6581 return new (Importer.getToContext())
6582 ArrayInitLoopExpr(ToType, ToCommon, ToSubExpr);
6585 Expr *ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
6586 QualType ToType = Importer.Import(E->getType());
6587 if (ToType.isNull())
6589 return new (Importer.getToContext()) ArrayInitIndexExpr(ToType);
6592 Expr *ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
6593 FieldDecl *ToField = llvm::dyn_cast_or_null<FieldDecl>(
6594 Importer.Import(DIE->getField()));
6595 if (!ToField && DIE->getField())
6598 return CXXDefaultInitExpr::Create(
6599 Importer.getToContext(), Importer.Import(DIE->getLocStart()), ToField);
6602 Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
6603 QualType ToType = Importer.Import(E->getType());
6604 if (ToType.isNull() && !E->getType().isNull())
6606 ExprValueKind VK = E->getValueKind();
6607 CastKind CK = E->getCastKind();
6608 Expr *ToOp = Importer.Import(E->getSubExpr());
6609 if (!ToOp && E->getSubExpr())
6611 CXXCastPath BasePath;
6612 if (ImportCastPath(E, BasePath))
6614 TypeSourceInfo *ToWritten = Importer.Import(E->getTypeInfoAsWritten());
6615 SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc());
6616 SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc());
6617 SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets());
6619 if (isa<CXXStaticCastExpr>(E)) {
6620 return CXXStaticCastExpr::Create(
6621 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6622 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6623 } else if (isa<CXXDynamicCastExpr>(E)) {
6624 return CXXDynamicCastExpr::Create(
6625 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6626 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6627 } else if (isa<CXXReinterpretCastExpr>(E)) {
6628 return CXXReinterpretCastExpr::Create(
6629 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6630 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6636 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
6637 ASTContext &FromContext, FileManager &FromFileManager,
6639 : ToContext(ToContext), FromContext(FromContext),
6640 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
6641 Minimal(MinimalImport), LastDiagFromFrom(false)
6643 ImportedDecls[FromContext.getTranslationUnitDecl()]
6644 = ToContext.getTranslationUnitDecl();
6647 ASTImporter::~ASTImporter() { }
6649 QualType ASTImporter::Import(QualType FromT) {
6653 const Type *fromTy = FromT.getTypePtr();
6655 // Check whether we've already imported this type.
6656 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6657 = ImportedTypes.find(fromTy);
6658 if (Pos != ImportedTypes.end())
6659 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
6662 ASTNodeImporter Importer(*this);
6663 QualType ToT = Importer.Visit(fromTy);
6667 // Record the imported type.
6668 ImportedTypes[fromTy] = ToT.getTypePtr();
6670 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
6673 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
6677 // FIXME: For now we just create a "trivial" type source info based
6678 // on the type and a single location. Implement a real version of this.
6679 QualType T = Import(FromTSI->getType());
6683 return ToContext.getTrivialTypeSourceInfo(T,
6684 Import(FromTSI->getTypeLoc().getLocStart()));
6687 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
6688 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6689 if (Pos != ImportedDecls.end()) {
6690 Decl *ToD = Pos->second;
6691 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
6698 Decl *ASTImporter::Import(Decl *FromD) {
6702 ASTNodeImporter Importer(*this);
6704 // Check whether we've already imported this declaration.
6705 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6706 if (Pos != ImportedDecls.end()) {
6707 Decl *ToD = Pos->second;
6708 Importer.ImportDefinitionIfNeeded(FromD, ToD);
6713 Decl *ToD = Importer.Visit(FromD);
6717 // Record the imported declaration.
6718 ImportedDecls[FromD] = ToD;
6720 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
6721 // Keep track of anonymous tags that have an associated typedef.
6722 if (FromTag->getTypedefNameForAnonDecl())
6723 AnonTagsWithPendingTypedefs.push_back(FromTag);
6724 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
6725 // When we've finished transforming a typedef, see whether it was the
6726 // typedef for an anonymous tag.
6727 for (SmallVectorImpl<TagDecl *>::iterator
6728 FromTag = AnonTagsWithPendingTypedefs.begin(),
6729 FromTagEnd = AnonTagsWithPendingTypedefs.end();
6730 FromTag != FromTagEnd; ++FromTag) {
6731 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
6732 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
6733 // We found the typedef for an anonymous tag; link them.
6734 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
6735 AnonTagsWithPendingTypedefs.erase(FromTag);
6745 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
6749 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
6753 // When we're using a record/enum/Objective-C class/protocol as a context, we
6754 // need it to have a definition.
6755 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
6756 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
6757 if (ToRecord->isCompleteDefinition()) {
6759 } else if (FromRecord->isCompleteDefinition()) {
6760 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
6761 ASTNodeImporter::IDK_Basic);
6763 CompleteDecl(ToRecord);
6765 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
6766 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
6767 if (ToEnum->isCompleteDefinition()) {
6769 } else if (FromEnum->isCompleteDefinition()) {
6770 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
6771 ASTNodeImporter::IDK_Basic);
6773 CompleteDecl(ToEnum);
6775 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
6776 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
6777 if (ToClass->getDefinition()) {
6779 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
6780 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
6781 ASTNodeImporter::IDK_Basic);
6783 CompleteDecl(ToClass);
6785 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
6786 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
6787 if (ToProto->getDefinition()) {
6789 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
6790 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
6791 ASTNodeImporter::IDK_Basic);
6793 CompleteDecl(ToProto);
6800 Expr *ASTImporter::Import(Expr *FromE) {
6804 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
6807 Stmt *ASTImporter::Import(Stmt *FromS) {
6811 // Check whether we've already imported this declaration.
6812 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
6813 if (Pos != ImportedStmts.end())
6817 ASTNodeImporter Importer(*this);
6818 Stmt *ToS = Importer.Visit(FromS);
6822 // Record the imported declaration.
6823 ImportedStmts[FromS] = ToS;
6827 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
6831 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
6833 switch (FromNNS->getKind()) {
6834 case NestedNameSpecifier::Identifier:
6835 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
6836 return NestedNameSpecifier::Create(ToContext, prefix, II);
6840 case NestedNameSpecifier::Namespace:
6841 if (NamespaceDecl *NS =
6842 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
6843 return NestedNameSpecifier::Create(ToContext, prefix, NS);
6847 case NestedNameSpecifier::NamespaceAlias:
6848 if (NamespaceAliasDecl *NSAD =
6849 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
6850 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
6854 case NestedNameSpecifier::Global:
6855 return NestedNameSpecifier::GlobalSpecifier(ToContext);
6857 case NestedNameSpecifier::Super:
6858 if (CXXRecordDecl *RD =
6859 cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
6860 return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
6864 case NestedNameSpecifier::TypeSpec:
6865 case NestedNameSpecifier::TypeSpecWithTemplate: {
6866 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
6868 bool bTemplate = FromNNS->getKind() ==
6869 NestedNameSpecifier::TypeSpecWithTemplate;
6870 return NestedNameSpecifier::Create(ToContext, prefix,
6871 bTemplate, T.getTypePtr());
6877 llvm_unreachable("Invalid nested name specifier kind");
6880 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
6881 // FIXME: Implement!
6882 return NestedNameSpecifierLoc();
6885 TemplateName ASTImporter::Import(TemplateName From) {
6886 switch (From.getKind()) {
6887 case TemplateName::Template:
6888 if (TemplateDecl *ToTemplate
6889 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6890 return TemplateName(ToTemplate);
6892 return TemplateName();
6894 case TemplateName::OverloadedTemplate: {
6895 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
6896 UnresolvedSet<2> ToTemplates;
6897 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
6898 E = FromStorage->end();
6900 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
6901 ToTemplates.addDecl(To);
6903 return TemplateName();
6905 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
6909 case TemplateName::QualifiedTemplate: {
6910 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
6911 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
6913 return TemplateName();
6915 if (TemplateDecl *ToTemplate
6916 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6917 return ToContext.getQualifiedTemplateName(Qualifier,
6918 QTN->hasTemplateKeyword(),
6921 return TemplateName();
6924 case TemplateName::DependentTemplate: {
6925 DependentTemplateName *DTN = From.getAsDependentTemplateName();
6926 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
6928 return TemplateName();
6930 if (DTN->isIdentifier()) {
6931 return ToContext.getDependentTemplateName(Qualifier,
6932 Import(DTN->getIdentifier()));
6935 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
6938 case TemplateName::SubstTemplateTemplateParm: {
6939 SubstTemplateTemplateParmStorage *subst
6940 = From.getAsSubstTemplateTemplateParm();
6941 TemplateTemplateParmDecl *param
6942 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
6944 return TemplateName();
6946 TemplateName replacement = Import(subst->getReplacement());
6947 if (replacement.isNull()) return TemplateName();
6949 return ToContext.getSubstTemplateTemplateParm(param, replacement);
6952 case TemplateName::SubstTemplateTemplateParmPack: {
6953 SubstTemplateTemplateParmPackStorage *SubstPack
6954 = From.getAsSubstTemplateTemplateParmPack();
6955 TemplateTemplateParmDecl *Param
6956 = cast_or_null<TemplateTemplateParmDecl>(
6957 Import(SubstPack->getParameterPack()));
6959 return TemplateName();
6961 ASTNodeImporter Importer(*this);
6962 TemplateArgument ArgPack
6963 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
6964 if (ArgPack.isNull())
6965 return TemplateName();
6967 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
6971 llvm_unreachable("Invalid template name kind");
6974 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
6975 if (FromLoc.isInvalid())
6976 return SourceLocation();
6978 SourceManager &FromSM = FromContext.getSourceManager();
6980 // For now, map everything down to its file location, so that we
6981 // don't have to import macro expansions.
6982 // FIXME: Import macro expansions!
6983 FromLoc = FromSM.getFileLoc(FromLoc);
6984 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
6985 SourceManager &ToSM = ToContext.getSourceManager();
6986 FileID ToFileID = Import(Decomposed.first);
6987 if (ToFileID.isInvalid())
6988 return SourceLocation();
6989 SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
6990 .getLocWithOffset(Decomposed.second);
6994 SourceRange ASTImporter::Import(SourceRange FromRange) {
6995 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
6998 FileID ASTImporter::Import(FileID FromID) {
6999 llvm::DenseMap<FileID, FileID>::iterator Pos
7000 = ImportedFileIDs.find(FromID);
7001 if (Pos != ImportedFileIDs.end())
7004 SourceManager &FromSM = FromContext.getSourceManager();
7005 SourceManager &ToSM = ToContext.getSourceManager();
7006 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
7007 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
7009 // Include location of this file.
7010 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
7012 // Map the FileID for to the "to" source manager.
7014 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
7015 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
7016 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
7018 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
7019 // than mmap the files several times.
7020 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
7023 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
7024 FromSLoc.getFile().getFileCharacteristic());
7026 // FIXME: We want to re-use the existing MemoryBuffer!
7027 const llvm::MemoryBuffer *
7028 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
7029 std::unique_ptr<llvm::MemoryBuffer> ToBuf
7030 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
7031 FromBuf->getBufferIdentifier());
7032 ToID = ToSM.createFileID(std::move(ToBuf),
7033 FromSLoc.getFile().getFileCharacteristic());
7037 ImportedFileIDs[FromID] = ToID;
7041 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
7042 Expr *ToExpr = Import(From->getInit());
7043 if (!ToExpr && From->getInit())
7046 if (From->isBaseInitializer()) {
7047 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
7048 if (!ToTInfo && From->getTypeSourceInfo())
7051 return new (ToContext) CXXCtorInitializer(
7052 ToContext, ToTInfo, From->isBaseVirtual(), Import(From->getLParenLoc()),
7053 ToExpr, Import(From->getRParenLoc()),
7054 From->isPackExpansion() ? Import(From->getEllipsisLoc())
7055 : SourceLocation());
7056 } else if (From->isMemberInitializer()) {
7057 FieldDecl *ToField =
7058 llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
7059 if (!ToField && From->getMember())
7062 return new (ToContext) CXXCtorInitializer(
7063 ToContext, ToField, Import(From->getMemberLocation()),
7064 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
7065 } else if (From->isIndirectMemberInitializer()) {
7066 IndirectFieldDecl *ToIField = llvm::cast_or_null<IndirectFieldDecl>(
7067 Import(From->getIndirectMember()));
7068 if (!ToIField && From->getIndirectMember())
7071 return new (ToContext) CXXCtorInitializer(
7072 ToContext, ToIField, Import(From->getMemberLocation()),
7073 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
7074 } else if (From->isDelegatingInitializer()) {
7075 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
7076 if (!ToTInfo && From->getTypeSourceInfo())
7079 return new (ToContext)
7080 CXXCtorInitializer(ToContext, ToTInfo, Import(From->getLParenLoc()),
7081 ToExpr, Import(From->getRParenLoc()));
7088 CXXBaseSpecifier *ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
7089 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
7090 if (Pos != ImportedCXXBaseSpecifiers.end())
7093 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
7094 Import(BaseSpec->getSourceRange()),
7095 BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
7096 BaseSpec->getAccessSpecifierAsWritten(),
7097 Import(BaseSpec->getTypeSourceInfo()),
7098 Import(BaseSpec->getEllipsisLoc()));
7099 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
7103 void ASTImporter::ImportDefinition(Decl *From) {
7104 Decl *To = Import(From);
7108 if (DeclContext *FromDC = cast<DeclContext>(From)) {
7109 ASTNodeImporter Importer(*this);
7111 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
7112 if (!ToRecord->getDefinition()) {
7113 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
7114 ASTNodeImporter::IDK_Everything);
7119 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
7120 if (!ToEnum->getDefinition()) {
7121 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
7122 ASTNodeImporter::IDK_Everything);
7127 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
7128 if (!ToIFace->getDefinition()) {
7129 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
7130 ASTNodeImporter::IDK_Everything);
7135 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
7136 if (!ToProto->getDefinition()) {
7137 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
7138 ASTNodeImporter::IDK_Everything);
7143 Importer.ImportDeclContext(FromDC, true);
7147 DeclarationName ASTImporter::Import(DeclarationName FromName) {
7149 return DeclarationName();
7151 switch (FromName.getNameKind()) {
7152 case DeclarationName::Identifier:
7153 return Import(FromName.getAsIdentifierInfo());
7155 case DeclarationName::ObjCZeroArgSelector:
7156 case DeclarationName::ObjCOneArgSelector:
7157 case DeclarationName::ObjCMultiArgSelector:
7158 return Import(FromName.getObjCSelector());
7160 case DeclarationName::CXXConstructorName: {
7161 QualType T = Import(FromName.getCXXNameType());
7163 return DeclarationName();
7165 return ToContext.DeclarationNames.getCXXConstructorName(
7166 ToContext.getCanonicalType(T));
7169 case DeclarationName::CXXDestructorName: {
7170 QualType T = Import(FromName.getCXXNameType());
7172 return DeclarationName();
7174 return ToContext.DeclarationNames.getCXXDestructorName(
7175 ToContext.getCanonicalType(T));
7178 case DeclarationName::CXXConversionFunctionName: {
7179 QualType T = Import(FromName.getCXXNameType());
7181 return DeclarationName();
7183 return ToContext.DeclarationNames.getCXXConversionFunctionName(
7184 ToContext.getCanonicalType(T));
7187 case DeclarationName::CXXOperatorName:
7188 return ToContext.DeclarationNames.getCXXOperatorName(
7189 FromName.getCXXOverloadedOperator());
7191 case DeclarationName::CXXLiteralOperatorName:
7192 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
7193 Import(FromName.getCXXLiteralIdentifier()));
7195 case DeclarationName::CXXUsingDirective:
7197 return DeclarationName::getUsingDirectiveName();
7200 llvm_unreachable("Invalid DeclarationName Kind!");
7203 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
7207 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
7209 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
7210 ToId->setBuiltinID(FromId->getBuiltinID());
7215 Selector ASTImporter::Import(Selector FromSel) {
7216 if (FromSel.isNull())
7219 SmallVector<IdentifierInfo *, 4> Idents;
7220 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
7221 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
7222 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
7223 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
7226 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
7230 unsigned NumDecls) {
7234 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
7235 if (LastDiagFromFrom)
7236 ToContext.getDiagnostics().notePriorDiagnosticFrom(
7237 FromContext.getDiagnostics());
7238 LastDiagFromFrom = false;
7239 return ToContext.getDiagnostics().Report(Loc, DiagID);
7242 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
7243 if (!LastDiagFromFrom)
7244 FromContext.getDiagnostics().notePriorDiagnosticFrom(
7245 ToContext.getDiagnostics());
7246 LastDiagFromFrom = true;
7247 return FromContext.getDiagnostics().Report(Loc, DiagID);
7250 void ASTImporter::CompleteDecl (Decl *D) {
7251 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
7252 if (!ID->getDefinition())
7253 ID->startDefinition();
7255 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
7256 if (!PD->getDefinition())
7257 PD->startDefinition();
7259 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7260 if (!TD->getDefinition() && !TD->isBeingDefined()) {
7261 TD->startDefinition();
7262 TD->setCompleteDefinition(true);
7266 assert (0 && "CompleteDecl called on a Decl that can't be completed");
7270 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
7271 if (From->hasAttrs()) {
7272 for (Attr *FromAttr : From->getAttrs())
7273 To->addAttr(FromAttr->clone(To->getASTContext()));
7275 if (From->isUsed()) {
7278 if (From->isImplicit()) {
7281 ImportedDecls[From] = To;
7285 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
7287 llvm::DenseMap<const Type *, const Type *>::iterator Pos
7288 = ImportedTypes.find(From.getTypePtr());
7289 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
7292 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
7294 return Ctx.IsStructurallyEquivalent(From, To);