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