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