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