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