]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/AST/ASTImporter.cpp
Update clang to 97654.
[FreeBSD/FreeBSD.git] / 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/TypeLoc.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include <deque>
28
29 using namespace clang;
30
31 namespace {
32   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
33                           public DeclVisitor<ASTNodeImporter, Decl *>,
34                           public StmtVisitor<ASTNodeImporter, Stmt *> {
35     ASTImporter &Importer;
36     
37   public:
38     explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
39     
40     using TypeVisitor<ASTNodeImporter, QualType>::Visit;
41     using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
42     using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
43
44     // Importing types
45     QualType VisitType(Type *T);
46     QualType VisitBuiltinType(BuiltinType *T);
47     QualType VisitComplexType(ComplexType *T);
48     QualType VisitPointerType(PointerType *T);
49     QualType VisitBlockPointerType(BlockPointerType *T);
50     QualType VisitLValueReferenceType(LValueReferenceType *T);
51     QualType VisitRValueReferenceType(RValueReferenceType *T);
52     QualType VisitMemberPointerType(MemberPointerType *T);
53     QualType VisitConstantArrayType(ConstantArrayType *T);
54     QualType VisitIncompleteArrayType(IncompleteArrayType *T);
55     QualType VisitVariableArrayType(VariableArrayType *T);
56     // FIXME: DependentSizedArrayType
57     // FIXME: DependentSizedExtVectorType
58     QualType VisitVectorType(VectorType *T);
59     QualType VisitExtVectorType(ExtVectorType *T);
60     QualType VisitFunctionNoProtoType(FunctionNoProtoType *T);
61     QualType VisitFunctionProtoType(FunctionProtoType *T);
62     // FIXME: UnresolvedUsingType
63     QualType VisitTypedefType(TypedefType *T);
64     QualType VisitTypeOfExprType(TypeOfExprType *T);
65     // FIXME: DependentTypeOfExprType
66     QualType VisitTypeOfType(TypeOfType *T);
67     QualType VisitDecltypeType(DecltypeType *T);
68     // FIXME: DependentDecltypeType
69     QualType VisitRecordType(RecordType *T);
70     QualType VisitEnumType(EnumType *T);
71     QualType VisitElaboratedType(ElaboratedType *T);
72     // FIXME: TemplateTypeParmType
73     // FIXME: SubstTemplateTypeParmType
74     // FIXME: TemplateSpecializationType
75     QualType VisitQualifiedNameType(QualifiedNameType *T);
76     // FIXME: TypenameType
77     QualType VisitObjCInterfaceType(ObjCInterfaceType *T);
78     QualType VisitObjCObjectPointerType(ObjCObjectPointerType *T);
79                             
80     // Importing declarations
81     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
82                          DeclContext *&LexicalDC, DeclarationName &Name, 
83                          SourceLocation &Loc);
84     void ImportDeclContext(DeclContext *FromDC);
85     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord);
86     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
87     Decl *VisitDecl(Decl *D);
88     Decl *VisitNamespaceDecl(NamespaceDecl *D);
89     Decl *VisitTypedefDecl(TypedefDecl *D);
90     Decl *VisitEnumDecl(EnumDecl *D);
91     Decl *VisitRecordDecl(RecordDecl *D);
92     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
93     Decl *VisitFunctionDecl(FunctionDecl *D);
94     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
95     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
96     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
97     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
98     Decl *VisitFieldDecl(FieldDecl *D);
99     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
100     Decl *VisitVarDecl(VarDecl *D);
101     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
102     Decl *VisitParmVarDecl(ParmVarDecl *D);
103     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
104     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
105     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
106     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
107     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
108     Decl *VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
109     Decl *VisitObjCClassDecl(ObjCClassDecl *D);
110                             
111     // Importing statements
112     Stmt *VisitStmt(Stmt *S);
113
114     // Importing expressions
115     Expr *VisitExpr(Expr *E);
116     Expr *VisitDeclRefExpr(DeclRefExpr *E);
117     Expr *VisitIntegerLiteral(IntegerLiteral *E);
118     Expr *VisitCharacterLiteral(CharacterLiteral *E);
119     Expr *VisitParenExpr(ParenExpr *E);
120     Expr *VisitUnaryOperator(UnaryOperator *E);
121     Expr *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
122     Expr *VisitBinaryOperator(BinaryOperator *E);
123     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
124     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
125     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
126   };
127 }
128
129 //----------------------------------------------------------------------------
130 // Structural Equivalence
131 //----------------------------------------------------------------------------
132
133 namespace {
134   struct StructuralEquivalenceContext {
135     /// \brief AST contexts for which we are checking structural equivalence.
136     ASTContext &C1, &C2;
137     
138     /// \brief Diagnostic object used to emit diagnostics.
139     Diagnostic &Diags;
140     
141     /// \brief The set of "tentative" equivalences between two canonical 
142     /// declarations, mapping from a declaration in the first context to the
143     /// declaration in the second context that we believe to be equivalent.
144     llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
145     
146     /// \brief Queue of declarations in the first context whose equivalence
147     /// with a declaration in the second context still needs to be verified.
148     std::deque<Decl *> DeclsToCheck;
149     
150     /// \brief Declaration (from, to) pairs that are known not to be equivalent
151     /// (which we have already complained about).
152     llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
153     
154     /// \brief Whether we're being strict about the spelling of types when 
155     /// unifying two types.
156     bool StrictTypeSpelling;
157     
158     StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
159                                  Diagnostic &Diags,
160                llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
161                                  bool StrictTypeSpelling = false)
162       : C1(C1), C2(C2), Diags(Diags), NonEquivalentDecls(NonEquivalentDecls),
163         StrictTypeSpelling(StrictTypeSpelling) { }
164
165     /// \brief Determine whether the two declarations are structurally
166     /// equivalent.
167     bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
168     
169     /// \brief Determine whether the two types are structurally equivalent.
170     bool IsStructurallyEquivalent(QualType T1, QualType T2);
171
172   private:
173     /// \brief Finish checking all of the structural equivalences.
174     ///
175     /// \returns true if an error occurred, false otherwise.
176     bool Finish();
177     
178   public:
179     DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
180       return Diags.Report(FullSourceLoc(Loc, C1.getSourceManager()), DiagID);
181     }
182
183     DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
184       return Diags.Report(FullSourceLoc(Loc, C2.getSourceManager()), DiagID);
185     }
186   };
187 }
188
189 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
190                                      QualType T1, QualType T2);
191 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
192                                      Decl *D1, Decl *D2);
193
194 /// \brief Determine if two APInts have the same value, after zero-extending
195 /// one of them (if needed!) to ensure that the bit-widths match.
196 static bool IsSameValue(const llvm::APInt &I1, const llvm::APInt &I2) {
197   if (I1.getBitWidth() == I2.getBitWidth())
198     return I1 == I2;
199   
200   if (I1.getBitWidth() > I2.getBitWidth())
201     return I1 == llvm::APInt(I2).zext(I1.getBitWidth());
202   
203   return llvm::APInt(I1).zext(I2.getBitWidth()) == I2;
204 }
205
206 /// \brief Determine if two APSInts have the same value, zero- or sign-extending
207 /// as needed.
208 static bool IsSameValue(const llvm::APSInt &I1, const llvm::APSInt &I2) {
209   if (I1.getBitWidth() == I2.getBitWidth() && I1.isSigned() == I2.isSigned())
210     return I1 == I2;
211   
212   // Check for a bit-width mismatch.
213   if (I1.getBitWidth() > I2.getBitWidth())
214     return IsSameValue(I1, llvm::APSInt(I2).extend(I1.getBitWidth()));
215   else if (I2.getBitWidth() > I1.getBitWidth())
216     return IsSameValue(llvm::APSInt(I1).extend(I2.getBitWidth()), I2);
217   
218   // We have a signedness mismatch. Turn the signed value into an unsigned 
219   // value.
220   if (I1.isSigned()) {
221     if (I1.isNegative())
222       return false;
223     
224     return llvm::APSInt(I1, true) == I2;
225   }
226  
227   if (I2.isNegative())
228     return false;
229   
230   return I1 == llvm::APSInt(I2, true);
231 }
232
233 /// \brief Determine structural equivalence of two expressions.
234 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
235                                      Expr *E1, Expr *E2) {
236   if (!E1 || !E2)
237     return E1 == E2;
238   
239   // FIXME: Actually perform a structural comparison!
240   return true;
241 }
242
243 /// \brief Determine whether two identifiers are equivalent.
244 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
245                                      const IdentifierInfo *Name2) {
246   if (!Name1 || !Name2)
247     return Name1 == Name2;
248   
249   return Name1->getName() == Name2->getName();
250 }
251
252 /// \brief Determine whether two nested-name-specifiers are equivalent.
253 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
254                                      NestedNameSpecifier *NNS1,
255                                      NestedNameSpecifier *NNS2) {
256   // FIXME: Implement!
257   return true;
258 }
259
260 /// \brief Determine whether two template arguments are equivalent.
261 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
262                                      const TemplateArgument &Arg1,
263                                      const TemplateArgument &Arg2) {
264   // FIXME: Implement!
265   return true;
266 }
267
268 /// \brief Determine structural equivalence for the common part of array 
269 /// types.
270 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
271                                           const ArrayType *Array1, 
272                                           const ArrayType *Array2) {
273   if (!IsStructurallyEquivalent(Context, 
274                                 Array1->getElementType(), 
275                                 Array2->getElementType()))
276     return false;
277   if (Array1->getSizeModifier() != Array2->getSizeModifier())
278     return false;
279   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
280     return false;
281   
282   return true;
283 }
284
285 /// \brief Determine structural equivalence of two types.
286 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
287                                      QualType T1, QualType T2) {
288   if (T1.isNull() || T2.isNull())
289     return T1.isNull() && T2.isNull();
290   
291   if (!Context.StrictTypeSpelling) {
292     // We aren't being strict about token-to-token equivalence of types,
293     // so map down to the canonical type.
294     T1 = Context.C1.getCanonicalType(T1);
295     T2 = Context.C2.getCanonicalType(T2);
296   }
297   
298   if (T1.getQualifiers() != T2.getQualifiers())
299     return false;
300   
301   Type::TypeClass TC = T1->getTypeClass();
302   
303   if (T1->getTypeClass() != T2->getTypeClass()) {
304     // Compare function types with prototypes vs. without prototypes as if
305     // both did not have prototypes.
306     if (T1->getTypeClass() == Type::FunctionProto &&
307         T2->getTypeClass() == Type::FunctionNoProto)
308       TC = Type::FunctionNoProto;
309     else if (T1->getTypeClass() == Type::FunctionNoProto &&
310              T2->getTypeClass() == Type::FunctionProto)
311       TC = Type::FunctionNoProto;
312     else
313       return false;
314   }
315   
316   switch (TC) {
317   case Type::Builtin:
318     // FIXME: Deal with Char_S/Char_U. 
319     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
320       return false;
321     break;
322   
323   case Type::Complex:
324     if (!IsStructurallyEquivalent(Context,
325                                   cast<ComplexType>(T1)->getElementType(),
326                                   cast<ComplexType>(T2)->getElementType()))
327       return false;
328     break;
329   
330   case Type::Pointer:
331     if (!IsStructurallyEquivalent(Context,
332                                   cast<PointerType>(T1)->getPointeeType(),
333                                   cast<PointerType>(T2)->getPointeeType()))
334       return false;
335     break;
336
337   case Type::BlockPointer:
338     if (!IsStructurallyEquivalent(Context,
339                                   cast<BlockPointerType>(T1)->getPointeeType(),
340                                   cast<BlockPointerType>(T2)->getPointeeType()))
341       return false;
342     break;
343
344   case Type::LValueReference:
345   case Type::RValueReference: {
346     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
347     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
348     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
349       return false;
350     if (Ref1->isInnerRef() != Ref2->isInnerRef())
351       return false;
352     if (!IsStructurallyEquivalent(Context,
353                                   Ref1->getPointeeTypeAsWritten(),
354                                   Ref2->getPointeeTypeAsWritten()))
355       return false;
356     break;
357   }
358       
359   case Type::MemberPointer: {
360     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
361     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
362     if (!IsStructurallyEquivalent(Context,
363                                   MemPtr1->getPointeeType(),
364                                   MemPtr2->getPointeeType()))
365       return false;
366     if (!IsStructurallyEquivalent(Context,
367                                   QualType(MemPtr1->getClass(), 0),
368                                   QualType(MemPtr2->getClass(), 0)))
369       return false;
370     break;
371   }
372       
373   case Type::ConstantArray: {
374     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
375     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
376     if (!IsSameValue(Array1->getSize(), Array2->getSize()))
377       return false;
378     
379     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
380       return false;
381     break;
382   }
383
384   case Type::IncompleteArray:
385     if (!IsArrayStructurallyEquivalent(Context, 
386                                        cast<ArrayType>(T1), 
387                                        cast<ArrayType>(T2)))
388       return false;
389     break;
390       
391   case Type::VariableArray: {
392     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
393     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
394     if (!IsStructurallyEquivalent(Context, 
395                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
396       return false;
397     
398     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
399       return false;
400     
401     break;
402   }
403   
404   case Type::DependentSizedArray: {
405     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
406     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
407     if (!IsStructurallyEquivalent(Context, 
408                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
409       return false;
410     
411     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
412       return false;
413     
414     break;
415   }
416       
417   case Type::DependentSizedExtVector: {
418     const DependentSizedExtVectorType *Vec1
419       = cast<DependentSizedExtVectorType>(T1);
420     const DependentSizedExtVectorType *Vec2
421       = cast<DependentSizedExtVectorType>(T2);
422     if (!IsStructurallyEquivalent(Context, 
423                                   Vec1->getSizeExpr(), Vec2->getSizeExpr()))
424       return false;
425     if (!IsStructurallyEquivalent(Context, 
426                                   Vec1->getElementType(), 
427                                   Vec2->getElementType()))
428       return false;
429     break;
430   }
431    
432   case Type::Vector: 
433   case Type::ExtVector: {
434     const VectorType *Vec1 = cast<VectorType>(T1);
435     const VectorType *Vec2 = cast<VectorType>(T2);
436     if (!IsStructurallyEquivalent(Context, 
437                                   Vec1->getElementType(),
438                                   Vec2->getElementType()))
439       return false;
440     if (Vec1->getNumElements() != Vec2->getNumElements())
441       return false;
442     if (Vec1->isAltiVec() != Vec2->isAltiVec())
443       return false;
444     if (Vec1->isPixel() != Vec2->isPixel())
445       return false;
446     break;
447   }
448
449   case Type::FunctionProto: {
450     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
451     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
452     if (Proto1->getNumArgs() != Proto2->getNumArgs())
453       return false;
454     for (unsigned I = 0, N = Proto1->getNumArgs(); I != N; ++I) {
455       if (!IsStructurallyEquivalent(Context, 
456                                     Proto1->getArgType(I),
457                                     Proto2->getArgType(I)))
458         return false;
459     }
460     if (Proto1->isVariadic() != Proto2->isVariadic())
461       return false;
462     if (Proto1->hasExceptionSpec() != Proto2->hasExceptionSpec())
463       return false;
464     if (Proto1->hasAnyExceptionSpec() != Proto2->hasAnyExceptionSpec())
465       return false;
466     if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
467       return false;
468     for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
469       if (!IsStructurallyEquivalent(Context,
470                                     Proto1->getExceptionType(I),
471                                     Proto2->getExceptionType(I)))
472         return false;
473     }
474     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
475       return false;
476     
477     // Fall through to check the bits common with FunctionNoProtoType.
478   }
479       
480   case Type::FunctionNoProto: {
481     const FunctionType *Function1 = cast<FunctionType>(T1);
482     const FunctionType *Function2 = cast<FunctionType>(T2);
483     if (!IsStructurallyEquivalent(Context, 
484                                   Function1->getResultType(),
485                                   Function2->getResultType()))
486       return false;
487     if (Function1->getNoReturnAttr() != Function2->getNoReturnAttr())
488       return false;
489     if (Function1->getCallConv() != Function2->getCallConv())
490       return false;
491     break;
492   }
493    
494   case Type::UnresolvedUsing:
495     if (!IsStructurallyEquivalent(Context,
496                                   cast<UnresolvedUsingType>(T1)->getDecl(),
497                                   cast<UnresolvedUsingType>(T2)->getDecl()))
498       return false;
499       
500     break;
501       
502   case Type::Typedef:
503     if (!IsStructurallyEquivalent(Context,
504                                   cast<TypedefType>(T1)->getDecl(),
505                                   cast<TypedefType>(T2)->getDecl()))
506       return false;
507     break;
508       
509   case Type::TypeOfExpr:
510     if (!IsStructurallyEquivalent(Context,
511                                 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
512                                 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
513       return false;
514     break;
515       
516   case Type::TypeOf:
517     if (!IsStructurallyEquivalent(Context,
518                                   cast<TypeOfType>(T1)->getUnderlyingType(),
519                                   cast<TypeOfType>(T2)->getUnderlyingType()))
520       return false;
521     break;
522       
523   case Type::Decltype:
524     if (!IsStructurallyEquivalent(Context,
525                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
526                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
527       return false;
528     break;
529
530   case Type::Record:
531   case Type::Enum:
532     if (!IsStructurallyEquivalent(Context,
533                                   cast<TagType>(T1)->getDecl(),
534                                   cast<TagType>(T2)->getDecl()))
535       return false;
536     break;
537       
538   case Type::Elaborated: {
539     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
540     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
541     if (Elab1->getTagKind() != Elab2->getTagKind())
542       return false;
543     if (!IsStructurallyEquivalent(Context, 
544                                   Elab1->getUnderlyingType(),
545                                   Elab2->getUnderlyingType()))
546       return false;
547     break;
548   }
549    
550   case Type::TemplateTypeParm: {
551     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
552     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
553     if (Parm1->getDepth() != Parm2->getDepth())
554       return false;
555     if (Parm1->getIndex() != Parm2->getIndex())
556       return false;
557     if (Parm1->isParameterPack() != Parm2->isParameterPack())
558       return false;
559     
560     // Names of template type parameters are never significant.
561     break;
562   }
563       
564   case Type::SubstTemplateTypeParm: {
565     const SubstTemplateTypeParmType *Subst1
566       = cast<SubstTemplateTypeParmType>(T1);
567     const SubstTemplateTypeParmType *Subst2
568       = cast<SubstTemplateTypeParmType>(T2);
569     if (!IsStructurallyEquivalent(Context,
570                                   QualType(Subst1->getReplacedParameter(), 0),
571                                   QualType(Subst2->getReplacedParameter(), 0)))
572       return false;
573     if (!IsStructurallyEquivalent(Context, 
574                                   Subst1->getReplacementType(),
575                                   Subst2->getReplacementType()))
576       return false;
577     break;
578   }
579
580   case Type::TemplateSpecialization: {
581     const TemplateSpecializationType *Spec1
582       = cast<TemplateSpecializationType>(T1);
583     const TemplateSpecializationType *Spec2
584       = cast<TemplateSpecializationType>(T2);
585     if (!IsStructurallyEquivalent(Context,
586                                   Spec1->getTemplateName(),
587                                   Spec2->getTemplateName()))
588       return false;
589     if (Spec1->getNumArgs() != Spec2->getNumArgs())
590       return false;
591     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
592       if (!IsStructurallyEquivalent(Context, 
593                                     Spec1->getArg(I), Spec2->getArg(I)))
594         return false;
595     }
596     break;
597   }
598       
599   case Type::QualifiedName: {
600     const QualifiedNameType *Qual1 = cast<QualifiedNameType>(T1);
601     const QualifiedNameType *Qual2 = cast<QualifiedNameType>(T2);
602     if (!IsStructurallyEquivalent(Context, 
603                                   Qual1->getQualifier(), 
604                                   Qual2->getQualifier()))
605       return false;
606     if (!IsStructurallyEquivalent(Context,
607                                   Qual1->getNamedType(),
608                                   Qual2->getNamedType()))
609       return false;
610     break;
611   }
612
613   case Type::Typename: {
614     const TypenameType *Typename1 = cast<TypenameType>(T1);
615     const TypenameType *Typename2 = cast<TypenameType>(T2);
616     if (!IsStructurallyEquivalent(Context, 
617                                   Typename1->getQualifier(),
618                                   Typename2->getQualifier()))
619       return false;
620     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
621                                   Typename2->getIdentifier()))
622       return false;
623     if (!IsStructurallyEquivalent(Context,
624                                   QualType(Typename1->getTemplateId(), 0),
625                                   QualType(Typename2->getTemplateId(), 0)))
626       return false;
627     
628     break;
629   }
630   
631   case Type::ObjCInterface: {
632     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
633     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
634     if (!IsStructurallyEquivalent(Context, 
635                                   Iface1->getDecl(), Iface2->getDecl()))
636       return false;
637     if (Iface1->getNumProtocols() != Iface2->getNumProtocols())
638       return false;
639     for (unsigned I = 0, N = Iface1->getNumProtocols(); I != N; ++I) {
640       if (!IsStructurallyEquivalent(Context,
641                                     Iface1->getProtocol(I),
642                                     Iface2->getProtocol(I)))
643         return false;
644     }
645     break;
646   }
647
648   case Type::ObjCObjectPointer: {
649     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
650     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
651     if (!IsStructurallyEquivalent(Context, 
652                                   Ptr1->getPointeeType(),
653                                   Ptr2->getPointeeType()))
654       return false;
655     if (Ptr1->getNumProtocols() != Ptr2->getNumProtocols())
656       return false;
657     for (unsigned I = 0, N = Ptr1->getNumProtocols(); I != N; ++I) {
658       if (!IsStructurallyEquivalent(Context,
659                                     Ptr1->getProtocol(I),
660                                     Ptr2->getProtocol(I)))
661         return false;
662     }
663     break;
664   }
665       
666   } // end switch
667
668   return true;
669 }
670
671 /// \brief Determine structural equivalence of two records.
672 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
673                                      RecordDecl *D1, RecordDecl *D2) {
674   if (D1->isUnion() != D2->isUnion()) {
675     Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
676       << Context.C2.getTypeDeclType(D2);
677     Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
678       << D1->getDeclName() << (unsigned)D1->getTagKind();
679     return false;
680   }
681   
682   // Compare the definitions of these two records. If either or both are
683   // incomplete, we assume that they are equivalent.
684   D1 = D1->getDefinition();
685   D2 = D2->getDefinition();
686   if (!D1 || !D2)
687     return true;
688   
689   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
690     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
691       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
692         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
693         << Context.C2.getTypeDeclType(D2);
694         Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
695         << D2CXX->getNumBases();
696         Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
697         << D1CXX->getNumBases();
698         return false;
699       }
700       
701       // Check the base classes. 
702       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), 
703                                            BaseEnd1 = D1CXX->bases_end(),
704                                                 Base2 = D2CXX->bases_begin();
705            Base1 != BaseEnd1;
706            ++Base1, ++Base2) {        
707         if (!IsStructurallyEquivalent(Context, 
708                                       Base1->getType(), Base2->getType())) {
709           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
710             << Context.C2.getTypeDeclType(D2);
711           Context.Diag2(Base2->getSourceRange().getBegin(), diag::note_odr_base)
712             << Base2->getType()
713             << Base2->getSourceRange();
714           Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
715             << Base1->getType()
716             << Base1->getSourceRange();
717           return false;
718         }
719         
720         // Check virtual vs. non-virtual inheritance mismatch.
721         if (Base1->isVirtual() != Base2->isVirtual()) {
722           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
723             << Context.C2.getTypeDeclType(D2);
724           Context.Diag2(Base2->getSourceRange().getBegin(),
725                         diag::note_odr_virtual_base)
726             << Base2->isVirtual() << Base2->getSourceRange();
727           Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
728             << Base1->isVirtual()
729             << Base1->getSourceRange();
730           return false;
731         }
732       }
733     } else if (D1CXX->getNumBases() > 0) {
734       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
735         << Context.C2.getTypeDeclType(D2);
736       const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
737       Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
738         << Base1->getType()
739         << Base1->getSourceRange();
740       Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
741       return false;
742     }
743   }
744   
745   // Check the fields for consistency.
746   CXXRecordDecl::field_iterator Field2 = D2->field_begin(),
747                              Field2End = D2->field_end();
748   for (CXXRecordDecl::field_iterator Field1 = D1->field_begin(),
749                                   Field1End = D1->field_end();
750        Field1 != Field1End;
751        ++Field1, ++Field2) {
752     if (Field2 == Field2End) {
753       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
754         << Context.C2.getTypeDeclType(D2);
755       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
756         << Field1->getDeclName() << Field1->getType();
757       Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
758       return false;
759     }
760     
761     if (!IsStructurallyEquivalent(Context, 
762                                   Field1->getType(), Field2->getType())) {
763       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
764         << Context.C2.getTypeDeclType(D2);
765       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
766         << Field2->getDeclName() << Field2->getType();
767       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
768         << Field1->getDeclName() << Field1->getType();
769       return false;
770     }
771     
772     if (Field1->isBitField() != Field2->isBitField()) {
773       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
774         << Context.C2.getTypeDeclType(D2);
775       if (Field1->isBitField()) {
776         llvm::APSInt Bits;
777         Field1->getBitWidth()->isIntegerConstantExpr(Bits, Context.C1);
778         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
779           << Field1->getDeclName() << Field1->getType()
780           << Bits.toString(10, false);
781         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
782           << Field2->getDeclName();
783       } else {
784         llvm::APSInt Bits;
785         Field2->getBitWidth()->isIntegerConstantExpr(Bits, Context.C2);
786         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
787           << Field2->getDeclName() << Field2->getType()
788           << Bits.toString(10, false);
789         Context.Diag1(Field1->getLocation(), 
790                           diag::note_odr_not_bit_field)
791         << Field1->getDeclName();
792       }
793       return false;
794     }
795     
796     if (Field1->isBitField()) {
797       // Make sure that the bit-fields are the same length.
798       llvm::APSInt Bits1, Bits2;
799       if (!Field1->getBitWidth()->isIntegerConstantExpr(Bits1, Context.C1))
800         return false;
801       if (!Field2->getBitWidth()->isIntegerConstantExpr(Bits2, Context.C2))
802         return false;
803       
804       if (!IsSameValue(Bits1, Bits2)) {
805         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
806           << Context.C2.getTypeDeclType(D2);
807         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
808           << Field2->getDeclName() << Field2->getType()
809           << Bits2.toString(10, false);
810         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
811           << Field1->getDeclName() << Field1->getType()
812           << Bits1.toString(10, false);
813         return false;
814       }
815     }
816   }
817   
818   if (Field2 != Field2End) {
819     Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
820       << Context.C2.getTypeDeclType(D2);
821     Context.Diag2(Field2->getLocation(), diag::note_odr_field)
822       << Field2->getDeclName() << Field2->getType();
823     Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
824     return false;
825   }
826   
827   return true;
828 }
829      
830 /// \brief Determine structural equivalence of two enums.
831 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
832                                      EnumDecl *D1, EnumDecl *D2) {
833   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
834                              EC2End = D2->enumerator_end();
835   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
836                                   EC1End = D1->enumerator_end();
837        EC1 != EC1End; ++EC1, ++EC2) {
838     if (EC2 == EC2End) {
839       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
840         << Context.C2.getTypeDeclType(D2);
841       Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
842         << EC1->getDeclName() 
843         << EC1->getInitVal().toString(10);
844       Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
845       return false;
846     }
847     
848     llvm::APSInt Val1 = EC1->getInitVal();
849     llvm::APSInt Val2 = EC2->getInitVal();
850     if (!IsSameValue(Val1, Val2) || 
851         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
852       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
853         << Context.C2.getTypeDeclType(D2);
854       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
855         << EC2->getDeclName() 
856         << EC2->getInitVal().toString(10);
857       Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
858         << EC1->getDeclName() 
859         << EC1->getInitVal().toString(10);
860       return false;
861     }
862   }
863   
864   if (EC2 != EC2End) {
865     Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
866       << Context.C2.getTypeDeclType(D2);
867     Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
868       << EC2->getDeclName() 
869       << EC2->getInitVal().toString(10);
870     Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
871     return false;
872   }
873   
874   return true;
875 }
876   
877 /// \brief Determine structural equivalence of two declarations.
878 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
879                                      Decl *D1, Decl *D2) {
880   // FIXME: Check for known structural equivalences via a callback of some sort.
881   
882   // Check whether we already know that these two declarations are not
883   // structurally equivalent.
884   if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
885                                                       D2->getCanonicalDecl())))
886     return false;
887   
888   // Determine whether we've already produced a tentative equivalence for D1.
889   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
890   if (EquivToD1)
891     return EquivToD1 == D2->getCanonicalDecl();
892   
893   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
894   EquivToD1 = D2->getCanonicalDecl();
895   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
896   return true;
897 }
898
899 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1, 
900                                                             Decl *D2) {
901   if (!::IsStructurallyEquivalent(*this, D1, D2))
902     return false;
903   
904   return !Finish();
905 }
906
907 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1, 
908                                                             QualType T2) {
909   if (!::IsStructurallyEquivalent(*this, T1, T2))
910     return false;
911   
912   return !Finish();
913 }
914
915 bool StructuralEquivalenceContext::Finish() {
916   while (!DeclsToCheck.empty()) {
917     // Check the next declaration.
918     Decl *D1 = DeclsToCheck.front();
919     DeclsToCheck.pop_front();
920     
921     Decl *D2 = TentativeEquivalences[D1];
922     assert(D2 && "Unrecorded tentative equivalence?");
923     
924     bool Equivalent = true;
925     
926     // FIXME: Switch on all declaration kinds. For now, we're just going to
927     // check the obvious ones.
928     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
929       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
930         // Check for equivalent structure names.
931         IdentifierInfo *Name1 = Record1->getIdentifier();
932         if (!Name1 && Record1->getTypedefForAnonDecl())
933           Name1 = Record1->getTypedefForAnonDecl()->getIdentifier();
934         IdentifierInfo *Name2 = Record2->getIdentifier();
935         if (!Name2 && Record2->getTypedefForAnonDecl())
936           Name2 = Record2->getTypedefForAnonDecl()->getIdentifier();
937         if (!::IsStructurallyEquivalent(Name1, Name2) ||
938             !::IsStructurallyEquivalent(*this, Record1, Record2))
939           Equivalent = false;
940       } else {
941         // Record/non-record mismatch.
942         Equivalent = false;
943       }
944     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
945       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
946         // Check for equivalent enum names.
947         IdentifierInfo *Name1 = Enum1->getIdentifier();
948         if (!Name1 && Enum1->getTypedefForAnonDecl())
949           Name1 = Enum1->getTypedefForAnonDecl()->getIdentifier();
950         IdentifierInfo *Name2 = Enum2->getIdentifier();
951         if (!Name2 && Enum2->getTypedefForAnonDecl())
952           Name2 = Enum2->getTypedefForAnonDecl()->getIdentifier();
953         if (!::IsStructurallyEquivalent(Name1, Name2) ||
954             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
955           Equivalent = false;
956       } else {
957         // Enum/non-enum mismatch
958         Equivalent = false;
959       }
960     } else if (TypedefDecl *Typedef1 = dyn_cast<TypedefDecl>(D1)) {
961       if (TypedefDecl *Typedef2 = dyn_cast<TypedefDecl>(D2)) {
962         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
963                                         Typedef2->getIdentifier()) ||
964             !::IsStructurallyEquivalent(*this,
965                                         Typedef1->getUnderlyingType(),
966                                         Typedef2->getUnderlyingType()))
967           Equivalent = false;
968       } else {
969         // Typedef/non-typedef mismatch.
970         Equivalent = false;
971       }
972     } 
973
974     if (!Equivalent) {
975       // Note that these two declarations are not equivalent (and we already
976       // know about it).
977       NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
978                                                D2->getCanonicalDecl()));
979       return true;
980     }
981     // FIXME: Check other declaration kinds!
982   }
983   
984   return false;
985 }
986
987 //----------------------------------------------------------------------------
988 // Import Types
989 //----------------------------------------------------------------------------
990
991 QualType ASTNodeImporter::VisitType(Type *T) {
992   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
993     << T->getTypeClassName();
994   return QualType();
995 }
996
997 QualType ASTNodeImporter::VisitBuiltinType(BuiltinType *T) {
998   switch (T->getKind()) {
999   case BuiltinType::Void: return Importer.getToContext().VoidTy;
1000   case BuiltinType::Bool: return Importer.getToContext().BoolTy;
1001     
1002   case BuiltinType::Char_U:
1003     // The context we're importing from has an unsigned 'char'. If we're 
1004     // importing into a context with a signed 'char', translate to 
1005     // 'unsigned char' instead.
1006     if (Importer.getToContext().getLangOptions().CharIsSigned)
1007       return Importer.getToContext().UnsignedCharTy;
1008     
1009     return Importer.getToContext().CharTy;
1010
1011   case BuiltinType::UChar: return Importer.getToContext().UnsignedCharTy;
1012     
1013   case BuiltinType::Char16:
1014     // FIXME: Make sure that the "to" context supports C++!
1015     return Importer.getToContext().Char16Ty;
1016     
1017   case BuiltinType::Char32: 
1018     // FIXME: Make sure that the "to" context supports C++!
1019     return Importer.getToContext().Char32Ty;
1020
1021   case BuiltinType::UShort: return Importer.getToContext().UnsignedShortTy;
1022   case BuiltinType::UInt: return Importer.getToContext().UnsignedIntTy;
1023   case BuiltinType::ULong: return Importer.getToContext().UnsignedLongTy;
1024   case BuiltinType::ULongLong: 
1025     return Importer.getToContext().UnsignedLongLongTy;
1026   case BuiltinType::UInt128: return Importer.getToContext().UnsignedInt128Ty;
1027     
1028   case BuiltinType::Char_S:
1029     // The context we're importing from has an unsigned 'char'. If we're 
1030     // importing into a context with a signed 'char', translate to 
1031     // 'unsigned char' instead.
1032     if (!Importer.getToContext().getLangOptions().CharIsSigned)
1033       return Importer.getToContext().SignedCharTy;
1034     
1035     return Importer.getToContext().CharTy;
1036
1037   case BuiltinType::SChar: return Importer.getToContext().SignedCharTy;
1038   case BuiltinType::WChar:
1039     // FIXME: If not in C++, shall we translate to the C equivalent of
1040     // wchar_t?
1041     return Importer.getToContext().WCharTy;
1042     
1043   case BuiltinType::Short : return Importer.getToContext().ShortTy;
1044   case BuiltinType::Int : return Importer.getToContext().IntTy;
1045   case BuiltinType::Long : return Importer.getToContext().LongTy;
1046   case BuiltinType::LongLong : return Importer.getToContext().LongLongTy;
1047   case BuiltinType::Int128 : return Importer.getToContext().Int128Ty;
1048   case BuiltinType::Float: return Importer.getToContext().FloatTy;
1049   case BuiltinType::Double: return Importer.getToContext().DoubleTy;
1050   case BuiltinType::LongDouble: return Importer.getToContext().LongDoubleTy;
1051
1052   case BuiltinType::NullPtr:
1053     // FIXME: Make sure that the "to" context supports C++0x!
1054     return Importer.getToContext().NullPtrTy;
1055     
1056   case BuiltinType::Overload: return Importer.getToContext().OverloadTy;
1057   case BuiltinType::Dependent: return Importer.getToContext().DependentTy;
1058   case BuiltinType::UndeducedAuto: 
1059     // FIXME: Make sure that the "to" context supports C++0x!
1060     return Importer.getToContext().UndeducedAutoTy;
1061
1062   case BuiltinType::ObjCId:
1063     // FIXME: Make sure that the "to" context supports Objective-C!
1064     return Importer.getToContext().ObjCBuiltinIdTy;
1065     
1066   case BuiltinType::ObjCClass:
1067     return Importer.getToContext().ObjCBuiltinClassTy;
1068
1069   case BuiltinType::ObjCSel:
1070     return Importer.getToContext().ObjCBuiltinSelTy;
1071   }
1072   
1073   return QualType();
1074 }
1075
1076 QualType ASTNodeImporter::VisitComplexType(ComplexType *T) {
1077   QualType ToElementType = Importer.Import(T->getElementType());
1078   if (ToElementType.isNull())
1079     return QualType();
1080   
1081   return Importer.getToContext().getComplexType(ToElementType);
1082 }
1083
1084 QualType ASTNodeImporter::VisitPointerType(PointerType *T) {
1085   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1086   if (ToPointeeType.isNull())
1087     return QualType();
1088   
1089   return Importer.getToContext().getPointerType(ToPointeeType);
1090 }
1091
1092 QualType ASTNodeImporter::VisitBlockPointerType(BlockPointerType *T) {
1093   // FIXME: Check for blocks support in "to" context.
1094   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1095   if (ToPointeeType.isNull())
1096     return QualType();
1097   
1098   return Importer.getToContext().getBlockPointerType(ToPointeeType);
1099 }
1100
1101 QualType ASTNodeImporter::VisitLValueReferenceType(LValueReferenceType *T) {
1102   // FIXME: Check for C++ support in "to" context.
1103   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1104   if (ToPointeeType.isNull())
1105     return QualType();
1106   
1107   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1108 }
1109
1110 QualType ASTNodeImporter::VisitRValueReferenceType(RValueReferenceType *T) {
1111   // FIXME: Check for C++0x support in "to" context.
1112   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1113   if (ToPointeeType.isNull())
1114     return QualType();
1115   
1116   return Importer.getToContext().getRValueReferenceType(ToPointeeType);  
1117 }
1118
1119 QualType ASTNodeImporter::VisitMemberPointerType(MemberPointerType *T) {
1120   // FIXME: Check for C++ support in "to" context.
1121   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1122   if (ToPointeeType.isNull())
1123     return QualType();
1124   
1125   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1126   return Importer.getToContext().getMemberPointerType(ToPointeeType, 
1127                                                       ClassType.getTypePtr());
1128 }
1129
1130 QualType ASTNodeImporter::VisitConstantArrayType(ConstantArrayType *T) {
1131   QualType ToElementType = Importer.Import(T->getElementType());
1132   if (ToElementType.isNull())
1133     return QualType();
1134   
1135   return Importer.getToContext().getConstantArrayType(ToElementType, 
1136                                                       T->getSize(),
1137                                                       T->getSizeModifier(),
1138                                                T->getIndexTypeCVRQualifiers());
1139 }
1140
1141 QualType ASTNodeImporter::VisitIncompleteArrayType(IncompleteArrayType *T) {
1142   QualType ToElementType = Importer.Import(T->getElementType());
1143   if (ToElementType.isNull())
1144     return QualType();
1145   
1146   return Importer.getToContext().getIncompleteArrayType(ToElementType, 
1147                                                         T->getSizeModifier(),
1148                                                 T->getIndexTypeCVRQualifiers());
1149 }
1150
1151 QualType ASTNodeImporter::VisitVariableArrayType(VariableArrayType *T) {
1152   QualType ToElementType = Importer.Import(T->getElementType());
1153   if (ToElementType.isNull())
1154     return QualType();
1155
1156   Expr *Size = Importer.Import(T->getSizeExpr());
1157   if (!Size)
1158     return QualType();
1159   
1160   SourceRange Brackets = Importer.Import(T->getBracketsRange());
1161   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1162                                                       T->getSizeModifier(),
1163                                                 T->getIndexTypeCVRQualifiers(),
1164                                                       Brackets);
1165 }
1166
1167 QualType ASTNodeImporter::VisitVectorType(VectorType *T) {
1168   QualType ToElementType = Importer.Import(T->getElementType());
1169   if (ToElementType.isNull())
1170     return QualType();
1171   
1172   return Importer.getToContext().getVectorType(ToElementType, 
1173                                                T->getNumElements(),
1174                                                T->isAltiVec(),
1175                                                T->isPixel());
1176 }
1177
1178 QualType ASTNodeImporter::VisitExtVectorType(ExtVectorType *T) {
1179   QualType ToElementType = Importer.Import(T->getElementType());
1180   if (ToElementType.isNull())
1181     return QualType();
1182   
1183   return Importer.getToContext().getExtVectorType(ToElementType, 
1184                                                   T->getNumElements());
1185 }
1186
1187 QualType ASTNodeImporter::VisitFunctionNoProtoType(FunctionNoProtoType *T) {
1188   // FIXME: What happens if we're importing a function without a prototype 
1189   // into C++? Should we make it variadic?
1190   QualType ToResultType = Importer.Import(T->getResultType());
1191   if (ToResultType.isNull())
1192     return QualType();
1193   
1194   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1195                                                         T->getNoReturnAttr(), 
1196                                                         T->getCallConv());
1197 }
1198
1199 QualType ASTNodeImporter::VisitFunctionProtoType(FunctionProtoType *T) {
1200   QualType ToResultType = Importer.Import(T->getResultType());
1201   if (ToResultType.isNull())
1202     return QualType();
1203   
1204   // Import argument types
1205   llvm::SmallVector<QualType, 4> ArgTypes;
1206   for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
1207                                          AEnd = T->arg_type_end();
1208        A != AEnd; ++A) {
1209     QualType ArgType = Importer.Import(*A);
1210     if (ArgType.isNull())
1211       return QualType();
1212     ArgTypes.push_back(ArgType);
1213   }
1214   
1215   // Import exception types
1216   llvm::SmallVector<QualType, 4> ExceptionTypes;
1217   for (FunctionProtoType::exception_iterator E = T->exception_begin(),
1218                                           EEnd = T->exception_end();
1219        E != EEnd; ++E) {
1220     QualType ExceptionType = Importer.Import(*E);
1221     if (ExceptionType.isNull())
1222       return QualType();
1223     ExceptionTypes.push_back(ExceptionType);
1224   }
1225        
1226   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes.data(),
1227                                                  ArgTypes.size(),
1228                                                  T->isVariadic(),
1229                                                  T->getTypeQuals(),
1230                                                  T->hasExceptionSpec(), 
1231                                                  T->hasAnyExceptionSpec(),
1232                                                  ExceptionTypes.size(),
1233                                                  ExceptionTypes.data(),
1234                                                  T->getNoReturnAttr(),
1235                                                  T->getCallConv());
1236 }
1237
1238 QualType ASTNodeImporter::VisitTypedefType(TypedefType *T) {
1239   TypedefDecl *ToDecl
1240                  = dyn_cast_or_null<TypedefDecl>(Importer.Import(T->getDecl()));
1241   if (!ToDecl)
1242     return QualType();
1243   
1244   return Importer.getToContext().getTypeDeclType(ToDecl);
1245 }
1246
1247 QualType ASTNodeImporter::VisitTypeOfExprType(TypeOfExprType *T) {
1248   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1249   if (!ToExpr)
1250     return QualType();
1251   
1252   return Importer.getToContext().getTypeOfExprType(ToExpr);
1253 }
1254
1255 QualType ASTNodeImporter::VisitTypeOfType(TypeOfType *T) {
1256   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1257   if (ToUnderlyingType.isNull())
1258     return QualType();
1259   
1260   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1261 }
1262
1263 QualType ASTNodeImporter::VisitDecltypeType(DecltypeType *T) {
1264   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1265   if (!ToExpr)
1266     return QualType();
1267   
1268   return Importer.getToContext().getDecltypeType(ToExpr);
1269 }
1270
1271 QualType ASTNodeImporter::VisitRecordType(RecordType *T) {
1272   RecordDecl *ToDecl
1273     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1274   if (!ToDecl)
1275     return QualType();
1276
1277   return Importer.getToContext().getTagDeclType(ToDecl);
1278 }
1279
1280 QualType ASTNodeImporter::VisitEnumType(EnumType *T) {
1281   EnumDecl *ToDecl
1282     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1283   if (!ToDecl)
1284     return QualType();
1285
1286   return Importer.getToContext().getTagDeclType(ToDecl);
1287 }
1288
1289 QualType ASTNodeImporter::VisitElaboratedType(ElaboratedType *T) {
1290   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1291   if (ToUnderlyingType.isNull())
1292     return QualType();
1293
1294   return Importer.getToContext().getElaboratedType(ToUnderlyingType,
1295                                                    T->getTagKind());
1296 }
1297
1298 QualType ASTNodeImporter::VisitQualifiedNameType(QualifiedNameType *T) {
1299   NestedNameSpecifier *ToQualifier = Importer.Import(T->getQualifier());
1300   if (!ToQualifier)
1301     return QualType();
1302
1303   QualType ToNamedType = Importer.Import(T->getNamedType());
1304   if (ToNamedType.isNull())
1305     return QualType();
1306
1307   return Importer.getToContext().getQualifiedNameType(ToQualifier, ToNamedType);
1308 }
1309
1310 QualType ASTNodeImporter::VisitObjCInterfaceType(ObjCInterfaceType *T) {
1311   ObjCInterfaceDecl *Class
1312     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1313   if (!Class)
1314     return QualType();
1315
1316   llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
1317   for (ObjCInterfaceType::qual_iterator P = T->qual_begin(), 
1318                                      PEnd = T->qual_end();
1319        P != PEnd; ++P) {
1320     ObjCProtocolDecl *Protocol
1321       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1322     if (!Protocol)
1323       return QualType();
1324     Protocols.push_back(Protocol);
1325   }
1326
1327   return Importer.getToContext().getObjCInterfaceType(Class,
1328                                                       Protocols.data(),
1329                                                       Protocols.size());
1330 }
1331
1332 QualType ASTNodeImporter::VisitObjCObjectPointerType(ObjCObjectPointerType *T) {
1333   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1334   if (ToPointeeType.isNull())
1335     return QualType();
1336
1337   llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
1338   for (ObjCObjectPointerType::qual_iterator P = T->qual_begin(), 
1339                                          PEnd = T->qual_end();
1340        P != PEnd; ++P) {
1341     ObjCProtocolDecl *Protocol
1342       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1343     if (!Protocol)
1344       return QualType();
1345     Protocols.push_back(Protocol);
1346   }
1347
1348   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType,
1349                                                           Protocols.data(),
1350                                                           Protocols.size());
1351 }
1352
1353 //----------------------------------------------------------------------------
1354 // Import Declarations
1355 //----------------------------------------------------------------------------
1356 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
1357                                       DeclContext *&LexicalDC, 
1358                                       DeclarationName &Name, 
1359                                       SourceLocation &Loc) {
1360   // Import the context of this declaration.
1361   DC = Importer.ImportContext(D->getDeclContext());
1362   if (!DC)
1363     return true;
1364   
1365   LexicalDC = DC;
1366   if (D->getDeclContext() != D->getLexicalDeclContext()) {
1367     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1368     if (!LexicalDC)
1369       return true;
1370   }
1371   
1372   // Import the name of this declaration.
1373   Name = Importer.Import(D->getDeclName());
1374   if (D->getDeclName() && !Name)
1375     return true;
1376   
1377   // Import the location of this declaration.
1378   Loc = Importer.Import(D->getLocation());
1379   return false;
1380 }
1381
1382 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC) {
1383   for (DeclContext::decl_iterator From = FromDC->decls_begin(),
1384                                FromEnd = FromDC->decls_end();
1385        From != FromEnd;
1386        ++From)
1387     Importer.Import(*From);
1388 }
1389
1390 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, 
1391                                         RecordDecl *ToRecord) {
1392   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1393                                    Importer.getToContext(),
1394                                    Importer.getDiags(),
1395                                    Importer.getNonEquivalentDecls());
1396   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
1397 }
1398
1399 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1400   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1401                                    Importer.getToContext(),
1402                                    Importer.getDiags(),
1403                                    Importer.getNonEquivalentDecls());
1404   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
1405 }
1406
1407 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
1408   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1409     << D->getDeclKindName();
1410   return 0;
1411 }
1412
1413 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
1414   // Import the major distinguishing characteristics of this namespace.
1415   DeclContext *DC, *LexicalDC;
1416   DeclarationName Name;
1417   SourceLocation Loc;
1418   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1419     return 0;
1420   
1421   NamespaceDecl *MergeWithNamespace = 0;
1422   if (!Name) {
1423     // This is an anonymous namespace. Adopt an existing anonymous
1424     // namespace if we can.
1425     // FIXME: Not testable.
1426     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1427       MergeWithNamespace = TU->getAnonymousNamespace();
1428     else
1429       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1430   } else {
1431     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1432     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1433          Lookup.first != Lookup.second; 
1434          ++Lookup.first) {
1435       if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1436         continue;
1437       
1438       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(*Lookup.first)) {
1439         MergeWithNamespace = FoundNS;
1440         ConflictingDecls.clear();
1441         break;
1442       }
1443       
1444       ConflictingDecls.push_back(*Lookup.first);
1445     }
1446     
1447     if (!ConflictingDecls.empty()) {
1448       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
1449                                          ConflictingDecls.data(), 
1450                                          ConflictingDecls.size());
1451     }
1452   }
1453   
1454   // Create the "to" namespace, if needed.
1455   NamespaceDecl *ToNamespace = MergeWithNamespace;
1456   if (!ToNamespace) {
1457     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC, Loc,
1458                                         Name.getAsIdentifierInfo());
1459     ToNamespace->setLexicalDeclContext(LexicalDC);
1460     LexicalDC->addDecl(ToNamespace);
1461     
1462     // If this is an anonymous namespace, register it as the anonymous
1463     // namespace within its context.
1464     if (!Name) {
1465       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1466         TU->setAnonymousNamespace(ToNamespace);
1467       else
1468         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
1469     }
1470   }
1471   Importer.Imported(D, ToNamespace);
1472   
1473   ImportDeclContext(D);
1474   
1475   return ToNamespace;
1476 }
1477
1478 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
1479   // Import the major distinguishing characteristics of this typedef.
1480   DeclContext *DC, *LexicalDC;
1481   DeclarationName Name;
1482   SourceLocation Loc;
1483   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1484     return 0;
1485   
1486   // If this typedef is not in block scope, determine whether we've
1487   // seen a typedef with the same name (that we can merge with) or any
1488   // other entity by that name (which name lookup could conflict with).
1489   if (!DC->isFunctionOrMethod()) {
1490     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1491     unsigned IDNS = Decl::IDNS_Ordinary;
1492     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1493          Lookup.first != Lookup.second; 
1494          ++Lookup.first) {
1495       if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1496         continue;
1497       if (TypedefDecl *FoundTypedef = dyn_cast<TypedefDecl>(*Lookup.first)) {
1498         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
1499                                             FoundTypedef->getUnderlyingType()))
1500           return Importer.Imported(D, FoundTypedef);
1501       }
1502       
1503       ConflictingDecls.push_back(*Lookup.first);
1504     }
1505     
1506     if (!ConflictingDecls.empty()) {
1507       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1508                                          ConflictingDecls.data(), 
1509                                          ConflictingDecls.size());
1510       if (!Name)
1511         return 0;
1512     }
1513   }
1514   
1515   // Import the underlying type of this typedef;
1516   QualType T = Importer.Import(D->getUnderlyingType());
1517   if (T.isNull())
1518     return 0;
1519   
1520   // Create the new typedef node.
1521   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1522   TypedefDecl *ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
1523                                                Loc, Name.getAsIdentifierInfo(),
1524                                                TInfo);
1525   ToTypedef->setAccess(D->getAccess());
1526   ToTypedef->setLexicalDeclContext(LexicalDC);
1527   Importer.Imported(D, ToTypedef);
1528   LexicalDC->addDecl(ToTypedef);
1529   
1530   return ToTypedef;
1531 }
1532
1533 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
1534   // Import the major distinguishing characteristics of this enum.
1535   DeclContext *DC, *LexicalDC;
1536   DeclarationName Name;
1537   SourceLocation Loc;
1538   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1539     return 0;
1540   
1541   // Figure out what enum name we're looking for.
1542   unsigned IDNS = Decl::IDNS_Tag;
1543   DeclarationName SearchName = Name;
1544   if (!SearchName && D->getTypedefForAnonDecl()) {
1545     SearchName = Importer.Import(D->getTypedefForAnonDecl()->getDeclName());
1546     IDNS = Decl::IDNS_Ordinary;
1547   } else if (Importer.getToContext().getLangOptions().CPlusPlus)
1548     IDNS |= Decl::IDNS_Ordinary;
1549   
1550   // We may already have an enum of the same name; try to find and match it.
1551   if (!DC->isFunctionOrMethod() && SearchName) {
1552     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1553     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1554          Lookup.first != Lookup.second; 
1555          ++Lookup.first) {
1556       if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1557         continue;
1558       
1559       Decl *Found = *Lookup.first;
1560       if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Found)) {
1561         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1562           Found = Tag->getDecl();
1563       }
1564       
1565       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
1566         if (IsStructuralMatch(D, FoundEnum))
1567           return Importer.Imported(D, FoundEnum);
1568       }
1569       
1570       ConflictingDecls.push_back(*Lookup.first);
1571     }
1572     
1573     if (!ConflictingDecls.empty()) {
1574       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1575                                          ConflictingDecls.data(), 
1576                                          ConflictingDecls.size());
1577     }
1578   }
1579   
1580   // Create the enum declaration.
1581   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC, Loc,
1582                                       Name.getAsIdentifierInfo(),
1583                                       Importer.Import(D->getTagKeywordLoc()),
1584                                       0);
1585   D2->setAccess(D->getAccess());
1586   D2->setLexicalDeclContext(LexicalDC);
1587   Importer.Imported(D, D2);
1588   LexicalDC->addDecl(D2);
1589
1590   // Import the integer type.
1591   QualType ToIntegerType = Importer.Import(D->getIntegerType());
1592   if (ToIntegerType.isNull())
1593     return 0;
1594   D2->setIntegerType(ToIntegerType);
1595   
1596   // Import the definition
1597   if (D->isDefinition()) {
1598     QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(D));
1599     if (T.isNull())
1600       return 0;
1601
1602     QualType ToPromotionType = Importer.Import(D->getPromotionType());
1603     if (ToPromotionType.isNull())
1604       return 0;
1605     
1606     D2->startDefinition();
1607     ImportDeclContext(D);
1608     D2->completeDefinition(T, ToPromotionType);
1609   }
1610   
1611   return D2;
1612 }
1613
1614 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
1615   // If this record has a definition in the translation unit we're coming from,
1616   // but this particular declaration is not that definition, import the
1617   // definition and map to that.
1618   TagDecl *Definition = D->getDefinition();
1619   if (Definition && Definition != D) {
1620     Decl *ImportedDef = Importer.Import(Definition);
1621     if (!ImportedDef)
1622       return 0;
1623     
1624     return Importer.Imported(D, ImportedDef);
1625   }
1626   
1627   // Import the major distinguishing characteristics of this record.
1628   DeclContext *DC, *LexicalDC;
1629   DeclarationName Name;
1630   SourceLocation Loc;
1631   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1632     return 0;
1633       
1634   // Figure out what structure name we're looking for.
1635   unsigned IDNS = Decl::IDNS_Tag;
1636   DeclarationName SearchName = Name;
1637   if (!SearchName && D->getTypedefForAnonDecl()) {
1638     SearchName = Importer.Import(D->getTypedefForAnonDecl()->getDeclName());
1639     IDNS = Decl::IDNS_Ordinary;
1640   } else if (Importer.getToContext().getLangOptions().CPlusPlus)
1641     IDNS |= Decl::IDNS_Ordinary;
1642
1643   // We may already have a record of the same name; try to find and match it.
1644   RecordDecl *AdoptDecl = 0;
1645   if (!DC->isFunctionOrMethod() && SearchName) {
1646     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1647     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1648          Lookup.first != Lookup.second; 
1649          ++Lookup.first) {
1650       if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1651         continue;
1652       
1653       Decl *Found = *Lookup.first;
1654       if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Found)) {
1655         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1656           Found = Tag->getDecl();
1657       }
1658       
1659       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
1660         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
1661           if (!D->isDefinition() || IsStructuralMatch(D, FoundDef)) {
1662             // The record types structurally match, or the "from" translation
1663             // unit only had a forward declaration anyway; call it the same
1664             // function.
1665             // FIXME: For C++, we should also merge methods here.
1666             return Importer.Imported(D, FoundDef);
1667           }
1668         } else {
1669           // We have a forward declaration of this type, so adopt that forward
1670           // declaration rather than building a new one.
1671           AdoptDecl = FoundRecord;
1672           continue;
1673         }          
1674       }
1675       
1676       ConflictingDecls.push_back(*Lookup.first);
1677     }
1678     
1679     if (!ConflictingDecls.empty()) {
1680       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1681                                          ConflictingDecls.data(), 
1682                                          ConflictingDecls.size());
1683     }
1684   }
1685   
1686   // Create the record declaration.
1687   RecordDecl *D2 = AdoptDecl;
1688   if (!D2) {
1689     if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D)) {
1690       CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(), 
1691                                                    D->getTagKind(),
1692                                                    DC, Loc,
1693                                                    Name.getAsIdentifierInfo(), 
1694                                         Importer.Import(D->getTagKeywordLoc()));
1695       D2 = D2CXX;
1696       D2->setAccess(D->getAccess());
1697       
1698       if (D->isDefinition()) {
1699         // Add base classes.
1700         llvm::SmallVector<CXXBaseSpecifier *, 4> Bases;
1701         for (CXXRecordDecl::base_class_iterator 
1702                   Base1 = D1CXX->bases_begin(),
1703                FromBaseEnd = D1CXX->bases_end();
1704              Base1 != FromBaseEnd;
1705              ++Base1) {
1706           QualType T = Importer.Import(Base1->getType());
1707           if (T.isNull())
1708             return 0;
1709           
1710           Bases.push_back(
1711             new (Importer.getToContext()) 
1712                   CXXBaseSpecifier(Importer.Import(Base1->getSourceRange()),
1713                                    Base1->isVirtual(),
1714                                    Base1->isBaseOfClass(),
1715                                    Base1->getAccessSpecifierAsWritten(),
1716                                    T));
1717         }
1718         if (!Bases.empty())
1719           D2CXX->setBases(Bases.data(), Bases.size());
1720       }
1721     } else {
1722       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
1723                                     DC, Loc,
1724                                     Name.getAsIdentifierInfo(), 
1725                                     Importer.Import(D->getTagKeywordLoc()));
1726     }
1727     D2->setLexicalDeclContext(LexicalDC);
1728     LexicalDC->addDecl(D2);
1729   }
1730   
1731   Importer.Imported(D, D2);
1732
1733   if (D->isDefinition()) {
1734     D2->startDefinition();
1735     ImportDeclContext(D);
1736     D2->completeDefinition();
1737   }
1738   
1739   return D2;
1740 }
1741
1742 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
1743   // Import the major distinguishing characteristics of this enumerator.
1744   DeclContext *DC, *LexicalDC;
1745   DeclarationName Name;
1746   SourceLocation Loc;
1747   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1748     return 0;
1749
1750   QualType T = Importer.Import(D->getType());
1751   if (T.isNull())
1752     return 0;
1753
1754   // Determine whether there are any other declarations with the same name and 
1755   // in the same context.
1756   if (!LexicalDC->isFunctionOrMethod()) {
1757     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1758     unsigned IDNS = Decl::IDNS_Ordinary;
1759     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1760          Lookup.first != Lookup.second; 
1761          ++Lookup.first) {
1762       if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1763         continue;
1764       
1765       ConflictingDecls.push_back(*Lookup.first);
1766     }
1767     
1768     if (!ConflictingDecls.empty()) {
1769       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1770                                          ConflictingDecls.data(), 
1771                                          ConflictingDecls.size());
1772       if (!Name)
1773         return 0;
1774     }
1775   }
1776   
1777   Expr *Init = Importer.Import(D->getInitExpr());
1778   if (D->getInitExpr() && !Init)
1779     return 0;
1780   
1781   EnumConstantDecl *ToEnumerator
1782     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc, 
1783                                Name.getAsIdentifierInfo(), T, 
1784                                Init, D->getInitVal());
1785   ToEnumerator->setAccess(D->getAccess());
1786   ToEnumerator->setLexicalDeclContext(LexicalDC);
1787   Importer.Imported(D, ToEnumerator);
1788   LexicalDC->addDecl(ToEnumerator);
1789   return ToEnumerator;
1790 }
1791
1792 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
1793   // Import the major distinguishing characteristics of this function.
1794   DeclContext *DC, *LexicalDC;
1795   DeclarationName Name;
1796   SourceLocation Loc;
1797   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1798     return 0;
1799   
1800   // Try to find a function in our own ("to") context with the same name, same
1801   // type, and in the same context as the function we're importing.
1802   if (!LexicalDC->isFunctionOrMethod()) {
1803     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1804     unsigned IDNS = Decl::IDNS_Ordinary;
1805     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1806          Lookup.first != Lookup.second; 
1807          ++Lookup.first) {
1808       if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1809         continue;
1810     
1811       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(*Lookup.first)) {
1812         if (isExternalLinkage(FoundFunction->getLinkage()) &&
1813             isExternalLinkage(D->getLinkage())) {
1814           if (Importer.IsStructurallyEquivalent(D->getType(), 
1815                                                 FoundFunction->getType())) {
1816             // FIXME: Actually try to merge the body and other attributes.
1817             return Importer.Imported(D, FoundFunction);
1818           }
1819         
1820           // FIXME: Check for overloading more carefully, e.g., by boosting
1821           // Sema::IsOverload out to the AST library.
1822           
1823           // Function overloading is okay in C++.
1824           if (Importer.getToContext().getLangOptions().CPlusPlus)
1825             continue;
1826           
1827           // Complain about inconsistent function types.
1828           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
1829             << Name << D->getType() << FoundFunction->getType();
1830           Importer.ToDiag(FoundFunction->getLocation(), 
1831                           diag::note_odr_value_here)
1832             << FoundFunction->getType();
1833         }
1834       }
1835       
1836       ConflictingDecls.push_back(*Lookup.first);
1837     }
1838     
1839     if (!ConflictingDecls.empty()) {
1840       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1841                                          ConflictingDecls.data(), 
1842                                          ConflictingDecls.size());
1843       if (!Name)
1844         return 0;
1845     }    
1846   }
1847
1848   // Import the type.
1849   QualType T = Importer.Import(D->getType());
1850   if (T.isNull())
1851     return 0;
1852   
1853   // Import the function parameters.
1854   llvm::SmallVector<ParmVarDecl *, 8> Parameters;
1855   for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
1856        P != PEnd; ++P) {
1857     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*P));
1858     if (!ToP)
1859       return 0;
1860     
1861     Parameters.push_back(ToP);
1862   }
1863   
1864   // Create the imported function.
1865   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1866   FunctionDecl *ToFunction = 0;
1867   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
1868     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
1869                                             cast<CXXRecordDecl>(DC),
1870                                             Loc, Name, T, TInfo, 
1871                                             FromConstructor->isExplicit(),
1872                                             D->isInlineSpecified(), 
1873                                             D->isImplicit());
1874   } else if (isa<CXXDestructorDecl>(D)) {
1875     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
1876                                            cast<CXXRecordDecl>(DC),
1877                                            Loc, Name, T, 
1878                                            D->isInlineSpecified(),
1879                                            D->isImplicit());
1880   } else if (CXXConversionDecl *FromConversion
1881                                            = dyn_cast<CXXConversionDecl>(D)) {
1882     ToFunction = CXXConversionDecl::Create(Importer.getToContext(), 
1883                                            cast<CXXRecordDecl>(DC),
1884                                            Loc, Name, T, TInfo,
1885                                            D->isInlineSpecified(),
1886                                            FromConversion->isExplicit());
1887   } else {
1888     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC, Loc, 
1889                                       Name, T, TInfo, D->getStorageClass(), 
1890                                       D->isInlineSpecified(),
1891                                       D->hasWrittenPrototype());
1892   }
1893   ToFunction->setAccess(D->getAccess());
1894   ToFunction->setLexicalDeclContext(LexicalDC);
1895   Importer.Imported(D, ToFunction);
1896   LexicalDC->addDecl(ToFunction);
1897
1898   // Set the parameters.
1899   for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
1900     Parameters[I]->setOwningFunction(ToFunction);
1901     ToFunction->addDecl(Parameters[I]);
1902   }
1903   ToFunction->setParams(Parameters.data(), Parameters.size());
1904
1905   // FIXME: Other bits to merge?
1906   
1907   return ToFunction;
1908 }
1909
1910 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
1911   return VisitFunctionDecl(D);
1912 }
1913
1914 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1915   return VisitCXXMethodDecl(D);
1916 }
1917
1918 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1919   return VisitCXXMethodDecl(D);
1920 }
1921
1922 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
1923   return VisitCXXMethodDecl(D);
1924 }
1925
1926 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
1927   // Import the major distinguishing characteristics of a variable.
1928   DeclContext *DC, *LexicalDC;
1929   DeclarationName Name;
1930   SourceLocation Loc;
1931   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1932     return 0;
1933   
1934   // Import the type.
1935   QualType T = Importer.Import(D->getType());
1936   if (T.isNull())
1937     return 0;
1938   
1939   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1940   Expr *BitWidth = Importer.Import(D->getBitWidth());
1941   if (!BitWidth && D->getBitWidth())
1942     return 0;
1943   
1944   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC, 
1945                                          Loc, Name.getAsIdentifierInfo(),
1946                                          T, TInfo, BitWidth, D->isMutable());
1947   ToField->setAccess(D->getAccess());
1948   ToField->setLexicalDeclContext(LexicalDC);
1949   Importer.Imported(D, ToField);
1950   LexicalDC->addDecl(ToField);
1951   return ToField;
1952 }
1953
1954 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
1955   // Import the major distinguishing characteristics of an ivar.
1956   DeclContext *DC, *LexicalDC;
1957   DeclarationName Name;
1958   SourceLocation Loc;
1959   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1960     return 0;
1961   
1962   // Determine whether we've already imported this ivar 
1963   for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1964        Lookup.first != Lookup.second; 
1965        ++Lookup.first) {
1966     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(*Lookup.first)) {
1967       if (Importer.IsStructurallyEquivalent(D->getType(), 
1968                                             FoundIvar->getType())) {
1969         Importer.Imported(D, FoundIvar);
1970         return FoundIvar;
1971       }
1972
1973       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
1974         << Name << D->getType() << FoundIvar->getType();
1975       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
1976         << FoundIvar->getType();
1977       return 0;
1978     }
1979   }
1980
1981   // Import the type.
1982   QualType T = Importer.Import(D->getType());
1983   if (T.isNull())
1984     return 0;
1985   
1986   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1987   Expr *BitWidth = Importer.Import(D->getBitWidth());
1988   if (!BitWidth && D->getBitWidth())
1989     return 0;
1990   
1991   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(), DC, 
1992                                               Loc, Name.getAsIdentifierInfo(),
1993                                               T, TInfo, D->getAccessControl(),
1994                                               BitWidth);
1995   ToIvar->setLexicalDeclContext(LexicalDC);
1996   Importer.Imported(D, ToIvar);
1997   LexicalDC->addDecl(ToIvar);
1998   return ToIvar;
1999   
2000 }
2001
2002 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
2003   // Import the major distinguishing characteristics of a variable.
2004   DeclContext *DC, *LexicalDC;
2005   DeclarationName Name;
2006   SourceLocation Loc;
2007   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2008     return 0;
2009   
2010   // Try to find a variable in our own ("to") context with the same name and
2011   // in the same context as the variable we're importing.
2012   if (D->isFileVarDecl()) {
2013     VarDecl *MergeWithVar = 0;
2014     llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2015     unsigned IDNS = Decl::IDNS_Ordinary;
2016     for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2017          Lookup.first != Lookup.second; 
2018          ++Lookup.first) {
2019       if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2020         continue;
2021       
2022       if (VarDecl *FoundVar = dyn_cast<VarDecl>(*Lookup.first)) {
2023         // We have found a variable that we may need to merge with. Check it.
2024         if (isExternalLinkage(FoundVar->getLinkage()) &&
2025             isExternalLinkage(D->getLinkage())) {
2026           if (Importer.IsStructurallyEquivalent(D->getType(), 
2027                                                 FoundVar->getType())) {
2028             MergeWithVar = FoundVar;
2029             break;
2030           }
2031
2032           const ArrayType *FoundArray
2033             = Importer.getToContext().getAsArrayType(FoundVar->getType());
2034           const ArrayType *TArray
2035             = Importer.getToContext().getAsArrayType(D->getType());
2036           if (FoundArray && TArray) {
2037             if (isa<IncompleteArrayType>(FoundArray) &&
2038                 isa<ConstantArrayType>(TArray)) {
2039               // Import the type.
2040               QualType T = Importer.Import(D->getType());
2041               if (T.isNull())
2042                 return 0;
2043               
2044               FoundVar->setType(T);
2045               MergeWithVar = FoundVar;
2046               break;
2047             } else if (isa<IncompleteArrayType>(TArray) &&
2048                        isa<ConstantArrayType>(FoundArray)) {
2049               MergeWithVar = FoundVar;
2050               break;
2051             }
2052           }
2053
2054           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
2055             << Name << D->getType() << FoundVar->getType();
2056           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
2057             << FoundVar->getType();
2058         }
2059       }
2060       
2061       ConflictingDecls.push_back(*Lookup.first);
2062     }
2063
2064     if (MergeWithVar) {
2065       // An equivalent variable with external linkage has been found. Link 
2066       // the two declarations, then merge them.
2067       Importer.Imported(D, MergeWithVar);
2068       
2069       if (VarDecl *DDef = D->getDefinition()) {
2070         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
2071           Importer.ToDiag(ExistingDef->getLocation(), 
2072                           diag::err_odr_variable_multiple_def)
2073             << Name;
2074           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
2075         } else {
2076           Expr *Init = Importer.Import(DDef->getInit());
2077           MergeWithVar->setInit(Init);
2078         }
2079       }
2080       
2081       return MergeWithVar;
2082     }
2083     
2084     if (!ConflictingDecls.empty()) {
2085       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2086                                          ConflictingDecls.data(), 
2087                                          ConflictingDecls.size());
2088       if (!Name)
2089         return 0;
2090     }
2091   }
2092     
2093   // Import the type.
2094   QualType T = Importer.Import(D->getType());
2095   if (T.isNull())
2096     return 0;
2097   
2098   // Create the imported variable.
2099   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2100   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC, Loc, 
2101                                    Name.getAsIdentifierInfo(), T, TInfo,
2102                                    D->getStorageClass());
2103   ToVar->setAccess(D->getAccess());
2104   ToVar->setLexicalDeclContext(LexicalDC);
2105   Importer.Imported(D, ToVar);
2106   LexicalDC->addDecl(ToVar);
2107
2108   // Merge the initializer.
2109   // FIXME: Can we really import any initializer? Alternatively, we could force
2110   // ourselves to import every declaration of a variable and then only use
2111   // getInit() here.
2112   ToVar->setInit(Importer.Import(const_cast<Expr *>(D->getAnyInitializer())));
2113
2114   // FIXME: Other bits to merge?
2115   
2116   return ToVar;
2117 }
2118
2119 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
2120   // Parameters are created in the translation unit's context, then moved
2121   // into the function declaration's context afterward.
2122   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2123   
2124   // Import the name of this declaration.
2125   DeclarationName Name = Importer.Import(D->getDeclName());
2126   if (D->getDeclName() && !Name)
2127     return 0;
2128   
2129   // Import the location of this declaration.
2130   SourceLocation Loc = Importer.Import(D->getLocation());
2131   
2132   // Import the parameter's type.
2133   QualType T = Importer.Import(D->getType());
2134   if (T.isNull())
2135     return 0;
2136   
2137   // Create the imported parameter.
2138   ImplicitParamDecl *ToParm
2139     = ImplicitParamDecl::Create(Importer.getToContext(), DC,
2140                                 Loc, Name.getAsIdentifierInfo(),
2141                                 T);
2142   return Importer.Imported(D, ToParm);
2143 }
2144
2145 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
2146   // Parameters are created in the translation unit's context, then moved
2147   // into the function declaration's context afterward.
2148   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2149   
2150   // Import the name of this declaration.
2151   DeclarationName Name = Importer.Import(D->getDeclName());
2152   if (D->getDeclName() && !Name)
2153     return 0;
2154   
2155   // Import the location of this declaration.
2156   SourceLocation Loc = Importer.Import(D->getLocation());
2157   
2158   // Import the parameter's type.
2159   QualType T = Importer.Import(D->getType());
2160   if (T.isNull())
2161     return 0;
2162   
2163   // Create the imported parameter.
2164   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2165   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
2166                                             Loc, Name.getAsIdentifierInfo(),
2167                                             T, TInfo, D->getStorageClass(),
2168                                             /*FIXME: Default argument*/ 0);
2169   return Importer.Imported(D, ToParm);
2170 }
2171
2172 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
2173   // Import the major distinguishing characteristics of a method.
2174   DeclContext *DC, *LexicalDC;
2175   DeclarationName Name;
2176   SourceLocation Loc;
2177   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2178     return 0;
2179   
2180   for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2181        Lookup.first != Lookup.second; 
2182        ++Lookup.first) {
2183     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(*Lookup.first)) {
2184       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
2185         continue;
2186
2187       // Check return types.
2188       if (!Importer.IsStructurallyEquivalent(D->getResultType(),
2189                                              FoundMethod->getResultType())) {
2190         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
2191           << D->isInstanceMethod() << Name
2192           << D->getResultType() << FoundMethod->getResultType();
2193         Importer.ToDiag(FoundMethod->getLocation(), 
2194                         diag::note_odr_objc_method_here)
2195           << D->isInstanceMethod() << Name;
2196         return 0;
2197       }
2198
2199       // Check the number of parameters.
2200       if (D->param_size() != FoundMethod->param_size()) {
2201         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
2202           << D->isInstanceMethod() << Name
2203           << D->param_size() << FoundMethod->param_size();
2204         Importer.ToDiag(FoundMethod->getLocation(), 
2205                         diag::note_odr_objc_method_here)
2206           << D->isInstanceMethod() << Name;
2207         return 0;
2208       }
2209
2210       // Check parameter types.
2211       for (ObjCMethodDecl::param_iterator P = D->param_begin(), 
2212              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
2213            P != PEnd; ++P, ++FoundP) {
2214         if (!Importer.IsStructurallyEquivalent((*P)->getType(), 
2215                                                (*FoundP)->getType())) {
2216           Importer.FromDiag((*P)->getLocation(), 
2217                             diag::err_odr_objc_method_param_type_inconsistent)
2218             << D->isInstanceMethod() << Name
2219             << (*P)->getType() << (*FoundP)->getType();
2220           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
2221             << (*FoundP)->getType();
2222           return 0;
2223         }
2224       }
2225
2226       // Check variadic/non-variadic.
2227       // Check the number of parameters.
2228       if (D->isVariadic() != FoundMethod->isVariadic()) {
2229         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
2230           << D->isInstanceMethod() << Name;
2231         Importer.ToDiag(FoundMethod->getLocation(), 
2232                         diag::note_odr_objc_method_here)
2233           << D->isInstanceMethod() << Name;
2234         return 0;
2235       }
2236
2237       // FIXME: Any other bits we need to merge?
2238       return Importer.Imported(D, FoundMethod);
2239     }
2240   }
2241
2242   // Import the result type.
2243   QualType ResultTy = Importer.Import(D->getResultType());
2244   if (ResultTy.isNull())
2245     return 0;
2246
2247   ObjCMethodDecl *ToMethod
2248     = ObjCMethodDecl::Create(Importer.getToContext(),
2249                              Loc,
2250                              Importer.Import(D->getLocEnd()),
2251                              Name.getObjCSelector(),
2252                              ResultTy, DC,
2253                              D->isInstanceMethod(),
2254                              D->isVariadic(),
2255                              D->isSynthesized(),
2256                              D->getImplementationControl());
2257
2258   // FIXME: When we decide to merge method definitions, we'll need to
2259   // deal with implicit parameters.
2260
2261   // Import the parameters
2262   llvm::SmallVector<ParmVarDecl *, 5> ToParams;
2263   for (ObjCMethodDecl::param_iterator FromP = D->param_begin(),
2264                                    FromPEnd = D->param_end();
2265        FromP != FromPEnd; 
2266        ++FromP) {
2267     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*FromP));
2268     if (!ToP)
2269       return 0;
2270     
2271     ToParams.push_back(ToP);
2272   }
2273   
2274   // Set the parameters.
2275   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
2276     ToParams[I]->setOwningFunction(ToMethod);
2277     ToMethod->addDecl(ToParams[I]);
2278   }
2279   ToMethod->setMethodParams(Importer.getToContext(), 
2280                             ToParams.data(), ToParams.size());
2281
2282   ToMethod->setLexicalDeclContext(LexicalDC);
2283   Importer.Imported(D, ToMethod);
2284   LexicalDC->addDecl(ToMethod);
2285   return ToMethod;
2286 }
2287
2288 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
2289   // Import the major distinguishing characteristics of a category.
2290   DeclContext *DC, *LexicalDC;
2291   DeclarationName Name;
2292   SourceLocation Loc;
2293   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2294     return 0;
2295   
2296   ObjCInterfaceDecl *ToInterface
2297     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
2298   if (!ToInterface)
2299     return 0;
2300   
2301   // Determine if we've already encountered this category.
2302   ObjCCategoryDecl *MergeWithCategory
2303     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
2304   ObjCCategoryDecl *ToCategory = MergeWithCategory;
2305   if (!ToCategory) {
2306     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
2307                                           Importer.Import(D->getAtLoc()),
2308                                           Loc, 
2309                                        Importer.Import(D->getCategoryNameLoc()), 
2310                                           Name.getAsIdentifierInfo());
2311     ToCategory->setLexicalDeclContext(LexicalDC);
2312     LexicalDC->addDecl(ToCategory);
2313     Importer.Imported(D, ToCategory);
2314     
2315     // Link this category into its class's category list.
2316     ToCategory->setClassInterface(ToInterface);
2317     ToCategory->insertNextClassCategory();
2318     
2319     // Import protocols
2320     llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2321     llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2322     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
2323       = D->protocol_loc_begin();
2324     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
2325                                           FromProtoEnd = D->protocol_end();
2326          FromProto != FromProtoEnd;
2327          ++FromProto, ++FromProtoLoc) {
2328       ObjCProtocolDecl *ToProto
2329         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2330       if (!ToProto)
2331         return 0;
2332       Protocols.push_back(ToProto);
2333       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2334     }
2335     
2336     // FIXME: If we're merging, make sure that the protocol list is the same.
2337     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
2338                                 ProtocolLocs.data(), Importer.getToContext());
2339     
2340   } else {
2341     Importer.Imported(D, ToCategory);
2342   }
2343   
2344   // Import all of the members of this category.
2345   ImportDeclContext(D);
2346  
2347   // If we have an implementation, import it as well.
2348   if (D->getImplementation()) {
2349     ObjCCategoryImplDecl *Impl
2350       = cast<ObjCCategoryImplDecl>(Importer.Import(D->getImplementation()));
2351     if (!Impl)
2352       return 0;
2353     
2354     ToCategory->setImplementation(Impl);
2355   }
2356   
2357   return ToCategory;
2358 }
2359
2360 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
2361   // Import the major distinguishing characteristics of a protocol.
2362   DeclContext *DC, *LexicalDC;
2363   DeclarationName Name;
2364   SourceLocation Loc;
2365   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2366     return 0;
2367
2368   ObjCProtocolDecl *MergeWithProtocol = 0;
2369   for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2370        Lookup.first != Lookup.second; 
2371        ++Lookup.first) {
2372     if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
2373       continue;
2374     
2375     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(*Lookup.first)))
2376       break;
2377   }
2378   
2379   ObjCProtocolDecl *ToProto = MergeWithProtocol;
2380   if (!ToProto || ToProto->isForwardDecl()) {
2381     if (!ToProto) {
2382       ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC, Loc,
2383                                          Name.getAsIdentifierInfo());
2384       ToProto->setForwardDecl(D->isForwardDecl());
2385       ToProto->setLexicalDeclContext(LexicalDC);
2386       LexicalDC->addDecl(ToProto);
2387     }
2388     Importer.Imported(D, ToProto);
2389
2390     // Import protocols
2391     llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2392     llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2393     ObjCProtocolDecl::protocol_loc_iterator 
2394       FromProtoLoc = D->protocol_loc_begin();
2395     for (ObjCProtocolDecl::protocol_iterator FromProto = D->protocol_begin(),
2396                                           FromProtoEnd = D->protocol_end();
2397        FromProto != FromProtoEnd;
2398        ++FromProto, ++FromProtoLoc) {
2399       ObjCProtocolDecl *ToProto
2400         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2401       if (!ToProto)
2402         return 0;
2403       Protocols.push_back(ToProto);
2404       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2405     }
2406     
2407     // FIXME: If we're merging, make sure that the protocol list is the same.
2408     ToProto->setProtocolList(Protocols.data(), Protocols.size(),
2409                              ProtocolLocs.data(), Importer.getToContext());
2410   } else {
2411     Importer.Imported(D, ToProto);
2412   }
2413
2414   // Import all of the members of this protocol.
2415   ImportDeclContext(D);
2416
2417   return ToProto;
2418 }
2419
2420 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
2421   // Import the major distinguishing characteristics of an @interface.
2422   DeclContext *DC, *LexicalDC;
2423   DeclarationName Name;
2424   SourceLocation Loc;
2425   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2426     return 0;
2427
2428   ObjCInterfaceDecl *MergeWithIface = 0;
2429   for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2430        Lookup.first != Lookup.second; 
2431        ++Lookup.first) {
2432     if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2433       continue;
2434     
2435     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(*Lookup.first)))
2436       break;
2437   }
2438   
2439   ObjCInterfaceDecl *ToIface = MergeWithIface;
2440   if (!ToIface || ToIface->isForwardDecl()) {
2441     if (!ToIface) {
2442       ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(),
2443                                           DC, Loc,
2444                                           Name.getAsIdentifierInfo(),
2445                                           Importer.Import(D->getClassLoc()),
2446                                           D->isForwardDecl(),
2447                                           D->isImplicitInterfaceDecl());
2448       ToIface->setForwardDecl(D->isForwardDecl());
2449       ToIface->setLexicalDeclContext(LexicalDC);
2450       LexicalDC->addDecl(ToIface);
2451     }
2452     Importer.Imported(D, ToIface);
2453
2454     if (D->getSuperClass()) {
2455       ObjCInterfaceDecl *Super
2456         = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getSuperClass()));
2457       if (!Super)
2458         return 0;
2459       
2460       ToIface->setSuperClass(Super);
2461       ToIface->setSuperClassLoc(Importer.Import(D->getSuperClassLoc()));
2462     }
2463     
2464     // Import protocols
2465     llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2466     llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2467     ObjCInterfaceDecl::protocol_loc_iterator 
2468       FromProtoLoc = D->protocol_loc_begin();
2469     for (ObjCInterfaceDecl::protocol_iterator FromProto = D->protocol_begin(),
2470                                            FromProtoEnd = D->protocol_end();
2471        FromProto != FromProtoEnd;
2472        ++FromProto, ++FromProtoLoc) {
2473       ObjCProtocolDecl *ToProto
2474         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2475       if (!ToProto)
2476         return 0;
2477       Protocols.push_back(ToProto);
2478       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2479     }
2480     
2481     // FIXME: If we're merging, make sure that the protocol list is the same.
2482     ToIface->setProtocolList(Protocols.data(), Protocols.size(),
2483                              ProtocolLocs.data(), Importer.getToContext());
2484     
2485     // Import @end range
2486     ToIface->setAtEndRange(Importer.Import(D->getAtEndRange()));
2487   } else {
2488     Importer.Imported(D, ToIface);
2489
2490     // Check for consistency of superclasses.
2491     DeclarationName FromSuperName, ToSuperName;
2492     if (D->getSuperClass())
2493       FromSuperName = Importer.Import(D->getSuperClass()->getDeclName());
2494     if (ToIface->getSuperClass())
2495       ToSuperName = ToIface->getSuperClass()->getDeclName();
2496     if (FromSuperName != ToSuperName) {
2497       Importer.ToDiag(ToIface->getLocation(), 
2498                       diag::err_odr_objc_superclass_inconsistent)
2499         << ToIface->getDeclName();
2500       if (ToIface->getSuperClass())
2501         Importer.ToDiag(ToIface->getSuperClassLoc(), 
2502                         diag::note_odr_objc_superclass)
2503           << ToIface->getSuperClass()->getDeclName();
2504       else
2505         Importer.ToDiag(ToIface->getLocation(), 
2506                         diag::note_odr_objc_missing_superclass);
2507       if (D->getSuperClass())
2508         Importer.FromDiag(D->getSuperClassLoc(), 
2509                           diag::note_odr_objc_superclass)
2510           << D->getSuperClass()->getDeclName();
2511       else
2512         Importer.FromDiag(D->getLocation(), 
2513                           diag::note_odr_objc_missing_superclass);
2514       return 0;
2515     }
2516   }
2517   
2518   // Import categories. When the categories themselves are imported, they'll
2519   // hook themselves into this interface.
2520   for (ObjCCategoryDecl *FromCat = D->getCategoryList(); FromCat;
2521        FromCat = FromCat->getNextClassCategory())
2522     Importer.Import(FromCat);
2523   
2524   // Import all of the members of this class.
2525   ImportDeclContext(D);
2526   
2527   // If we have an @implementation, import it as well.
2528   if (D->getImplementation()) {
2529     ObjCImplementationDecl *Impl
2530       = cast<ObjCImplementationDecl>(Importer.Import(D->getImplementation()));
2531     if (!Impl)
2532       return 0;
2533     
2534     ToIface->setImplementation(Impl);
2535   }
2536   
2537   return ToIface;
2538 }
2539
2540 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
2541   // Import the major distinguishing characteristics of an @property.
2542   DeclContext *DC, *LexicalDC;
2543   DeclarationName Name;
2544   SourceLocation Loc;
2545   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2546     return 0;
2547
2548   // Check whether we have already imported this property.
2549   for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2550        Lookup.first != Lookup.second; 
2551        ++Lookup.first) {
2552     if (ObjCPropertyDecl *FoundProp
2553                                 = dyn_cast<ObjCPropertyDecl>(*Lookup.first)) {
2554       // Check property types.
2555       if (!Importer.IsStructurallyEquivalent(D->getType(), 
2556                                              FoundProp->getType())) {
2557         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
2558           << Name << D->getType() << FoundProp->getType();
2559         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
2560           << FoundProp->getType();
2561         return 0;
2562       }
2563
2564       // FIXME: Check property attributes, getters, setters, etc.?
2565
2566       // Consider these properties to be equivalent.
2567       Importer.Imported(D, FoundProp);
2568       return FoundProp;
2569     }
2570   }
2571
2572   // Import the type.
2573   QualType T = Importer.Import(D->getType());
2574   if (T.isNull())
2575     return 0;
2576
2577   // Create the new property.
2578   ObjCPropertyDecl *ToProperty
2579     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
2580                                Name.getAsIdentifierInfo(), 
2581                                Importer.Import(D->getAtLoc()),
2582                                T,
2583                                D->getPropertyImplementation());
2584   Importer.Imported(D, ToProperty);
2585   ToProperty->setLexicalDeclContext(LexicalDC);
2586   LexicalDC->addDecl(ToProperty);
2587
2588   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
2589   ToProperty->setGetterName(Importer.Import(D->getGetterName()));
2590   ToProperty->setSetterName(Importer.Import(D->getSetterName()));
2591   ToProperty->setGetterMethodDecl(
2592      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
2593   ToProperty->setSetterMethodDecl(
2594      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
2595   ToProperty->setPropertyIvarDecl(
2596        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
2597   return ToProperty;
2598 }
2599
2600 Decl *
2601 ASTNodeImporter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
2602   // Import the context of this declaration.
2603   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2604   if (!DC)
2605     return 0;
2606   
2607   DeclContext *LexicalDC = DC;
2608   if (D->getDeclContext() != D->getLexicalDeclContext()) {
2609     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2610     if (!LexicalDC)
2611       return 0;
2612   }
2613   
2614   // Import the location of this declaration.
2615   SourceLocation Loc = Importer.Import(D->getLocation());
2616   
2617   llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2618   llvm::SmallVector<SourceLocation, 4> Locations;
2619   ObjCForwardProtocolDecl::protocol_loc_iterator FromProtoLoc
2620     = D->protocol_loc_begin();
2621   for (ObjCForwardProtocolDecl::protocol_iterator FromProto
2622          = D->protocol_begin(), FromProtoEnd = D->protocol_end();
2623        FromProto != FromProtoEnd; 
2624        ++FromProto, ++FromProtoLoc) {
2625     ObjCProtocolDecl *ToProto
2626       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2627     if (!ToProto)
2628       continue;
2629     
2630     Protocols.push_back(ToProto);
2631     Locations.push_back(Importer.Import(*FromProtoLoc));
2632   }
2633   
2634   ObjCForwardProtocolDecl *ToForward
2635     = ObjCForwardProtocolDecl::Create(Importer.getToContext(), DC, Loc, 
2636                                       Protocols.data(), Protocols.size(),
2637                                       Locations.data());
2638   ToForward->setLexicalDeclContext(LexicalDC);
2639   LexicalDC->addDecl(ToForward);
2640   Importer.Imported(D, ToForward);
2641   return ToForward;
2642 }
2643
2644 Decl *ASTNodeImporter::VisitObjCClassDecl(ObjCClassDecl *D) {
2645   // Import the context of this declaration.
2646   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2647   if (!DC)
2648     return 0;
2649   
2650   DeclContext *LexicalDC = DC;
2651   if (D->getDeclContext() != D->getLexicalDeclContext()) {
2652     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2653     if (!LexicalDC)
2654       return 0;
2655   }
2656   
2657   // Import the location of this declaration.
2658   SourceLocation Loc = Importer.Import(D->getLocation());
2659
2660   llvm::SmallVector<ObjCInterfaceDecl *, 4> Interfaces;
2661   llvm::SmallVector<SourceLocation, 4> Locations;
2662   for (ObjCClassDecl::iterator From = D->begin(), FromEnd = D->end();
2663        From != FromEnd; ++From) {
2664     ObjCInterfaceDecl *ToIface
2665       = cast_or_null<ObjCInterfaceDecl>(Importer.Import(From->getInterface()));
2666     if (!ToIface)
2667       continue;
2668     
2669     Interfaces.push_back(ToIface);
2670     Locations.push_back(Importer.Import(From->getLocation()));
2671   }
2672   
2673   ObjCClassDecl *ToClass = ObjCClassDecl::Create(Importer.getToContext(), DC,
2674                                                  Loc, 
2675                                                  Interfaces.data(),
2676                                                  Locations.data(),
2677                                                  Interfaces.size());
2678   ToClass->setLexicalDeclContext(LexicalDC);
2679   LexicalDC->addDecl(ToClass);
2680   Importer.Imported(D, ToClass);
2681   return ToClass;
2682 }
2683
2684 //----------------------------------------------------------------------------
2685 // Import Statements
2686 //----------------------------------------------------------------------------
2687
2688 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
2689   Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
2690     << S->getStmtClassName();
2691   return 0;
2692 }
2693
2694 //----------------------------------------------------------------------------
2695 // Import Expressions
2696 //----------------------------------------------------------------------------
2697 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
2698   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
2699     << E->getStmtClassName();
2700   return 0;
2701 }
2702
2703 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
2704   NestedNameSpecifier *Qualifier = 0;
2705   if (E->getQualifier()) {
2706     Qualifier = Importer.Import(E->getQualifier());
2707     if (!E->getQualifier())
2708       return 0;
2709   }
2710   
2711   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
2712   if (!ToD)
2713     return 0;
2714   
2715   QualType T = Importer.Import(E->getType());
2716   if (T.isNull())
2717     return 0;
2718   
2719   return DeclRefExpr::Create(Importer.getToContext(), Qualifier,
2720                              Importer.Import(E->getQualifierRange()),
2721                              ToD,
2722                              Importer.Import(E->getLocation()),
2723                              T,
2724                              /*FIXME:TemplateArgs=*/0);
2725 }
2726
2727 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
2728   QualType T = Importer.Import(E->getType());
2729   if (T.isNull())
2730     return 0;
2731
2732   return new (Importer.getToContext()) 
2733     IntegerLiteral(E->getValue(), T, Importer.Import(E->getLocation()));
2734 }
2735
2736 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
2737   QualType T = Importer.Import(E->getType());
2738   if (T.isNull())
2739     return 0;
2740   
2741   return new (Importer.getToContext()) CharacterLiteral(E->getValue(), 
2742                                                         E->isWide(), T,
2743                                           Importer.Import(E->getLocation()));
2744 }
2745
2746 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
2747   Expr *SubExpr = Importer.Import(E->getSubExpr());
2748   if (!SubExpr)
2749     return 0;
2750   
2751   return new (Importer.getToContext()) 
2752                                   ParenExpr(Importer.Import(E->getLParen()),
2753                                             Importer.Import(E->getRParen()),
2754                                             SubExpr);
2755 }
2756
2757 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
2758   QualType T = Importer.Import(E->getType());
2759   if (T.isNull())
2760     return 0;
2761
2762   Expr *SubExpr = Importer.Import(E->getSubExpr());
2763   if (!SubExpr)
2764     return 0;
2765   
2766   return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
2767                                                      T,
2768                                          Importer.Import(E->getOperatorLoc()));                                        
2769 }
2770
2771 Expr *ASTNodeImporter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
2772   QualType ResultType = Importer.Import(E->getType());
2773   
2774   if (E->isArgumentType()) {
2775     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
2776     if (!TInfo)
2777       return 0;
2778     
2779     return new (Importer.getToContext()) SizeOfAlignOfExpr(E->isSizeOf(),
2780                                                            TInfo, ResultType,
2781                                            Importer.Import(E->getOperatorLoc()),
2782                                            Importer.Import(E->getRParenLoc()));
2783   }
2784   
2785   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
2786   if (!SubExpr)
2787     return 0;
2788   
2789   return new (Importer.getToContext()) SizeOfAlignOfExpr(E->isSizeOf(),
2790                                                          SubExpr, ResultType,
2791                                           Importer.Import(E->getOperatorLoc()),
2792                                           Importer.Import(E->getRParenLoc()));
2793 }
2794
2795 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
2796   QualType T = Importer.Import(E->getType());
2797   if (T.isNull())
2798     return 0;
2799
2800   Expr *LHS = Importer.Import(E->getLHS());
2801   if (!LHS)
2802     return 0;
2803   
2804   Expr *RHS = Importer.Import(E->getRHS());
2805   if (!RHS)
2806     return 0;
2807   
2808   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
2809                                                       T,
2810                                           Importer.Import(E->getOperatorLoc()));
2811 }
2812
2813 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
2814   QualType T = Importer.Import(E->getType());
2815   if (T.isNull())
2816     return 0;
2817   
2818   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
2819   if (CompLHSType.isNull())
2820     return 0;
2821   
2822   QualType CompResultType = Importer.Import(E->getComputationResultType());
2823   if (CompResultType.isNull())
2824     return 0;
2825   
2826   Expr *LHS = Importer.Import(E->getLHS());
2827   if (!LHS)
2828     return 0;
2829   
2830   Expr *RHS = Importer.Import(E->getRHS());
2831   if (!RHS)
2832     return 0;
2833   
2834   return new (Importer.getToContext()) 
2835                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
2836                                                T, CompLHSType, CompResultType,
2837                                           Importer.Import(E->getOperatorLoc()));
2838 }
2839
2840 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
2841   QualType T = Importer.Import(E->getType());
2842   if (T.isNull())
2843     return 0;
2844
2845   Expr *SubExpr = Importer.Import(E->getSubExpr());
2846   if (!SubExpr)
2847     return 0;
2848   
2849   return new (Importer.getToContext()) ImplicitCastExpr(T, E->getCastKind(),
2850                                                         SubExpr, 
2851                                                         E->isLvalueCast());
2852 }
2853
2854 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
2855   QualType T = Importer.Import(E->getType());
2856   if (T.isNull())
2857     return 0;
2858   
2859   Expr *SubExpr = Importer.Import(E->getSubExpr());
2860   if (!SubExpr)
2861     return 0;
2862
2863   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
2864   if (!TInfo && E->getTypeInfoAsWritten())
2865     return 0;
2866   
2867   return new (Importer.getToContext()) CStyleCastExpr(T, E->getCastKind(),
2868                                                       SubExpr, TInfo,
2869                                             Importer.Import(E->getLParenLoc()),
2870                                             Importer.Import(E->getRParenLoc()));
2871 }
2872
2873 ASTImporter::ASTImporter(Diagnostic &Diags,
2874                          ASTContext &ToContext, FileManager &ToFileManager,
2875                          ASTContext &FromContext, FileManager &FromFileManager)
2876   : ToContext(ToContext), FromContext(FromContext),
2877     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
2878     Diags(Diags) {
2879   ImportedDecls[FromContext.getTranslationUnitDecl()]
2880     = ToContext.getTranslationUnitDecl();
2881 }
2882
2883 ASTImporter::~ASTImporter() { }
2884
2885 QualType ASTImporter::Import(QualType FromT) {
2886   if (FromT.isNull())
2887     return QualType();
2888   
2889   // Check whether we've already imported this type.  
2890   llvm::DenseMap<Type *, Type *>::iterator Pos
2891     = ImportedTypes.find(FromT.getTypePtr());
2892   if (Pos != ImportedTypes.end())
2893     return ToContext.getQualifiedType(Pos->second, FromT.getQualifiers());
2894   
2895   // Import the type
2896   ASTNodeImporter Importer(*this);
2897   QualType ToT = Importer.Visit(FromT.getTypePtr());
2898   if (ToT.isNull())
2899     return ToT;
2900   
2901   // Record the imported type.
2902   ImportedTypes[FromT.getTypePtr()] = ToT.getTypePtr();
2903   
2904   return ToContext.getQualifiedType(ToT, FromT.getQualifiers());
2905 }
2906
2907 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
2908   if (!FromTSI)
2909     return FromTSI;
2910
2911   // FIXME: For now we just create a "trivial" type source info based
2912   // on the type and a seingle location. Implement a real version of
2913   // this.
2914   QualType T = Import(FromTSI->getType());
2915   if (T.isNull())
2916     return 0;
2917
2918   return ToContext.getTrivialTypeSourceInfo(T, 
2919                         FromTSI->getTypeLoc().getFullSourceRange().getBegin());
2920 }
2921
2922 Decl *ASTImporter::Import(Decl *FromD) {
2923   if (!FromD)
2924     return 0;
2925
2926   // Check whether we've already imported this declaration.  
2927   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
2928   if (Pos != ImportedDecls.end())
2929     return Pos->second;
2930   
2931   // Import the type
2932   ASTNodeImporter Importer(*this);
2933   Decl *ToD = Importer.Visit(FromD);
2934   if (!ToD)
2935     return 0;
2936   
2937   // Record the imported declaration.
2938   ImportedDecls[FromD] = ToD;
2939   
2940   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
2941     // Keep track of anonymous tags that have an associated typedef.
2942     if (FromTag->getTypedefForAnonDecl())
2943       AnonTagsWithPendingTypedefs.push_back(FromTag);
2944   } else if (TypedefDecl *FromTypedef = dyn_cast<TypedefDecl>(FromD)) {
2945     // When we've finished transforming a typedef, see whether it was the
2946     // typedef for an anonymous tag.
2947     for (llvm::SmallVector<TagDecl *, 4>::iterator
2948                FromTag = AnonTagsWithPendingTypedefs.begin(), 
2949             FromTagEnd = AnonTagsWithPendingTypedefs.end();
2950          FromTag != FromTagEnd; ++FromTag) {
2951       if ((*FromTag)->getTypedefForAnonDecl() == FromTypedef) {
2952         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
2953           // We found the typedef for an anonymous tag; link them.
2954           ToTag->setTypedefForAnonDecl(cast<TypedefDecl>(ToD));
2955           AnonTagsWithPendingTypedefs.erase(FromTag);
2956           break;
2957         }
2958       }
2959     }
2960   }
2961   
2962   return ToD;
2963 }
2964
2965 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
2966   if (!FromDC)
2967     return FromDC;
2968
2969   return cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
2970 }
2971
2972 Expr *ASTImporter::Import(Expr *FromE) {
2973   if (!FromE)
2974     return 0;
2975
2976   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
2977 }
2978
2979 Stmt *ASTImporter::Import(Stmt *FromS) {
2980   if (!FromS)
2981     return 0;
2982
2983   // Check whether we've already imported this declaration.  
2984   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
2985   if (Pos != ImportedStmts.end())
2986     return Pos->second;
2987   
2988   // Import the type
2989   ASTNodeImporter Importer(*this);
2990   Stmt *ToS = Importer.Visit(FromS);
2991   if (!ToS)
2992     return 0;
2993   
2994   // Record the imported declaration.
2995   ImportedStmts[FromS] = ToS;
2996   return ToS;
2997 }
2998
2999 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
3000   if (!FromNNS)
3001     return 0;
3002
3003   // FIXME: Implement!
3004   return 0;
3005 }
3006
3007 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
3008   if (FromLoc.isInvalid())
3009     return SourceLocation();
3010
3011   SourceManager &FromSM = FromContext.getSourceManager();
3012   
3013   // For now, map everything down to its spelling location, so that we
3014   // don't have to import macro instantiations.
3015   // FIXME: Import macro instantiations!
3016   FromLoc = FromSM.getSpellingLoc(FromLoc);
3017   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
3018   SourceManager &ToSM = ToContext.getSourceManager();
3019   return ToSM.getLocForStartOfFile(Import(Decomposed.first))
3020              .getFileLocWithOffset(Decomposed.second);
3021 }
3022
3023 SourceRange ASTImporter::Import(SourceRange FromRange) {
3024   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
3025 }
3026
3027 FileID ASTImporter::Import(FileID FromID) {
3028   llvm::DenseMap<unsigned, FileID>::iterator Pos
3029     = ImportedFileIDs.find(FromID.getHashValue());
3030   if (Pos != ImportedFileIDs.end())
3031     return Pos->second;
3032   
3033   SourceManager &FromSM = FromContext.getSourceManager();
3034   SourceManager &ToSM = ToContext.getSourceManager();
3035   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
3036   assert(FromSLoc.isFile() && "Cannot handle macro instantiations yet");
3037   
3038   // Include location of this file.
3039   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
3040   
3041   // Map the FileID for to the "to" source manager.
3042   FileID ToID;
3043   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
3044   if (Cache->Entry) {
3045     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
3046     // disk again
3047     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
3048     // than mmap the files several times.
3049     const FileEntry *Entry = ToFileManager.getFile(Cache->Entry->getName());
3050     ToID = ToSM.createFileID(Entry, ToIncludeLoc, 
3051                              FromSLoc.getFile().getFileCharacteristic());
3052   } else {
3053     // FIXME: We want to re-use the existing MemoryBuffer!
3054     const llvm::MemoryBuffer *FromBuf = Cache->getBuffer();
3055     llvm::MemoryBuffer *ToBuf
3056       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBufferStart(),
3057                                              FromBuf->getBufferEnd(),
3058                                              FromBuf->getBufferIdentifier());
3059     ToID = ToSM.createFileIDForMemBuffer(ToBuf);
3060   }
3061   
3062   
3063   ImportedFileIDs[FromID.getHashValue()] = ToID;
3064   return ToID;
3065 }
3066
3067 DeclarationName ASTImporter::Import(DeclarationName FromName) {
3068   if (!FromName)
3069     return DeclarationName();
3070
3071   switch (FromName.getNameKind()) {
3072   case DeclarationName::Identifier:
3073     return Import(FromName.getAsIdentifierInfo());
3074
3075   case DeclarationName::ObjCZeroArgSelector:
3076   case DeclarationName::ObjCOneArgSelector:
3077   case DeclarationName::ObjCMultiArgSelector:
3078     return Import(FromName.getObjCSelector());
3079
3080   case DeclarationName::CXXConstructorName: {
3081     QualType T = Import(FromName.getCXXNameType());
3082     if (T.isNull())
3083       return DeclarationName();
3084
3085     return ToContext.DeclarationNames.getCXXConstructorName(
3086                                                ToContext.getCanonicalType(T));
3087   }
3088
3089   case DeclarationName::CXXDestructorName: {
3090     QualType T = Import(FromName.getCXXNameType());
3091     if (T.isNull())
3092       return DeclarationName();
3093
3094     return ToContext.DeclarationNames.getCXXDestructorName(
3095                                                ToContext.getCanonicalType(T));
3096   }
3097
3098   case DeclarationName::CXXConversionFunctionName: {
3099     QualType T = Import(FromName.getCXXNameType());
3100     if (T.isNull())
3101       return DeclarationName();
3102
3103     return ToContext.DeclarationNames.getCXXConversionFunctionName(
3104                                                ToContext.getCanonicalType(T));
3105   }
3106
3107   case DeclarationName::CXXOperatorName:
3108     return ToContext.DeclarationNames.getCXXOperatorName(
3109                                           FromName.getCXXOverloadedOperator());
3110
3111   case DeclarationName::CXXLiteralOperatorName:
3112     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
3113                                    Import(FromName.getCXXLiteralIdentifier()));
3114
3115   case DeclarationName::CXXUsingDirective:
3116     // FIXME: STATICS!
3117     return DeclarationName::getUsingDirectiveName();
3118   }
3119
3120   // Silence bogus GCC warning
3121   return DeclarationName();
3122 }
3123
3124 IdentifierInfo *ASTImporter::Import(IdentifierInfo *FromId) {
3125   if (!FromId)
3126     return 0;
3127
3128   return &ToContext.Idents.get(FromId->getName());
3129 }
3130
3131 Selector ASTImporter::Import(Selector FromSel) {
3132   if (FromSel.isNull())
3133     return Selector();
3134
3135   llvm::SmallVector<IdentifierInfo *, 4> Idents;
3136   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
3137   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
3138     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
3139   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
3140 }
3141
3142 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
3143                                                 DeclContext *DC,
3144                                                 unsigned IDNS,
3145                                                 NamedDecl **Decls,
3146                                                 unsigned NumDecls) {
3147   return Name;
3148 }
3149
3150 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
3151   return Diags.Report(FullSourceLoc(Loc, ToContext.getSourceManager()), 
3152                       DiagID);
3153 }
3154
3155 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
3156   return Diags.Report(FullSourceLoc(Loc, FromContext.getSourceManager()), 
3157                       DiagID);
3158 }
3159
3160 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
3161   ImportedDecls[From] = To;
3162   return To;
3163 }
3164
3165 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To) {
3166   llvm::DenseMap<Type *, Type *>::iterator Pos
3167    = ImportedTypes.find(From.getTypePtr());
3168   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
3169     return true;
3170       
3171   StructuralEquivalenceContext Ctx(FromContext, ToContext, Diags, 
3172                                    NonEquivalentDecls);
3173   return Ctx.IsStructurallyEquivalent(From, To);
3174 }