1 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTImporter class which imports AST nodes from one
11 // context into another context.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTDiagnostic.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/FileManager.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include <deque>
27
28 namespace clang {
29 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
30 public DeclVisitor<ASTNodeImporter, Decl *>,
31 public StmtVisitor<ASTNodeImporter, Stmt *> {
32 ASTImporter &Importer;
33
34 public:
ASTNodeImporter(ASTImporter & Importer)35 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
36
37 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
38 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
39 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
40
41 // Importing types
42 QualType VisitType(const Type *T);
43 QualType VisitBuiltinType(const BuiltinType *T);
44 QualType VisitComplexType(const ComplexType *T);
45 QualType VisitPointerType(const PointerType *T);
46 QualType VisitBlockPointerType(const BlockPointerType *T);
47 QualType VisitLValueReferenceType(const LValueReferenceType *T);
48 QualType VisitRValueReferenceType(const RValueReferenceType *T);
49 QualType VisitMemberPointerType(const MemberPointerType *T);
50 QualType VisitConstantArrayType(const ConstantArrayType *T);
51 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
52 QualType VisitVariableArrayType(const VariableArrayType *T);
53 // FIXME: DependentSizedArrayType
54 // FIXME: DependentSizedExtVectorType
55 QualType VisitVectorType(const VectorType *T);
56 QualType VisitExtVectorType(const ExtVectorType *T);
57 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
58 QualType VisitFunctionProtoType(const FunctionProtoType *T);
59 // FIXME: UnresolvedUsingType
60 QualType VisitParenType(const ParenType *T);
61 QualType VisitTypedefType(const TypedefType *T);
62 QualType VisitTypeOfExprType(const TypeOfExprType *T);
63 // FIXME: DependentTypeOfExprType
64 QualType VisitTypeOfType(const TypeOfType *T);
65 QualType VisitDecltypeType(const DecltypeType *T);
66 QualType VisitUnaryTransformType(const UnaryTransformType *T);
67 QualType VisitAutoType(const AutoType *T);
68 // FIXME: DependentDecltypeType
69 QualType VisitRecordType(const RecordType *T);
70 QualType VisitEnumType(const EnumType *T);
71 // FIXME: TemplateTypeParmType
72 // FIXME: SubstTemplateTypeParmType
73 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
74 QualType VisitElaboratedType(const ElaboratedType *T);
75 // FIXME: DependentNameType
76 // FIXME: DependentTemplateSpecializationType
77 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
78 QualType VisitObjCObjectType(const ObjCObjectType *T);
79 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
80
81 // Importing declarations
82 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
83 DeclContext *&LexicalDC, DeclarationName &Name,
84 SourceLocation &Loc);
85 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = 0);
86 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87 DeclarationNameInfo& To);
88 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89
90 /// \brief What we should import from the definition.
91 enum ImportDefinitionKind {
92 /// \brief Import the default subset of the definition, which might be
93 /// nothing (if minimal import is set) or might be everything (if minimal
94 /// import is not set).
95 IDK_Default,
96 /// \brief Import everything.
97 IDK_Everything,
98 /// \brief Import only the bare bones needed to establish a valid
99 /// DeclContext.
100 IDK_Basic
101 };
102
shouldForceImportDeclContext(ImportDefinitionKind IDK)103 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
104 return IDK == IDK_Everything ||
105 (IDK == IDK_Default && !Importer.isMinimalImport());
106 }
107
108 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
109 ImportDefinitionKind Kind = IDK_Default);
110 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
111 ImportDefinitionKind Kind = IDK_Default);
112 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
113 ImportDefinitionKind Kind = IDK_Default);
114 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
115 ImportDefinitionKind Kind = IDK_Default);
116 TemplateParameterList *ImportTemplateParameterList(
117 TemplateParameterList *Params);
118 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
119 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
120 unsigned NumFromArgs,
121 SmallVectorImpl<TemplateArgument> &ToArgs);
122 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord);
123 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
124 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
125 Decl *VisitDecl(Decl *D);
126 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
127 Decl *VisitNamespaceDecl(NamespaceDecl *D);
128 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
129 Decl *VisitTypedefDecl(TypedefDecl *D);
130 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
131 Decl *VisitEnumDecl(EnumDecl *D);
132 Decl *VisitRecordDecl(RecordDecl *D);
133 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
134 Decl *VisitFunctionDecl(FunctionDecl *D);
135 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
136 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
137 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
138 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
139 Decl *VisitFieldDecl(FieldDecl *D);
140 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
141 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
142 Decl *VisitVarDecl(VarDecl *D);
143 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
144 Decl *VisitParmVarDecl(ParmVarDecl *D);
145 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
146 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
147 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
148 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
149 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
150 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
151 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
152 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
153 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
154 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
155 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
156 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
157 Decl *VisitClassTemplateSpecializationDecl(
158 ClassTemplateSpecializationDecl *D);
159
160 // Importing statements
161 Stmt *VisitStmt(Stmt *S);
162
163 // Importing expressions
164 Expr *VisitExpr(Expr *E);
165 Expr *VisitDeclRefExpr(DeclRefExpr *E);
166 Expr *VisitIntegerLiteral(IntegerLiteral *E);
167 Expr *VisitCharacterLiteral(CharacterLiteral *E);
168 Expr *VisitParenExpr(ParenExpr *E);
169 Expr *VisitUnaryOperator(UnaryOperator *E);
170 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
171 Expr *VisitBinaryOperator(BinaryOperator *E);
172 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
173 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
174 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
175 };
176 }
177 using namespace clang;
178
179 //----------------------------------------------------------------------------
180 // Structural Equivalence
181 //----------------------------------------------------------------------------
182
183 namespace {
184 struct StructuralEquivalenceContext {
185 /// \brief AST contexts for which we are checking structural equivalence.
186 ASTContext &C1, &C2;
187
188 /// \brief The set of "tentative" equivalences between two canonical
189 /// declarations, mapping from a declaration in the first context to the
190 /// declaration in the second context that we believe to be equivalent.
191 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
192
193 /// \brief Queue of declarations in the first context whose equivalence
194 /// with a declaration in the second context still needs to be verified.
195 std::deque<Decl *> DeclsToCheck;
196
197 /// \brief Declaration (from, to) pairs that are known not to be equivalent
198 /// (which we have already complained about).
199 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
200
201 /// \brief Whether we're being strict about the spelling of types when
202 /// unifying two types.
203 bool StrictTypeSpelling;
204
StructuralEquivalenceContext__anond9d3d2910111::StructuralEquivalenceContext205 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
206 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
207 bool StrictTypeSpelling = false)
208 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
209 StrictTypeSpelling(StrictTypeSpelling) { }
210
211 /// \brief Determine whether the two declarations are structurally
212 /// equivalent.
213 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
214
215 /// \brief Determine whether the two types are structurally equivalent.
216 bool IsStructurallyEquivalent(QualType T1, QualType T2);
217
218 private:
219 /// \brief Finish checking all of the structural equivalences.
220 ///
221 /// \returns true if an error occurred, false otherwise.
222 bool Finish();
223
224 public:
Diag1__anond9d3d2910111::StructuralEquivalenceContext225 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
226 return C1.getDiagnostics().Report(Loc, DiagID);
227 }
228
Diag2__anond9d3d2910111::StructuralEquivalenceContext229 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
230 return C2.getDiagnostics().Report(Loc, DiagID);
231 }
232 };
233 }
234
235 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
236 QualType T1, QualType T2);
237 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
238 Decl *D1, Decl *D2);
239
240 /// \brief Determine if two APInts have the same value, after zero-extending
241 /// one of them (if needed!) to ensure that the bit-widths match.
IsSameValue(const llvm::APInt & I1,const llvm::APInt & I2)242 static bool IsSameValue(const llvm::APInt &I1, const llvm::APInt &I2) {
243 if (I1.getBitWidth() == I2.getBitWidth())
244 return I1 == I2;
245
246 if (I1.getBitWidth() > I2.getBitWidth())
247 return I1 == I2.zext(I1.getBitWidth());
248
249 return I1.zext(I2.getBitWidth()) == I2;
250 }
251
252 /// \brief Determine if two APSInts have the same value, zero- or sign-extending
253 /// as needed.
IsSameValue(const llvm::APSInt & I1,const llvm::APSInt & I2)254 static bool IsSameValue(const llvm::APSInt &I1, const llvm::APSInt &I2) {
255 if (I1.getBitWidth() == I2.getBitWidth() && I1.isSigned() == I2.isSigned())
256 return I1 == I2;
257
258 // Check for a bit-width mismatch.
259 if (I1.getBitWidth() > I2.getBitWidth())
260 return IsSameValue(I1, I2.extend(I1.getBitWidth()));
261 else if (I2.getBitWidth() > I1.getBitWidth())
262 return IsSameValue(I1.extend(I2.getBitWidth()), I2);
263
264 // We have a signedness mismatch. Turn the signed value into an unsigned
265 // value.
266 if (I1.isSigned()) {
267 if (I1.isNegative())
268 return false;
269
270 return llvm::APSInt(I1, true) == I2;
271 }
272
273 if (I2.isNegative())
274 return false;
275
276 return I1 == llvm::APSInt(I2, true);
277 }
278
279 /// \brief Determine structural equivalence of two expressions.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Expr * E1,Expr * E2)280 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
281 Expr *E1, Expr *E2) {
282 if (!E1 || !E2)
283 return E1 == E2;
284
285 // FIXME: Actually perform a structural comparison!
286 return true;
287 }
288
289 /// \brief Determine whether two identifiers are equivalent.
IsStructurallyEquivalent(const IdentifierInfo * Name1,const IdentifierInfo * Name2)290 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
291 const IdentifierInfo *Name2) {
292 if (!Name1 || !Name2)
293 return Name1 == Name2;
294
295 return Name1->getName() == Name2->getName();
296 }
297
298 /// \brief Determine whether two nested-name-specifiers are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NestedNameSpecifier * NNS1,NestedNameSpecifier * NNS2)299 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
300 NestedNameSpecifier *NNS1,
301 NestedNameSpecifier *NNS2) {
302 // FIXME: Implement!
303 return true;
304 }
305
306 /// \brief Determine whether two template arguments are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,const TemplateArgument & Arg1,const TemplateArgument & Arg2)307 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
308 const TemplateArgument &Arg1,
309 const TemplateArgument &Arg2) {
310 if (Arg1.getKind() != Arg2.getKind())
311 return false;
312
313 switch (Arg1.getKind()) {
314 case TemplateArgument::Null:
315 return true;
316
317 case TemplateArgument::Type:
318 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
319
320 case TemplateArgument::Integral:
321 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
322 Arg2.getIntegralType()))
323 return false;
324
325 return IsSameValue(*Arg1.getAsIntegral(), *Arg2.getAsIntegral());
326
327 case TemplateArgument::Declaration:
328 if (!Arg1.getAsDecl() || !Arg2.getAsDecl())
329 return !Arg1.getAsDecl() && !Arg2.getAsDecl();
330 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
331
332 case TemplateArgument::Template:
333 return IsStructurallyEquivalent(Context,
334 Arg1.getAsTemplate(),
335 Arg2.getAsTemplate());
336
337 case TemplateArgument::TemplateExpansion:
338 return IsStructurallyEquivalent(Context,
339 Arg1.getAsTemplateOrTemplatePattern(),
340 Arg2.getAsTemplateOrTemplatePattern());
341
342 case TemplateArgument::Expression:
343 return IsStructurallyEquivalent(Context,
344 Arg1.getAsExpr(), Arg2.getAsExpr());
345
346 case TemplateArgument::Pack:
347 if (Arg1.pack_size() != Arg2.pack_size())
348 return false;
349
350 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
351 if (!IsStructurallyEquivalent(Context,
352 Arg1.pack_begin()[I],
353 Arg2.pack_begin()[I]))
354 return false;
355
356 return true;
357 }
358
359 llvm_unreachable("Invalid template argument kind");
360 }
361
362 /// \brief Determine structural equivalence for the common part of array
363 /// types.
IsArrayStructurallyEquivalent(StructuralEquivalenceContext & Context,const ArrayType * Array1,const ArrayType * Array2)364 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
365 const ArrayType *Array1,
366 const ArrayType *Array2) {
367 if (!IsStructurallyEquivalent(Context,
368 Array1->getElementType(),
369 Array2->getElementType()))
370 return false;
371 if (Array1->getSizeModifier() != Array2->getSizeModifier())
372 return false;
373 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
374 return false;
375
376 return true;
377 }
378
379 /// \brief Determine structural equivalence of two types.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,QualType T1,QualType T2)380 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
381 QualType T1, QualType T2) {
382 if (T1.isNull() || T2.isNull())
383 return T1.isNull() && T2.isNull();
384
385 if (!Context.StrictTypeSpelling) {
386 // We aren't being strict about token-to-token equivalence of types,
387 // so map down to the canonical type.
388 T1 = Context.C1.getCanonicalType(T1);
389 T2 = Context.C2.getCanonicalType(T2);
390 }
391
392 if (T1.getQualifiers() != T2.getQualifiers())
393 return false;
394
395 Type::TypeClass TC = T1->getTypeClass();
396
397 if (T1->getTypeClass() != T2->getTypeClass()) {
398 // Compare function types with prototypes vs. without prototypes as if
399 // both did not have prototypes.
400 if (T1->getTypeClass() == Type::FunctionProto &&
401 T2->getTypeClass() == Type::FunctionNoProto)
402 TC = Type::FunctionNoProto;
403 else if (T1->getTypeClass() == Type::FunctionNoProto &&
404 T2->getTypeClass() == Type::FunctionProto)
405 TC = Type::FunctionNoProto;
406 else
407 return false;
408 }
409
410 switch (TC) {
411 case Type::Builtin:
412 // FIXME: Deal with Char_S/Char_U.
413 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
414 return false;
415 break;
416
417 case Type::Complex:
418 if (!IsStructurallyEquivalent(Context,
419 cast<ComplexType>(T1)->getElementType(),
420 cast<ComplexType>(T2)->getElementType()))
421 return false;
422 break;
423
424 case Type::Pointer:
425 if (!IsStructurallyEquivalent(Context,
426 cast<PointerType>(T1)->getPointeeType(),
427 cast<PointerType>(T2)->getPointeeType()))
428 return false;
429 break;
430
431 case Type::BlockPointer:
432 if (!IsStructurallyEquivalent(Context,
433 cast<BlockPointerType>(T1)->getPointeeType(),
434 cast<BlockPointerType>(T2)->getPointeeType()))
435 return false;
436 break;
437
438 case Type::LValueReference:
439 case Type::RValueReference: {
440 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
441 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
442 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
443 return false;
444 if (Ref1->isInnerRef() != Ref2->isInnerRef())
445 return false;
446 if (!IsStructurallyEquivalent(Context,
447 Ref1->getPointeeTypeAsWritten(),
448 Ref2->getPointeeTypeAsWritten()))
449 return false;
450 break;
451 }
452
453 case Type::MemberPointer: {
454 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
455 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
456 if (!IsStructurallyEquivalent(Context,
457 MemPtr1->getPointeeType(),
458 MemPtr2->getPointeeType()))
459 return false;
460 if (!IsStructurallyEquivalent(Context,
461 QualType(MemPtr1->getClass(), 0),
462 QualType(MemPtr2->getClass(), 0)))
463 return false;
464 break;
465 }
466
467 case Type::ConstantArray: {
468 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
469 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
470 if (!IsSameValue(Array1->getSize(), Array2->getSize()))
471 return false;
472
473 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
474 return false;
475 break;
476 }
477
478 case Type::IncompleteArray:
479 if (!IsArrayStructurallyEquivalent(Context,
480 cast<ArrayType>(T1),
481 cast<ArrayType>(T2)))
482 return false;
483 break;
484
485 case Type::VariableArray: {
486 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
487 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
488 if (!IsStructurallyEquivalent(Context,
489 Array1->getSizeExpr(), Array2->getSizeExpr()))
490 return false;
491
492 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
493 return false;
494
495 break;
496 }
497
498 case Type::DependentSizedArray: {
499 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
500 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
501 if (!IsStructurallyEquivalent(Context,
502 Array1->getSizeExpr(), Array2->getSizeExpr()))
503 return false;
504
505 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
506 return false;
507
508 break;
509 }
510
511 case Type::DependentSizedExtVector: {
512 const DependentSizedExtVectorType *Vec1
513 = cast<DependentSizedExtVectorType>(T1);
514 const DependentSizedExtVectorType *Vec2
515 = cast<DependentSizedExtVectorType>(T2);
516 if (!IsStructurallyEquivalent(Context,
517 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
518 return false;
519 if (!IsStructurallyEquivalent(Context,
520 Vec1->getElementType(),
521 Vec2->getElementType()))
522 return false;
523 break;
524 }
525
526 case Type::Vector:
527 case Type::ExtVector: {
528 const VectorType *Vec1 = cast<VectorType>(T1);
529 const VectorType *Vec2 = cast<VectorType>(T2);
530 if (!IsStructurallyEquivalent(Context,
531 Vec1->getElementType(),
532 Vec2->getElementType()))
533 return false;
534 if (Vec1->getNumElements() != Vec2->getNumElements())
535 return false;
536 if (Vec1->getVectorKind() != Vec2->getVectorKind())
537 return false;
538 break;
539 }
540
541 case Type::FunctionProto: {
542 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
543 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
544 if (Proto1->getNumArgs() != Proto2->getNumArgs())
545 return false;
546 for (unsigned I = 0, N = Proto1->getNumArgs(); I != N; ++I) {
547 if (!IsStructurallyEquivalent(Context,
548 Proto1->getArgType(I),
549 Proto2->getArgType(I)))
550 return false;
551 }
552 if (Proto1->isVariadic() != Proto2->isVariadic())
553 return false;
554 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
555 return false;
556 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
557 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
558 return false;
559 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
560 if (!IsStructurallyEquivalent(Context,
561 Proto1->getExceptionType(I),
562 Proto2->getExceptionType(I)))
563 return false;
564 }
565 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
566 if (!IsStructurallyEquivalent(Context,
567 Proto1->getNoexceptExpr(),
568 Proto2->getNoexceptExpr()))
569 return false;
570 }
571 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
572 return false;
573
574 // Fall through to check the bits common with FunctionNoProtoType.
575 }
576
577 case Type::FunctionNoProto: {
578 const FunctionType *Function1 = cast<FunctionType>(T1);
579 const FunctionType *Function2 = cast<FunctionType>(T2);
580 if (!IsStructurallyEquivalent(Context,
581 Function1->getResultType(),
582 Function2->getResultType()))
583 return false;
584 if (Function1->getExtInfo() != Function2->getExtInfo())
585 return false;
586 break;
587 }
588
589 case Type::UnresolvedUsing:
590 if (!IsStructurallyEquivalent(Context,
591 cast<UnresolvedUsingType>(T1)->getDecl(),
592 cast<UnresolvedUsingType>(T2)->getDecl()))
593 return false;
594
595 break;
596
597 case Type::Attributed:
598 if (!IsStructurallyEquivalent(Context,
599 cast<AttributedType>(T1)->getModifiedType(),
600 cast<AttributedType>(T2)->getModifiedType()))
601 return false;
602 if (!IsStructurallyEquivalent(Context,
603 cast<AttributedType>(T1)->getEquivalentType(),
604 cast<AttributedType>(T2)->getEquivalentType()))
605 return false;
606 break;
607
608 case Type::Paren:
609 if (!IsStructurallyEquivalent(Context,
610 cast<ParenType>(T1)->getInnerType(),
611 cast<ParenType>(T2)->getInnerType()))
612 return false;
613 break;
614
615 case Type::Typedef:
616 if (!IsStructurallyEquivalent(Context,
617 cast<TypedefType>(T1)->getDecl(),
618 cast<TypedefType>(T2)->getDecl()))
619 return false;
620 break;
621
622 case Type::TypeOfExpr:
623 if (!IsStructurallyEquivalent(Context,
624 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
625 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
626 return false;
627 break;
628
629 case Type::TypeOf:
630 if (!IsStructurallyEquivalent(Context,
631 cast<TypeOfType>(T1)->getUnderlyingType(),
632 cast<TypeOfType>(T2)->getUnderlyingType()))
633 return false;
634 break;
635
636 case Type::UnaryTransform:
637 if (!IsStructurallyEquivalent(Context,
638 cast<UnaryTransformType>(T1)->getUnderlyingType(),
639 cast<UnaryTransformType>(T1)->getUnderlyingType()))
640 return false;
641 break;
642
643 case Type::Decltype:
644 if (!IsStructurallyEquivalent(Context,
645 cast<DecltypeType>(T1)->getUnderlyingExpr(),
646 cast<DecltypeType>(T2)->getUnderlyingExpr()))
647 return false;
648 break;
649
650 case Type::Auto:
651 if (!IsStructurallyEquivalent(Context,
652 cast<AutoType>(T1)->getDeducedType(),
653 cast<AutoType>(T2)->getDeducedType()))
654 return false;
655 break;
656
657 case Type::Record:
658 case Type::Enum:
659 if (!IsStructurallyEquivalent(Context,
660 cast<TagType>(T1)->getDecl(),
661 cast<TagType>(T2)->getDecl()))
662 return false;
663 break;
664
665 case Type::TemplateTypeParm: {
666 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
667 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
668 if (Parm1->getDepth() != Parm2->getDepth())
669 return false;
670 if (Parm1->getIndex() != Parm2->getIndex())
671 return false;
672 if (Parm1->isParameterPack() != Parm2->isParameterPack())
673 return false;
674
675 // Names of template type parameters are never significant.
676 break;
677 }
678
679 case Type::SubstTemplateTypeParm: {
680 const SubstTemplateTypeParmType *Subst1
681 = cast<SubstTemplateTypeParmType>(T1);
682 const SubstTemplateTypeParmType *Subst2
683 = cast<SubstTemplateTypeParmType>(T2);
684 if (!IsStructurallyEquivalent(Context,
685 QualType(Subst1->getReplacedParameter(), 0),
686 QualType(Subst2->getReplacedParameter(), 0)))
687 return false;
688 if (!IsStructurallyEquivalent(Context,
689 Subst1->getReplacementType(),
690 Subst2->getReplacementType()))
691 return false;
692 break;
693 }
694
695 case Type::SubstTemplateTypeParmPack: {
696 const SubstTemplateTypeParmPackType *Subst1
697 = cast<SubstTemplateTypeParmPackType>(T1);
698 const SubstTemplateTypeParmPackType *Subst2
699 = cast<SubstTemplateTypeParmPackType>(T2);
700 if (!IsStructurallyEquivalent(Context,
701 QualType(Subst1->getReplacedParameter(), 0),
702 QualType(Subst2->getReplacedParameter(), 0)))
703 return false;
704 if (!IsStructurallyEquivalent(Context,
705 Subst1->getArgumentPack(),
706 Subst2->getArgumentPack()))
707 return false;
708 break;
709 }
710 case Type::TemplateSpecialization: {
711 const TemplateSpecializationType *Spec1
712 = cast<TemplateSpecializationType>(T1);
713 const TemplateSpecializationType *Spec2
714 = cast<TemplateSpecializationType>(T2);
715 if (!IsStructurallyEquivalent(Context,
716 Spec1->getTemplateName(),
717 Spec2->getTemplateName()))
718 return false;
719 if (Spec1->getNumArgs() != Spec2->getNumArgs())
720 return false;
721 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
722 if (!IsStructurallyEquivalent(Context,
723 Spec1->getArg(I), Spec2->getArg(I)))
724 return false;
725 }
726 break;
727 }
728
729 case Type::Elaborated: {
730 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
731 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
732 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
733 if (Elab1->getKeyword() != Elab2->getKeyword())
734 return false;
735 if (!IsStructurallyEquivalent(Context,
736 Elab1->getQualifier(),
737 Elab2->getQualifier()))
738 return false;
739 if (!IsStructurallyEquivalent(Context,
740 Elab1->getNamedType(),
741 Elab2->getNamedType()))
742 return false;
743 break;
744 }
745
746 case Type::InjectedClassName: {
747 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
748 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
749 if (!IsStructurallyEquivalent(Context,
750 Inj1->getInjectedSpecializationType(),
751 Inj2->getInjectedSpecializationType()))
752 return false;
753 break;
754 }
755
756 case Type::DependentName: {
757 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
758 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
759 if (!IsStructurallyEquivalent(Context,
760 Typename1->getQualifier(),
761 Typename2->getQualifier()))
762 return false;
763 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
764 Typename2->getIdentifier()))
765 return false;
766
767 break;
768 }
769
770 case Type::DependentTemplateSpecialization: {
771 const DependentTemplateSpecializationType *Spec1 =
772 cast<DependentTemplateSpecializationType>(T1);
773 const DependentTemplateSpecializationType *Spec2 =
774 cast<DependentTemplateSpecializationType>(T2);
775 if (!IsStructurallyEquivalent(Context,
776 Spec1->getQualifier(),
777 Spec2->getQualifier()))
778 return false;
779 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
780 Spec2->getIdentifier()))
781 return false;
782 if (Spec1->getNumArgs() != Spec2->getNumArgs())
783 return false;
784 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
785 if (!IsStructurallyEquivalent(Context,
786 Spec1->getArg(I), Spec2->getArg(I)))
787 return false;
788 }
789 break;
790 }
791
792 case Type::PackExpansion:
793 if (!IsStructurallyEquivalent(Context,
794 cast<PackExpansionType>(T1)->getPattern(),
795 cast<PackExpansionType>(T2)->getPattern()))
796 return false;
797 break;
798
799 case Type::ObjCInterface: {
800 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
801 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
802 if (!IsStructurallyEquivalent(Context,
803 Iface1->getDecl(), Iface2->getDecl()))
804 return false;
805 break;
806 }
807
808 case Type::ObjCObject: {
809 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
810 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
811 if (!IsStructurallyEquivalent(Context,
812 Obj1->getBaseType(),
813 Obj2->getBaseType()))
814 return false;
815 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
816 return false;
817 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
818 if (!IsStructurallyEquivalent(Context,
819 Obj1->getProtocol(I),
820 Obj2->getProtocol(I)))
821 return false;
822 }
823 break;
824 }
825
826 case Type::ObjCObjectPointer: {
827 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
828 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
829 if (!IsStructurallyEquivalent(Context,
830 Ptr1->getPointeeType(),
831 Ptr2->getPointeeType()))
832 return false;
833 break;
834 }
835
836 case Type::Atomic: {
837 if (!IsStructurallyEquivalent(Context,
838 cast<AtomicType>(T1)->getValueType(),
839 cast<AtomicType>(T2)->getValueType()))
840 return false;
841 break;
842 }
843
844 } // end switch
845
846 return true;
847 }
848
849 /// \brief Determine structural equivalence of two fields.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,FieldDecl * Field1,FieldDecl * Field2)850 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
851 FieldDecl *Field1, FieldDecl *Field2) {
852 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
853
854 if (!IsStructurallyEquivalent(Context,
855 Field1->getType(), Field2->getType())) {
856 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
857 << Context.C2.getTypeDeclType(Owner2);
858 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
859 << Field2->getDeclName() << Field2->getType();
860 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
861 << Field1->getDeclName() << Field1->getType();
862 return false;
863 }
864
865 if (Field1->isBitField() != Field2->isBitField()) {
866 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
867 << Context.C2.getTypeDeclType(Owner2);
868 if (Field1->isBitField()) {
869 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
870 << Field1->getDeclName() << Field1->getType()
871 << Field1->getBitWidthValue(Context.C1);
872 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
873 << Field2->getDeclName();
874 } else {
875 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
876 << Field2->getDeclName() << Field2->getType()
877 << Field2->getBitWidthValue(Context.C2);
878 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
879 << Field1->getDeclName();
880 }
881 return false;
882 }
883
884 if (Field1->isBitField()) {
885 // Make sure that the bit-fields are the same length.
886 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
887 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
888
889 if (Bits1 != Bits2) {
890 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
891 << Context.C2.getTypeDeclType(Owner2);
892 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
893 << Field2->getDeclName() << Field2->getType() << Bits2;
894 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
895 << Field1->getDeclName() << Field1->getType() << Bits1;
896 return false;
897 }
898 }
899
900 return true;
901 }
902
903 /// \brief Determine structural equivalence of two records.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,RecordDecl * D1,RecordDecl * D2)904 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
905 RecordDecl *D1, RecordDecl *D2) {
906 if (D1->isUnion() != D2->isUnion()) {
907 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
908 << Context.C2.getTypeDeclType(D2);
909 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
910 << D1->getDeclName() << (unsigned)D1->getTagKind();
911 return false;
912 }
913
914 // If both declarations are class template specializations, we know
915 // the ODR applies, so check the template and template arguments.
916 ClassTemplateSpecializationDecl *Spec1
917 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
918 ClassTemplateSpecializationDecl *Spec2
919 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
920 if (Spec1 && Spec2) {
921 // Check that the specialized templates are the same.
922 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
923 Spec2->getSpecializedTemplate()))
924 return false;
925
926 // Check that the template arguments are the same.
927 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
928 return false;
929
930 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
931 if (!IsStructurallyEquivalent(Context,
932 Spec1->getTemplateArgs().get(I),
933 Spec2->getTemplateArgs().get(I)))
934 return false;
935 }
936 // If one is a class template specialization and the other is not, these
937 // structures are different.
938 else if (Spec1 || Spec2)
939 return false;
940
941 // Compare the definitions of these two records. If either or both are
942 // incomplete, we assume that they are equivalent.
943 D1 = D1->getDefinition();
944 D2 = D2->getDefinition();
945 if (!D1 || !D2)
946 return true;
947
948 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
949 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
950 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
951 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
952 << Context.C2.getTypeDeclType(D2);
953 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
954 << D2CXX->getNumBases();
955 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
956 << D1CXX->getNumBases();
957 return false;
958 }
959
960 // Check the base classes.
961 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
962 BaseEnd1 = D1CXX->bases_end(),
963 Base2 = D2CXX->bases_begin();
964 Base1 != BaseEnd1;
965 ++Base1, ++Base2) {
966 if (!IsStructurallyEquivalent(Context,
967 Base1->getType(), Base2->getType())) {
968 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
969 << Context.C2.getTypeDeclType(D2);
970 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
971 << Base2->getType()
972 << Base2->getSourceRange();
973 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
974 << Base1->getType()
975 << Base1->getSourceRange();
976 return false;
977 }
978
979 // Check virtual vs. non-virtual inheritance mismatch.
980 if (Base1->isVirtual() != Base2->isVirtual()) {
981 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
982 << Context.C2.getTypeDeclType(D2);
983 Context.Diag2(Base2->getLocStart(),
984 diag::note_odr_virtual_base)
985 << Base2->isVirtual() << Base2->getSourceRange();
986 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
987 << Base1->isVirtual()
988 << Base1->getSourceRange();
989 return false;
990 }
991 }
992 } else if (D1CXX->getNumBases() > 0) {
993 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
994 << Context.C2.getTypeDeclType(D2);
995 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
996 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
997 << Base1->getType()
998 << Base1->getSourceRange();
999 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1000 return false;
1001 }
1002 }
1003
1004 // Check the fields for consistency.
1005 CXXRecordDecl::field_iterator Field2 = D2->field_begin(),
1006 Field2End = D2->field_end();
1007 for (CXXRecordDecl::field_iterator Field1 = D1->field_begin(),
1008 Field1End = D1->field_end();
1009 Field1 != Field1End;
1010 ++Field1, ++Field2) {
1011 if (Field2 == Field2End) {
1012 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1013 << Context.C2.getTypeDeclType(D2);
1014 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1015 << Field1->getDeclName() << Field1->getType();
1016 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1017 return false;
1018 }
1019
1020 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1021 return false;
1022 }
1023
1024 if (Field2 != Field2End) {
1025 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1026 << Context.C2.getTypeDeclType(D2);
1027 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1028 << Field2->getDeclName() << Field2->getType();
1029 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1030 return false;
1031 }
1032
1033 return true;
1034 }
1035
1036 /// \brief Determine structural equivalence of two enums.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,EnumDecl * D1,EnumDecl * D2)1037 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1038 EnumDecl *D1, EnumDecl *D2) {
1039 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1040 EC2End = D2->enumerator_end();
1041 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1042 EC1End = D1->enumerator_end();
1043 EC1 != EC1End; ++EC1, ++EC2) {
1044 if (EC2 == EC2End) {
1045 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1046 << Context.C2.getTypeDeclType(D2);
1047 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1048 << EC1->getDeclName()
1049 << EC1->getInitVal().toString(10);
1050 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1051 return false;
1052 }
1053
1054 llvm::APSInt Val1 = EC1->getInitVal();
1055 llvm::APSInt Val2 = EC2->getInitVal();
1056 if (!IsSameValue(Val1, Val2) ||
1057 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1058 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1059 << Context.C2.getTypeDeclType(D2);
1060 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1061 << EC2->getDeclName()
1062 << EC2->getInitVal().toString(10);
1063 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1064 << EC1->getDeclName()
1065 << EC1->getInitVal().toString(10);
1066 return false;
1067 }
1068 }
1069
1070 if (EC2 != EC2End) {
1071 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1072 << Context.C2.getTypeDeclType(D2);
1073 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1074 << EC2->getDeclName()
1075 << EC2->getInitVal().toString(10);
1076 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1077 return false;
1078 }
1079
1080 return true;
1081 }
1082
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateParameterList * Params1,TemplateParameterList * Params2)1083 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1084 TemplateParameterList *Params1,
1085 TemplateParameterList *Params2) {
1086 if (Params1->size() != Params2->size()) {
1087 Context.Diag2(Params2->getTemplateLoc(),
1088 diag::err_odr_different_num_template_parameters)
1089 << Params1->size() << Params2->size();
1090 Context.Diag1(Params1->getTemplateLoc(),
1091 diag::note_odr_template_parameter_list);
1092 return false;
1093 }
1094
1095 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1096 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1097 Context.Diag2(Params2->getParam(I)->getLocation(),
1098 diag::err_odr_different_template_parameter_kind);
1099 Context.Diag1(Params1->getParam(I)->getLocation(),
1100 diag::note_odr_template_parameter_here);
1101 return false;
1102 }
1103
1104 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1105 Params2->getParam(I))) {
1106
1107 return false;
1108 }
1109 }
1110
1111 return true;
1112 }
1113
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTypeParmDecl * D1,TemplateTypeParmDecl * D2)1114 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1115 TemplateTypeParmDecl *D1,
1116 TemplateTypeParmDecl *D2) {
1117 if (D1->isParameterPack() != D2->isParameterPack()) {
1118 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1119 << D2->isParameterPack();
1120 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1121 << D1->isParameterPack();
1122 return false;
1123 }
1124
1125 return true;
1126 }
1127
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NonTypeTemplateParmDecl * D1,NonTypeTemplateParmDecl * D2)1128 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1129 NonTypeTemplateParmDecl *D1,
1130 NonTypeTemplateParmDecl *D2) {
1131 // FIXME: Enable once we have variadic templates.
1132 #if 0
1133 if (D1->isParameterPack() != D2->isParameterPack()) {
1134 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1135 << D2->isParameterPack();
1136 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1137 << D1->isParameterPack();
1138 return false;
1139 }
1140 #endif
1141
1142 // Check types.
1143 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1144 Context.Diag2(D2->getLocation(),
1145 diag::err_odr_non_type_parameter_type_inconsistent)
1146 << D2->getType() << D1->getType();
1147 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1148 << D1->getType();
1149 return false;
1150 }
1151
1152 return true;
1153 }
1154
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTemplateParmDecl * D1,TemplateTemplateParmDecl * D2)1155 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1156 TemplateTemplateParmDecl *D1,
1157 TemplateTemplateParmDecl *D2) {
1158 // FIXME: Enable once we have variadic templates.
1159 #if 0
1160 if (D1->isParameterPack() != D2->isParameterPack()) {
1161 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1162 << D2->isParameterPack();
1163 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1164 << D1->isParameterPack();
1165 return false;
1166 }
1167 #endif
1168
1169 // Check template parameter lists.
1170 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1171 D2->getTemplateParameters());
1172 }
1173
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,ClassTemplateDecl * D1,ClassTemplateDecl * D2)1174 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1175 ClassTemplateDecl *D1,
1176 ClassTemplateDecl *D2) {
1177 // Check template parameters.
1178 if (!IsStructurallyEquivalent(Context,
1179 D1->getTemplateParameters(),
1180 D2->getTemplateParameters()))
1181 return false;
1182
1183 // Check the templated declaration.
1184 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1185 D2->getTemplatedDecl());
1186 }
1187
1188 /// \brief Determine structural equivalence of two declarations.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Decl * D1,Decl * D2)1189 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1190 Decl *D1, Decl *D2) {
1191 // FIXME: Check for known structural equivalences via a callback of some sort.
1192
1193 // Check whether we already know that these two declarations are not
1194 // structurally equivalent.
1195 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1196 D2->getCanonicalDecl())))
1197 return false;
1198
1199 // Determine whether we've already produced a tentative equivalence for D1.
1200 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1201 if (EquivToD1)
1202 return EquivToD1 == D2->getCanonicalDecl();
1203
1204 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1205 EquivToD1 = D2->getCanonicalDecl();
1206 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1207 return true;
1208 }
1209
IsStructurallyEquivalent(Decl * D1,Decl * D2)1210 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1211 Decl *D2) {
1212 if (!::IsStructurallyEquivalent(*this, D1, D2))
1213 return false;
1214
1215 return !Finish();
1216 }
1217
IsStructurallyEquivalent(QualType T1,QualType T2)1218 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1219 QualType T2) {
1220 if (!::IsStructurallyEquivalent(*this, T1, T2))
1221 return false;
1222
1223 return !Finish();
1224 }
1225
Finish()1226 bool StructuralEquivalenceContext::Finish() {
1227 while (!DeclsToCheck.empty()) {
1228 // Check the next declaration.
1229 Decl *D1 = DeclsToCheck.front();
1230 DeclsToCheck.pop_front();
1231
1232 Decl *D2 = TentativeEquivalences[D1];
1233 assert(D2 && "Unrecorded tentative equivalence?");
1234
1235 bool Equivalent = true;
1236
1237 // FIXME: Switch on all declaration kinds. For now, we're just going to
1238 // check the obvious ones.
1239 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1240 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1241 // Check for equivalent structure names.
1242 IdentifierInfo *Name1 = Record1->getIdentifier();
1243 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1244 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1245 IdentifierInfo *Name2 = Record2->getIdentifier();
1246 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1247 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1248 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1249 !::IsStructurallyEquivalent(*this, Record1, Record2))
1250 Equivalent = false;
1251 } else {
1252 // Record/non-record mismatch.
1253 Equivalent = false;
1254 }
1255 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1256 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1257 // Check for equivalent enum names.
1258 IdentifierInfo *Name1 = Enum1->getIdentifier();
1259 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1260 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1261 IdentifierInfo *Name2 = Enum2->getIdentifier();
1262 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1263 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1264 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1265 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1266 Equivalent = false;
1267 } else {
1268 // Enum/non-enum mismatch
1269 Equivalent = false;
1270 }
1271 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1272 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1273 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1274 Typedef2->getIdentifier()) ||
1275 !::IsStructurallyEquivalent(*this,
1276 Typedef1->getUnderlyingType(),
1277 Typedef2->getUnderlyingType()))
1278 Equivalent = false;
1279 } else {
1280 // Typedef/non-typedef mismatch.
1281 Equivalent = false;
1282 }
1283 } else if (ClassTemplateDecl *ClassTemplate1
1284 = dyn_cast<ClassTemplateDecl>(D1)) {
1285 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1286 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1287 ClassTemplate2->getIdentifier()) ||
1288 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1289 Equivalent = false;
1290 } else {
1291 // Class template/non-class-template mismatch.
1292 Equivalent = false;
1293 }
1294 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1295 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1296 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1297 Equivalent = false;
1298 } else {
1299 // Kind mismatch.
1300 Equivalent = false;
1301 }
1302 } else if (NonTypeTemplateParmDecl *NTTP1
1303 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1304 if (NonTypeTemplateParmDecl *NTTP2
1305 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1306 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1307 Equivalent = false;
1308 } else {
1309 // Kind mismatch.
1310 Equivalent = false;
1311 }
1312 } else if (TemplateTemplateParmDecl *TTP1
1313 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1314 if (TemplateTemplateParmDecl *TTP2
1315 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1316 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1317 Equivalent = false;
1318 } else {
1319 // Kind mismatch.
1320 Equivalent = false;
1321 }
1322 }
1323
1324 if (!Equivalent) {
1325 // Note that these two declarations are not equivalent (and we already
1326 // know about it).
1327 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1328 D2->getCanonicalDecl()));
1329 return true;
1330 }
1331 // FIXME: Check other declaration kinds!
1332 }
1333
1334 return false;
1335 }
1336
1337 //----------------------------------------------------------------------------
1338 // Import Types
1339 //----------------------------------------------------------------------------
1340
VisitType(const Type * T)1341 QualType ASTNodeImporter::VisitType(const Type *T) {
1342 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1343 << T->getTypeClassName();
1344 return QualType();
1345 }
1346
VisitBuiltinType(const BuiltinType * T)1347 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1348 switch (T->getKind()) {
1349 #define SHARED_SINGLETON_TYPE(Expansion)
1350 #define BUILTIN_TYPE(Id, SingletonId) \
1351 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1352 #include "clang/AST/BuiltinTypes.def"
1353
1354 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1355 // context supports C++.
1356
1357 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1358 // context supports ObjC.
1359
1360 case BuiltinType::Char_U:
1361 // The context we're importing from has an unsigned 'char'. If we're
1362 // importing into a context with a signed 'char', translate to
1363 // 'unsigned char' instead.
1364 if (Importer.getToContext().getLangOpts().CharIsSigned)
1365 return Importer.getToContext().UnsignedCharTy;
1366
1367 return Importer.getToContext().CharTy;
1368
1369 case BuiltinType::Char_S:
1370 // The context we're importing from has an unsigned 'char'. If we're
1371 // importing into a context with a signed 'char', translate to
1372 // 'unsigned char' instead.
1373 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1374 return Importer.getToContext().SignedCharTy;
1375
1376 return Importer.getToContext().CharTy;
1377
1378 case BuiltinType::WChar_S:
1379 case BuiltinType::WChar_U:
1380 // FIXME: If not in C++, shall we translate to the C equivalent of
1381 // wchar_t?
1382 return Importer.getToContext().WCharTy;
1383 }
1384
1385 llvm_unreachable("Invalid BuiltinType Kind!");
1386 }
1387
VisitComplexType(const ComplexType * T)1388 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1389 QualType ToElementType = Importer.Import(T->getElementType());
1390 if (ToElementType.isNull())
1391 return QualType();
1392
1393 return Importer.getToContext().getComplexType(ToElementType);
1394 }
1395
VisitPointerType(const PointerType * T)1396 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1397 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1398 if (ToPointeeType.isNull())
1399 return QualType();
1400
1401 return Importer.getToContext().getPointerType(ToPointeeType);
1402 }
1403
VisitBlockPointerType(const BlockPointerType * T)1404 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1405 // FIXME: Check for blocks support in "to" context.
1406 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1407 if (ToPointeeType.isNull())
1408 return QualType();
1409
1410 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1411 }
1412
1413 QualType
VisitLValueReferenceType(const LValueReferenceType * T)1414 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1415 // FIXME: Check for C++ support in "to" context.
1416 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1417 if (ToPointeeType.isNull())
1418 return QualType();
1419
1420 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1421 }
1422
1423 QualType
VisitRValueReferenceType(const RValueReferenceType * T)1424 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1425 // FIXME: Check for C++0x support in "to" context.
1426 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1427 if (ToPointeeType.isNull())
1428 return QualType();
1429
1430 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1431 }
1432
VisitMemberPointerType(const MemberPointerType * T)1433 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1434 // FIXME: Check for C++ support in "to" context.
1435 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1436 if (ToPointeeType.isNull())
1437 return QualType();
1438
1439 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1440 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1441 ClassType.getTypePtr());
1442 }
1443
VisitConstantArrayType(const ConstantArrayType * T)1444 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1445 QualType ToElementType = Importer.Import(T->getElementType());
1446 if (ToElementType.isNull())
1447 return QualType();
1448
1449 return Importer.getToContext().getConstantArrayType(ToElementType,
1450 T->getSize(),
1451 T->getSizeModifier(),
1452 T->getIndexTypeCVRQualifiers());
1453 }
1454
1455 QualType
VisitIncompleteArrayType(const IncompleteArrayType * T)1456 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1457 QualType ToElementType = Importer.Import(T->getElementType());
1458 if (ToElementType.isNull())
1459 return QualType();
1460
1461 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1462 T->getSizeModifier(),
1463 T->getIndexTypeCVRQualifiers());
1464 }
1465
VisitVariableArrayType(const VariableArrayType * T)1466 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1467 QualType ToElementType = Importer.Import(T->getElementType());
1468 if (ToElementType.isNull())
1469 return QualType();
1470
1471 Expr *Size = Importer.Import(T->getSizeExpr());
1472 if (!Size)
1473 return QualType();
1474
1475 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1476 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1477 T->getSizeModifier(),
1478 T->getIndexTypeCVRQualifiers(),
1479 Brackets);
1480 }
1481
VisitVectorType(const VectorType * T)1482 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1483 QualType ToElementType = Importer.Import(T->getElementType());
1484 if (ToElementType.isNull())
1485 return QualType();
1486
1487 return Importer.getToContext().getVectorType(ToElementType,
1488 T->getNumElements(),
1489 T->getVectorKind());
1490 }
1491
VisitExtVectorType(const ExtVectorType * T)1492 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1493 QualType ToElementType = Importer.Import(T->getElementType());
1494 if (ToElementType.isNull())
1495 return QualType();
1496
1497 return Importer.getToContext().getExtVectorType(ToElementType,
1498 T->getNumElements());
1499 }
1500
1501 QualType
VisitFunctionNoProtoType(const FunctionNoProtoType * T)1502 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1503 // FIXME: What happens if we're importing a function without a prototype
1504 // into C++? Should we make it variadic?
1505 QualType ToResultType = Importer.Import(T->getResultType());
1506 if (ToResultType.isNull())
1507 return QualType();
1508
1509 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1510 T->getExtInfo());
1511 }
1512
VisitFunctionProtoType(const FunctionProtoType * T)1513 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1514 QualType ToResultType = Importer.Import(T->getResultType());
1515 if (ToResultType.isNull())
1516 return QualType();
1517
1518 // Import argument types
1519 SmallVector<QualType, 4> ArgTypes;
1520 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
1521 AEnd = T->arg_type_end();
1522 A != AEnd; ++A) {
1523 QualType ArgType = Importer.Import(*A);
1524 if (ArgType.isNull())
1525 return QualType();
1526 ArgTypes.push_back(ArgType);
1527 }
1528
1529 // Import exception types
1530 SmallVector<QualType, 4> ExceptionTypes;
1531 for (FunctionProtoType::exception_iterator E = T->exception_begin(),
1532 EEnd = T->exception_end();
1533 E != EEnd; ++E) {
1534 QualType ExceptionType = Importer.Import(*E);
1535 if (ExceptionType.isNull())
1536 return QualType();
1537 ExceptionTypes.push_back(ExceptionType);
1538 }
1539
1540 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
1541 EPI.Exceptions = ExceptionTypes.data();
1542
1543 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes.data(),
1544 ArgTypes.size(), EPI);
1545 }
1546
VisitParenType(const ParenType * T)1547 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1548 QualType ToInnerType = Importer.Import(T->getInnerType());
1549 if (ToInnerType.isNull())
1550 return QualType();
1551
1552 return Importer.getToContext().getParenType(ToInnerType);
1553 }
1554
VisitTypedefType(const TypedefType * T)1555 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1556 TypedefNameDecl *ToDecl
1557 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1558 if (!ToDecl)
1559 return QualType();
1560
1561 return Importer.getToContext().getTypeDeclType(ToDecl);
1562 }
1563
VisitTypeOfExprType(const TypeOfExprType * T)1564 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1565 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1566 if (!ToExpr)
1567 return QualType();
1568
1569 return Importer.getToContext().getTypeOfExprType(ToExpr);
1570 }
1571
VisitTypeOfType(const TypeOfType * T)1572 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1573 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1574 if (ToUnderlyingType.isNull())
1575 return QualType();
1576
1577 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1578 }
1579
VisitDecltypeType(const DecltypeType * T)1580 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1581 // FIXME: Make sure that the "to" context supports C++0x!
1582 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1583 if (!ToExpr)
1584 return QualType();
1585
1586 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1587 if (UnderlyingType.isNull())
1588 return QualType();
1589
1590 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1591 }
1592
VisitUnaryTransformType(const UnaryTransformType * T)1593 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1594 QualType ToBaseType = Importer.Import(T->getBaseType());
1595 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1596 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1597 return QualType();
1598
1599 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1600 ToUnderlyingType,
1601 T->getUTTKind());
1602 }
1603
VisitAutoType(const AutoType * T)1604 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1605 // FIXME: Make sure that the "to" context supports C++0x!
1606 QualType FromDeduced = T->getDeducedType();
1607 QualType ToDeduced;
1608 if (!FromDeduced.isNull()) {
1609 ToDeduced = Importer.Import(FromDeduced);
1610 if (ToDeduced.isNull())
1611 return QualType();
1612 }
1613
1614 return Importer.getToContext().getAutoType(ToDeduced);
1615 }
1616
VisitRecordType(const RecordType * T)1617 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1618 RecordDecl *ToDecl
1619 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1620 if (!ToDecl)
1621 return QualType();
1622
1623 return Importer.getToContext().getTagDeclType(ToDecl);
1624 }
1625
VisitEnumType(const EnumType * T)1626 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1627 EnumDecl *ToDecl
1628 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1629 if (!ToDecl)
1630 return QualType();
1631
1632 return Importer.getToContext().getTagDeclType(ToDecl);
1633 }
1634
VisitTemplateSpecializationType(const TemplateSpecializationType * T)1635 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1636 const TemplateSpecializationType *T) {
1637 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1638 if (ToTemplate.isNull())
1639 return QualType();
1640
1641 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1642 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1643 return QualType();
1644
1645 QualType ToCanonType;
1646 if (!QualType(T, 0).isCanonical()) {
1647 QualType FromCanonType
1648 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1649 ToCanonType =Importer.Import(FromCanonType);
1650 if (ToCanonType.isNull())
1651 return QualType();
1652 }
1653 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1654 ToTemplateArgs.data(),
1655 ToTemplateArgs.size(),
1656 ToCanonType);
1657 }
1658
VisitElaboratedType(const ElaboratedType * T)1659 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1660 NestedNameSpecifier *ToQualifier = 0;
1661 // Note: the qualifier in an ElaboratedType is optional.
1662 if (T->getQualifier()) {
1663 ToQualifier = Importer.Import(T->getQualifier());
1664 if (!ToQualifier)
1665 return QualType();
1666 }
1667
1668 QualType ToNamedType = Importer.Import(T->getNamedType());
1669 if (ToNamedType.isNull())
1670 return QualType();
1671
1672 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1673 ToQualifier, ToNamedType);
1674 }
1675
VisitObjCInterfaceType(const ObjCInterfaceType * T)1676 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1677 ObjCInterfaceDecl *Class
1678 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1679 if (!Class)
1680 return QualType();
1681
1682 return Importer.getToContext().getObjCInterfaceType(Class);
1683 }
1684
VisitObjCObjectType(const ObjCObjectType * T)1685 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1686 QualType ToBaseType = Importer.Import(T->getBaseType());
1687 if (ToBaseType.isNull())
1688 return QualType();
1689
1690 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1691 for (ObjCObjectType::qual_iterator P = T->qual_begin(),
1692 PEnd = T->qual_end();
1693 P != PEnd; ++P) {
1694 ObjCProtocolDecl *Protocol
1695 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1696 if (!Protocol)
1697 return QualType();
1698 Protocols.push_back(Protocol);
1699 }
1700
1701 return Importer.getToContext().getObjCObjectType(ToBaseType,
1702 Protocols.data(),
1703 Protocols.size());
1704 }
1705
1706 QualType
VisitObjCObjectPointerType(const ObjCObjectPointerType * T)1707 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1708 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1709 if (ToPointeeType.isNull())
1710 return QualType();
1711
1712 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1713 }
1714
1715 //----------------------------------------------------------------------------
1716 // Import Declarations
1717 //----------------------------------------------------------------------------
ImportDeclParts(NamedDecl * D,DeclContext * & DC,DeclContext * & LexicalDC,DeclarationName & Name,SourceLocation & Loc)1718 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1719 DeclContext *&LexicalDC,
1720 DeclarationName &Name,
1721 SourceLocation &Loc) {
1722 // Import the context of this declaration.
1723 DC = Importer.ImportContext(D->getDeclContext());
1724 if (!DC)
1725 return true;
1726
1727 LexicalDC = DC;
1728 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1729 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1730 if (!LexicalDC)
1731 return true;
1732 }
1733
1734 // Import the name of this declaration.
1735 Name = Importer.Import(D->getDeclName());
1736 if (D->getDeclName() && !Name)
1737 return true;
1738
1739 // Import the location of this declaration.
1740 Loc = Importer.Import(D->getLocation());
1741 return false;
1742 }
1743
ImportDefinitionIfNeeded(Decl * FromD,Decl * ToD)1744 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1745 if (!FromD)
1746 return;
1747
1748 if (!ToD) {
1749 ToD = Importer.Import(FromD);
1750 if (!ToD)
1751 return;
1752 }
1753
1754 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1755 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1756 if (FromRecord->getDefinition() && !ToRecord->getDefinition()) {
1757 ImportDefinition(FromRecord, ToRecord);
1758 }
1759 }
1760 return;
1761 }
1762
1763 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1764 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1765 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1766 ImportDefinition(FromEnum, ToEnum);
1767 }
1768 }
1769 return;
1770 }
1771 }
1772
1773 void
ImportDeclarationNameLoc(const DeclarationNameInfo & From,DeclarationNameInfo & To)1774 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1775 DeclarationNameInfo& To) {
1776 // NOTE: To.Name and To.Loc are already imported.
1777 // We only have to import To.LocInfo.
1778 switch (To.getName().getNameKind()) {
1779 case DeclarationName::Identifier:
1780 case DeclarationName::ObjCZeroArgSelector:
1781 case DeclarationName::ObjCOneArgSelector:
1782 case DeclarationName::ObjCMultiArgSelector:
1783 case DeclarationName::CXXUsingDirective:
1784 return;
1785
1786 case DeclarationName::CXXOperatorName: {
1787 SourceRange Range = From.getCXXOperatorNameRange();
1788 To.setCXXOperatorNameRange(Importer.Import(Range));
1789 return;
1790 }
1791 case DeclarationName::CXXLiteralOperatorName: {
1792 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1793 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1794 return;
1795 }
1796 case DeclarationName::CXXConstructorName:
1797 case DeclarationName::CXXDestructorName:
1798 case DeclarationName::CXXConversionFunctionName: {
1799 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1800 To.setNamedTypeInfo(Importer.Import(FromTInfo));
1801 return;
1802 }
1803 }
1804 llvm_unreachable("Unknown name kind.");
1805 }
1806
ImportDeclContext(DeclContext * FromDC,bool ForceImport)1807 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1808 if (Importer.isMinimalImport() && !ForceImport) {
1809 Importer.ImportContext(FromDC);
1810 return;
1811 }
1812
1813 for (DeclContext::decl_iterator From = FromDC->decls_begin(),
1814 FromEnd = FromDC->decls_end();
1815 From != FromEnd;
1816 ++From)
1817 Importer.Import(*From);
1818 }
1819
ImportDefinition(RecordDecl * From,RecordDecl * To,ImportDefinitionKind Kind)1820 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1821 ImportDefinitionKind Kind) {
1822 if (To->getDefinition() || To->isBeingDefined()) {
1823 if (Kind == IDK_Everything)
1824 ImportDeclContext(From, /*ForceImport=*/true);
1825
1826 return false;
1827 }
1828
1829 To->startDefinition();
1830
1831 // Add base classes.
1832 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1833 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1834
1835 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1836 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1837 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1838 ToData.UserDeclaredCopyConstructor = FromData.UserDeclaredCopyConstructor;
1839 ToData.UserDeclaredMoveConstructor = FromData.UserDeclaredMoveConstructor;
1840 ToData.UserDeclaredCopyAssignment = FromData.UserDeclaredCopyAssignment;
1841 ToData.UserDeclaredMoveAssignment = FromData.UserDeclaredMoveAssignment;
1842 ToData.UserDeclaredDestructor = FromData.UserDeclaredDestructor;
1843 ToData.Aggregate = FromData.Aggregate;
1844 ToData.PlainOldData = FromData.PlainOldData;
1845 ToData.Empty = FromData.Empty;
1846 ToData.Polymorphic = FromData.Polymorphic;
1847 ToData.Abstract = FromData.Abstract;
1848 ToData.IsStandardLayout = FromData.IsStandardLayout;
1849 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
1850 ToData.HasPrivateFields = FromData.HasPrivateFields;
1851 ToData.HasProtectedFields = FromData.HasProtectedFields;
1852 ToData.HasPublicFields = FromData.HasPublicFields;
1853 ToData.HasMutableFields = FromData.HasMutableFields;
1854 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1855 ToData.HasTrivialDefaultConstructor = FromData.HasTrivialDefaultConstructor;
1856 ToData.HasConstexprNonCopyMoveConstructor
1857 = FromData.HasConstexprNonCopyMoveConstructor;
1858 ToData.DefaultedDefaultConstructorIsConstexpr
1859 = FromData.DefaultedDefaultConstructorIsConstexpr;
1860 ToData.DefaultedCopyConstructorIsConstexpr
1861 = FromData.DefaultedCopyConstructorIsConstexpr;
1862 ToData.DefaultedMoveConstructorIsConstexpr
1863 = FromData.DefaultedMoveConstructorIsConstexpr;
1864 ToData.HasConstexprDefaultConstructor
1865 = FromData.HasConstexprDefaultConstructor;
1866 ToData.HasConstexprCopyConstructor = FromData.HasConstexprCopyConstructor;
1867 ToData.HasConstexprMoveConstructor = FromData.HasConstexprMoveConstructor;
1868 ToData.HasTrivialCopyConstructor = FromData.HasTrivialCopyConstructor;
1869 ToData.HasTrivialMoveConstructor = FromData.HasTrivialMoveConstructor;
1870 ToData.HasTrivialCopyAssignment = FromData.HasTrivialCopyAssignment;
1871 ToData.HasTrivialMoveAssignment = FromData.HasTrivialMoveAssignment;
1872 ToData.HasTrivialDestructor = FromData.HasTrivialDestructor;
1873 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1874 ToData.HasNonLiteralTypeFieldsOrBases
1875 = FromData.HasNonLiteralTypeFieldsOrBases;
1876 // ComputedVisibleConversions not imported.
1877 ToData.UserProvidedDefaultConstructor
1878 = FromData.UserProvidedDefaultConstructor;
1879 ToData.DeclaredDefaultConstructor = FromData.DeclaredDefaultConstructor;
1880 ToData.DeclaredCopyConstructor = FromData.DeclaredCopyConstructor;
1881 ToData.DeclaredMoveConstructor = FromData.DeclaredMoveConstructor;
1882 ToData.DeclaredCopyAssignment = FromData.DeclaredCopyAssignment;
1883 ToData.DeclaredMoveAssignment = FromData.DeclaredMoveAssignment;
1884 ToData.DeclaredDestructor = FromData.DeclaredDestructor;
1885 ToData.FailedImplicitMoveConstructor
1886 = FromData.FailedImplicitMoveConstructor;
1887 ToData.FailedImplicitMoveAssignment = FromData.FailedImplicitMoveAssignment;
1888 ToData.IsLambda = FromData.IsLambda;
1889
1890 SmallVector<CXXBaseSpecifier *, 4> Bases;
1891 for (CXXRecordDecl::base_class_iterator
1892 Base1 = FromCXX->bases_begin(),
1893 FromBaseEnd = FromCXX->bases_end();
1894 Base1 != FromBaseEnd;
1895 ++Base1) {
1896 QualType T = Importer.Import(Base1->getType());
1897 if (T.isNull())
1898 return true;
1899
1900 SourceLocation EllipsisLoc;
1901 if (Base1->isPackExpansion())
1902 EllipsisLoc = Importer.Import(Base1->getEllipsisLoc());
1903
1904 // Ensure that we have a definition for the base.
1905 ImportDefinitionIfNeeded(Base1->getType()->getAsCXXRecordDecl());
1906
1907 Bases.push_back(
1908 new (Importer.getToContext())
1909 CXXBaseSpecifier(Importer.Import(Base1->getSourceRange()),
1910 Base1->isVirtual(),
1911 Base1->isBaseOfClass(),
1912 Base1->getAccessSpecifierAsWritten(),
1913 Importer.Import(Base1->getTypeSourceInfo()),
1914 EllipsisLoc));
1915 }
1916 if (!Bases.empty())
1917 ToCXX->setBases(Bases.data(), Bases.size());
1918 }
1919
1920 if (shouldForceImportDeclContext(Kind))
1921 ImportDeclContext(From, /*ForceImport=*/true);
1922
1923 To->completeDefinition();
1924 return false;
1925 }
1926
ImportDefinition(EnumDecl * From,EnumDecl * To,ImportDefinitionKind Kind)1927 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
1928 ImportDefinitionKind Kind) {
1929 if (To->getDefinition() || To->isBeingDefined()) {
1930 if (Kind == IDK_Everything)
1931 ImportDeclContext(From, /*ForceImport=*/true);
1932 return false;
1933 }
1934
1935 To->startDefinition();
1936
1937 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
1938 if (T.isNull())
1939 return true;
1940
1941 QualType ToPromotionType = Importer.Import(From->getPromotionType());
1942 if (ToPromotionType.isNull())
1943 return true;
1944
1945 if (shouldForceImportDeclContext(Kind))
1946 ImportDeclContext(From, /*ForceImport=*/true);
1947
1948 // FIXME: we might need to merge the number of positive or negative bits
1949 // if the enumerator lists don't match.
1950 To->completeDefinition(T, ToPromotionType,
1951 From->getNumPositiveBits(),
1952 From->getNumNegativeBits());
1953 return false;
1954 }
1955
ImportTemplateParameterList(TemplateParameterList * Params)1956 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
1957 TemplateParameterList *Params) {
1958 SmallVector<NamedDecl *, 4> ToParams;
1959 ToParams.reserve(Params->size());
1960 for (TemplateParameterList::iterator P = Params->begin(),
1961 PEnd = Params->end();
1962 P != PEnd; ++P) {
1963 Decl *To = Importer.Import(*P);
1964 if (!To)
1965 return 0;
1966
1967 ToParams.push_back(cast<NamedDecl>(To));
1968 }
1969
1970 return TemplateParameterList::Create(Importer.getToContext(),
1971 Importer.Import(Params->getTemplateLoc()),
1972 Importer.Import(Params->getLAngleLoc()),
1973 ToParams.data(), ToParams.size(),
1974 Importer.Import(Params->getRAngleLoc()));
1975 }
1976
1977 TemplateArgument
ImportTemplateArgument(const TemplateArgument & From)1978 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1979 switch (From.getKind()) {
1980 case TemplateArgument::Null:
1981 return TemplateArgument();
1982
1983 case TemplateArgument::Type: {
1984 QualType ToType = Importer.Import(From.getAsType());
1985 if (ToType.isNull())
1986 return TemplateArgument();
1987 return TemplateArgument(ToType);
1988 }
1989
1990 case TemplateArgument::Integral: {
1991 QualType ToType = Importer.Import(From.getIntegralType());
1992 if (ToType.isNull())
1993 return TemplateArgument();
1994 return TemplateArgument(*From.getAsIntegral(), ToType);
1995 }
1996
1997 case TemplateArgument::Declaration:
1998 if (Decl *To = Importer.Import(From.getAsDecl()))
1999 return TemplateArgument(To);
2000 return TemplateArgument();
2001
2002 case TemplateArgument::Template: {
2003 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2004 if (ToTemplate.isNull())
2005 return TemplateArgument();
2006
2007 return TemplateArgument(ToTemplate);
2008 }
2009
2010 case TemplateArgument::TemplateExpansion: {
2011 TemplateName ToTemplate
2012 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2013 if (ToTemplate.isNull())
2014 return TemplateArgument();
2015
2016 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2017 }
2018
2019 case TemplateArgument::Expression:
2020 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2021 return TemplateArgument(ToExpr);
2022 return TemplateArgument();
2023
2024 case TemplateArgument::Pack: {
2025 SmallVector<TemplateArgument, 2> ToPack;
2026 ToPack.reserve(From.pack_size());
2027 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2028 return TemplateArgument();
2029
2030 TemplateArgument *ToArgs
2031 = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
2032 std::copy(ToPack.begin(), ToPack.end(), ToArgs);
2033 return TemplateArgument(ToArgs, ToPack.size());
2034 }
2035 }
2036
2037 llvm_unreachable("Invalid template argument kind");
2038 }
2039
ImportTemplateArguments(const TemplateArgument * FromArgs,unsigned NumFromArgs,SmallVectorImpl<TemplateArgument> & ToArgs)2040 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2041 unsigned NumFromArgs,
2042 SmallVectorImpl<TemplateArgument> &ToArgs) {
2043 for (unsigned I = 0; I != NumFromArgs; ++I) {
2044 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2045 if (To.isNull() && !FromArgs[I].isNull())
2046 return true;
2047
2048 ToArgs.push_back(To);
2049 }
2050
2051 return false;
2052 }
2053
IsStructuralMatch(RecordDecl * FromRecord,RecordDecl * ToRecord)2054 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2055 RecordDecl *ToRecord) {
2056 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2057 Importer.getToContext(),
2058 Importer.getNonEquivalentDecls());
2059 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2060 }
2061
IsStructuralMatch(EnumDecl * FromEnum,EnumDecl * ToEnum)2062 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2063 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2064 Importer.getToContext(),
2065 Importer.getNonEquivalentDecls());
2066 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2067 }
2068
IsStructuralMatch(ClassTemplateDecl * From,ClassTemplateDecl * To)2069 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2070 ClassTemplateDecl *To) {
2071 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2072 Importer.getToContext(),
2073 Importer.getNonEquivalentDecls());
2074 return Ctx.IsStructurallyEquivalent(From, To);
2075 }
2076
VisitDecl(Decl * D)2077 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2078 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2079 << D->getDeclKindName();
2080 return 0;
2081 }
2082
VisitTranslationUnitDecl(TranslationUnitDecl * D)2083 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2084 TranslationUnitDecl *ToD =
2085 Importer.getToContext().getTranslationUnitDecl();
2086
2087 Importer.Imported(D, ToD);
2088
2089 return ToD;
2090 }
2091
VisitNamespaceDecl(NamespaceDecl * D)2092 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2093 // Import the major distinguishing characteristics of this namespace.
2094 DeclContext *DC, *LexicalDC;
2095 DeclarationName Name;
2096 SourceLocation Loc;
2097 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2098 return 0;
2099
2100 NamespaceDecl *MergeWithNamespace = 0;
2101 if (!Name) {
2102 // This is an anonymous namespace. Adopt an existing anonymous
2103 // namespace if we can.
2104 // FIXME: Not testable.
2105 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2106 MergeWithNamespace = TU->getAnonymousNamespace();
2107 else
2108 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2109 } else {
2110 SmallVector<NamedDecl *, 4> ConflictingDecls;
2111 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2112 DC->localUncachedLookup(Name, FoundDecls);
2113 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2114 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2115 continue;
2116
2117 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2118 MergeWithNamespace = FoundNS;
2119 ConflictingDecls.clear();
2120 break;
2121 }
2122
2123 ConflictingDecls.push_back(FoundDecls[I]);
2124 }
2125
2126 if (!ConflictingDecls.empty()) {
2127 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2128 ConflictingDecls.data(),
2129 ConflictingDecls.size());
2130 }
2131 }
2132
2133 // Create the "to" namespace, if needed.
2134 NamespaceDecl *ToNamespace = MergeWithNamespace;
2135 if (!ToNamespace) {
2136 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2137 D->isInline(),
2138 Importer.Import(D->getLocStart()),
2139 Loc, Name.getAsIdentifierInfo(),
2140 /*PrevDecl=*/0);
2141 ToNamespace->setLexicalDeclContext(LexicalDC);
2142 LexicalDC->addDeclInternal(ToNamespace);
2143
2144 // If this is an anonymous namespace, register it as the anonymous
2145 // namespace within its context.
2146 if (!Name) {
2147 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2148 TU->setAnonymousNamespace(ToNamespace);
2149 else
2150 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2151 }
2152 }
2153 Importer.Imported(D, ToNamespace);
2154
2155 ImportDeclContext(D);
2156
2157 return ToNamespace;
2158 }
2159
VisitTypedefNameDecl(TypedefNameDecl * D,bool IsAlias)2160 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2161 // Import the major distinguishing characteristics of this typedef.
2162 DeclContext *DC, *LexicalDC;
2163 DeclarationName Name;
2164 SourceLocation Loc;
2165 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2166 return 0;
2167
2168 // If this typedef is not in block scope, determine whether we've
2169 // seen a typedef with the same name (that we can merge with) or any
2170 // other entity by that name (which name lookup could conflict with).
2171 if (!DC->isFunctionOrMethod()) {
2172 SmallVector<NamedDecl *, 4> ConflictingDecls;
2173 unsigned IDNS = Decl::IDNS_Ordinary;
2174 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2175 DC->localUncachedLookup(Name, FoundDecls);
2176 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2177 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2178 continue;
2179 if (TypedefNameDecl *FoundTypedef =
2180 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2181 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2182 FoundTypedef->getUnderlyingType()))
2183 return Importer.Imported(D, FoundTypedef);
2184 }
2185
2186 ConflictingDecls.push_back(FoundDecls[I]);
2187 }
2188
2189 if (!ConflictingDecls.empty()) {
2190 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2191 ConflictingDecls.data(),
2192 ConflictingDecls.size());
2193 if (!Name)
2194 return 0;
2195 }
2196 }
2197
2198 // Import the underlying type of this typedef;
2199 QualType T = Importer.Import(D->getUnderlyingType());
2200 if (T.isNull())
2201 return 0;
2202
2203 // Create the new typedef node.
2204 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2205 SourceLocation StartL = Importer.Import(D->getLocStart());
2206 TypedefNameDecl *ToTypedef;
2207 if (IsAlias)
2208 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2209 StartL, Loc,
2210 Name.getAsIdentifierInfo(),
2211 TInfo);
2212 else
2213 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2214 StartL, Loc,
2215 Name.getAsIdentifierInfo(),
2216 TInfo);
2217
2218 ToTypedef->setAccess(D->getAccess());
2219 ToTypedef->setLexicalDeclContext(LexicalDC);
2220 Importer.Imported(D, ToTypedef);
2221 LexicalDC->addDeclInternal(ToTypedef);
2222
2223 return ToTypedef;
2224 }
2225
VisitTypedefDecl(TypedefDecl * D)2226 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2227 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2228 }
2229
VisitTypeAliasDecl(TypeAliasDecl * D)2230 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2231 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2232 }
2233
VisitEnumDecl(EnumDecl * D)2234 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2235 // Import the major distinguishing characteristics of this enum.
2236 DeclContext *DC, *LexicalDC;
2237 DeclarationName Name;
2238 SourceLocation Loc;
2239 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2240 return 0;
2241
2242 // Figure out what enum name we're looking for.
2243 unsigned IDNS = Decl::IDNS_Tag;
2244 DeclarationName SearchName = Name;
2245 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2246 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2247 IDNS = Decl::IDNS_Ordinary;
2248 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2249 IDNS |= Decl::IDNS_Ordinary;
2250
2251 // We may already have an enum of the same name; try to find and match it.
2252 if (!DC->isFunctionOrMethod() && SearchName) {
2253 SmallVector<NamedDecl *, 4> ConflictingDecls;
2254 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2255 DC->localUncachedLookup(SearchName, FoundDecls);
2256 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2257 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2258 continue;
2259
2260 Decl *Found = FoundDecls[I];
2261 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2262 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2263 Found = Tag->getDecl();
2264 }
2265
2266 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2267 if (IsStructuralMatch(D, FoundEnum))
2268 return Importer.Imported(D, FoundEnum);
2269 }
2270
2271 ConflictingDecls.push_back(FoundDecls[I]);
2272 }
2273
2274 if (!ConflictingDecls.empty()) {
2275 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2276 ConflictingDecls.data(),
2277 ConflictingDecls.size());
2278 }
2279 }
2280
2281 // Create the enum declaration.
2282 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2283 Importer.Import(D->getLocStart()),
2284 Loc, Name.getAsIdentifierInfo(), 0,
2285 D->isScoped(), D->isScopedUsingClassTag(),
2286 D->isFixed());
2287 // Import the qualifier, if any.
2288 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2289 D2->setAccess(D->getAccess());
2290 D2->setLexicalDeclContext(LexicalDC);
2291 Importer.Imported(D, D2);
2292 LexicalDC->addDeclInternal(D2);
2293
2294 // Import the integer type.
2295 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2296 if (ToIntegerType.isNull())
2297 return 0;
2298 D2->setIntegerType(ToIntegerType);
2299
2300 // Import the definition
2301 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2302 return 0;
2303
2304 return D2;
2305 }
2306
VisitRecordDecl(RecordDecl * D)2307 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2308 // If this record has a definition in the translation unit we're coming from,
2309 // but this particular declaration is not that definition, import the
2310 // definition and map to that.
2311 TagDecl *Definition = D->getDefinition();
2312 if (Definition && Definition != D) {
2313 Decl *ImportedDef = Importer.Import(Definition);
2314 if (!ImportedDef)
2315 return 0;
2316
2317 return Importer.Imported(D, ImportedDef);
2318 }
2319
2320 // Import the major distinguishing characteristics of this record.
2321 DeclContext *DC, *LexicalDC;
2322 DeclarationName Name;
2323 SourceLocation Loc;
2324 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2325 return 0;
2326
2327 // Figure out what structure name we're looking for.
2328 unsigned IDNS = Decl::IDNS_Tag;
2329 DeclarationName SearchName = Name;
2330 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2331 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2332 IDNS = Decl::IDNS_Ordinary;
2333 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2334 IDNS |= Decl::IDNS_Ordinary;
2335
2336 // We may already have a record of the same name; try to find and match it.
2337 RecordDecl *AdoptDecl = 0;
2338 if (!DC->isFunctionOrMethod() && SearchName) {
2339 SmallVector<NamedDecl *, 4> ConflictingDecls;
2340 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2341 DC->localUncachedLookup(SearchName, FoundDecls);
2342 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2343 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2344 continue;
2345
2346 Decl *Found = FoundDecls[I];
2347 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2348 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2349 Found = Tag->getDecl();
2350 }
2351
2352 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2353 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2354 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
2355 // The record types structurally match, or the "from" translation
2356 // unit only had a forward declaration anyway; call it the same
2357 // function.
2358 // FIXME: For C++, we should also merge methods here.
2359 return Importer.Imported(D, FoundDef);
2360 }
2361 } else {
2362 // We have a forward declaration of this type, so adopt that forward
2363 // declaration rather than building a new one.
2364 AdoptDecl = FoundRecord;
2365 continue;
2366 }
2367 }
2368
2369 ConflictingDecls.push_back(FoundDecls[I]);
2370 }
2371
2372 if (!ConflictingDecls.empty()) {
2373 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2374 ConflictingDecls.data(),
2375 ConflictingDecls.size());
2376 }
2377 }
2378
2379 // Create the record declaration.
2380 RecordDecl *D2 = AdoptDecl;
2381 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2382 if (!D2) {
2383 if (isa<CXXRecordDecl>(D)) {
2384 CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2385 D->getTagKind(),
2386 DC, StartLoc, Loc,
2387 Name.getAsIdentifierInfo());
2388 D2 = D2CXX;
2389 D2->setAccess(D->getAccess());
2390 } else {
2391 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2392 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2393 }
2394
2395 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2396 D2->setLexicalDeclContext(LexicalDC);
2397 LexicalDC->addDeclInternal(D2);
2398 }
2399
2400 Importer.Imported(D, D2);
2401
2402 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2403 return 0;
2404
2405 return D2;
2406 }
2407
VisitEnumConstantDecl(EnumConstantDecl * D)2408 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2409 // Import the major distinguishing characteristics of this enumerator.
2410 DeclContext *DC, *LexicalDC;
2411 DeclarationName Name;
2412 SourceLocation Loc;
2413 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2414 return 0;
2415
2416 QualType T = Importer.Import(D->getType());
2417 if (T.isNull())
2418 return 0;
2419
2420 // Determine whether there are any other declarations with the same name and
2421 // in the same context.
2422 if (!LexicalDC->isFunctionOrMethod()) {
2423 SmallVector<NamedDecl *, 4> ConflictingDecls;
2424 unsigned IDNS = Decl::IDNS_Ordinary;
2425 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2426 DC->localUncachedLookup(Name, FoundDecls);
2427 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2428 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2429 continue;
2430
2431 ConflictingDecls.push_back(FoundDecls[I]);
2432 }
2433
2434 if (!ConflictingDecls.empty()) {
2435 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2436 ConflictingDecls.data(),
2437 ConflictingDecls.size());
2438 if (!Name)
2439 return 0;
2440 }
2441 }
2442
2443 Expr *Init = Importer.Import(D->getInitExpr());
2444 if (D->getInitExpr() && !Init)
2445 return 0;
2446
2447 EnumConstantDecl *ToEnumerator
2448 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2449 Name.getAsIdentifierInfo(), T,
2450 Init, D->getInitVal());
2451 ToEnumerator->setAccess(D->getAccess());
2452 ToEnumerator->setLexicalDeclContext(LexicalDC);
2453 Importer.Imported(D, ToEnumerator);
2454 LexicalDC->addDeclInternal(ToEnumerator);
2455 return ToEnumerator;
2456 }
2457
VisitFunctionDecl(FunctionDecl * D)2458 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2459 // Import the major distinguishing characteristics of this function.
2460 DeclContext *DC, *LexicalDC;
2461 DeclarationName Name;
2462 SourceLocation Loc;
2463 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2464 return 0;
2465
2466 // Try to find a function in our own ("to") context with the same name, same
2467 // type, and in the same context as the function we're importing.
2468 if (!LexicalDC->isFunctionOrMethod()) {
2469 SmallVector<NamedDecl *, 4> ConflictingDecls;
2470 unsigned IDNS = Decl::IDNS_Ordinary;
2471 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2472 DC->localUncachedLookup(Name, FoundDecls);
2473 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2474 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2475 continue;
2476
2477 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2478 if (isExternalLinkage(FoundFunction->getLinkage()) &&
2479 isExternalLinkage(D->getLinkage())) {
2480 if (Importer.IsStructurallyEquivalent(D->getType(),
2481 FoundFunction->getType())) {
2482 // FIXME: Actually try to merge the body and other attributes.
2483 return Importer.Imported(D, FoundFunction);
2484 }
2485
2486 // FIXME: Check for overloading more carefully, e.g., by boosting
2487 // Sema::IsOverload out to the AST library.
2488
2489 // Function overloading is okay in C++.
2490 if (Importer.getToContext().getLangOpts().CPlusPlus)
2491 continue;
2492
2493 // Complain about inconsistent function types.
2494 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2495 << Name << D->getType() << FoundFunction->getType();
2496 Importer.ToDiag(FoundFunction->getLocation(),
2497 diag::note_odr_value_here)
2498 << FoundFunction->getType();
2499 }
2500 }
2501
2502 ConflictingDecls.push_back(FoundDecls[I]);
2503 }
2504
2505 if (!ConflictingDecls.empty()) {
2506 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2507 ConflictingDecls.data(),
2508 ConflictingDecls.size());
2509 if (!Name)
2510 return 0;
2511 }
2512 }
2513
2514 DeclarationNameInfo NameInfo(Name, Loc);
2515 // Import additional name location/type info.
2516 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2517
2518 // Import the type.
2519 QualType T = Importer.Import(D->getType());
2520 if (T.isNull())
2521 return 0;
2522
2523 // Import the function parameters.
2524 SmallVector<ParmVarDecl *, 8> Parameters;
2525 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
2526 P != PEnd; ++P) {
2527 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*P));
2528 if (!ToP)
2529 return 0;
2530
2531 Parameters.push_back(ToP);
2532 }
2533
2534 // Create the imported function.
2535 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2536 FunctionDecl *ToFunction = 0;
2537 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2538 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2539 cast<CXXRecordDecl>(DC),
2540 D->getInnerLocStart(),
2541 NameInfo, T, TInfo,
2542 FromConstructor->isExplicit(),
2543 D->isInlineSpecified(),
2544 D->isImplicit(),
2545 D->isConstexpr());
2546 } else if (isa<CXXDestructorDecl>(D)) {
2547 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2548 cast<CXXRecordDecl>(DC),
2549 D->getInnerLocStart(),
2550 NameInfo, T, TInfo,
2551 D->isInlineSpecified(),
2552 D->isImplicit());
2553 } else if (CXXConversionDecl *FromConversion
2554 = dyn_cast<CXXConversionDecl>(D)) {
2555 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2556 cast<CXXRecordDecl>(DC),
2557 D->getInnerLocStart(),
2558 NameInfo, T, TInfo,
2559 D->isInlineSpecified(),
2560 FromConversion->isExplicit(),
2561 D->isConstexpr(),
2562 Importer.Import(D->getLocEnd()));
2563 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2564 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2565 cast<CXXRecordDecl>(DC),
2566 D->getInnerLocStart(),
2567 NameInfo, T, TInfo,
2568 Method->isStatic(),
2569 Method->getStorageClassAsWritten(),
2570 Method->isInlineSpecified(),
2571 D->isConstexpr(),
2572 Importer.Import(D->getLocEnd()));
2573 } else {
2574 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2575 D->getInnerLocStart(),
2576 NameInfo, T, TInfo, D->getStorageClass(),
2577 D->getStorageClassAsWritten(),
2578 D->isInlineSpecified(),
2579 D->hasWrittenPrototype(),
2580 D->isConstexpr());
2581 }
2582
2583 // Import the qualifier, if any.
2584 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2585 ToFunction->setAccess(D->getAccess());
2586 ToFunction->setLexicalDeclContext(LexicalDC);
2587 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2588 ToFunction->setTrivial(D->isTrivial());
2589 ToFunction->setPure(D->isPure());
2590 Importer.Imported(D, ToFunction);
2591
2592 // Set the parameters.
2593 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2594 Parameters[I]->setOwningFunction(ToFunction);
2595 ToFunction->addDeclInternal(Parameters[I]);
2596 }
2597 ToFunction->setParams(Parameters);
2598
2599 // FIXME: Other bits to merge?
2600
2601 // Add this function to the lexical context.
2602 LexicalDC->addDeclInternal(ToFunction);
2603
2604 return ToFunction;
2605 }
2606
VisitCXXMethodDecl(CXXMethodDecl * D)2607 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2608 return VisitFunctionDecl(D);
2609 }
2610
VisitCXXConstructorDecl(CXXConstructorDecl * D)2611 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2612 return VisitCXXMethodDecl(D);
2613 }
2614
VisitCXXDestructorDecl(CXXDestructorDecl * D)2615 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2616 return VisitCXXMethodDecl(D);
2617 }
2618
VisitCXXConversionDecl(CXXConversionDecl * D)2619 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2620 return VisitCXXMethodDecl(D);
2621 }
2622
VisitFieldDecl(FieldDecl * D)2623 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2624 // Import the major distinguishing characteristics of a variable.
2625 DeclContext *DC, *LexicalDC;
2626 DeclarationName Name;
2627 SourceLocation Loc;
2628 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2629 return 0;
2630
2631 // Determine whether we've already imported this field.
2632 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2633 DC->localUncachedLookup(Name, FoundDecls);
2634 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2635 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2636 if (Importer.IsStructurallyEquivalent(D->getType(),
2637 FoundField->getType())) {
2638 Importer.Imported(D, FoundField);
2639 return FoundField;
2640 }
2641
2642 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2643 << Name << D->getType() << FoundField->getType();
2644 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2645 << FoundField->getType();
2646 return 0;
2647 }
2648 }
2649
2650 // Import the type.
2651 QualType T = Importer.Import(D->getType());
2652 if (T.isNull())
2653 return 0;
2654
2655 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2656 Expr *BitWidth = Importer.Import(D->getBitWidth());
2657 if (!BitWidth && D->getBitWidth())
2658 return 0;
2659
2660 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2661 Importer.Import(D->getInnerLocStart()),
2662 Loc, Name.getAsIdentifierInfo(),
2663 T, TInfo, BitWidth, D->isMutable(),
2664 D->hasInClassInitializer());
2665 ToField->setAccess(D->getAccess());
2666 ToField->setLexicalDeclContext(LexicalDC);
2667 if (ToField->hasInClassInitializer())
2668 ToField->setInClassInitializer(D->getInClassInitializer());
2669 Importer.Imported(D, ToField);
2670 LexicalDC->addDeclInternal(ToField);
2671 return ToField;
2672 }
2673
VisitIndirectFieldDecl(IndirectFieldDecl * D)2674 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2675 // Import the major distinguishing characteristics of a variable.
2676 DeclContext *DC, *LexicalDC;
2677 DeclarationName Name;
2678 SourceLocation Loc;
2679 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2680 return 0;
2681
2682 // Determine whether we've already imported this field.
2683 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2684 DC->localUncachedLookup(Name, FoundDecls);
2685 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2686 if (IndirectFieldDecl *FoundField
2687 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2688 if (Importer.IsStructurallyEquivalent(D->getType(),
2689 FoundField->getType())) {
2690 Importer.Imported(D, FoundField);
2691 return FoundField;
2692 }
2693
2694 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2695 << Name << D->getType() << FoundField->getType();
2696 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2697 << FoundField->getType();
2698 return 0;
2699 }
2700 }
2701
2702 // Import the type.
2703 QualType T = Importer.Import(D->getType());
2704 if (T.isNull())
2705 return 0;
2706
2707 NamedDecl **NamedChain =
2708 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2709
2710 unsigned i = 0;
2711 for (IndirectFieldDecl::chain_iterator PI = D->chain_begin(),
2712 PE = D->chain_end(); PI != PE; ++PI) {
2713 Decl* D = Importer.Import(*PI);
2714 if (!D)
2715 return 0;
2716 NamedChain[i++] = cast<NamedDecl>(D);
2717 }
2718
2719 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2720 Importer.getToContext(), DC,
2721 Loc, Name.getAsIdentifierInfo(), T,
2722 NamedChain, D->getChainingSize());
2723 ToIndirectField->setAccess(D->getAccess());
2724 ToIndirectField->setLexicalDeclContext(LexicalDC);
2725 Importer.Imported(D, ToIndirectField);
2726 LexicalDC->addDeclInternal(ToIndirectField);
2727 return ToIndirectField;
2728 }
2729
VisitObjCIvarDecl(ObjCIvarDecl * D)2730 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2731 // Import the major distinguishing characteristics of an ivar.
2732 DeclContext *DC, *LexicalDC;
2733 DeclarationName Name;
2734 SourceLocation Loc;
2735 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2736 return 0;
2737
2738 // Determine whether we've already imported this ivar
2739 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2740 DC->localUncachedLookup(Name, FoundDecls);
2741 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2742 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
2743 if (Importer.IsStructurallyEquivalent(D->getType(),
2744 FoundIvar->getType())) {
2745 Importer.Imported(D, FoundIvar);
2746 return FoundIvar;
2747 }
2748
2749 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
2750 << Name << D->getType() << FoundIvar->getType();
2751 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
2752 << FoundIvar->getType();
2753 return 0;
2754 }
2755 }
2756
2757 // Import the type.
2758 QualType T = Importer.Import(D->getType());
2759 if (T.isNull())
2760 return 0;
2761
2762 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2763 Expr *BitWidth = Importer.Import(D->getBitWidth());
2764 if (!BitWidth && D->getBitWidth())
2765 return 0;
2766
2767 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
2768 cast<ObjCContainerDecl>(DC),
2769 Importer.Import(D->getInnerLocStart()),
2770 Loc, Name.getAsIdentifierInfo(),
2771 T, TInfo, D->getAccessControl(),
2772 BitWidth, D->getSynthesize());
2773 ToIvar->setLexicalDeclContext(LexicalDC);
2774 Importer.Imported(D, ToIvar);
2775 LexicalDC->addDeclInternal(ToIvar);
2776 return ToIvar;
2777
2778 }
2779
VisitVarDecl(VarDecl * D)2780 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
2781 // Import the major distinguishing characteristics of a variable.
2782 DeclContext *DC, *LexicalDC;
2783 DeclarationName Name;
2784 SourceLocation Loc;
2785 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2786 return 0;
2787
2788 // Try to find a variable in our own ("to") context with the same name and
2789 // in the same context as the variable we're importing.
2790 if (D->isFileVarDecl()) {
2791 VarDecl *MergeWithVar = 0;
2792 SmallVector<NamedDecl *, 4> ConflictingDecls;
2793 unsigned IDNS = Decl::IDNS_Ordinary;
2794 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2795 DC->localUncachedLookup(Name, FoundDecls);
2796 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2797 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2798 continue;
2799
2800 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
2801 // We have found a variable that we may need to merge with. Check it.
2802 if (isExternalLinkage(FoundVar->getLinkage()) &&
2803 isExternalLinkage(D->getLinkage())) {
2804 if (Importer.IsStructurallyEquivalent(D->getType(),
2805 FoundVar->getType())) {
2806 MergeWithVar = FoundVar;
2807 break;
2808 }
2809
2810 const ArrayType *FoundArray
2811 = Importer.getToContext().getAsArrayType(FoundVar->getType());
2812 const ArrayType *TArray
2813 = Importer.getToContext().getAsArrayType(D->getType());
2814 if (FoundArray && TArray) {
2815 if (isa<IncompleteArrayType>(FoundArray) &&
2816 isa<ConstantArrayType>(TArray)) {
2817 // Import the type.
2818 QualType T = Importer.Import(D->getType());
2819 if (T.isNull())
2820 return 0;
2821
2822 FoundVar->setType(T);
2823 MergeWithVar = FoundVar;
2824 break;
2825 } else if (isa<IncompleteArrayType>(TArray) &&
2826 isa<ConstantArrayType>(FoundArray)) {
2827 MergeWithVar = FoundVar;
2828 break;
2829 }
2830 }
2831
2832 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
2833 << Name << D->getType() << FoundVar->getType();
2834 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
2835 << FoundVar->getType();
2836 }
2837 }
2838
2839 ConflictingDecls.push_back(FoundDecls[I]);
2840 }
2841
2842 if (MergeWithVar) {
2843 // An equivalent variable with external linkage has been found. Link
2844 // the two declarations, then merge them.
2845 Importer.Imported(D, MergeWithVar);
2846
2847 if (VarDecl *DDef = D->getDefinition()) {
2848 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
2849 Importer.ToDiag(ExistingDef->getLocation(),
2850 diag::err_odr_variable_multiple_def)
2851 << Name;
2852 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
2853 } else {
2854 Expr *Init = Importer.Import(DDef->getInit());
2855 MergeWithVar->setInit(Init);
2856 if (DDef->isInitKnownICE()) {
2857 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
2858 Eval->CheckedICE = true;
2859 Eval->IsICE = DDef->isInitICE();
2860 }
2861 }
2862 }
2863
2864 return MergeWithVar;
2865 }
2866
2867 if (!ConflictingDecls.empty()) {
2868 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2869 ConflictingDecls.data(),
2870 ConflictingDecls.size());
2871 if (!Name)
2872 return 0;
2873 }
2874 }
2875
2876 // Import the type.
2877 QualType T = Importer.Import(D->getType());
2878 if (T.isNull())
2879 return 0;
2880
2881 // Create the imported variable.
2882 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2883 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
2884 Importer.Import(D->getInnerLocStart()),
2885 Loc, Name.getAsIdentifierInfo(),
2886 T, TInfo,
2887 D->getStorageClass(),
2888 D->getStorageClassAsWritten());
2889 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2890 ToVar->setAccess(D->getAccess());
2891 ToVar->setLexicalDeclContext(LexicalDC);
2892 Importer.Imported(D, ToVar);
2893 LexicalDC->addDeclInternal(ToVar);
2894
2895 // Merge the initializer.
2896 // FIXME: Can we really import any initializer? Alternatively, we could force
2897 // ourselves to import every declaration of a variable and then only use
2898 // getInit() here.
2899 ToVar->setInit(Importer.Import(const_cast<Expr *>(D->getAnyInitializer())));
2900
2901 // FIXME: Other bits to merge?
2902
2903 return ToVar;
2904 }
2905
VisitImplicitParamDecl(ImplicitParamDecl * D)2906 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
2907 // Parameters are created in the translation unit's context, then moved
2908 // into the function declaration's context afterward.
2909 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2910
2911 // Import the name of this declaration.
2912 DeclarationName Name = Importer.Import(D->getDeclName());
2913 if (D->getDeclName() && !Name)
2914 return 0;
2915
2916 // Import the location of this declaration.
2917 SourceLocation Loc = Importer.Import(D->getLocation());
2918
2919 // Import the parameter's type.
2920 QualType T = Importer.Import(D->getType());
2921 if (T.isNull())
2922 return 0;
2923
2924 // Create the imported parameter.
2925 ImplicitParamDecl *ToParm
2926 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
2927 Loc, Name.getAsIdentifierInfo(),
2928 T);
2929 return Importer.Imported(D, ToParm);
2930 }
2931
VisitParmVarDecl(ParmVarDecl * D)2932 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
2933 // Parameters are created in the translation unit's context, then moved
2934 // into the function declaration's context afterward.
2935 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2936
2937 // Import the name of this declaration.
2938 DeclarationName Name = Importer.Import(D->getDeclName());
2939 if (D->getDeclName() && !Name)
2940 return 0;
2941
2942 // Import the location of this declaration.
2943 SourceLocation Loc = Importer.Import(D->getLocation());
2944
2945 // Import the parameter's type.
2946 QualType T = Importer.Import(D->getType());
2947 if (T.isNull())
2948 return 0;
2949
2950 // Create the imported parameter.
2951 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2952 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
2953 Importer.Import(D->getInnerLocStart()),
2954 Loc, Name.getAsIdentifierInfo(),
2955 T, TInfo, D->getStorageClass(),
2956 D->getStorageClassAsWritten(),
2957 /*FIXME: Default argument*/ 0);
2958 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
2959 return Importer.Imported(D, ToParm);
2960 }
2961
VisitObjCMethodDecl(ObjCMethodDecl * D)2962 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
2963 // Import the major distinguishing characteristics of a method.
2964 DeclContext *DC, *LexicalDC;
2965 DeclarationName Name;
2966 SourceLocation Loc;
2967 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2968 return 0;
2969
2970 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
2971 DC->localUncachedLookup(Name, FoundDecls);
2972 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2973 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
2974 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
2975 continue;
2976
2977 // Check return types.
2978 if (!Importer.IsStructurallyEquivalent(D->getResultType(),
2979 FoundMethod->getResultType())) {
2980 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
2981 << D->isInstanceMethod() << Name
2982 << D->getResultType() << FoundMethod->getResultType();
2983 Importer.ToDiag(FoundMethod->getLocation(),
2984 diag::note_odr_objc_method_here)
2985 << D->isInstanceMethod() << Name;
2986 return 0;
2987 }
2988
2989 // Check the number of parameters.
2990 if (D->param_size() != FoundMethod->param_size()) {
2991 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
2992 << D->isInstanceMethod() << Name
2993 << D->param_size() << FoundMethod->param_size();
2994 Importer.ToDiag(FoundMethod->getLocation(),
2995 diag::note_odr_objc_method_here)
2996 << D->isInstanceMethod() << Name;
2997 return 0;
2998 }
2999
3000 // Check parameter types.
3001 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3002 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3003 P != PEnd; ++P, ++FoundP) {
3004 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3005 (*FoundP)->getType())) {
3006 Importer.FromDiag((*P)->getLocation(),
3007 diag::err_odr_objc_method_param_type_inconsistent)
3008 << D->isInstanceMethod() << Name
3009 << (*P)->getType() << (*FoundP)->getType();
3010 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3011 << (*FoundP)->getType();
3012 return 0;
3013 }
3014 }
3015
3016 // Check variadic/non-variadic.
3017 // Check the number of parameters.
3018 if (D->isVariadic() != FoundMethod->isVariadic()) {
3019 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3020 << D->isInstanceMethod() << Name;
3021 Importer.ToDiag(FoundMethod->getLocation(),
3022 diag::note_odr_objc_method_here)
3023 << D->isInstanceMethod() << Name;
3024 return 0;
3025 }
3026
3027 // FIXME: Any other bits we need to merge?
3028 return Importer.Imported(D, FoundMethod);
3029 }
3030 }
3031
3032 // Import the result type.
3033 QualType ResultTy = Importer.Import(D->getResultType());
3034 if (ResultTy.isNull())
3035 return 0;
3036
3037 TypeSourceInfo *ResultTInfo = Importer.Import(D->getResultTypeSourceInfo());
3038
3039 ObjCMethodDecl *ToMethod
3040 = ObjCMethodDecl::Create(Importer.getToContext(),
3041 Loc,
3042 Importer.Import(D->getLocEnd()),
3043 Name.getObjCSelector(),
3044 ResultTy, ResultTInfo, DC,
3045 D->isInstanceMethod(),
3046 D->isVariadic(),
3047 D->isSynthesized(),
3048 D->isImplicit(),
3049 D->isDefined(),
3050 D->getImplementationControl(),
3051 D->hasRelatedResultType());
3052
3053 // FIXME: When we decide to merge method definitions, we'll need to
3054 // deal with implicit parameters.
3055
3056 // Import the parameters
3057 SmallVector<ParmVarDecl *, 5> ToParams;
3058 for (ObjCMethodDecl::param_iterator FromP = D->param_begin(),
3059 FromPEnd = D->param_end();
3060 FromP != FromPEnd;
3061 ++FromP) {
3062 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*FromP));
3063 if (!ToP)
3064 return 0;
3065
3066 ToParams.push_back(ToP);
3067 }
3068
3069 // Set the parameters.
3070 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3071 ToParams[I]->setOwningFunction(ToMethod);
3072 ToMethod->addDeclInternal(ToParams[I]);
3073 }
3074 SmallVector<SourceLocation, 12> SelLocs;
3075 D->getSelectorLocs(SelLocs);
3076 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3077
3078 ToMethod->setLexicalDeclContext(LexicalDC);
3079 Importer.Imported(D, ToMethod);
3080 LexicalDC->addDeclInternal(ToMethod);
3081 return ToMethod;
3082 }
3083
VisitObjCCategoryDecl(ObjCCategoryDecl * D)3084 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3085 // Import the major distinguishing characteristics of a category.
3086 DeclContext *DC, *LexicalDC;
3087 DeclarationName Name;
3088 SourceLocation Loc;
3089 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3090 return 0;
3091
3092 ObjCInterfaceDecl *ToInterface
3093 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3094 if (!ToInterface)
3095 return 0;
3096
3097 // Determine if we've already encountered this category.
3098 ObjCCategoryDecl *MergeWithCategory
3099 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3100 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3101 if (!ToCategory) {
3102 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3103 Importer.Import(D->getAtStartLoc()),
3104 Loc,
3105 Importer.Import(D->getCategoryNameLoc()),
3106 Name.getAsIdentifierInfo(),
3107 ToInterface,
3108 Importer.Import(D->getIvarLBraceLoc()),
3109 Importer.Import(D->getIvarRBraceLoc()));
3110 ToCategory->setLexicalDeclContext(LexicalDC);
3111 LexicalDC->addDeclInternal(ToCategory);
3112 Importer.Imported(D, ToCategory);
3113
3114 // Import protocols
3115 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3116 SmallVector<SourceLocation, 4> ProtocolLocs;
3117 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3118 = D->protocol_loc_begin();
3119 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3120 FromProtoEnd = D->protocol_end();
3121 FromProto != FromProtoEnd;
3122 ++FromProto, ++FromProtoLoc) {
3123 ObjCProtocolDecl *ToProto
3124 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3125 if (!ToProto)
3126 return 0;
3127 Protocols.push_back(ToProto);
3128 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3129 }
3130
3131 // FIXME: If we're merging, make sure that the protocol list is the same.
3132 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3133 ProtocolLocs.data(), Importer.getToContext());
3134
3135 } else {
3136 Importer.Imported(D, ToCategory);
3137 }
3138
3139 // Import all of the members of this category.
3140 ImportDeclContext(D);
3141
3142 // If we have an implementation, import it as well.
3143 if (D->getImplementation()) {
3144 ObjCCategoryImplDecl *Impl
3145 = cast_or_null<ObjCCategoryImplDecl>(
3146 Importer.Import(D->getImplementation()));
3147 if (!Impl)
3148 return 0;
3149
3150 ToCategory->setImplementation(Impl);
3151 }
3152
3153 return ToCategory;
3154 }
3155
ImportDefinition(ObjCProtocolDecl * From,ObjCProtocolDecl * To,ImportDefinitionKind Kind)3156 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3157 ObjCProtocolDecl *To,
3158 ImportDefinitionKind Kind) {
3159 if (To->getDefinition()) {
3160 if (shouldForceImportDeclContext(Kind))
3161 ImportDeclContext(From);
3162 return false;
3163 }
3164
3165 // Start the protocol definition
3166 To->startDefinition();
3167
3168 // Import protocols
3169 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3170 SmallVector<SourceLocation, 4> ProtocolLocs;
3171 ObjCProtocolDecl::protocol_loc_iterator
3172 FromProtoLoc = From->protocol_loc_begin();
3173 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3174 FromProtoEnd = From->protocol_end();
3175 FromProto != FromProtoEnd;
3176 ++FromProto, ++FromProtoLoc) {
3177 ObjCProtocolDecl *ToProto
3178 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3179 if (!ToProto)
3180 return true;
3181 Protocols.push_back(ToProto);
3182 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3183 }
3184
3185 // FIXME: If we're merging, make sure that the protocol list is the same.
3186 To->setProtocolList(Protocols.data(), Protocols.size(),
3187 ProtocolLocs.data(), Importer.getToContext());
3188
3189 if (shouldForceImportDeclContext(Kind)) {
3190 // Import all of the members of this protocol.
3191 ImportDeclContext(From, /*ForceImport=*/true);
3192 }
3193 return false;
3194 }
3195
VisitObjCProtocolDecl(ObjCProtocolDecl * D)3196 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3197 // If this protocol has a definition in the translation unit we're coming
3198 // from, but this particular declaration is not that definition, import the
3199 // definition and map to that.
3200 ObjCProtocolDecl *Definition = D->getDefinition();
3201 if (Definition && Definition != D) {
3202 Decl *ImportedDef = Importer.Import(Definition);
3203 if (!ImportedDef)
3204 return 0;
3205
3206 return Importer.Imported(D, ImportedDef);
3207 }
3208
3209 // Import the major distinguishing characteristics of a protocol.
3210 DeclContext *DC, *LexicalDC;
3211 DeclarationName Name;
3212 SourceLocation Loc;
3213 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3214 return 0;
3215
3216 ObjCProtocolDecl *MergeWithProtocol = 0;
3217 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
3218 DC->localUncachedLookup(Name, FoundDecls);
3219 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3220 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3221 continue;
3222
3223 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3224 break;
3225 }
3226
3227 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3228 if (!ToProto) {
3229 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3230 Name.getAsIdentifierInfo(), Loc,
3231 Importer.Import(D->getAtStartLoc()),
3232 /*PrevDecl=*/0);
3233 ToProto->setLexicalDeclContext(LexicalDC);
3234 LexicalDC->addDeclInternal(ToProto);
3235 }
3236
3237 Importer.Imported(D, ToProto);
3238
3239 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3240 return 0;
3241
3242 return ToProto;
3243 }
3244
ImportDefinition(ObjCInterfaceDecl * From,ObjCInterfaceDecl * To,ImportDefinitionKind Kind)3245 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3246 ObjCInterfaceDecl *To,
3247 ImportDefinitionKind Kind) {
3248 if (To->getDefinition()) {
3249 // Check consistency of superclass.
3250 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3251 if (FromSuper) {
3252 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3253 if (!FromSuper)
3254 return true;
3255 }
3256
3257 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3258 if ((bool)FromSuper != (bool)ToSuper ||
3259 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3260 Importer.ToDiag(To->getLocation(),
3261 diag::err_odr_objc_superclass_inconsistent)
3262 << To->getDeclName();
3263 if (ToSuper)
3264 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3265 << To->getSuperClass()->getDeclName();
3266 else
3267 Importer.ToDiag(To->getLocation(),
3268 diag::note_odr_objc_missing_superclass);
3269 if (From->getSuperClass())
3270 Importer.FromDiag(From->getSuperClassLoc(),
3271 diag::note_odr_objc_superclass)
3272 << From->getSuperClass()->getDeclName();
3273 else
3274 Importer.FromDiag(From->getLocation(),
3275 diag::note_odr_objc_missing_superclass);
3276 }
3277
3278 if (shouldForceImportDeclContext(Kind))
3279 ImportDeclContext(From);
3280 return false;
3281 }
3282
3283 // Start the definition.
3284 To->startDefinition();
3285
3286 // If this class has a superclass, import it.
3287 if (From->getSuperClass()) {
3288 ObjCInterfaceDecl *Super = cast_or_null<ObjCInterfaceDecl>(
3289 Importer.Import(From->getSuperClass()));
3290 if (!Super)
3291 return true;
3292
3293 To->setSuperClass(Super);
3294 To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
3295 }
3296
3297 // Import protocols
3298 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3299 SmallVector<SourceLocation, 4> ProtocolLocs;
3300 ObjCInterfaceDecl::protocol_loc_iterator
3301 FromProtoLoc = From->protocol_loc_begin();
3302
3303 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3304 FromProtoEnd = From->protocol_end();
3305 FromProto != FromProtoEnd;
3306 ++FromProto, ++FromProtoLoc) {
3307 ObjCProtocolDecl *ToProto
3308 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3309 if (!ToProto)
3310 return true;
3311 Protocols.push_back(ToProto);
3312 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3313 }
3314
3315 // FIXME: If we're merging, make sure that the protocol list is the same.
3316 To->setProtocolList(Protocols.data(), Protocols.size(),
3317 ProtocolLocs.data(), Importer.getToContext());
3318
3319 // Import categories. When the categories themselves are imported, they'll
3320 // hook themselves into this interface.
3321 for (ObjCCategoryDecl *FromCat = From->getCategoryList(); FromCat;
3322 FromCat = FromCat->getNextClassCategory())
3323 Importer.Import(FromCat);
3324
3325 // If we have an @implementation, import it as well.
3326 if (From->getImplementation()) {
3327 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3328 Importer.Import(From->getImplementation()));
3329 if (!Impl)
3330 return true;
3331
3332 To->setImplementation(Impl);
3333 }
3334
3335 if (shouldForceImportDeclContext(Kind)) {
3336 // Import all of the members of this class.
3337 ImportDeclContext(From, /*ForceImport=*/true);
3338 }
3339 return false;
3340 }
3341
VisitObjCInterfaceDecl(ObjCInterfaceDecl * D)3342 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3343 // If this class has a definition in the translation unit we're coming from,
3344 // but this particular declaration is not that definition, import the
3345 // definition and map to that.
3346 ObjCInterfaceDecl *Definition = D->getDefinition();
3347 if (Definition && Definition != D) {
3348 Decl *ImportedDef = Importer.Import(Definition);
3349 if (!ImportedDef)
3350 return 0;
3351
3352 return Importer.Imported(D, ImportedDef);
3353 }
3354
3355 // Import the major distinguishing characteristics of an @interface.
3356 DeclContext *DC, *LexicalDC;
3357 DeclarationName Name;
3358 SourceLocation Loc;
3359 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3360 return 0;
3361
3362 // Look for an existing interface with the same name.
3363 ObjCInterfaceDecl *MergeWithIface = 0;
3364 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
3365 DC->localUncachedLookup(Name, FoundDecls);
3366 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3367 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3368 continue;
3369
3370 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3371 break;
3372 }
3373
3374 // Create an interface declaration, if one does not already exist.
3375 ObjCInterfaceDecl *ToIface = MergeWithIface;
3376 if (!ToIface) {
3377 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3378 Importer.Import(D->getAtStartLoc()),
3379 Name.getAsIdentifierInfo(),
3380 /*PrevDecl=*/0,Loc,
3381 D->isImplicitInterfaceDecl());
3382 ToIface->setLexicalDeclContext(LexicalDC);
3383 LexicalDC->addDeclInternal(ToIface);
3384 }
3385 Importer.Imported(D, ToIface);
3386
3387 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3388 return 0;
3389
3390 return ToIface;
3391 }
3392
VisitObjCCategoryImplDecl(ObjCCategoryImplDecl * D)3393 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3394 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3395 Importer.Import(D->getCategoryDecl()));
3396 if (!Category)
3397 return 0;
3398
3399 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3400 if (!ToImpl) {
3401 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3402 if (!DC)
3403 return 0;
3404
3405 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3406 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3407 Importer.Import(D->getIdentifier()),
3408 Category->getClassInterface(),
3409 Importer.Import(D->getLocation()),
3410 Importer.Import(D->getAtStartLoc()),
3411 CategoryNameLoc);
3412
3413 DeclContext *LexicalDC = DC;
3414 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3415 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3416 if (!LexicalDC)
3417 return 0;
3418
3419 ToImpl->setLexicalDeclContext(LexicalDC);
3420 }
3421
3422 LexicalDC->addDeclInternal(ToImpl);
3423 Category->setImplementation(ToImpl);
3424 }
3425
3426 Importer.Imported(D, ToImpl);
3427 ImportDeclContext(D);
3428 return ToImpl;
3429 }
3430
VisitObjCImplementationDecl(ObjCImplementationDecl * D)3431 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3432 // Find the corresponding interface.
3433 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3434 Importer.Import(D->getClassInterface()));
3435 if (!Iface)
3436 return 0;
3437
3438 // Import the superclass, if any.
3439 ObjCInterfaceDecl *Super = 0;
3440 if (D->getSuperClass()) {
3441 Super = cast_or_null<ObjCInterfaceDecl>(
3442 Importer.Import(D->getSuperClass()));
3443 if (!Super)
3444 return 0;
3445 }
3446
3447 ObjCImplementationDecl *Impl = Iface->getImplementation();
3448 if (!Impl) {
3449 // We haven't imported an implementation yet. Create a new @implementation
3450 // now.
3451 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3452 Importer.ImportContext(D->getDeclContext()),
3453 Iface, Super,
3454 Importer.Import(D->getLocation()),
3455 Importer.Import(D->getAtStartLoc()),
3456 Importer.Import(D->getIvarLBraceLoc()),
3457 Importer.Import(D->getIvarRBraceLoc()));
3458
3459 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3460 DeclContext *LexicalDC
3461 = Importer.ImportContext(D->getLexicalDeclContext());
3462 if (!LexicalDC)
3463 return 0;
3464 Impl->setLexicalDeclContext(LexicalDC);
3465 }
3466
3467 // Associate the implementation with the class it implements.
3468 Iface->setImplementation(Impl);
3469 Importer.Imported(D, Iface->getImplementation());
3470 } else {
3471 Importer.Imported(D, Iface->getImplementation());
3472
3473 // Verify that the existing @implementation has the same superclass.
3474 if ((Super && !Impl->getSuperClass()) ||
3475 (!Super && Impl->getSuperClass()) ||
3476 (Super && Impl->getSuperClass() &&
3477 !declaresSameEntity(Super->getCanonicalDecl(), Impl->getSuperClass()))) {
3478 Importer.ToDiag(Impl->getLocation(),
3479 diag::err_odr_objc_superclass_inconsistent)
3480 << Iface->getDeclName();
3481 // FIXME: It would be nice to have the location of the superclass
3482 // below.
3483 if (Impl->getSuperClass())
3484 Importer.ToDiag(Impl->getLocation(),
3485 diag::note_odr_objc_superclass)
3486 << Impl->getSuperClass()->getDeclName();
3487 else
3488 Importer.ToDiag(Impl->getLocation(),
3489 diag::note_odr_objc_missing_superclass);
3490 if (D->getSuperClass())
3491 Importer.FromDiag(D->getLocation(),
3492 diag::note_odr_objc_superclass)
3493 << D->getSuperClass()->getDeclName();
3494 else
3495 Importer.FromDiag(D->getLocation(),
3496 diag::note_odr_objc_missing_superclass);
3497 return 0;
3498 }
3499 }
3500
3501 // Import all of the members of this @implementation.
3502 ImportDeclContext(D);
3503
3504 return Impl;
3505 }
3506
VisitObjCPropertyDecl(ObjCPropertyDecl * D)3507 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3508 // Import the major distinguishing characteristics of an @property.
3509 DeclContext *DC, *LexicalDC;
3510 DeclarationName Name;
3511 SourceLocation Loc;
3512 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3513 return 0;
3514
3515 // Check whether we have already imported this property.
3516 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
3517 DC->localUncachedLookup(Name, FoundDecls);
3518 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3519 if (ObjCPropertyDecl *FoundProp
3520 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3521 // Check property types.
3522 if (!Importer.IsStructurallyEquivalent(D->getType(),
3523 FoundProp->getType())) {
3524 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3525 << Name << D->getType() << FoundProp->getType();
3526 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3527 << FoundProp->getType();
3528 return 0;
3529 }
3530
3531 // FIXME: Check property attributes, getters, setters, etc.?
3532
3533 // Consider these properties to be equivalent.
3534 Importer.Imported(D, FoundProp);
3535 return FoundProp;
3536 }
3537 }
3538
3539 // Import the type.
3540 TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
3541 if (!T)
3542 return 0;
3543
3544 // Create the new property.
3545 ObjCPropertyDecl *ToProperty
3546 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3547 Name.getAsIdentifierInfo(),
3548 Importer.Import(D->getAtLoc()),
3549 Importer.Import(D->getLParenLoc()),
3550 T,
3551 D->getPropertyImplementation());
3552 Importer.Imported(D, ToProperty);
3553 ToProperty->setLexicalDeclContext(LexicalDC);
3554 LexicalDC->addDeclInternal(ToProperty);
3555
3556 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3557 ToProperty->setPropertyAttributesAsWritten(
3558 D->getPropertyAttributesAsWritten());
3559 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
3560 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
3561 ToProperty->setGetterMethodDecl(
3562 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3563 ToProperty->setSetterMethodDecl(
3564 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3565 ToProperty->setPropertyIvarDecl(
3566 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3567 return ToProperty;
3568 }
3569
VisitObjCPropertyImplDecl(ObjCPropertyImplDecl * D)3570 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3571 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3572 Importer.Import(D->getPropertyDecl()));
3573 if (!Property)
3574 return 0;
3575
3576 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3577 if (!DC)
3578 return 0;
3579
3580 // Import the lexical declaration context.
3581 DeclContext *LexicalDC = DC;
3582 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3583 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3584 if (!LexicalDC)
3585 return 0;
3586 }
3587
3588 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3589 if (!InImpl)
3590 return 0;
3591
3592 // Import the ivar (for an @synthesize).
3593 ObjCIvarDecl *Ivar = 0;
3594 if (D->getPropertyIvarDecl()) {
3595 Ivar = cast_or_null<ObjCIvarDecl>(
3596 Importer.Import(D->getPropertyIvarDecl()));
3597 if (!Ivar)
3598 return 0;
3599 }
3600
3601 ObjCPropertyImplDecl *ToImpl
3602 = InImpl->FindPropertyImplDecl(Property->getIdentifier());
3603 if (!ToImpl) {
3604 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3605 Importer.Import(D->getLocStart()),
3606 Importer.Import(D->getLocation()),
3607 Property,
3608 D->getPropertyImplementation(),
3609 Ivar,
3610 Importer.Import(D->getPropertyIvarDeclLoc()));
3611 ToImpl->setLexicalDeclContext(LexicalDC);
3612 Importer.Imported(D, ToImpl);
3613 LexicalDC->addDeclInternal(ToImpl);
3614 } else {
3615 // Check that we have the same kind of property implementation (@synthesize
3616 // vs. @dynamic).
3617 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3618 Importer.ToDiag(ToImpl->getLocation(),
3619 diag::err_odr_objc_property_impl_kind_inconsistent)
3620 << Property->getDeclName()
3621 << (ToImpl->getPropertyImplementation()
3622 == ObjCPropertyImplDecl::Dynamic);
3623 Importer.FromDiag(D->getLocation(),
3624 diag::note_odr_objc_property_impl_kind)
3625 << D->getPropertyDecl()->getDeclName()
3626 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3627 return 0;
3628 }
3629
3630 // For @synthesize, check that we have the same
3631 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3632 Ivar != ToImpl->getPropertyIvarDecl()) {
3633 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3634 diag::err_odr_objc_synthesize_ivar_inconsistent)
3635 << Property->getDeclName()
3636 << ToImpl->getPropertyIvarDecl()->getDeclName()
3637 << Ivar->getDeclName();
3638 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3639 diag::note_odr_objc_synthesize_ivar_here)
3640 << D->getPropertyIvarDecl()->getDeclName();
3641 return 0;
3642 }
3643
3644 // Merge the existing implementation with the new implementation.
3645 Importer.Imported(D, ToImpl);
3646 }
3647
3648 return ToImpl;
3649 }
3650
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)3651 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3652 // For template arguments, we adopt the translation unit as our declaration
3653 // context. This context will be fixed when the actual template declaration
3654 // is created.
3655
3656 // FIXME: Import default argument.
3657 return TemplateTypeParmDecl::Create(Importer.getToContext(),
3658 Importer.getToContext().getTranslationUnitDecl(),
3659 Importer.Import(D->getLocStart()),
3660 Importer.Import(D->getLocation()),
3661 D->getDepth(),
3662 D->getIndex(),
3663 Importer.Import(D->getIdentifier()),
3664 D->wasDeclaredWithTypename(),
3665 D->isParameterPack());
3666 }
3667
3668 Decl *
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)3669 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3670 // Import the name of this declaration.
3671 DeclarationName Name = Importer.Import(D->getDeclName());
3672 if (D->getDeclName() && !Name)
3673 return 0;
3674
3675 // Import the location of this declaration.
3676 SourceLocation Loc = Importer.Import(D->getLocation());
3677
3678 // Import the type of this declaration.
3679 QualType T = Importer.Import(D->getType());
3680 if (T.isNull())
3681 return 0;
3682
3683 // Import type-source information.
3684 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3685 if (D->getTypeSourceInfo() && !TInfo)
3686 return 0;
3687
3688 // FIXME: Import default argument.
3689
3690 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3691 Importer.getToContext().getTranslationUnitDecl(),
3692 Importer.Import(D->getInnerLocStart()),
3693 Loc, D->getDepth(), D->getPosition(),
3694 Name.getAsIdentifierInfo(),
3695 T, D->isParameterPack(), TInfo);
3696 }
3697
3698 Decl *
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)3699 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3700 // Import the name of this declaration.
3701 DeclarationName Name = Importer.Import(D->getDeclName());
3702 if (D->getDeclName() && !Name)
3703 return 0;
3704
3705 // Import the location of this declaration.
3706 SourceLocation Loc = Importer.Import(D->getLocation());
3707
3708 // Import template parameters.
3709 TemplateParameterList *TemplateParams
3710 = ImportTemplateParameterList(D->getTemplateParameters());
3711 if (!TemplateParams)
3712 return 0;
3713
3714 // FIXME: Import default argument.
3715
3716 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3717 Importer.getToContext().getTranslationUnitDecl(),
3718 Loc, D->getDepth(), D->getPosition(),
3719 D->isParameterPack(),
3720 Name.getAsIdentifierInfo(),
3721 TemplateParams);
3722 }
3723
VisitClassTemplateDecl(ClassTemplateDecl * D)3724 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
3725 // If this record has a definition in the translation unit we're coming from,
3726 // but this particular declaration is not that definition, import the
3727 // definition and map to that.
3728 CXXRecordDecl *Definition
3729 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
3730 if (Definition && Definition != D->getTemplatedDecl()) {
3731 Decl *ImportedDef
3732 = Importer.Import(Definition->getDescribedClassTemplate());
3733 if (!ImportedDef)
3734 return 0;
3735
3736 return Importer.Imported(D, ImportedDef);
3737 }
3738
3739 // Import the major distinguishing characteristics of this class template.
3740 DeclContext *DC, *LexicalDC;
3741 DeclarationName Name;
3742 SourceLocation Loc;
3743 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3744 return 0;
3745
3746 // We may already have a template of the same name; try to find and match it.
3747 if (!DC->isFunctionOrMethod()) {
3748 SmallVector<NamedDecl *, 4> ConflictingDecls;
3749 llvm::SmallVector<NamedDecl *, 2> FoundDecls;
3750 DC->localUncachedLookup(Name, FoundDecls);
3751 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3752 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3753 continue;
3754
3755 Decl *Found = FoundDecls[I];
3756 if (ClassTemplateDecl *FoundTemplate
3757 = dyn_cast<ClassTemplateDecl>(Found)) {
3758 if (IsStructuralMatch(D, FoundTemplate)) {
3759 // The class templates structurally match; call it the same template.
3760 // FIXME: We may be filling in a forward declaration here. Handle
3761 // this case!
3762 Importer.Imported(D->getTemplatedDecl(),
3763 FoundTemplate->getTemplatedDecl());
3764 return Importer.Imported(D, FoundTemplate);
3765 }
3766 }
3767
3768 ConflictingDecls.push_back(FoundDecls[I]);
3769 }
3770
3771 if (!ConflictingDecls.empty()) {
3772 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
3773 ConflictingDecls.data(),
3774 ConflictingDecls.size());
3775 }
3776
3777 if (!Name)
3778 return 0;
3779 }
3780
3781 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
3782
3783 // Create the declaration that is being templated.
3784 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
3785 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
3786 CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
3787 DTemplated->getTagKind(),
3788 DC, StartLoc, IdLoc,
3789 Name.getAsIdentifierInfo());
3790 D2Templated->setAccess(DTemplated->getAccess());
3791 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
3792 D2Templated->setLexicalDeclContext(LexicalDC);
3793
3794 // Create the class template declaration itself.
3795 TemplateParameterList *TemplateParams
3796 = ImportTemplateParameterList(D->getTemplateParameters());
3797 if (!TemplateParams)
3798 return 0;
3799
3800 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
3801 Loc, Name, TemplateParams,
3802 D2Templated,
3803 /*PrevDecl=*/0);
3804 D2Templated->setDescribedClassTemplate(D2);
3805
3806 D2->setAccess(D->getAccess());
3807 D2->setLexicalDeclContext(LexicalDC);
3808 LexicalDC->addDeclInternal(D2);
3809
3810 // Note the relationship between the class templates.
3811 Importer.Imported(D, D2);
3812 Importer.Imported(DTemplated, D2Templated);
3813
3814 if (DTemplated->isCompleteDefinition() &&
3815 !D2Templated->isCompleteDefinition()) {
3816 // FIXME: Import definition!
3817 }
3818
3819 return D2;
3820 }
3821
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)3822 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
3823 ClassTemplateSpecializationDecl *D) {
3824 // If this record has a definition in the translation unit we're coming from,
3825 // but this particular declaration is not that definition, import the
3826 // definition and map to that.
3827 TagDecl *Definition = D->getDefinition();
3828 if (Definition && Definition != D) {
3829 Decl *ImportedDef = Importer.Import(Definition);
3830 if (!ImportedDef)
3831 return 0;
3832
3833 return Importer.Imported(D, ImportedDef);
3834 }
3835
3836 ClassTemplateDecl *ClassTemplate
3837 = cast_or_null<ClassTemplateDecl>(Importer.Import(
3838 D->getSpecializedTemplate()));
3839 if (!ClassTemplate)
3840 return 0;
3841
3842 // Import the context of this declaration.
3843 DeclContext *DC = ClassTemplate->getDeclContext();
3844 if (!DC)
3845 return 0;
3846
3847 DeclContext *LexicalDC = DC;
3848 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3849 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3850 if (!LexicalDC)
3851 return 0;
3852 }
3853
3854 // Import the location of this declaration.
3855 SourceLocation StartLoc = Importer.Import(D->getLocStart());
3856 SourceLocation IdLoc = Importer.Import(D->getLocation());
3857
3858 // Import template arguments.
3859 SmallVector<TemplateArgument, 2> TemplateArgs;
3860 if (ImportTemplateArguments(D->getTemplateArgs().data(),
3861 D->getTemplateArgs().size(),
3862 TemplateArgs))
3863 return 0;
3864
3865 // Try to find an existing specialization with these template arguments.
3866 void *InsertPos = 0;
3867 ClassTemplateSpecializationDecl *D2
3868 = ClassTemplate->findSpecialization(TemplateArgs.data(),
3869 TemplateArgs.size(), InsertPos);
3870 if (D2) {
3871 // We already have a class template specialization with these template
3872 // arguments.
3873
3874 // FIXME: Check for specialization vs. instantiation errors.
3875
3876 if (RecordDecl *FoundDef = D2->getDefinition()) {
3877 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
3878 // The record types structurally match, or the "from" translation
3879 // unit only had a forward declaration anyway; call it the same
3880 // function.
3881 return Importer.Imported(D, FoundDef);
3882 }
3883 }
3884 } else {
3885 // Create a new specialization.
3886 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
3887 D->getTagKind(), DC,
3888 StartLoc, IdLoc,
3889 ClassTemplate,
3890 TemplateArgs.data(),
3891 TemplateArgs.size(),
3892 /*PrevDecl=*/0);
3893 D2->setSpecializationKind(D->getSpecializationKind());
3894
3895 // Add this specialization to the class template.
3896 ClassTemplate->AddSpecialization(D2, InsertPos);
3897
3898 // Import the qualifier, if any.
3899 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3900
3901 // Add the specialization to this context.
3902 D2->setLexicalDeclContext(LexicalDC);
3903 LexicalDC->addDeclInternal(D2);
3904 }
3905 Importer.Imported(D, D2);
3906
3907 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
3908 return 0;
3909
3910 return D2;
3911 }
3912
3913 //----------------------------------------------------------------------------
3914 // Import Statements
3915 //----------------------------------------------------------------------------
3916
VisitStmt(Stmt * S)3917 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
3918 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
3919 << S->getStmtClassName();
3920 return 0;
3921 }
3922
3923 //----------------------------------------------------------------------------
3924 // Import Expressions
3925 //----------------------------------------------------------------------------
VisitExpr(Expr * E)3926 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
3927 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
3928 << E->getStmtClassName();
3929 return 0;
3930 }
3931
VisitDeclRefExpr(DeclRefExpr * E)3932 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
3933 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
3934 if (!ToD)
3935 return 0;
3936
3937 NamedDecl *FoundD = 0;
3938 if (E->getDecl() != E->getFoundDecl()) {
3939 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
3940 if (!FoundD)
3941 return 0;
3942 }
3943
3944 QualType T = Importer.Import(E->getType());
3945 if (T.isNull())
3946 return 0;
3947
3948 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
3949 Importer.Import(E->getQualifierLoc()),
3950 Importer.Import(E->getTemplateKeywordLoc()),
3951 ToD,
3952 E->refersToEnclosingLocal(),
3953 Importer.Import(E->getLocation()),
3954 T, E->getValueKind(),
3955 FoundD,
3956 /*FIXME:TemplateArgs=*/0);
3957 if (E->hadMultipleCandidates())
3958 DRE->setHadMultipleCandidates(true);
3959 return DRE;
3960 }
3961
VisitIntegerLiteral(IntegerLiteral * E)3962 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
3963 QualType T = Importer.Import(E->getType());
3964 if (T.isNull())
3965 return 0;
3966
3967 return IntegerLiteral::Create(Importer.getToContext(),
3968 E->getValue(), T,
3969 Importer.Import(E->getLocation()));
3970 }
3971
VisitCharacterLiteral(CharacterLiteral * E)3972 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
3973 QualType T = Importer.Import(E->getType());
3974 if (T.isNull())
3975 return 0;
3976
3977 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
3978 E->getKind(), T,
3979 Importer.Import(E->getLocation()));
3980 }
3981
VisitParenExpr(ParenExpr * E)3982 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
3983 Expr *SubExpr = Importer.Import(E->getSubExpr());
3984 if (!SubExpr)
3985 return 0;
3986
3987 return new (Importer.getToContext())
3988 ParenExpr(Importer.Import(E->getLParen()),
3989 Importer.Import(E->getRParen()),
3990 SubExpr);
3991 }
3992
VisitUnaryOperator(UnaryOperator * E)3993 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
3994 QualType T = Importer.Import(E->getType());
3995 if (T.isNull())
3996 return 0;
3997
3998 Expr *SubExpr = Importer.Import(E->getSubExpr());
3999 if (!SubExpr)
4000 return 0;
4001
4002 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
4003 T, E->getValueKind(),
4004 E->getObjectKind(),
4005 Importer.Import(E->getOperatorLoc()));
4006 }
4007
VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * E)4008 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
4009 UnaryExprOrTypeTraitExpr *E) {
4010 QualType ResultType = Importer.Import(E->getType());
4011
4012 if (E->isArgumentType()) {
4013 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
4014 if (!TInfo)
4015 return 0;
4016
4017 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4018 TInfo, ResultType,
4019 Importer.Import(E->getOperatorLoc()),
4020 Importer.Import(E->getRParenLoc()));
4021 }
4022
4023 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
4024 if (!SubExpr)
4025 return 0;
4026
4027 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4028 SubExpr, ResultType,
4029 Importer.Import(E->getOperatorLoc()),
4030 Importer.Import(E->getRParenLoc()));
4031 }
4032
VisitBinaryOperator(BinaryOperator * E)4033 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
4034 QualType T = Importer.Import(E->getType());
4035 if (T.isNull())
4036 return 0;
4037
4038 Expr *LHS = Importer.Import(E->getLHS());
4039 if (!LHS)
4040 return 0;
4041
4042 Expr *RHS = Importer.Import(E->getRHS());
4043 if (!RHS)
4044 return 0;
4045
4046 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
4047 T, E->getValueKind(),
4048 E->getObjectKind(),
4049 Importer.Import(E->getOperatorLoc()));
4050 }
4051
VisitCompoundAssignOperator(CompoundAssignOperator * E)4052 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
4053 QualType T = Importer.Import(E->getType());
4054 if (T.isNull())
4055 return 0;
4056
4057 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
4058 if (CompLHSType.isNull())
4059 return 0;
4060
4061 QualType CompResultType = Importer.Import(E->getComputationResultType());
4062 if (CompResultType.isNull())
4063 return 0;
4064
4065 Expr *LHS = Importer.Import(E->getLHS());
4066 if (!LHS)
4067 return 0;
4068
4069 Expr *RHS = Importer.Import(E->getRHS());
4070 if (!RHS)
4071 return 0;
4072
4073 return new (Importer.getToContext())
4074 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
4075 T, E->getValueKind(),
4076 E->getObjectKind(),
4077 CompLHSType, CompResultType,
4078 Importer.Import(E->getOperatorLoc()));
4079 }
4080
ImportCastPath(CastExpr * E,CXXCastPath & Path)4081 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
4082 if (E->path_empty()) return false;
4083
4084 // TODO: import cast paths
4085 return true;
4086 }
4087
VisitImplicitCastExpr(ImplicitCastExpr * E)4088 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
4089 QualType T = Importer.Import(E->getType());
4090 if (T.isNull())
4091 return 0;
4092
4093 Expr *SubExpr = Importer.Import(E->getSubExpr());
4094 if (!SubExpr)
4095 return 0;
4096
4097 CXXCastPath BasePath;
4098 if (ImportCastPath(E, BasePath))
4099 return 0;
4100
4101 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
4102 SubExpr, &BasePath, E->getValueKind());
4103 }
4104
VisitCStyleCastExpr(CStyleCastExpr * E)4105 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
4106 QualType T = Importer.Import(E->getType());
4107 if (T.isNull())
4108 return 0;
4109
4110 Expr *SubExpr = Importer.Import(E->getSubExpr());
4111 if (!SubExpr)
4112 return 0;
4113
4114 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
4115 if (!TInfo && E->getTypeInfoAsWritten())
4116 return 0;
4117
4118 CXXCastPath BasePath;
4119 if (ImportCastPath(E, BasePath))
4120 return 0;
4121
4122 return CStyleCastExpr::Create(Importer.getToContext(), T,
4123 E->getValueKind(), E->getCastKind(),
4124 SubExpr, &BasePath, TInfo,
4125 Importer.Import(E->getLParenLoc()),
4126 Importer.Import(E->getRParenLoc()));
4127 }
4128
ASTImporter(ASTContext & ToContext,FileManager & ToFileManager,ASTContext & FromContext,FileManager & FromFileManager,bool MinimalImport)4129 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
4130 ASTContext &FromContext, FileManager &FromFileManager,
4131 bool MinimalImport)
4132 : ToContext(ToContext), FromContext(FromContext),
4133 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
4134 Minimal(MinimalImport)
4135 {
4136 ImportedDecls[FromContext.getTranslationUnitDecl()]
4137 = ToContext.getTranslationUnitDecl();
4138 }
4139
~ASTImporter()4140 ASTImporter::~ASTImporter() { }
4141
Import(QualType FromT)4142 QualType ASTImporter::Import(QualType FromT) {
4143 if (FromT.isNull())
4144 return QualType();
4145
4146 const Type *fromTy = FromT.getTypePtr();
4147
4148 // Check whether we've already imported this type.
4149 llvm::DenseMap<const Type *, const Type *>::iterator Pos
4150 = ImportedTypes.find(fromTy);
4151 if (Pos != ImportedTypes.end())
4152 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
4153
4154 // Import the type
4155 ASTNodeImporter Importer(*this);
4156 QualType ToT = Importer.Visit(fromTy);
4157 if (ToT.isNull())
4158 return ToT;
4159
4160 // Record the imported type.
4161 ImportedTypes[fromTy] = ToT.getTypePtr();
4162
4163 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
4164 }
4165
Import(TypeSourceInfo * FromTSI)4166 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
4167 if (!FromTSI)
4168 return FromTSI;
4169
4170 // FIXME: For now we just create a "trivial" type source info based
4171 // on the type and a single location. Implement a real version of this.
4172 QualType T = Import(FromTSI->getType());
4173 if (T.isNull())
4174 return 0;
4175
4176 return ToContext.getTrivialTypeSourceInfo(T,
4177 FromTSI->getTypeLoc().getLocStart());
4178 }
4179
Import(Decl * FromD)4180 Decl *ASTImporter::Import(Decl *FromD) {
4181 if (!FromD)
4182 return 0;
4183
4184 ASTNodeImporter Importer(*this);
4185
4186 // Check whether we've already imported this declaration.
4187 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
4188 if (Pos != ImportedDecls.end()) {
4189 Decl *ToD = Pos->second;
4190 Importer.ImportDefinitionIfNeeded(FromD, ToD);
4191 return ToD;
4192 }
4193
4194 // Import the type
4195 Decl *ToD = Importer.Visit(FromD);
4196 if (!ToD)
4197 return 0;
4198
4199 // Record the imported declaration.
4200 ImportedDecls[FromD] = ToD;
4201
4202 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
4203 // Keep track of anonymous tags that have an associated typedef.
4204 if (FromTag->getTypedefNameForAnonDecl())
4205 AnonTagsWithPendingTypedefs.push_back(FromTag);
4206 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
4207 // When we've finished transforming a typedef, see whether it was the
4208 // typedef for an anonymous tag.
4209 for (SmallVector<TagDecl *, 4>::iterator
4210 FromTag = AnonTagsWithPendingTypedefs.begin(),
4211 FromTagEnd = AnonTagsWithPendingTypedefs.end();
4212 FromTag != FromTagEnd; ++FromTag) {
4213 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
4214 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
4215 // We found the typedef for an anonymous tag; link them.
4216 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
4217 AnonTagsWithPendingTypedefs.erase(FromTag);
4218 break;
4219 }
4220 }
4221 }
4222 }
4223
4224 return ToD;
4225 }
4226
ImportContext(DeclContext * FromDC)4227 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
4228 if (!FromDC)
4229 return FromDC;
4230
4231 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
4232 if (!ToDC)
4233 return 0;
4234
4235 // When we're using a record/enum/Objective-C class/protocol as a context, we
4236 // need it to have a definition.
4237 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
4238 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
4239 if (ToRecord->isCompleteDefinition()) {
4240 // Do nothing.
4241 } else if (FromRecord->isCompleteDefinition()) {
4242 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
4243 ASTNodeImporter::IDK_Basic);
4244 } else {
4245 CompleteDecl(ToRecord);
4246 }
4247 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
4248 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
4249 if (ToEnum->isCompleteDefinition()) {
4250 // Do nothing.
4251 } else if (FromEnum->isCompleteDefinition()) {
4252 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
4253 ASTNodeImporter::IDK_Basic);
4254 } else {
4255 CompleteDecl(ToEnum);
4256 }
4257 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
4258 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
4259 if (ToClass->getDefinition()) {
4260 // Do nothing.
4261 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
4262 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
4263 ASTNodeImporter::IDK_Basic);
4264 } else {
4265 CompleteDecl(ToClass);
4266 }
4267 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
4268 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
4269 if (ToProto->getDefinition()) {
4270 // Do nothing.
4271 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
4272 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
4273 ASTNodeImporter::IDK_Basic);
4274 } else {
4275 CompleteDecl(ToProto);
4276 }
4277 }
4278
4279 return ToDC;
4280 }
4281
Import(Expr * FromE)4282 Expr *ASTImporter::Import(Expr *FromE) {
4283 if (!FromE)
4284 return 0;
4285
4286 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
4287 }
4288
Import(Stmt * FromS)4289 Stmt *ASTImporter::Import(Stmt *FromS) {
4290 if (!FromS)
4291 return 0;
4292
4293 // Check whether we've already imported this declaration.
4294 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
4295 if (Pos != ImportedStmts.end())
4296 return Pos->second;
4297
4298 // Import the type
4299 ASTNodeImporter Importer(*this);
4300 Stmt *ToS = Importer.Visit(FromS);
4301 if (!ToS)
4302 return 0;
4303
4304 // Record the imported declaration.
4305 ImportedStmts[FromS] = ToS;
4306 return ToS;
4307 }
4308
Import(NestedNameSpecifier * FromNNS)4309 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
4310 if (!FromNNS)
4311 return 0;
4312
4313 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
4314
4315 switch (FromNNS->getKind()) {
4316 case NestedNameSpecifier::Identifier:
4317 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
4318 return NestedNameSpecifier::Create(ToContext, prefix, II);
4319 }
4320 return 0;
4321
4322 case NestedNameSpecifier::Namespace:
4323 if (NamespaceDecl *NS =
4324 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
4325 return NestedNameSpecifier::Create(ToContext, prefix, NS);
4326 }
4327 return 0;
4328
4329 case NestedNameSpecifier::NamespaceAlias:
4330 if (NamespaceAliasDecl *NSAD =
4331 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
4332 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
4333 }
4334 return 0;
4335
4336 case NestedNameSpecifier::Global:
4337 return NestedNameSpecifier::GlobalSpecifier(ToContext);
4338
4339 case NestedNameSpecifier::TypeSpec:
4340 case NestedNameSpecifier::TypeSpecWithTemplate: {
4341 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
4342 if (!T.isNull()) {
4343 bool bTemplate = FromNNS->getKind() ==
4344 NestedNameSpecifier::TypeSpecWithTemplate;
4345 return NestedNameSpecifier::Create(ToContext, prefix,
4346 bTemplate, T.getTypePtr());
4347 }
4348 }
4349 return 0;
4350 }
4351
4352 llvm_unreachable("Invalid nested name specifier kind");
4353 }
4354
Import(NestedNameSpecifierLoc FromNNS)4355 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
4356 // FIXME: Implement!
4357 return NestedNameSpecifierLoc();
4358 }
4359
Import(TemplateName From)4360 TemplateName ASTImporter::Import(TemplateName From) {
4361 switch (From.getKind()) {
4362 case TemplateName::Template:
4363 if (TemplateDecl *ToTemplate
4364 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4365 return TemplateName(ToTemplate);
4366
4367 return TemplateName();
4368
4369 case TemplateName::OverloadedTemplate: {
4370 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
4371 UnresolvedSet<2> ToTemplates;
4372 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
4373 E = FromStorage->end();
4374 I != E; ++I) {
4375 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
4376 ToTemplates.addDecl(To);
4377 else
4378 return TemplateName();
4379 }
4380 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
4381 ToTemplates.end());
4382 }
4383
4384 case TemplateName::QualifiedTemplate: {
4385 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
4386 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
4387 if (!Qualifier)
4388 return TemplateName();
4389
4390 if (TemplateDecl *ToTemplate
4391 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4392 return ToContext.getQualifiedTemplateName(Qualifier,
4393 QTN->hasTemplateKeyword(),
4394 ToTemplate);
4395
4396 return TemplateName();
4397 }
4398
4399 case TemplateName::DependentTemplate: {
4400 DependentTemplateName *DTN = From.getAsDependentTemplateName();
4401 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
4402 if (!Qualifier)
4403 return TemplateName();
4404
4405 if (DTN->isIdentifier()) {
4406 return ToContext.getDependentTemplateName(Qualifier,
4407 Import(DTN->getIdentifier()));
4408 }
4409
4410 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
4411 }
4412
4413 case TemplateName::SubstTemplateTemplateParm: {
4414 SubstTemplateTemplateParmStorage *subst
4415 = From.getAsSubstTemplateTemplateParm();
4416 TemplateTemplateParmDecl *param
4417 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
4418 if (!param)
4419 return TemplateName();
4420
4421 TemplateName replacement = Import(subst->getReplacement());
4422 if (replacement.isNull()) return TemplateName();
4423
4424 return ToContext.getSubstTemplateTemplateParm(param, replacement);
4425 }
4426
4427 case TemplateName::SubstTemplateTemplateParmPack: {
4428 SubstTemplateTemplateParmPackStorage *SubstPack
4429 = From.getAsSubstTemplateTemplateParmPack();
4430 TemplateTemplateParmDecl *Param
4431 = cast_or_null<TemplateTemplateParmDecl>(
4432 Import(SubstPack->getParameterPack()));
4433 if (!Param)
4434 return TemplateName();
4435
4436 ASTNodeImporter Importer(*this);
4437 TemplateArgument ArgPack
4438 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
4439 if (ArgPack.isNull())
4440 return TemplateName();
4441
4442 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
4443 }
4444 }
4445
4446 llvm_unreachable("Invalid template name kind");
4447 }
4448
Import(SourceLocation FromLoc)4449 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
4450 if (FromLoc.isInvalid())
4451 return SourceLocation();
4452
4453 SourceManager &FromSM = FromContext.getSourceManager();
4454
4455 // For now, map everything down to its spelling location, so that we
4456 // don't have to import macro expansions.
4457 // FIXME: Import macro expansions!
4458 FromLoc = FromSM.getSpellingLoc(FromLoc);
4459 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
4460 SourceManager &ToSM = ToContext.getSourceManager();
4461 return ToSM.getLocForStartOfFile(Import(Decomposed.first))
4462 .getLocWithOffset(Decomposed.second);
4463 }
4464
Import(SourceRange FromRange)4465 SourceRange ASTImporter::Import(SourceRange FromRange) {
4466 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
4467 }
4468
Import(FileID FromID)4469 FileID ASTImporter::Import(FileID FromID) {
4470 llvm::DenseMap<FileID, FileID>::iterator Pos
4471 = ImportedFileIDs.find(FromID);
4472 if (Pos != ImportedFileIDs.end())
4473 return Pos->second;
4474
4475 SourceManager &FromSM = FromContext.getSourceManager();
4476 SourceManager &ToSM = ToContext.getSourceManager();
4477 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
4478 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
4479
4480 // Include location of this file.
4481 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
4482
4483 // Map the FileID for to the "to" source manager.
4484 FileID ToID;
4485 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
4486 if (Cache->OrigEntry) {
4487 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
4488 // disk again
4489 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
4490 // than mmap the files several times.
4491 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
4492 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
4493 FromSLoc.getFile().getFileCharacteristic());
4494 } else {
4495 // FIXME: We want to re-use the existing MemoryBuffer!
4496 const llvm::MemoryBuffer *
4497 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
4498 llvm::MemoryBuffer *ToBuf
4499 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
4500 FromBuf->getBufferIdentifier());
4501 ToID = ToSM.createFileIDForMemBuffer(ToBuf);
4502 }
4503
4504
4505 ImportedFileIDs[FromID] = ToID;
4506 return ToID;
4507 }
4508
ImportDefinition(Decl * From)4509 void ASTImporter::ImportDefinition(Decl *From) {
4510 Decl *To = Import(From);
4511 if (!To)
4512 return;
4513
4514 if (DeclContext *FromDC = cast<DeclContext>(From)) {
4515 ASTNodeImporter Importer(*this);
4516
4517 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
4518 if (!ToRecord->getDefinition()) {
4519 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
4520 ASTNodeImporter::IDK_Everything);
4521 return;
4522 }
4523 }
4524
4525 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
4526 if (!ToEnum->getDefinition()) {
4527 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
4528 ASTNodeImporter::IDK_Everything);
4529 return;
4530 }
4531 }
4532
4533 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
4534 if (!ToIFace->getDefinition()) {
4535 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
4536 ASTNodeImporter::IDK_Everything);
4537 return;
4538 }
4539 }
4540
4541 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
4542 if (!ToProto->getDefinition()) {
4543 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
4544 ASTNodeImporter::IDK_Everything);
4545 return;
4546 }
4547 }
4548
4549 Importer.ImportDeclContext(FromDC, true);
4550 }
4551 }
4552
Import(DeclarationName FromName)4553 DeclarationName ASTImporter::Import(DeclarationName FromName) {
4554 if (!FromName)
4555 return DeclarationName();
4556
4557 switch (FromName.getNameKind()) {
4558 case DeclarationName::Identifier:
4559 return Import(FromName.getAsIdentifierInfo());
4560
4561 case DeclarationName::ObjCZeroArgSelector:
4562 case DeclarationName::ObjCOneArgSelector:
4563 case DeclarationName::ObjCMultiArgSelector:
4564 return Import(FromName.getObjCSelector());
4565
4566 case DeclarationName::CXXConstructorName: {
4567 QualType T = Import(FromName.getCXXNameType());
4568 if (T.isNull())
4569 return DeclarationName();
4570
4571 return ToContext.DeclarationNames.getCXXConstructorName(
4572 ToContext.getCanonicalType(T));
4573 }
4574
4575 case DeclarationName::CXXDestructorName: {
4576 QualType T = Import(FromName.getCXXNameType());
4577 if (T.isNull())
4578 return DeclarationName();
4579
4580 return ToContext.DeclarationNames.getCXXDestructorName(
4581 ToContext.getCanonicalType(T));
4582 }
4583
4584 case DeclarationName::CXXConversionFunctionName: {
4585 QualType T = Import(FromName.getCXXNameType());
4586 if (T.isNull())
4587 return DeclarationName();
4588
4589 return ToContext.DeclarationNames.getCXXConversionFunctionName(
4590 ToContext.getCanonicalType(T));
4591 }
4592
4593 case DeclarationName::CXXOperatorName:
4594 return ToContext.DeclarationNames.getCXXOperatorName(
4595 FromName.getCXXOverloadedOperator());
4596
4597 case DeclarationName::CXXLiteralOperatorName:
4598 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
4599 Import(FromName.getCXXLiteralIdentifier()));
4600
4601 case DeclarationName::CXXUsingDirective:
4602 // FIXME: STATICS!
4603 return DeclarationName::getUsingDirectiveName();
4604 }
4605
4606 llvm_unreachable("Invalid DeclarationName Kind!");
4607 }
4608
Import(const IdentifierInfo * FromId)4609 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
4610 if (!FromId)
4611 return 0;
4612
4613 return &ToContext.Idents.get(FromId->getName());
4614 }
4615
Import(Selector FromSel)4616 Selector ASTImporter::Import(Selector FromSel) {
4617 if (FromSel.isNull())
4618 return Selector();
4619
4620 SmallVector<IdentifierInfo *, 4> Idents;
4621 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
4622 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
4623 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
4624 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
4625 }
4626
HandleNameConflict(DeclarationName Name,DeclContext * DC,unsigned IDNS,NamedDecl ** Decls,unsigned NumDecls)4627 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
4628 DeclContext *DC,
4629 unsigned IDNS,
4630 NamedDecl **Decls,
4631 unsigned NumDecls) {
4632 return Name;
4633 }
4634
ToDiag(SourceLocation Loc,unsigned DiagID)4635 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
4636 return ToContext.getDiagnostics().Report(Loc, DiagID);
4637 }
4638
FromDiag(SourceLocation Loc,unsigned DiagID)4639 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
4640 return FromContext.getDiagnostics().Report(Loc, DiagID);
4641 }
4642
CompleteDecl(Decl * D)4643 void ASTImporter::CompleteDecl (Decl *D) {
4644 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
4645 if (!ID->getDefinition())
4646 ID->startDefinition();
4647 }
4648 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
4649 if (!PD->getDefinition())
4650 PD->startDefinition();
4651 }
4652 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
4653 if (!TD->getDefinition() && !TD->isBeingDefined()) {
4654 TD->startDefinition();
4655 TD->setCompleteDefinition(true);
4656 }
4657 }
4658 else {
4659 assert (0 && "CompleteDecl called on a Decl that can't be completed");
4660 }
4661 }
4662
Imported(Decl * From,Decl * To)4663 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
4664 ImportedDecls[From] = To;
4665 return To;
4666 }
4667
IsStructurallyEquivalent(QualType From,QualType To)4668 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To) {
4669 llvm::DenseMap<const Type *, const Type *>::iterator Pos
4670 = ImportedTypes.find(From.getTypePtr());
4671 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
4672 return true;
4673
4674 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls);
4675 return Ctx.IsStructurallyEquivalent(From, To);
4676 }
4677