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