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