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