]> granicus.if.org Git - clang/blob - lib/AST/ASTImporter.cpp
Class Property: class property and instance property can have the same name.
[clang] / lib / AST / ASTImporter.cpp
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 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include <deque>
26
27 namespace clang {
28   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
29                           public DeclVisitor<ASTNodeImporter, Decl *>,
30                           public StmtVisitor<ASTNodeImporter, Stmt *> {
31     ASTImporter &Importer;
32     
33   public:
34     explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
35     
36     using TypeVisitor<ASTNodeImporter, QualType>::Visit;
37     using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
38     using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
39
40     // Importing types
41     QualType VisitType(const Type *T);
42     QualType VisitBuiltinType(const BuiltinType *T);
43     QualType VisitComplexType(const ComplexType *T);
44     QualType VisitPointerType(const PointerType *T);
45     QualType VisitBlockPointerType(const BlockPointerType *T);
46     QualType VisitLValueReferenceType(const LValueReferenceType *T);
47     QualType VisitRValueReferenceType(const RValueReferenceType *T);
48     QualType VisitMemberPointerType(const MemberPointerType *T);
49     QualType VisitConstantArrayType(const ConstantArrayType *T);
50     QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
51     QualType VisitVariableArrayType(const VariableArrayType *T);
52     // FIXME: DependentSizedArrayType
53     // FIXME: DependentSizedExtVectorType
54     QualType VisitVectorType(const VectorType *T);
55     QualType VisitExtVectorType(const ExtVectorType *T);
56     QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
57     QualType VisitFunctionProtoType(const FunctionProtoType *T);
58     // FIXME: UnresolvedUsingType
59     QualType VisitParenType(const ParenType *T);
60     QualType VisitTypedefType(const TypedefType *T);
61     QualType VisitTypeOfExprType(const TypeOfExprType *T);
62     // FIXME: DependentTypeOfExprType
63     QualType VisitTypeOfType(const TypeOfType *T);
64     QualType VisitDecltypeType(const DecltypeType *T);
65     QualType VisitUnaryTransformType(const UnaryTransformType *T);
66     QualType VisitAutoType(const AutoType *T);
67     // FIXME: DependentDecltypeType
68     QualType VisitRecordType(const RecordType *T);
69     QualType VisitEnumType(const EnumType *T);
70     QualType VisitAttributedType(const AttributedType *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                          NamedDecl *&ToD, SourceLocation &Loc);
85     void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
86     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87                                   DeclarationNameInfo& To);
88     void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89                         
90     /// \brief What we should import from the definition.
91     enum ImportDefinitionKind { 
92       /// \brief Import the default subset of the definition, which might be
93       /// nothing (if minimal import is set) or might be everything (if minimal
94       /// import is not set).
95       IDK_Default,
96       /// \brief Import everything.
97       IDK_Everything,
98       /// \brief Import only the bare bones needed to establish a valid
99       /// DeclContext.
100       IDK_Basic
101     };
102
103     bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
104       return IDK == IDK_Everything ||
105              (IDK == IDK_Default && !Importer.isMinimalImport());
106     }
107
108     bool ImportDefinition(RecordDecl *From, RecordDecl *To, 
109                           ImportDefinitionKind Kind = IDK_Default);
110     bool ImportDefinition(VarDecl *From, VarDecl *To,
111                           ImportDefinitionKind Kind = IDK_Default);
112     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
113                           ImportDefinitionKind Kind = IDK_Default);
114     bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
115                           ImportDefinitionKind Kind = IDK_Default);
116     bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
117                           ImportDefinitionKind Kind = IDK_Default);
118     TemplateParameterList *ImportTemplateParameterList(
119                                                  TemplateParameterList *Params);
120     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
121     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
122                                  unsigned NumFromArgs,
123                                SmallVectorImpl<TemplateArgument> &ToArgs);
124     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
125                            bool Complain = true);
126     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
127                            bool Complain = true);
128     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
129     bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
130     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
131     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
132     Decl *VisitDecl(Decl *D);
133     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
134     Decl *VisitNamespaceDecl(NamespaceDecl *D);
135     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
136     Decl *VisitTypedefDecl(TypedefDecl *D);
137     Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
138     Decl *VisitEnumDecl(EnumDecl *D);
139     Decl *VisitRecordDecl(RecordDecl *D);
140     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
141     Decl *VisitFunctionDecl(FunctionDecl *D);
142     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
143     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
144     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
145     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
146     Decl *VisitFieldDecl(FieldDecl *D);
147     Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
148     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
149     Decl *VisitVarDecl(VarDecl *D);
150     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
151     Decl *VisitParmVarDecl(ParmVarDecl *D);
152     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
153     Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
154     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
155     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
156     Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
157
158     ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
159     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
160     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
161     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
162     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
163     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
164     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
165     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
166     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
167     Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
168     Decl *VisitClassTemplateSpecializationDecl(
169                                             ClassTemplateSpecializationDecl *D);
170     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
171     Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
172
173     // Importing statements
174     DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
175
176     Stmt *VisitStmt(Stmt *S);
177     Stmt *VisitDeclStmt(DeclStmt *S);
178     Stmt *VisitNullStmt(NullStmt *S);
179     Stmt *VisitCompoundStmt(CompoundStmt *S);
180     Stmt *VisitCaseStmt(CaseStmt *S);
181     Stmt *VisitDefaultStmt(DefaultStmt *S);
182     Stmt *VisitLabelStmt(LabelStmt *S);
183     Stmt *VisitAttributedStmt(AttributedStmt *S);
184     Stmt *VisitIfStmt(IfStmt *S);
185     Stmt *VisitSwitchStmt(SwitchStmt *S);
186     Stmt *VisitWhileStmt(WhileStmt *S);
187     Stmt *VisitDoStmt(DoStmt *S);
188     Stmt *VisitForStmt(ForStmt *S);
189     Stmt *VisitGotoStmt(GotoStmt *S);
190     Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
191     Stmt *VisitContinueStmt(ContinueStmt *S);
192     Stmt *VisitBreakStmt(BreakStmt *S);
193     Stmt *VisitReturnStmt(ReturnStmt *S);
194     // FIXME: GCCAsmStmt
195     // FIXME: MSAsmStmt
196     // FIXME: SEHExceptStmt
197     // FIXME: SEHFinallyStmt
198     // FIXME: SEHTryStmt
199     // FIXME: SEHLeaveStmt
200     // FIXME: CapturedStmt
201     Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
202     Stmt *VisitCXXTryStmt(CXXTryStmt *S);
203     Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
204     // FIXME: MSDependentExistsStmt
205     Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
206     Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
207     Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
208     Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
209     Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
210     Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
211     Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
212
213     // Importing expressions
214     Expr *VisitExpr(Expr *E);
215     Expr *VisitDeclRefExpr(DeclRefExpr *E);
216     Expr *VisitIntegerLiteral(IntegerLiteral *E);
217     Expr *VisitCharacterLiteral(CharacterLiteral *E);
218     Expr *VisitParenExpr(ParenExpr *E);
219     Expr *VisitUnaryOperator(UnaryOperator *E);
220     Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
221     Expr *VisitBinaryOperator(BinaryOperator *E);
222     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
223     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
224     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
225     Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
226     Expr *VisitMemberExpr(MemberExpr *E);
227     Expr *VisitCallExpr(CallExpr *E);
228   };
229 }
230 using namespace clang;
231
232 //----------------------------------------------------------------------------
233 // Structural Equivalence
234 //----------------------------------------------------------------------------
235
236 namespace {
237   struct StructuralEquivalenceContext {
238     /// \brief AST contexts for which we are checking structural equivalence.
239     ASTContext &C1, &C2;
240     
241     /// \brief The set of "tentative" equivalences between two canonical 
242     /// declarations, mapping from a declaration in the first context to the
243     /// declaration in the second context that we believe to be equivalent.
244     llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
245     
246     /// \brief Queue of declarations in the first context whose equivalence
247     /// with a declaration in the second context still needs to be verified.
248     std::deque<Decl *> DeclsToCheck;
249     
250     /// \brief Declaration (from, to) pairs that are known not to be equivalent
251     /// (which we have already complained about).
252     llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
253     
254     /// \brief Whether we're being strict about the spelling of types when 
255     /// unifying two types.
256     bool StrictTypeSpelling;
257
258     /// \brief Whether to complain about failures.
259     bool Complain;
260
261     /// \brief \c true if the last diagnostic came from C2.
262     bool LastDiagFromC2;
263
264     StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
265                llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
266                                  bool StrictTypeSpelling = false,
267                                  bool Complain = true)
268       : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
269         StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
270         LastDiagFromC2(false) {}
271
272     /// \brief Determine whether the two declarations are structurally
273     /// equivalent.
274     bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
275     
276     /// \brief Determine whether the two types are structurally equivalent.
277     bool IsStructurallyEquivalent(QualType T1, QualType T2);
278
279   private:
280     /// \brief Finish checking all of the structural equivalences.
281     ///
282     /// \returns true if an error occurred, false otherwise.
283     bool Finish();
284     
285   public:
286     DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
287       assert(Complain && "Not allowed to complain");
288       if (LastDiagFromC2)
289         C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
290       LastDiagFromC2 = false;
291       return C1.getDiagnostics().Report(Loc, DiagID);
292     }
293
294     DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
295       assert(Complain && "Not allowed to complain");
296       if (!LastDiagFromC2)
297         C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
298       LastDiagFromC2 = true;
299       return C2.getDiagnostics().Report(Loc, DiagID);
300     }
301   };
302 }
303
304 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
305                                      QualType T1, QualType T2);
306 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
307                                      Decl *D1, Decl *D2);
308
309 /// \brief Determine structural equivalence of two expressions.
310 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
311                                      Expr *E1, Expr *E2) {
312   if (!E1 || !E2)
313     return E1 == E2;
314   
315   // FIXME: Actually perform a structural comparison!
316   return true;
317 }
318
319 /// \brief Determine whether two identifiers are equivalent.
320 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
321                                      const IdentifierInfo *Name2) {
322   if (!Name1 || !Name2)
323     return Name1 == Name2;
324   
325   return Name1->getName() == Name2->getName();
326 }
327
328 /// \brief Determine whether two nested-name-specifiers are equivalent.
329 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
330                                      NestedNameSpecifier *NNS1,
331                                      NestedNameSpecifier *NNS2) {
332   // FIXME: Implement!
333   return true;
334 }
335
336 /// \brief Determine whether two template arguments are equivalent.
337 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
338                                      const TemplateArgument &Arg1,
339                                      const TemplateArgument &Arg2) {
340   if (Arg1.getKind() != Arg2.getKind())
341     return false;
342
343   switch (Arg1.getKind()) {
344   case TemplateArgument::Null:
345     return true;
346       
347   case TemplateArgument::Type:
348     return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
349
350   case TemplateArgument::Integral:
351     if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(), 
352                                           Arg2.getIntegralType()))
353       return false;
354     
355     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
356       
357   case TemplateArgument::Declaration:
358     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
359
360   case TemplateArgument::NullPtr:
361     return true; // FIXME: Is this correct?
362
363   case TemplateArgument::Template:
364     return IsStructurallyEquivalent(Context, 
365                                     Arg1.getAsTemplate(), 
366                                     Arg2.getAsTemplate());
367
368   case TemplateArgument::TemplateExpansion:
369     return IsStructurallyEquivalent(Context, 
370                                     Arg1.getAsTemplateOrTemplatePattern(), 
371                                     Arg2.getAsTemplateOrTemplatePattern());
372
373   case TemplateArgument::Expression:
374     return IsStructurallyEquivalent(Context, 
375                                     Arg1.getAsExpr(), Arg2.getAsExpr());
376       
377   case TemplateArgument::Pack:
378     if (Arg1.pack_size() != Arg2.pack_size())
379       return false;
380       
381     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
382       if (!IsStructurallyEquivalent(Context, 
383                                     Arg1.pack_begin()[I],
384                                     Arg2.pack_begin()[I]))
385         return false;
386       
387     return true;
388   }
389   
390   llvm_unreachable("Invalid template argument kind");
391 }
392
393 /// \brief Determine structural equivalence for the common part of array 
394 /// types.
395 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
396                                           const ArrayType *Array1, 
397                                           const ArrayType *Array2) {
398   if (!IsStructurallyEquivalent(Context, 
399                                 Array1->getElementType(), 
400                                 Array2->getElementType()))
401     return false;
402   if (Array1->getSizeModifier() != Array2->getSizeModifier())
403     return false;
404   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
405     return false;
406   
407   return true;
408 }
409
410 /// \brief Determine structural equivalence of two types.
411 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
412                                      QualType T1, QualType T2) {
413   if (T1.isNull() || T2.isNull())
414     return T1.isNull() && T2.isNull();
415   
416   if (!Context.StrictTypeSpelling) {
417     // We aren't being strict about token-to-token equivalence of types,
418     // so map down to the canonical type.
419     T1 = Context.C1.getCanonicalType(T1);
420     T2 = Context.C2.getCanonicalType(T2);
421   }
422   
423   if (T1.getQualifiers() != T2.getQualifiers())
424     return false;
425   
426   Type::TypeClass TC = T1->getTypeClass();
427   
428   if (T1->getTypeClass() != T2->getTypeClass()) {
429     // Compare function types with prototypes vs. without prototypes as if
430     // both did not have prototypes.
431     if (T1->getTypeClass() == Type::FunctionProto &&
432         T2->getTypeClass() == Type::FunctionNoProto)
433       TC = Type::FunctionNoProto;
434     else if (T1->getTypeClass() == Type::FunctionNoProto &&
435              T2->getTypeClass() == Type::FunctionProto)
436       TC = Type::FunctionNoProto;
437     else
438       return false;
439   }
440   
441   switch (TC) {
442   case Type::Builtin:
443     // FIXME: Deal with Char_S/Char_U. 
444     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
445       return false;
446     break;
447   
448   case Type::Complex:
449     if (!IsStructurallyEquivalent(Context,
450                                   cast<ComplexType>(T1)->getElementType(),
451                                   cast<ComplexType>(T2)->getElementType()))
452       return false;
453     break;
454   
455   case Type::Adjusted:
456   case Type::Decayed:
457     if (!IsStructurallyEquivalent(Context,
458                                   cast<AdjustedType>(T1)->getOriginalType(),
459                                   cast<AdjustedType>(T2)->getOriginalType()))
460       return false;
461     break;
462
463   case Type::Pointer:
464     if (!IsStructurallyEquivalent(Context,
465                                   cast<PointerType>(T1)->getPointeeType(),
466                                   cast<PointerType>(T2)->getPointeeType()))
467       return false;
468     break;
469
470   case Type::BlockPointer:
471     if (!IsStructurallyEquivalent(Context,
472                                   cast<BlockPointerType>(T1)->getPointeeType(),
473                                   cast<BlockPointerType>(T2)->getPointeeType()))
474       return false;
475     break;
476
477   case Type::LValueReference:
478   case Type::RValueReference: {
479     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
480     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
481     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
482       return false;
483     if (Ref1->isInnerRef() != Ref2->isInnerRef())
484       return false;
485     if (!IsStructurallyEquivalent(Context,
486                                   Ref1->getPointeeTypeAsWritten(),
487                                   Ref2->getPointeeTypeAsWritten()))
488       return false;
489     break;
490   }
491       
492   case Type::MemberPointer: {
493     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
494     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
495     if (!IsStructurallyEquivalent(Context,
496                                   MemPtr1->getPointeeType(),
497                                   MemPtr2->getPointeeType()))
498       return false;
499     if (!IsStructurallyEquivalent(Context,
500                                   QualType(MemPtr1->getClass(), 0),
501                                   QualType(MemPtr2->getClass(), 0)))
502       return false;
503     break;
504   }
505       
506   case Type::ConstantArray: {
507     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
508     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
509     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
510       return false;
511     
512     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
513       return false;
514     break;
515   }
516
517   case Type::IncompleteArray:
518     if (!IsArrayStructurallyEquivalent(Context, 
519                                        cast<ArrayType>(T1), 
520                                        cast<ArrayType>(T2)))
521       return false;
522     break;
523       
524   case Type::VariableArray: {
525     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
526     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
527     if (!IsStructurallyEquivalent(Context, 
528                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
529       return false;
530     
531     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
532       return false;
533     
534     break;
535   }
536   
537   case Type::DependentSizedArray: {
538     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
539     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
540     if (!IsStructurallyEquivalent(Context, 
541                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
542       return false;
543     
544     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
545       return false;
546     
547     break;
548   }
549       
550   case Type::DependentSizedExtVector: {
551     const DependentSizedExtVectorType *Vec1
552       = cast<DependentSizedExtVectorType>(T1);
553     const DependentSizedExtVectorType *Vec2
554       = cast<DependentSizedExtVectorType>(T2);
555     if (!IsStructurallyEquivalent(Context, 
556                                   Vec1->getSizeExpr(), Vec2->getSizeExpr()))
557       return false;
558     if (!IsStructurallyEquivalent(Context, 
559                                   Vec1->getElementType(), 
560                                   Vec2->getElementType()))
561       return false;
562     break;
563   }
564    
565   case Type::Vector: 
566   case Type::ExtVector: {
567     const VectorType *Vec1 = cast<VectorType>(T1);
568     const VectorType *Vec2 = cast<VectorType>(T2);
569     if (!IsStructurallyEquivalent(Context, 
570                                   Vec1->getElementType(),
571                                   Vec2->getElementType()))
572       return false;
573     if (Vec1->getNumElements() != Vec2->getNumElements())
574       return false;
575     if (Vec1->getVectorKind() != Vec2->getVectorKind())
576       return false;
577     break;
578   }
579
580   case Type::FunctionProto: {
581     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
582     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
583     if (Proto1->getNumParams() != Proto2->getNumParams())
584       return false;
585     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
586       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
587                                     Proto2->getParamType(I)))
588         return false;
589     }
590     if (Proto1->isVariadic() != Proto2->isVariadic())
591       return false;
592     if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
593       return false;
594     if (Proto1->getExceptionSpecType() == EST_Dynamic) {
595       if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
596         return false;
597       for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
598         if (!IsStructurallyEquivalent(Context,
599                                       Proto1->getExceptionType(I),
600                                       Proto2->getExceptionType(I)))
601           return false;
602       }
603     } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
604       if (!IsStructurallyEquivalent(Context,
605                                     Proto1->getNoexceptExpr(),
606                                     Proto2->getNoexceptExpr()))
607         return false;
608     }
609     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
610       return false;
611     
612     // Fall through to check the bits common with FunctionNoProtoType.
613   }
614       
615   case Type::FunctionNoProto: {
616     const FunctionType *Function1 = cast<FunctionType>(T1);
617     const FunctionType *Function2 = cast<FunctionType>(T2);
618     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
619                                   Function2->getReturnType()))
620       return false;
621       if (Function1->getExtInfo() != Function2->getExtInfo())
622         return false;
623     break;
624   }
625    
626   case Type::UnresolvedUsing:
627     if (!IsStructurallyEquivalent(Context,
628                                   cast<UnresolvedUsingType>(T1)->getDecl(),
629                                   cast<UnresolvedUsingType>(T2)->getDecl()))
630       return false;
631       
632     break;
633
634   case Type::Attributed:
635     if (!IsStructurallyEquivalent(Context,
636                                   cast<AttributedType>(T1)->getModifiedType(),
637                                   cast<AttributedType>(T2)->getModifiedType()))
638       return false;
639     if (!IsStructurallyEquivalent(Context,
640                                 cast<AttributedType>(T1)->getEquivalentType(),
641                                 cast<AttributedType>(T2)->getEquivalentType()))
642       return false;
643     break;
644       
645   case Type::Paren:
646     if (!IsStructurallyEquivalent(Context,
647                                   cast<ParenType>(T1)->getInnerType(),
648                                   cast<ParenType>(T2)->getInnerType()))
649       return false;
650     break;
651
652   case Type::Typedef:
653     if (!IsStructurallyEquivalent(Context,
654                                   cast<TypedefType>(T1)->getDecl(),
655                                   cast<TypedefType>(T2)->getDecl()))
656       return false;
657     break;
658       
659   case Type::TypeOfExpr:
660     if (!IsStructurallyEquivalent(Context,
661                                 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
662                                 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
663       return false;
664     break;
665       
666   case Type::TypeOf:
667     if (!IsStructurallyEquivalent(Context,
668                                   cast<TypeOfType>(T1)->getUnderlyingType(),
669                                   cast<TypeOfType>(T2)->getUnderlyingType()))
670       return false;
671     break;
672
673   case Type::UnaryTransform:
674     if (!IsStructurallyEquivalent(Context,
675                              cast<UnaryTransformType>(T1)->getUnderlyingType(),
676                              cast<UnaryTransformType>(T1)->getUnderlyingType()))
677       return false;
678     break;
679
680   case Type::Decltype:
681     if (!IsStructurallyEquivalent(Context,
682                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
683                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
684       return false;
685     break;
686
687   case Type::Auto:
688     if (!IsStructurallyEquivalent(Context,
689                                   cast<AutoType>(T1)->getDeducedType(),
690                                   cast<AutoType>(T2)->getDeducedType()))
691       return false;
692     break;
693
694   case Type::Record:
695   case Type::Enum:
696     if (!IsStructurallyEquivalent(Context,
697                                   cast<TagType>(T1)->getDecl(),
698                                   cast<TagType>(T2)->getDecl()))
699       return false;
700     break;
701
702   case Type::TemplateTypeParm: {
703     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
704     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
705     if (Parm1->getDepth() != Parm2->getDepth())
706       return false;
707     if (Parm1->getIndex() != Parm2->getIndex())
708       return false;
709     if (Parm1->isParameterPack() != Parm2->isParameterPack())
710       return false;
711     
712     // Names of template type parameters are never significant.
713     break;
714   }
715       
716   case Type::SubstTemplateTypeParm: {
717     const SubstTemplateTypeParmType *Subst1
718       = cast<SubstTemplateTypeParmType>(T1);
719     const SubstTemplateTypeParmType *Subst2
720       = cast<SubstTemplateTypeParmType>(T2);
721     if (!IsStructurallyEquivalent(Context,
722                                   QualType(Subst1->getReplacedParameter(), 0),
723                                   QualType(Subst2->getReplacedParameter(), 0)))
724       return false;
725     if (!IsStructurallyEquivalent(Context, 
726                                   Subst1->getReplacementType(),
727                                   Subst2->getReplacementType()))
728       return false;
729     break;
730   }
731
732   case Type::SubstTemplateTypeParmPack: {
733     const SubstTemplateTypeParmPackType *Subst1
734       = cast<SubstTemplateTypeParmPackType>(T1);
735     const SubstTemplateTypeParmPackType *Subst2
736       = cast<SubstTemplateTypeParmPackType>(T2);
737     if (!IsStructurallyEquivalent(Context,
738                                   QualType(Subst1->getReplacedParameter(), 0),
739                                   QualType(Subst2->getReplacedParameter(), 0)))
740       return false;
741     if (!IsStructurallyEquivalent(Context, 
742                                   Subst1->getArgumentPack(),
743                                   Subst2->getArgumentPack()))
744       return false;
745     break;
746   }
747   case Type::TemplateSpecialization: {
748     const TemplateSpecializationType *Spec1
749       = cast<TemplateSpecializationType>(T1);
750     const TemplateSpecializationType *Spec2
751       = cast<TemplateSpecializationType>(T2);
752     if (!IsStructurallyEquivalent(Context,
753                                   Spec1->getTemplateName(),
754                                   Spec2->getTemplateName()))
755       return false;
756     if (Spec1->getNumArgs() != Spec2->getNumArgs())
757       return false;
758     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
759       if (!IsStructurallyEquivalent(Context, 
760                                     Spec1->getArg(I), Spec2->getArg(I)))
761         return false;
762     }
763     break;
764   }
765       
766   case Type::Elaborated: {
767     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
768     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
769     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
770     if (Elab1->getKeyword() != Elab2->getKeyword())
771       return false;
772     if (!IsStructurallyEquivalent(Context, 
773                                   Elab1->getQualifier(), 
774                                   Elab2->getQualifier()))
775       return false;
776     if (!IsStructurallyEquivalent(Context,
777                                   Elab1->getNamedType(),
778                                   Elab2->getNamedType()))
779       return false;
780     break;
781   }
782
783   case Type::InjectedClassName: {
784     const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
785     const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
786     if (!IsStructurallyEquivalent(Context,
787                                   Inj1->getInjectedSpecializationType(),
788                                   Inj2->getInjectedSpecializationType()))
789       return false;
790     break;
791   }
792
793   case Type::DependentName: {
794     const DependentNameType *Typename1 = cast<DependentNameType>(T1);
795     const DependentNameType *Typename2 = cast<DependentNameType>(T2);
796     if (!IsStructurallyEquivalent(Context, 
797                                   Typename1->getQualifier(),
798                                   Typename2->getQualifier()))
799       return false;
800     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
801                                   Typename2->getIdentifier()))
802       return false;
803     
804     break;
805   }
806   
807   case Type::DependentTemplateSpecialization: {
808     const DependentTemplateSpecializationType *Spec1 =
809       cast<DependentTemplateSpecializationType>(T1);
810     const DependentTemplateSpecializationType *Spec2 =
811       cast<DependentTemplateSpecializationType>(T2);
812     if (!IsStructurallyEquivalent(Context, 
813                                   Spec1->getQualifier(),
814                                   Spec2->getQualifier()))
815       return false;
816     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
817                                   Spec2->getIdentifier()))
818       return false;
819     if (Spec1->getNumArgs() != Spec2->getNumArgs())
820       return false;
821     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
822       if (!IsStructurallyEquivalent(Context,
823                                     Spec1->getArg(I), Spec2->getArg(I)))
824         return false;
825     }
826     break;
827   }
828
829   case Type::PackExpansion:
830     if (!IsStructurallyEquivalent(Context,
831                                   cast<PackExpansionType>(T1)->getPattern(),
832                                   cast<PackExpansionType>(T2)->getPattern()))
833       return false;
834     break;
835
836   case Type::ObjCInterface: {
837     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
838     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
839     if (!IsStructurallyEquivalent(Context, 
840                                   Iface1->getDecl(), Iface2->getDecl()))
841       return false;
842     break;
843   }
844
845   case Type::ObjCObject: {
846     const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
847     const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
848     if (!IsStructurallyEquivalent(Context,
849                                   Obj1->getBaseType(),
850                                   Obj2->getBaseType()))
851       return false;
852     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
853       return false;
854     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
855       if (!IsStructurallyEquivalent(Context,
856                                     Obj1->getProtocol(I),
857                                     Obj2->getProtocol(I)))
858         return false;
859     }
860     break;
861   }
862
863   case Type::ObjCObjectPointer: {
864     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
865     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
866     if (!IsStructurallyEquivalent(Context, 
867                                   Ptr1->getPointeeType(),
868                                   Ptr2->getPointeeType()))
869       return false;
870     break;
871   }
872
873   case Type::Atomic: {
874     if (!IsStructurallyEquivalent(Context,
875                                   cast<AtomicType>(T1)->getValueType(),
876                                   cast<AtomicType>(T2)->getValueType()))
877       return false;
878     break;
879   }
880
881   case Type::Pipe: {
882     if (!IsStructurallyEquivalent(Context,
883                                   cast<PipeType>(T1)->getElementType(),
884                                   cast<PipeType>(T2)->getElementType()))
885       return false;
886     break;
887   }
888
889   } // end switch
890
891   return true;
892 }
893
894 /// \brief Determine structural equivalence of two fields.
895 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
896                                      FieldDecl *Field1, FieldDecl *Field2) {
897   RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
898
899   // For anonymous structs/unions, match up the anonymous struct/union type
900   // declarations directly, so that we don't go off searching for anonymous
901   // types
902   if (Field1->isAnonymousStructOrUnion() &&
903       Field2->isAnonymousStructOrUnion()) {
904     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
905     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
906     return IsStructurallyEquivalent(Context, D1, D2);
907   }
908     
909   // Check for equivalent field names.
910   IdentifierInfo *Name1 = Field1->getIdentifier();
911   IdentifierInfo *Name2 = Field2->getIdentifier();
912   if (!::IsStructurallyEquivalent(Name1, Name2))
913     return false;
914
915   if (!IsStructurallyEquivalent(Context,
916                                 Field1->getType(), Field2->getType())) {
917     if (Context.Complain) {
918       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
919         << Context.C2.getTypeDeclType(Owner2);
920       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
921         << Field2->getDeclName() << Field2->getType();
922       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
923         << Field1->getDeclName() << Field1->getType();
924     }
925     return false;
926   }
927   
928   if (Field1->isBitField() != Field2->isBitField()) {
929     if (Context.Complain) {
930       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
931         << Context.C2.getTypeDeclType(Owner2);
932       if (Field1->isBitField()) {
933         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
934         << Field1->getDeclName() << Field1->getType()
935         << Field1->getBitWidthValue(Context.C1);
936         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
937         << Field2->getDeclName();
938       } else {
939         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
940         << Field2->getDeclName() << Field2->getType()
941         << Field2->getBitWidthValue(Context.C2);
942         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
943         << Field1->getDeclName();
944       }
945     }
946     return false;
947   }
948   
949   if (Field1->isBitField()) {
950     // Make sure that the bit-fields are the same length.
951     unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
952     unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
953     
954     if (Bits1 != Bits2) {
955       if (Context.Complain) {
956         Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
957           << Context.C2.getTypeDeclType(Owner2);
958         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
959           << Field2->getDeclName() << Field2->getType() << Bits2;
960         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
961           << Field1->getDeclName() << Field1->getType() << Bits1;
962       }
963       return false;
964     }
965   }
966
967   return true;
968 }
969
970 /// \brief Find the index of the given anonymous struct/union within its
971 /// context.
972 ///
973 /// \returns Returns the index of this anonymous struct/union in its context,
974 /// including the next assigned index (if none of them match). Returns an
975 /// empty option if the context is not a record, i.e.. if the anonymous
976 /// struct/union is at namespace or block scope.
977 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
978   ASTContext &Context = Anon->getASTContext();
979   QualType AnonTy = Context.getRecordType(Anon);
980
981   RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
982   if (!Owner)
983     return None;
984
985   unsigned Index = 0;
986   for (const auto *D : Owner->noload_decls()) {
987     const auto *F = dyn_cast<FieldDecl>(D);
988     if (!F || !F->isAnonymousStructOrUnion())
989       continue;
990
991     if (Context.hasSameType(F->getType(), AnonTy))
992       break;
993
994     ++Index;
995   }
996
997   return Index;
998 }
999
1000 /// \brief Determine structural equivalence of two records.
1001 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1002                                      RecordDecl *D1, RecordDecl *D2) {
1003   if (D1->isUnion() != D2->isUnion()) {
1004     if (Context.Complain) {
1005       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1006         << Context.C2.getTypeDeclType(D2);
1007       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1008         << D1->getDeclName() << (unsigned)D1->getTagKind();
1009     }
1010     return false;
1011   }
1012
1013   if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1014     // If both anonymous structs/unions are in a record context, make sure
1015     // they occur in the same location in the context records.
1016     if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
1017       if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
1018         if (*Index1 != *Index2)
1019           return false;
1020       }
1021     }
1022   }
1023
1024   // If both declarations are class template specializations, we know
1025   // the ODR applies, so check the template and template arguments.
1026   ClassTemplateSpecializationDecl *Spec1
1027     = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1028   ClassTemplateSpecializationDecl *Spec2
1029     = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1030   if (Spec1 && Spec2) {
1031     // Check that the specialized templates are the same.
1032     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1033                                   Spec2->getSpecializedTemplate()))
1034       return false;
1035     
1036     // Check that the template arguments are the same.
1037     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1038       return false;
1039     
1040     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1041       if (!IsStructurallyEquivalent(Context, 
1042                                     Spec1->getTemplateArgs().get(I),
1043                                     Spec2->getTemplateArgs().get(I)))
1044         return false;
1045   }  
1046   // If one is a class template specialization and the other is not, these
1047   // structures are different.
1048   else if (Spec1 || Spec2)
1049     return false;
1050
1051   // Compare the definitions of these two records. If either or both are
1052   // incomplete, we assume that they are equivalent.
1053   D1 = D1->getDefinition();
1054   D2 = D2->getDefinition();
1055   if (!D1 || !D2)
1056     return true;
1057   
1058   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1059     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1060       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1061         if (Context.Complain) {
1062           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1063             << Context.C2.getTypeDeclType(D2);
1064           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1065             << D2CXX->getNumBases();
1066           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1067             << D1CXX->getNumBases();
1068         }
1069         return false;
1070       }
1071       
1072       // Check the base classes. 
1073       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), 
1074                                            BaseEnd1 = D1CXX->bases_end(),
1075                                                 Base2 = D2CXX->bases_begin();
1076            Base1 != BaseEnd1;
1077            ++Base1, ++Base2) {        
1078         if (!IsStructurallyEquivalent(Context, 
1079                                       Base1->getType(), Base2->getType())) {
1080           if (Context.Complain) {
1081             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1082               << Context.C2.getTypeDeclType(D2);
1083             Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1084               << Base2->getType()
1085               << Base2->getSourceRange();
1086             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1087               << Base1->getType()
1088               << Base1->getSourceRange();
1089           }
1090           return false;
1091         }
1092         
1093         // Check virtual vs. non-virtual inheritance mismatch.
1094         if (Base1->isVirtual() != Base2->isVirtual()) {
1095           if (Context.Complain) {
1096             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1097               << Context.C2.getTypeDeclType(D2);
1098             Context.Diag2(Base2->getLocStart(),
1099                           diag::note_odr_virtual_base)
1100               << Base2->isVirtual() << Base2->getSourceRange();
1101             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1102               << Base1->isVirtual()
1103               << Base1->getSourceRange();
1104           }
1105           return false;
1106         }
1107       }
1108     } else if (D1CXX->getNumBases() > 0) {
1109       if (Context.Complain) {
1110         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1111           << Context.C2.getTypeDeclType(D2);
1112         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1113         Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1114           << Base1->getType()
1115           << Base1->getSourceRange();
1116         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1117       }
1118       return false;
1119     }
1120   }
1121   
1122   // Check the fields for consistency.
1123   RecordDecl::field_iterator Field2 = D2->field_begin(),
1124                              Field2End = D2->field_end();
1125   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1126                                   Field1End = D1->field_end();
1127        Field1 != Field1End;
1128        ++Field1, ++Field2) {
1129     if (Field2 == Field2End) {
1130       if (Context.Complain) {
1131         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1132           << Context.C2.getTypeDeclType(D2);
1133         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1134           << Field1->getDeclName() << Field1->getType();
1135         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1136       }
1137       return false;
1138     }
1139     
1140     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1141       return false;    
1142   }
1143   
1144   if (Field2 != Field2End) {
1145     if (Context.Complain) {
1146       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1147         << Context.C2.getTypeDeclType(D2);
1148       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1149         << Field2->getDeclName() << Field2->getType();
1150       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1151     }
1152     return false;
1153   }
1154   
1155   return true;
1156 }
1157      
1158 /// \brief Determine structural equivalence of two enums.
1159 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1160                                      EnumDecl *D1, EnumDecl *D2) {
1161   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1162                              EC2End = D2->enumerator_end();
1163   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1164                                   EC1End = D1->enumerator_end();
1165        EC1 != EC1End; ++EC1, ++EC2) {
1166     if (EC2 == EC2End) {
1167       if (Context.Complain) {
1168         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1169           << Context.C2.getTypeDeclType(D2);
1170         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1171           << EC1->getDeclName() 
1172           << EC1->getInitVal().toString(10);
1173         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1174       }
1175       return false;
1176     }
1177     
1178     llvm::APSInt Val1 = EC1->getInitVal();
1179     llvm::APSInt Val2 = EC2->getInitVal();
1180     if (!llvm::APSInt::isSameValue(Val1, Val2) || 
1181         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1182       if (Context.Complain) {
1183         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1184           << Context.C2.getTypeDeclType(D2);
1185         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1186           << EC2->getDeclName() 
1187           << EC2->getInitVal().toString(10);
1188         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1189           << EC1->getDeclName() 
1190           << EC1->getInitVal().toString(10);
1191       }
1192       return false;
1193     }
1194   }
1195   
1196   if (EC2 != EC2End) {
1197     if (Context.Complain) {
1198       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1199         << Context.C2.getTypeDeclType(D2);
1200       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1201         << EC2->getDeclName() 
1202         << EC2->getInitVal().toString(10);
1203       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1204     }
1205     return false;
1206   }
1207   
1208   return true;
1209 }
1210
1211 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1212                                      TemplateParameterList *Params1,
1213                                      TemplateParameterList *Params2) {
1214   if (Params1->size() != Params2->size()) {
1215     if (Context.Complain) {
1216       Context.Diag2(Params2->getTemplateLoc(), 
1217                     diag::err_odr_different_num_template_parameters)
1218         << Params1->size() << Params2->size();
1219       Context.Diag1(Params1->getTemplateLoc(), 
1220                     diag::note_odr_template_parameter_list);
1221     }
1222     return false;
1223   }
1224   
1225   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1226     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1227       if (Context.Complain) {
1228         Context.Diag2(Params2->getParam(I)->getLocation(), 
1229                       diag::err_odr_different_template_parameter_kind);
1230         Context.Diag1(Params1->getParam(I)->getLocation(),
1231                       diag::note_odr_template_parameter_here);
1232       }
1233       return false;
1234     }
1235     
1236     if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1237                                           Params2->getParam(I))) {
1238       
1239       return false;
1240     }
1241   }
1242   
1243   return true;
1244 }
1245
1246 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1247                                      TemplateTypeParmDecl *D1,
1248                                      TemplateTypeParmDecl *D2) {
1249   if (D1->isParameterPack() != D2->isParameterPack()) {
1250     if (Context.Complain) {
1251       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1252         << D2->isParameterPack();
1253       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1254         << D1->isParameterPack();
1255     }
1256     return false;
1257   }
1258   
1259   return true;
1260 }
1261
1262 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1263                                      NonTypeTemplateParmDecl *D1,
1264                                      NonTypeTemplateParmDecl *D2) {
1265   if (D1->isParameterPack() != D2->isParameterPack()) {
1266     if (Context.Complain) {
1267       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1268         << D2->isParameterPack();
1269       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1270         << D1->isParameterPack();
1271     }
1272     return false;
1273   }
1274   
1275   // Check types.
1276   if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1277     if (Context.Complain) {
1278       Context.Diag2(D2->getLocation(),
1279                     diag::err_odr_non_type_parameter_type_inconsistent)
1280         << D2->getType() << D1->getType();
1281       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1282         << D1->getType();
1283     }
1284     return false;
1285   }
1286   
1287   return true;
1288 }
1289
1290 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1291                                      TemplateTemplateParmDecl *D1,
1292                                      TemplateTemplateParmDecl *D2) {
1293   if (D1->isParameterPack() != D2->isParameterPack()) {
1294     if (Context.Complain) {
1295       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1296         << D2->isParameterPack();
1297       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1298         << D1->isParameterPack();
1299     }
1300     return false;
1301   }
1302
1303   // Check template parameter lists.
1304   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1305                                   D2->getTemplateParameters());
1306 }
1307
1308 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1309                                      ClassTemplateDecl *D1, 
1310                                      ClassTemplateDecl *D2) {
1311   // Check template parameters.
1312   if (!IsStructurallyEquivalent(Context,
1313                                 D1->getTemplateParameters(),
1314                                 D2->getTemplateParameters()))
1315     return false;
1316   
1317   // Check the templated declaration.
1318   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(), 
1319                                           D2->getTemplatedDecl());
1320 }
1321
1322 /// \brief Determine structural equivalence of two declarations.
1323 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1324                                      Decl *D1, Decl *D2) {
1325   // FIXME: Check for known structural equivalences via a callback of some sort.
1326   
1327   // Check whether we already know that these two declarations are not
1328   // structurally equivalent.
1329   if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1330                                                       D2->getCanonicalDecl())))
1331     return false;
1332   
1333   // Determine whether we've already produced a tentative equivalence for D1.
1334   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1335   if (EquivToD1)
1336     return EquivToD1 == D2->getCanonicalDecl();
1337   
1338   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1339   EquivToD1 = D2->getCanonicalDecl();
1340   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1341   return true;
1342 }
1343
1344 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1, 
1345                                                             Decl *D2) {
1346   if (!::IsStructurallyEquivalent(*this, D1, D2))
1347     return false;
1348   
1349   return !Finish();
1350 }
1351
1352 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1, 
1353                                                             QualType T2) {
1354   if (!::IsStructurallyEquivalent(*this, T1, T2))
1355     return false;
1356   
1357   return !Finish();
1358 }
1359
1360 bool StructuralEquivalenceContext::Finish() {
1361   while (!DeclsToCheck.empty()) {
1362     // Check the next declaration.
1363     Decl *D1 = DeclsToCheck.front();
1364     DeclsToCheck.pop_front();
1365     
1366     Decl *D2 = TentativeEquivalences[D1];
1367     assert(D2 && "Unrecorded tentative equivalence?");
1368     
1369     bool Equivalent = true;
1370     
1371     // FIXME: Switch on all declaration kinds. For now, we're just going to
1372     // check the obvious ones.
1373     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1374       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1375         // Check for equivalent structure names.
1376         IdentifierInfo *Name1 = Record1->getIdentifier();
1377         if (!Name1 && Record1->getTypedefNameForAnonDecl())
1378           Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1379         IdentifierInfo *Name2 = Record2->getIdentifier();
1380         if (!Name2 && Record2->getTypedefNameForAnonDecl())
1381           Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1382         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1383             !::IsStructurallyEquivalent(*this, Record1, Record2))
1384           Equivalent = false;
1385       } else {
1386         // Record/non-record mismatch.
1387         Equivalent = false;
1388       }
1389     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1390       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1391         // Check for equivalent enum names.
1392         IdentifierInfo *Name1 = Enum1->getIdentifier();
1393         if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1394           Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1395         IdentifierInfo *Name2 = Enum2->getIdentifier();
1396         if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1397           Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1398         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1399             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1400           Equivalent = false;
1401       } else {
1402         // Enum/non-enum mismatch
1403         Equivalent = false;
1404       }
1405     } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1406       if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1407         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1408                                         Typedef2->getIdentifier()) ||
1409             !::IsStructurallyEquivalent(*this,
1410                                         Typedef1->getUnderlyingType(),
1411                                         Typedef2->getUnderlyingType()))
1412           Equivalent = false;
1413       } else {
1414         // Typedef/non-typedef mismatch.
1415         Equivalent = false;
1416       }
1417     } else if (ClassTemplateDecl *ClassTemplate1 
1418                                            = dyn_cast<ClassTemplateDecl>(D1)) {
1419       if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1420         if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1421                                         ClassTemplate2->getIdentifier()) ||
1422             !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1423           Equivalent = false;
1424       } else {
1425         // Class template/non-class-template mismatch.
1426         Equivalent = false;
1427       }
1428     } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1429       if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1430         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1431           Equivalent = false;
1432       } else {
1433         // Kind mismatch.
1434         Equivalent = false;
1435       }
1436     } else if (NonTypeTemplateParmDecl *NTTP1
1437                                      = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1438       if (NonTypeTemplateParmDecl *NTTP2
1439                                       = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1440         if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1441           Equivalent = false;
1442       } else {
1443         // Kind mismatch.
1444         Equivalent = false;
1445       }
1446     } else if (TemplateTemplateParmDecl *TTP1
1447                                   = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1448       if (TemplateTemplateParmDecl *TTP2
1449                                     = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1450         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1451           Equivalent = false;
1452       } else {
1453         // Kind mismatch.
1454         Equivalent = false;
1455       }
1456     }
1457     
1458     if (!Equivalent) {
1459       // Note that these two declarations are not equivalent (and we already
1460       // know about it).
1461       NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1462                                                D2->getCanonicalDecl()));
1463       return true;
1464     }
1465     // FIXME: Check other declaration kinds!
1466   }
1467   
1468   return false;
1469 }
1470
1471 //----------------------------------------------------------------------------
1472 // Import Types
1473 //----------------------------------------------------------------------------
1474
1475 QualType ASTNodeImporter::VisitType(const Type *T) {
1476   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1477     << T->getTypeClassName();
1478   return QualType();
1479 }
1480
1481 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1482   switch (T->getKind()) {
1483 #define SHARED_SINGLETON_TYPE(Expansion)
1484 #define BUILTIN_TYPE(Id, SingletonId) \
1485   case BuiltinType::Id: return Importer.getToContext().SingletonId;
1486 #include "clang/AST/BuiltinTypes.def"
1487
1488   // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1489   // context supports C++.
1490
1491   // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1492   // context supports ObjC.
1493
1494   case BuiltinType::Char_U:
1495     // The context we're importing from has an unsigned 'char'. If we're 
1496     // importing into a context with a signed 'char', translate to 
1497     // 'unsigned char' instead.
1498     if (Importer.getToContext().getLangOpts().CharIsSigned)
1499       return Importer.getToContext().UnsignedCharTy;
1500     
1501     return Importer.getToContext().CharTy;
1502
1503   case BuiltinType::Char_S:
1504     // The context we're importing from has an unsigned 'char'. If we're 
1505     // importing into a context with a signed 'char', translate to 
1506     // 'unsigned char' instead.
1507     if (!Importer.getToContext().getLangOpts().CharIsSigned)
1508       return Importer.getToContext().SignedCharTy;
1509     
1510     return Importer.getToContext().CharTy;
1511
1512   case BuiltinType::WChar_S:
1513   case BuiltinType::WChar_U:
1514     // FIXME: If not in C++, shall we translate to the C equivalent of
1515     // wchar_t?
1516     return Importer.getToContext().WCharTy;
1517   }
1518
1519   llvm_unreachable("Invalid BuiltinType Kind!");
1520 }
1521
1522 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1523   QualType ToElementType = Importer.Import(T->getElementType());
1524   if (ToElementType.isNull())
1525     return QualType();
1526   
1527   return Importer.getToContext().getComplexType(ToElementType);
1528 }
1529
1530 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1531   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1532   if (ToPointeeType.isNull())
1533     return QualType();
1534   
1535   return Importer.getToContext().getPointerType(ToPointeeType);
1536 }
1537
1538 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1539   // FIXME: Check for blocks support in "to" context.
1540   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1541   if (ToPointeeType.isNull())
1542     return QualType();
1543   
1544   return Importer.getToContext().getBlockPointerType(ToPointeeType);
1545 }
1546
1547 QualType
1548 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1549   // FIXME: Check for C++ support in "to" context.
1550   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1551   if (ToPointeeType.isNull())
1552     return QualType();
1553   
1554   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1555 }
1556
1557 QualType
1558 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1559   // FIXME: Check for C++0x support in "to" context.
1560   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1561   if (ToPointeeType.isNull())
1562     return QualType();
1563   
1564   return Importer.getToContext().getRValueReferenceType(ToPointeeType);  
1565 }
1566
1567 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1568   // FIXME: Check for C++ support in "to" context.
1569   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1570   if (ToPointeeType.isNull())
1571     return QualType();
1572   
1573   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1574   return Importer.getToContext().getMemberPointerType(ToPointeeType, 
1575                                                       ClassType.getTypePtr());
1576 }
1577
1578 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1579   QualType ToElementType = Importer.Import(T->getElementType());
1580   if (ToElementType.isNull())
1581     return QualType();
1582   
1583   return Importer.getToContext().getConstantArrayType(ToElementType, 
1584                                                       T->getSize(),
1585                                                       T->getSizeModifier(),
1586                                                T->getIndexTypeCVRQualifiers());
1587 }
1588
1589 QualType
1590 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1591   QualType ToElementType = Importer.Import(T->getElementType());
1592   if (ToElementType.isNull())
1593     return QualType();
1594   
1595   return Importer.getToContext().getIncompleteArrayType(ToElementType, 
1596                                                         T->getSizeModifier(),
1597                                                 T->getIndexTypeCVRQualifiers());
1598 }
1599
1600 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1601   QualType ToElementType = Importer.Import(T->getElementType());
1602   if (ToElementType.isNull())
1603     return QualType();
1604
1605   Expr *Size = Importer.Import(T->getSizeExpr());
1606   if (!Size)
1607     return QualType();
1608   
1609   SourceRange Brackets = Importer.Import(T->getBracketsRange());
1610   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1611                                                       T->getSizeModifier(),
1612                                                 T->getIndexTypeCVRQualifiers(),
1613                                                       Brackets);
1614 }
1615
1616 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1617   QualType ToElementType = Importer.Import(T->getElementType());
1618   if (ToElementType.isNull())
1619     return QualType();
1620   
1621   return Importer.getToContext().getVectorType(ToElementType, 
1622                                                T->getNumElements(),
1623                                                T->getVectorKind());
1624 }
1625
1626 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1627   QualType ToElementType = Importer.Import(T->getElementType());
1628   if (ToElementType.isNull())
1629     return QualType();
1630   
1631   return Importer.getToContext().getExtVectorType(ToElementType, 
1632                                                   T->getNumElements());
1633 }
1634
1635 QualType
1636 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1637   // FIXME: What happens if we're importing a function without a prototype 
1638   // into C++? Should we make it variadic?
1639   QualType ToResultType = Importer.Import(T->getReturnType());
1640   if (ToResultType.isNull())
1641     return QualType();
1642
1643   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1644                                                         T->getExtInfo());
1645 }
1646
1647 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1648   QualType ToResultType = Importer.Import(T->getReturnType());
1649   if (ToResultType.isNull())
1650     return QualType();
1651   
1652   // Import argument types
1653   SmallVector<QualType, 4> ArgTypes;
1654   for (const auto &A : T->param_types()) {
1655     QualType ArgType = Importer.Import(A);
1656     if (ArgType.isNull())
1657       return QualType();
1658     ArgTypes.push_back(ArgType);
1659   }
1660   
1661   // Import exception types
1662   SmallVector<QualType, 4> ExceptionTypes;
1663   for (const auto &E : T->exceptions()) {
1664     QualType ExceptionType = Importer.Import(E);
1665     if (ExceptionType.isNull())
1666       return QualType();
1667     ExceptionTypes.push_back(ExceptionType);
1668   }
1669
1670   FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1671   FunctionProtoType::ExtProtoInfo ToEPI;
1672
1673   ToEPI.ExtInfo = FromEPI.ExtInfo;
1674   ToEPI.Variadic = FromEPI.Variadic;
1675   ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1676   ToEPI.TypeQuals = FromEPI.TypeQuals;
1677   ToEPI.RefQualifier = FromEPI.RefQualifier;
1678   ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1679   ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1680   ToEPI.ExceptionSpec.NoexceptExpr =
1681       Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1682   ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1683       Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1684   ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1685       Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1686
1687   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1688 }
1689
1690 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1691   QualType ToInnerType = Importer.Import(T->getInnerType());
1692   if (ToInnerType.isNull())
1693     return QualType();
1694     
1695   return Importer.getToContext().getParenType(ToInnerType);
1696 }
1697
1698 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1699   TypedefNameDecl *ToDecl
1700              = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1701   if (!ToDecl)
1702     return QualType();
1703   
1704   return Importer.getToContext().getTypeDeclType(ToDecl);
1705 }
1706
1707 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1708   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1709   if (!ToExpr)
1710     return QualType();
1711   
1712   return Importer.getToContext().getTypeOfExprType(ToExpr);
1713 }
1714
1715 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1716   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1717   if (ToUnderlyingType.isNull())
1718     return QualType();
1719   
1720   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1721 }
1722
1723 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1724   // FIXME: Make sure that the "to" context supports C++0x!
1725   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1726   if (!ToExpr)
1727     return QualType();
1728   
1729   QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1730   if (UnderlyingType.isNull())
1731     return QualType();
1732
1733   return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1734 }
1735
1736 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1737   QualType ToBaseType = Importer.Import(T->getBaseType());
1738   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1739   if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1740     return QualType();
1741
1742   return Importer.getToContext().getUnaryTransformType(ToBaseType,
1743                                                        ToUnderlyingType,
1744                                                        T->getUTTKind());
1745 }
1746
1747 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1748   // FIXME: Make sure that the "to" context supports C++11!
1749   QualType FromDeduced = T->getDeducedType();
1750   QualType ToDeduced;
1751   if (!FromDeduced.isNull()) {
1752     ToDeduced = Importer.Import(FromDeduced);
1753     if (ToDeduced.isNull())
1754       return QualType();
1755   }
1756   
1757   return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
1758                                              /*IsDependent*/false);
1759 }
1760
1761 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1762   RecordDecl *ToDecl
1763     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1764   if (!ToDecl)
1765     return QualType();
1766
1767   return Importer.getToContext().getTagDeclType(ToDecl);
1768 }
1769
1770 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1771   EnumDecl *ToDecl
1772     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1773   if (!ToDecl)
1774     return QualType();
1775
1776   return Importer.getToContext().getTagDeclType(ToDecl);
1777 }
1778
1779 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1780   QualType FromModifiedType = T->getModifiedType();
1781   QualType FromEquivalentType = T->getEquivalentType();
1782   QualType ToModifiedType;
1783   QualType ToEquivalentType;
1784
1785   if (!FromModifiedType.isNull()) {
1786     ToModifiedType = Importer.Import(FromModifiedType);
1787     if (ToModifiedType.isNull())
1788       return QualType();
1789   }
1790   if (!FromEquivalentType.isNull()) {
1791     ToEquivalentType = Importer.Import(FromEquivalentType);
1792     if (ToEquivalentType.isNull())
1793       return QualType();
1794   }
1795
1796   return Importer.getToContext().getAttributedType(T->getAttrKind(),
1797     ToModifiedType, ToEquivalentType);
1798 }
1799
1800 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1801                                        const TemplateSpecializationType *T) {
1802   TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1803   if (ToTemplate.isNull())
1804     return QualType();
1805   
1806   SmallVector<TemplateArgument, 2> ToTemplateArgs;
1807   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1808     return QualType();
1809   
1810   QualType ToCanonType;
1811   if (!QualType(T, 0).isCanonical()) {
1812     QualType FromCanonType 
1813       = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1814     ToCanonType =Importer.Import(FromCanonType);
1815     if (ToCanonType.isNull())
1816       return QualType();
1817   }
1818   return Importer.getToContext().getTemplateSpecializationType(ToTemplate, 
1819                                                          ToTemplateArgs.data(), 
1820                                                          ToTemplateArgs.size(),
1821                                                                ToCanonType);
1822 }
1823
1824 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1825   NestedNameSpecifier *ToQualifier = nullptr;
1826   // Note: the qualifier in an ElaboratedType is optional.
1827   if (T->getQualifier()) {
1828     ToQualifier = Importer.Import(T->getQualifier());
1829     if (!ToQualifier)
1830       return QualType();
1831   }
1832
1833   QualType ToNamedType = Importer.Import(T->getNamedType());
1834   if (ToNamedType.isNull())
1835     return QualType();
1836
1837   return Importer.getToContext().getElaboratedType(T->getKeyword(),
1838                                                    ToQualifier, ToNamedType);
1839 }
1840
1841 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1842   ObjCInterfaceDecl *Class
1843     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1844   if (!Class)
1845     return QualType();
1846
1847   return Importer.getToContext().getObjCInterfaceType(Class);
1848 }
1849
1850 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1851   QualType ToBaseType = Importer.Import(T->getBaseType());
1852   if (ToBaseType.isNull())
1853     return QualType();
1854
1855   SmallVector<QualType, 4> TypeArgs;
1856   for (auto TypeArg : T->getTypeArgsAsWritten()) {
1857     QualType ImportedTypeArg = Importer.Import(TypeArg);
1858     if (ImportedTypeArg.isNull())
1859       return QualType();
1860
1861     TypeArgs.push_back(ImportedTypeArg);
1862   }
1863
1864   SmallVector<ObjCProtocolDecl *, 4> Protocols;
1865   for (auto *P : T->quals()) {
1866     ObjCProtocolDecl *Protocol
1867       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1868     if (!Protocol)
1869       return QualType();
1870     Protocols.push_back(Protocol);
1871   }
1872
1873   return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1874                                                    Protocols,
1875                                                    T->isKindOfTypeAsWritten());
1876 }
1877
1878 QualType
1879 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1880   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1881   if (ToPointeeType.isNull())
1882     return QualType();
1883
1884   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1885 }
1886
1887 //----------------------------------------------------------------------------
1888 // Import Declarations
1889 //----------------------------------------------------------------------------
1890 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
1891                                       DeclContext *&LexicalDC, 
1892                                       DeclarationName &Name, 
1893                                       NamedDecl *&ToD,
1894                                       SourceLocation &Loc) {
1895   // Import the context of this declaration.
1896   DC = Importer.ImportContext(D->getDeclContext());
1897   if (!DC)
1898     return true;
1899   
1900   LexicalDC = DC;
1901   if (D->getDeclContext() != D->getLexicalDeclContext()) {
1902     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1903     if (!LexicalDC)
1904       return true;
1905   }
1906   
1907   // Import the name of this declaration.
1908   Name = Importer.Import(D->getDeclName());
1909   if (D->getDeclName() && !Name)
1910     return true;
1911   
1912   // Import the location of this declaration.
1913   Loc = Importer.Import(D->getLocation());
1914   ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1915   return false;
1916 }
1917
1918 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1919   if (!FromD)
1920     return;
1921   
1922   if (!ToD) {
1923     ToD = Importer.Import(FromD);
1924     if (!ToD)
1925       return;
1926   }
1927   
1928   if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1929     if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1930       if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1931         ImportDefinition(FromRecord, ToRecord);
1932       }
1933     }
1934     return;
1935   }
1936
1937   if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1938     if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1939       if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1940         ImportDefinition(FromEnum, ToEnum);
1941       }
1942     }
1943     return;
1944   }
1945 }
1946
1947 void
1948 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1949                                           DeclarationNameInfo& To) {
1950   // NOTE: To.Name and To.Loc are already imported.
1951   // We only have to import To.LocInfo.
1952   switch (To.getName().getNameKind()) {
1953   case DeclarationName::Identifier:
1954   case DeclarationName::ObjCZeroArgSelector:
1955   case DeclarationName::ObjCOneArgSelector:
1956   case DeclarationName::ObjCMultiArgSelector:
1957   case DeclarationName::CXXUsingDirective:
1958     return;
1959
1960   case DeclarationName::CXXOperatorName: {
1961     SourceRange Range = From.getCXXOperatorNameRange();
1962     To.setCXXOperatorNameRange(Importer.Import(Range));
1963     return;
1964   }
1965   case DeclarationName::CXXLiteralOperatorName: {
1966     SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1967     To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1968     return;
1969   }
1970   case DeclarationName::CXXConstructorName:
1971   case DeclarationName::CXXDestructorName:
1972   case DeclarationName::CXXConversionFunctionName: {
1973     TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1974     To.setNamedTypeInfo(Importer.Import(FromTInfo));
1975     return;
1976   }
1977   }
1978   llvm_unreachable("Unknown name kind.");
1979 }
1980
1981 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {  
1982   if (Importer.isMinimalImport() && !ForceImport) {
1983     Importer.ImportContext(FromDC);
1984     return;
1985   }
1986   
1987   for (auto *From : FromDC->decls())
1988     Importer.Import(From);
1989 }
1990
1991 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, 
1992                                        ImportDefinitionKind Kind) {
1993   if (To->getDefinition() || To->isBeingDefined()) {
1994     if (Kind == IDK_Everything)
1995       ImportDeclContext(From, /*ForceImport=*/true);
1996     
1997     return false;
1998   }
1999   
2000   To->startDefinition();
2001   
2002   // Add base classes.
2003   if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
2004     CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
2005
2006     struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2007     struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2008     ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
2009     ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
2010     ToData.Aggregate = FromData.Aggregate;
2011     ToData.PlainOldData = FromData.PlainOldData;
2012     ToData.Empty = FromData.Empty;
2013     ToData.Polymorphic = FromData.Polymorphic;
2014     ToData.Abstract = FromData.Abstract;
2015     ToData.IsStandardLayout = FromData.IsStandardLayout;
2016     ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
2017     ToData.HasPrivateFields = FromData.HasPrivateFields;
2018     ToData.HasProtectedFields = FromData.HasProtectedFields;
2019     ToData.HasPublicFields = FromData.HasPublicFields;
2020     ToData.HasMutableFields = FromData.HasMutableFields;
2021     ToData.HasVariantMembers = FromData.HasVariantMembers;
2022     ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2023     ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2024     ToData.HasUninitializedReferenceMember
2025       = FromData.HasUninitializedReferenceMember;
2026     ToData.NeedOverloadResolutionForMoveConstructor
2027       = FromData.NeedOverloadResolutionForMoveConstructor;
2028     ToData.NeedOverloadResolutionForMoveAssignment
2029       = FromData.NeedOverloadResolutionForMoveAssignment;
2030     ToData.NeedOverloadResolutionForDestructor
2031       = FromData.NeedOverloadResolutionForDestructor;
2032     ToData.DefaultedMoveConstructorIsDeleted
2033       = FromData.DefaultedMoveConstructorIsDeleted;
2034     ToData.DefaultedMoveAssignmentIsDeleted
2035       = FromData.DefaultedMoveAssignmentIsDeleted;
2036     ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2037     ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2038     ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2039     ToData.HasConstexprNonCopyMoveConstructor
2040       = FromData.HasConstexprNonCopyMoveConstructor;
2041     ToData.DefaultedDefaultConstructorIsConstexpr
2042       = FromData.DefaultedDefaultConstructorIsConstexpr;
2043     ToData.HasConstexprDefaultConstructor
2044       = FromData.HasConstexprDefaultConstructor;
2045     ToData.HasNonLiteralTypeFieldsOrBases
2046       = FromData.HasNonLiteralTypeFieldsOrBases;
2047     // ComputedVisibleConversions not imported.
2048     ToData.UserProvidedDefaultConstructor
2049       = FromData.UserProvidedDefaultConstructor;
2050     ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2051     ToData.ImplicitCopyConstructorHasConstParam
2052       = FromData.ImplicitCopyConstructorHasConstParam;
2053     ToData.ImplicitCopyAssignmentHasConstParam
2054       = FromData.ImplicitCopyAssignmentHasConstParam;
2055     ToData.HasDeclaredCopyConstructorWithConstParam
2056       = FromData.HasDeclaredCopyConstructorWithConstParam;
2057     ToData.HasDeclaredCopyAssignmentWithConstParam
2058       = FromData.HasDeclaredCopyAssignmentWithConstParam;
2059     ToData.IsLambda = FromData.IsLambda;
2060
2061     SmallVector<CXXBaseSpecifier *, 4> Bases;
2062     for (const auto &Base1 : FromCXX->bases()) {
2063       QualType T = Importer.Import(Base1.getType());
2064       if (T.isNull())
2065         return true;
2066
2067       SourceLocation EllipsisLoc;
2068       if (Base1.isPackExpansion())
2069         EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2070
2071       // Ensure that we have a definition for the base.
2072       ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2073         
2074       Bases.push_back(
2075                     new (Importer.getToContext()) 
2076                       CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2077                                        Base1.isVirtual(),
2078                                        Base1.isBaseOfClass(),
2079                                        Base1.getAccessSpecifierAsWritten(),
2080                                    Importer.Import(Base1.getTypeSourceInfo()),
2081                                        EllipsisLoc));
2082     }
2083     if (!Bases.empty())
2084       ToCXX->setBases(Bases.data(), Bases.size());
2085   }
2086   
2087   if (shouldForceImportDeclContext(Kind))
2088     ImportDeclContext(From, /*ForceImport=*/true);
2089   
2090   To->completeDefinition();
2091   return false;
2092 }
2093
2094 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2095                                        ImportDefinitionKind Kind) {
2096   if (To->getAnyInitializer())
2097     return false;
2098
2099   // FIXME: Can we really import any initializer? Alternatively, we could force
2100   // ourselves to import every declaration of a variable and then only use
2101   // getInit() here.
2102   To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2103
2104   // FIXME: Other bits to merge?
2105
2106   return false;
2107 }
2108
2109 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, 
2110                                        ImportDefinitionKind Kind) {
2111   if (To->getDefinition() || To->isBeingDefined()) {
2112     if (Kind == IDK_Everything)
2113       ImportDeclContext(From, /*ForceImport=*/true);
2114     return false;
2115   }
2116   
2117   To->startDefinition();
2118
2119   QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2120   if (T.isNull())
2121     return true;
2122   
2123   QualType ToPromotionType = Importer.Import(From->getPromotionType());
2124   if (ToPromotionType.isNull())
2125     return true;
2126
2127   if (shouldForceImportDeclContext(Kind))
2128     ImportDeclContext(From, /*ForceImport=*/true);
2129   
2130   // FIXME: we might need to merge the number of positive or negative bits
2131   // if the enumerator lists don't match.
2132   To->completeDefinition(T, ToPromotionType,
2133                          From->getNumPositiveBits(),
2134                          From->getNumNegativeBits());
2135   return false;
2136 }
2137
2138 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2139                                                 TemplateParameterList *Params) {
2140   SmallVector<NamedDecl *, 4> ToParams;
2141   ToParams.reserve(Params->size());
2142   for (TemplateParameterList::iterator P = Params->begin(), 
2143                                     PEnd = Params->end();
2144        P != PEnd; ++P) {
2145     Decl *To = Importer.Import(*P);
2146     if (!To)
2147       return nullptr;
2148
2149     ToParams.push_back(cast<NamedDecl>(To));
2150   }
2151   
2152   return TemplateParameterList::Create(Importer.getToContext(),
2153                                        Importer.Import(Params->getTemplateLoc()),
2154                                        Importer.Import(Params->getLAngleLoc()),
2155                                        ToParams,
2156                                        Importer.Import(Params->getRAngleLoc()));
2157 }
2158
2159 TemplateArgument 
2160 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2161   switch (From.getKind()) {
2162   case TemplateArgument::Null:
2163     return TemplateArgument();
2164      
2165   case TemplateArgument::Type: {
2166     QualType ToType = Importer.Import(From.getAsType());
2167     if (ToType.isNull())
2168       return TemplateArgument();
2169     return TemplateArgument(ToType);
2170   }
2171       
2172   case TemplateArgument::Integral: {
2173     QualType ToType = Importer.Import(From.getIntegralType());
2174     if (ToType.isNull())
2175       return TemplateArgument();
2176     return TemplateArgument(From, ToType);
2177   }
2178
2179   case TemplateArgument::Declaration: {
2180     ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2181     QualType ToType = Importer.Import(From.getParamTypeForDecl());
2182     if (!To || ToType.isNull())
2183       return TemplateArgument();
2184     return TemplateArgument(To, ToType);
2185   }
2186
2187   case TemplateArgument::NullPtr: {
2188     QualType ToType = Importer.Import(From.getNullPtrType());
2189     if (ToType.isNull())
2190       return TemplateArgument();
2191     return TemplateArgument(ToType, /*isNullPtr*/true);
2192   }
2193
2194   case TemplateArgument::Template: {
2195     TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2196     if (ToTemplate.isNull())
2197       return TemplateArgument();
2198     
2199     return TemplateArgument(ToTemplate);
2200   }
2201
2202   case TemplateArgument::TemplateExpansion: {
2203     TemplateName ToTemplate 
2204       = Importer.Import(From.getAsTemplateOrTemplatePattern());
2205     if (ToTemplate.isNull())
2206       return TemplateArgument();
2207     
2208     return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2209   }
2210
2211   case TemplateArgument::Expression:
2212     if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2213       return TemplateArgument(ToExpr);
2214     return TemplateArgument();
2215       
2216   case TemplateArgument::Pack: {
2217     SmallVector<TemplateArgument, 2> ToPack;
2218     ToPack.reserve(From.pack_size());
2219     if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2220       return TemplateArgument();
2221
2222     return TemplateArgument(
2223         llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
2224   }
2225   }
2226   
2227   llvm_unreachable("Invalid template argument kind");
2228 }
2229
2230 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2231                                               unsigned NumFromArgs,
2232                               SmallVectorImpl<TemplateArgument> &ToArgs) {
2233   for (unsigned I = 0; I != NumFromArgs; ++I) {
2234     TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2235     if (To.isNull() && !FromArgs[I].isNull())
2236       return true;
2237     
2238     ToArgs.push_back(To);
2239   }
2240   
2241   return false;
2242 }
2243
2244 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, 
2245                                         RecordDecl *ToRecord, bool Complain) {
2246   // Eliminate a potential failure point where we attempt to re-import
2247   // something we're trying to import while completing ToRecord.
2248   Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2249   if (ToOrigin) {
2250     RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2251     if (ToOriginRecord)
2252       ToRecord = ToOriginRecord;
2253   }
2254
2255   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2256                                    ToRecord->getASTContext(),
2257                                    Importer.getNonEquivalentDecls(),
2258                                    false, Complain);
2259   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2260 }
2261
2262 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2263                                         bool Complain) {
2264   StructuralEquivalenceContext Ctx(
2265       Importer.getFromContext(), Importer.getToContext(),
2266       Importer.getNonEquivalentDecls(), false, Complain);
2267   return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2268 }
2269
2270 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2271   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2272                                    Importer.getToContext(),
2273                                    Importer.getNonEquivalentDecls());
2274   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2275 }
2276
2277 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2278                                         EnumConstantDecl *ToEC)
2279 {
2280   const llvm::APSInt &FromVal = FromEC->getInitVal();
2281   const llvm::APSInt &ToVal = ToEC->getInitVal();
2282
2283   return FromVal.isSigned() == ToVal.isSigned() &&
2284          FromVal.getBitWidth() == ToVal.getBitWidth() &&
2285          FromVal == ToVal;
2286 }
2287
2288 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2289                                         ClassTemplateDecl *To) {
2290   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2291                                    Importer.getToContext(),
2292                                    Importer.getNonEquivalentDecls());
2293   return Ctx.IsStructurallyEquivalent(From, To);  
2294 }
2295
2296 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2297                                         VarTemplateDecl *To) {
2298   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2299                                    Importer.getToContext(),
2300                                    Importer.getNonEquivalentDecls());
2301   return Ctx.IsStructurallyEquivalent(From, To);
2302 }
2303
2304 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2305   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2306     << D->getDeclKindName();
2307   return nullptr;
2308 }
2309
2310 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2311   TranslationUnitDecl *ToD = 
2312     Importer.getToContext().getTranslationUnitDecl();
2313     
2314   Importer.Imported(D, ToD);
2315     
2316   return ToD;
2317 }
2318
2319 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2320   // Import the major distinguishing characteristics of this namespace.
2321   DeclContext *DC, *LexicalDC;
2322   DeclarationName Name;
2323   SourceLocation Loc;
2324   NamedDecl *ToD;
2325   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2326     return nullptr;
2327   if (ToD)
2328     return ToD;
2329
2330   NamespaceDecl *MergeWithNamespace = nullptr;
2331   if (!Name) {
2332     // This is an anonymous namespace. Adopt an existing anonymous
2333     // namespace if we can.
2334     // FIXME: Not testable.
2335     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2336       MergeWithNamespace = TU->getAnonymousNamespace();
2337     else
2338       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2339   } else {
2340     SmallVector<NamedDecl *, 4> ConflictingDecls;
2341     SmallVector<NamedDecl *, 2> FoundDecls;
2342     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2343     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2344       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2345         continue;
2346       
2347       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2348         MergeWithNamespace = FoundNS;
2349         ConflictingDecls.clear();
2350         break;
2351       }
2352       
2353       ConflictingDecls.push_back(FoundDecls[I]);
2354     }
2355     
2356     if (!ConflictingDecls.empty()) {
2357       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2358                                          ConflictingDecls.data(), 
2359                                          ConflictingDecls.size());
2360     }
2361   }
2362   
2363   // Create the "to" namespace, if needed.
2364   NamespaceDecl *ToNamespace = MergeWithNamespace;
2365   if (!ToNamespace) {
2366     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2367                                         D->isInline(),
2368                                         Importer.Import(D->getLocStart()),
2369                                         Loc, Name.getAsIdentifierInfo(),
2370                                         /*PrevDecl=*/nullptr);
2371     ToNamespace->setLexicalDeclContext(LexicalDC);
2372     LexicalDC->addDeclInternal(ToNamespace);
2373     
2374     // If this is an anonymous namespace, register it as the anonymous
2375     // namespace within its context.
2376     if (!Name) {
2377       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2378         TU->setAnonymousNamespace(ToNamespace);
2379       else
2380         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2381     }
2382   }
2383   Importer.Imported(D, ToNamespace);
2384   
2385   ImportDeclContext(D);
2386   
2387   return ToNamespace;
2388 }
2389
2390 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2391   // Import the major distinguishing characteristics of this typedef.
2392   DeclContext *DC, *LexicalDC;
2393   DeclarationName Name;
2394   SourceLocation Loc;
2395   NamedDecl *ToD;
2396   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2397     return nullptr;
2398   if (ToD)
2399     return ToD;
2400
2401   // If this typedef is not in block scope, determine whether we've
2402   // seen a typedef with the same name (that we can merge with) or any
2403   // other entity by that name (which name lookup could conflict with).
2404   if (!DC->isFunctionOrMethod()) {
2405     SmallVector<NamedDecl *, 4> ConflictingDecls;
2406     unsigned IDNS = Decl::IDNS_Ordinary;
2407     SmallVector<NamedDecl *, 2> FoundDecls;
2408     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2409     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2410       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2411         continue;
2412       if (TypedefNameDecl *FoundTypedef =
2413             dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2414         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2415                                             FoundTypedef->getUnderlyingType()))
2416           return Importer.Imported(D, FoundTypedef);
2417       }
2418       
2419       ConflictingDecls.push_back(FoundDecls[I]);
2420     }
2421     
2422     if (!ConflictingDecls.empty()) {
2423       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2424                                          ConflictingDecls.data(), 
2425                                          ConflictingDecls.size());
2426       if (!Name)
2427         return nullptr;
2428     }
2429   }
2430   
2431   // Import the underlying type of this typedef;
2432   QualType T = Importer.Import(D->getUnderlyingType());
2433   if (T.isNull())
2434     return nullptr;
2435
2436   // Create the new typedef node.
2437   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2438   SourceLocation StartL = Importer.Import(D->getLocStart());
2439   TypedefNameDecl *ToTypedef;
2440   if (IsAlias)
2441     ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2442                                       StartL, Loc,
2443                                       Name.getAsIdentifierInfo(),
2444                                       TInfo);
2445   else
2446     ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2447                                     StartL, Loc,
2448                                     Name.getAsIdentifierInfo(),
2449                                     TInfo);
2450   
2451   ToTypedef->setAccess(D->getAccess());
2452   ToTypedef->setLexicalDeclContext(LexicalDC);
2453   Importer.Imported(D, ToTypedef);
2454   LexicalDC->addDeclInternal(ToTypedef);
2455   
2456   return ToTypedef;
2457 }
2458
2459 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2460   return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2461 }
2462
2463 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2464   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2465 }
2466
2467 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2468   // Import the major distinguishing characteristics of this enum.
2469   DeclContext *DC, *LexicalDC;
2470   DeclarationName Name;
2471   SourceLocation Loc;
2472   NamedDecl *ToD;
2473   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2474     return nullptr;
2475   if (ToD)
2476     return ToD;
2477
2478   // Figure out what enum name we're looking for.
2479   unsigned IDNS = Decl::IDNS_Tag;
2480   DeclarationName SearchName = Name;
2481   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2482     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2483     IDNS = Decl::IDNS_Ordinary;
2484   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2485     IDNS |= Decl::IDNS_Ordinary;
2486   
2487   // We may already have an enum of the same name; try to find and match it.
2488   if (!DC->isFunctionOrMethod() && SearchName) {
2489     SmallVector<NamedDecl *, 4> ConflictingDecls;
2490     SmallVector<NamedDecl *, 2> FoundDecls;
2491     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2492     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2493       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2494         continue;
2495       
2496       Decl *Found = FoundDecls[I];
2497       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2498         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2499           Found = Tag->getDecl();
2500       }
2501       
2502       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2503         if (IsStructuralMatch(D, FoundEnum))
2504           return Importer.Imported(D, FoundEnum);
2505       }
2506       
2507       ConflictingDecls.push_back(FoundDecls[I]);
2508     }
2509     
2510     if (!ConflictingDecls.empty()) {
2511       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2512                                          ConflictingDecls.data(), 
2513                                          ConflictingDecls.size());
2514     }
2515   }
2516   
2517   // Create the enum declaration.
2518   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2519                                   Importer.Import(D->getLocStart()),
2520                                   Loc, Name.getAsIdentifierInfo(), nullptr,
2521                                   D->isScoped(), D->isScopedUsingClassTag(),
2522                                   D->isFixed());
2523   // Import the qualifier, if any.
2524   D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2525   D2->setAccess(D->getAccess());
2526   D2->setLexicalDeclContext(LexicalDC);
2527   Importer.Imported(D, D2);
2528   LexicalDC->addDeclInternal(D2);
2529
2530   // Import the integer type.
2531   QualType ToIntegerType = Importer.Import(D->getIntegerType());
2532   if (ToIntegerType.isNull())
2533     return nullptr;
2534   D2->setIntegerType(ToIntegerType);
2535   
2536   // Import the definition
2537   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2538     return nullptr;
2539
2540   return D2;
2541 }
2542
2543 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2544   // If this record has a definition in the translation unit we're coming from,
2545   // but this particular declaration is not that definition, import the
2546   // definition and map to that.
2547   TagDecl *Definition = D->getDefinition();
2548   if (Definition && Definition != D) {
2549     Decl *ImportedDef = Importer.Import(Definition);
2550     if (!ImportedDef)
2551       return nullptr;
2552
2553     return Importer.Imported(D, ImportedDef);
2554   }
2555   
2556   // Import the major distinguishing characteristics of this record.
2557   DeclContext *DC, *LexicalDC;
2558   DeclarationName Name;
2559   SourceLocation Loc;
2560   NamedDecl *ToD;
2561   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2562     return nullptr;
2563   if (ToD)
2564     return ToD;
2565
2566   // Figure out what structure name we're looking for.
2567   unsigned IDNS = Decl::IDNS_Tag;
2568   DeclarationName SearchName = Name;
2569   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2570     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2571     IDNS = Decl::IDNS_Ordinary;
2572   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2573     IDNS |= Decl::IDNS_Ordinary;
2574
2575   // We may already have a record of the same name; try to find and match it.
2576   RecordDecl *AdoptDecl = nullptr;
2577   if (!DC->isFunctionOrMethod()) {
2578     SmallVector<NamedDecl *, 4> ConflictingDecls;
2579     SmallVector<NamedDecl *, 2> FoundDecls;
2580     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2581     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2582       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2583         continue;
2584       
2585       Decl *Found = FoundDecls[I];
2586       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2587         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2588           Found = Tag->getDecl();
2589       }
2590       
2591       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2592         if (D->isAnonymousStructOrUnion() && 
2593             FoundRecord->isAnonymousStructOrUnion()) {
2594           // If both anonymous structs/unions are in a record context, make sure
2595           // they occur in the same location in the context records.
2596           if (Optional<unsigned> Index1
2597               = findAnonymousStructOrUnionIndex(D)) {
2598             if (Optional<unsigned> Index2 =
2599                     findAnonymousStructOrUnionIndex(FoundRecord)) {
2600               if (*Index1 != *Index2)
2601                 continue;
2602             }
2603           }
2604         }
2605
2606         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2607           if ((SearchName && !D->isCompleteDefinition())
2608               || (D->isCompleteDefinition() &&
2609                   D->isAnonymousStructOrUnion()
2610                     == FoundDef->isAnonymousStructOrUnion() &&
2611                   IsStructuralMatch(D, FoundDef))) {
2612             // The record types structurally match, or the "from" translation
2613             // unit only had a forward declaration anyway; call it the same
2614             // function.
2615             // FIXME: For C++, we should also merge methods here.
2616             return Importer.Imported(D, FoundDef);
2617           }
2618         } else if (!D->isCompleteDefinition()) {
2619           // We have a forward declaration of this type, so adopt that forward
2620           // declaration rather than building a new one.
2621             
2622           // If one or both can be completed from external storage then try one
2623           // last time to complete and compare them before doing this.
2624             
2625           if (FoundRecord->hasExternalLexicalStorage() &&
2626               !FoundRecord->isCompleteDefinition())
2627             FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2628           if (D->hasExternalLexicalStorage())
2629             D->getASTContext().getExternalSource()->CompleteType(D);
2630             
2631           if (FoundRecord->isCompleteDefinition() &&
2632               D->isCompleteDefinition() &&
2633               !IsStructuralMatch(D, FoundRecord))
2634             continue;
2635               
2636           AdoptDecl = FoundRecord;
2637           continue;
2638         } else if (!SearchName) {
2639           continue;
2640         }
2641       }
2642       
2643       ConflictingDecls.push_back(FoundDecls[I]);
2644     }
2645     
2646     if (!ConflictingDecls.empty() && SearchName) {
2647       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2648                                          ConflictingDecls.data(), 
2649                                          ConflictingDecls.size());
2650     }
2651   }
2652   
2653   // Create the record declaration.
2654   RecordDecl *D2 = AdoptDecl;
2655   SourceLocation StartLoc = Importer.Import(D->getLocStart());
2656   if (!D2) {
2657     if (isa<CXXRecordDecl>(D)) {
2658       CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(), 
2659                                                    D->getTagKind(),
2660                                                    DC, StartLoc, Loc,
2661                                                    Name.getAsIdentifierInfo());
2662       D2 = D2CXX;
2663       D2->setAccess(D->getAccess());
2664     } else {
2665       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2666                               DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2667     }
2668     
2669     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2670     D2->setLexicalDeclContext(LexicalDC);
2671     LexicalDC->addDeclInternal(D2);
2672     if (D->isAnonymousStructOrUnion())
2673       D2->setAnonymousStructOrUnion(true);
2674   }
2675   
2676   Importer.Imported(D, D2);
2677
2678   if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2679     return nullptr;
2680
2681   return D2;
2682 }
2683
2684 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2685   // Import the major distinguishing characteristics of this enumerator.
2686   DeclContext *DC, *LexicalDC;
2687   DeclarationName Name;
2688   SourceLocation Loc;
2689   NamedDecl *ToD;
2690   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2691     return nullptr;
2692   if (ToD)
2693     return ToD;
2694
2695   QualType T = Importer.Import(D->getType());
2696   if (T.isNull())
2697     return nullptr;
2698
2699   // Determine whether there are any other declarations with the same name and 
2700   // in the same context.
2701   if (!LexicalDC->isFunctionOrMethod()) {
2702     SmallVector<NamedDecl *, 4> ConflictingDecls;
2703     unsigned IDNS = Decl::IDNS_Ordinary;
2704     SmallVector<NamedDecl *, 2> FoundDecls;
2705     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2706     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2707       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2708         continue;
2709
2710       if (EnumConstantDecl *FoundEnumConstant
2711             = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2712         if (IsStructuralMatch(D, FoundEnumConstant))
2713           return Importer.Imported(D, FoundEnumConstant);
2714       }
2715
2716       ConflictingDecls.push_back(FoundDecls[I]);
2717     }
2718     
2719     if (!ConflictingDecls.empty()) {
2720       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2721                                          ConflictingDecls.data(), 
2722                                          ConflictingDecls.size());
2723       if (!Name)
2724         return nullptr;
2725     }
2726   }
2727   
2728   Expr *Init = Importer.Import(D->getInitExpr());
2729   if (D->getInitExpr() && !Init)
2730     return nullptr;
2731
2732   EnumConstantDecl *ToEnumerator
2733     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc, 
2734                                Name.getAsIdentifierInfo(), T, 
2735                                Init, D->getInitVal());
2736   ToEnumerator->setAccess(D->getAccess());
2737   ToEnumerator->setLexicalDeclContext(LexicalDC);
2738   Importer.Imported(D, ToEnumerator);
2739   LexicalDC->addDeclInternal(ToEnumerator);
2740   return ToEnumerator;
2741 }
2742
2743 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2744   // Import the major distinguishing characteristics of this function.
2745   DeclContext *DC, *LexicalDC;
2746   DeclarationName Name;
2747   SourceLocation Loc;
2748   NamedDecl *ToD;
2749   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2750     return nullptr;
2751   if (ToD)
2752     return ToD;
2753
2754   // Try to find a function in our own ("to") context with the same name, same
2755   // type, and in the same context as the function we're importing.
2756   if (!LexicalDC->isFunctionOrMethod()) {
2757     SmallVector<NamedDecl *, 4> ConflictingDecls;
2758     unsigned IDNS = Decl::IDNS_Ordinary;
2759     SmallVector<NamedDecl *, 2> FoundDecls;
2760     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2761     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2762       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2763         continue;
2764     
2765       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2766         if (FoundFunction->hasExternalFormalLinkage() &&
2767             D->hasExternalFormalLinkage()) {
2768           if (Importer.IsStructurallyEquivalent(D->getType(), 
2769                                                 FoundFunction->getType())) {
2770             // FIXME: Actually try to merge the body and other attributes.
2771             return Importer.Imported(D, FoundFunction);
2772           }
2773         
2774           // FIXME: Check for overloading more carefully, e.g., by boosting
2775           // Sema::IsOverload out to the AST library.
2776           
2777           // Function overloading is okay in C++.
2778           if (Importer.getToContext().getLangOpts().CPlusPlus)
2779             continue;
2780           
2781           // Complain about inconsistent function types.
2782           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2783             << Name << D->getType() << FoundFunction->getType();
2784           Importer.ToDiag(FoundFunction->getLocation(), 
2785                           diag::note_odr_value_here)
2786             << FoundFunction->getType();
2787         }
2788       }
2789       
2790       ConflictingDecls.push_back(FoundDecls[I]);
2791     }
2792     
2793     if (!ConflictingDecls.empty()) {
2794       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2795                                          ConflictingDecls.data(), 
2796                                          ConflictingDecls.size());
2797       if (!Name)
2798         return nullptr;
2799     }    
2800   }
2801
2802   DeclarationNameInfo NameInfo(Name, Loc);
2803   // Import additional name location/type info.
2804   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2805
2806   QualType FromTy = D->getType();
2807   bool usedDifferentExceptionSpec = false;
2808
2809   if (const FunctionProtoType *
2810         FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2811     FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2812     // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2813     // FunctionDecl that we are importing the FunctionProtoType for.
2814     // To avoid an infinite recursion when importing, create the FunctionDecl
2815     // with a simplified function type and update it afterwards.
2816     if (FromEPI.ExceptionSpec.SourceDecl ||
2817         FromEPI.ExceptionSpec.SourceTemplate ||
2818         FromEPI.ExceptionSpec.NoexceptExpr) {
2819       FunctionProtoType::ExtProtoInfo DefaultEPI;
2820       FromTy = Importer.getFromContext().getFunctionType(
2821           FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2822       usedDifferentExceptionSpec = true;
2823     }
2824   }
2825
2826   // Import the type.
2827   QualType T = Importer.Import(FromTy);
2828   if (T.isNull())
2829     return nullptr;
2830
2831   // Import the function parameters.
2832   SmallVector<ParmVarDecl *, 8> Parameters;
2833   for (auto P : D->params()) {
2834     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2835     if (!ToP)
2836       return nullptr;
2837
2838     Parameters.push_back(ToP);
2839   }
2840   
2841   // Create the imported function.
2842   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2843   FunctionDecl *ToFunction = nullptr;
2844   SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2845   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2846     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2847                                             cast<CXXRecordDecl>(DC),
2848                                             InnerLocStart,
2849                                             NameInfo, T, TInfo, 
2850                                             FromConstructor->isExplicit(),
2851                                             D->isInlineSpecified(), 
2852                                             D->isImplicit(),
2853                                             D->isConstexpr());
2854   } else if (isa<CXXDestructorDecl>(D)) {
2855     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2856                                            cast<CXXRecordDecl>(DC),
2857                                            InnerLocStart,
2858                                            NameInfo, T, TInfo,
2859                                            D->isInlineSpecified(),
2860                                            D->isImplicit());
2861   } else if (CXXConversionDecl *FromConversion
2862                                            = dyn_cast<CXXConversionDecl>(D)) {
2863     ToFunction = CXXConversionDecl::Create(Importer.getToContext(), 
2864                                            cast<CXXRecordDecl>(DC),
2865                                            InnerLocStart,
2866                                            NameInfo, T, TInfo,
2867                                            D->isInlineSpecified(),
2868                                            FromConversion->isExplicit(),
2869                                            D->isConstexpr(),
2870                                            Importer.Import(D->getLocEnd()));
2871   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2872     ToFunction = CXXMethodDecl::Create(Importer.getToContext(), 
2873                                        cast<CXXRecordDecl>(DC),
2874                                        InnerLocStart,
2875                                        NameInfo, T, TInfo,
2876                                        Method->getStorageClass(),
2877                                        Method->isInlineSpecified(),
2878                                        D->isConstexpr(),
2879                                        Importer.Import(D->getLocEnd()));
2880   } else {
2881     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2882                                       InnerLocStart,
2883                                       NameInfo, T, TInfo, D->getStorageClass(),
2884                                       D->isInlineSpecified(),
2885                                       D->hasWrittenPrototype(),
2886                                       D->isConstexpr());
2887   }
2888
2889   // Import the qualifier, if any.
2890   ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2891   ToFunction->setAccess(D->getAccess());
2892   ToFunction->setLexicalDeclContext(LexicalDC);
2893   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2894   ToFunction->setTrivial(D->isTrivial());
2895   ToFunction->setPure(D->isPure());
2896   Importer.Imported(D, ToFunction);
2897
2898   // Set the parameters.
2899   for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2900     Parameters[I]->setOwningFunction(ToFunction);
2901     ToFunction->addDeclInternal(Parameters[I]);
2902   }
2903   ToFunction->setParams(Parameters);
2904
2905   if (usedDifferentExceptionSpec) {
2906     // Update FunctionProtoType::ExtProtoInfo.
2907     QualType T = Importer.Import(D->getType());
2908     if (T.isNull())
2909       return nullptr;
2910     ToFunction->setType(T);
2911   }
2912
2913   // Import the body, if any.
2914   if (Stmt *FromBody = D->getBody()) {
2915     if (Stmt *ToBody = Importer.Import(FromBody)) {
2916       ToFunction->setBody(ToBody);
2917     }
2918   }
2919
2920   // FIXME: Other bits to merge?
2921
2922   // Add this function to the lexical context.
2923   LexicalDC->addDeclInternal(ToFunction);
2924
2925   return ToFunction;
2926 }
2927
2928 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2929   return VisitFunctionDecl(D);
2930 }
2931
2932 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2933   return VisitCXXMethodDecl(D);
2934 }
2935
2936 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2937   return VisitCXXMethodDecl(D);
2938 }
2939
2940 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2941   return VisitCXXMethodDecl(D);
2942 }
2943
2944 static unsigned getFieldIndex(Decl *F) {
2945   RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2946   if (!Owner)
2947     return 0;
2948
2949   unsigned Index = 1;
2950   for (const auto *D : Owner->noload_decls()) {
2951     if (D == F)
2952       return Index;
2953
2954     if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2955       ++Index;
2956   }
2957
2958   return Index;
2959 }
2960
2961 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2962   // Import the major distinguishing characteristics of a variable.
2963   DeclContext *DC, *LexicalDC;
2964   DeclarationName Name;
2965   SourceLocation Loc;
2966   NamedDecl *ToD;
2967   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2968     return nullptr;
2969   if (ToD)
2970     return ToD;
2971
2972   // Determine whether we've already imported this field. 
2973   SmallVector<NamedDecl *, 2> FoundDecls;
2974   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2975   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2976     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2977       // For anonymous fields, match up by index.
2978       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2979         continue;
2980
2981       if (Importer.IsStructurallyEquivalent(D->getType(), 
2982                                             FoundField->getType())) {
2983         Importer.Imported(D, FoundField);
2984         return FoundField;
2985       }
2986       
2987       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2988         << Name << D->getType() << FoundField->getType();
2989       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2990         << FoundField->getType();
2991       return nullptr;
2992     }
2993   }
2994
2995   // Import the type.
2996   QualType T = Importer.Import(D->getType());
2997   if (T.isNull())
2998     return nullptr;
2999
3000   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3001   Expr *BitWidth = Importer.Import(D->getBitWidth());
3002   if (!BitWidth && D->getBitWidth())
3003     return nullptr;
3004
3005   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
3006                                          Importer.Import(D->getInnerLocStart()),
3007                                          Loc, Name.getAsIdentifierInfo(),
3008                                          T, TInfo, BitWidth, D->isMutable(),
3009                                          D->getInClassInitStyle());
3010   ToField->setAccess(D->getAccess());
3011   ToField->setLexicalDeclContext(LexicalDC);
3012   if (ToField->hasInClassInitializer())
3013     ToField->setInClassInitializer(D->getInClassInitializer());
3014   ToField->setImplicit(D->isImplicit());
3015   Importer.Imported(D, ToField);
3016   LexicalDC->addDeclInternal(ToField);
3017   return ToField;
3018 }
3019
3020 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3021   // Import the major distinguishing characteristics of a variable.
3022   DeclContext *DC, *LexicalDC;
3023   DeclarationName Name;
3024   SourceLocation Loc;
3025   NamedDecl *ToD;
3026   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3027     return nullptr;
3028   if (ToD)
3029     return ToD;
3030
3031   // Determine whether we've already imported this field. 
3032   SmallVector<NamedDecl *, 2> FoundDecls;
3033   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3034   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3035     if (IndirectFieldDecl *FoundField 
3036                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3037       // For anonymous indirect fields, match up by index.
3038       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3039         continue;
3040
3041       if (Importer.IsStructurallyEquivalent(D->getType(), 
3042                                             FoundField->getType(),
3043                                             !Name.isEmpty())) {
3044         Importer.Imported(D, FoundField);
3045         return FoundField;
3046       }
3047
3048       // If there are more anonymous fields to check, continue.
3049       if (!Name && I < N-1)
3050         continue;
3051
3052       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3053         << Name << D->getType() << FoundField->getType();
3054       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3055         << FoundField->getType();
3056       return nullptr;
3057     }
3058   }
3059
3060   // Import the type.
3061   QualType T = Importer.Import(D->getType());
3062   if (T.isNull())
3063     return nullptr;
3064
3065   NamedDecl **NamedChain =
3066     new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3067
3068   unsigned i = 0;
3069   for (auto *PI : D->chain()) {
3070     Decl *D = Importer.Import(PI);
3071     if (!D)
3072       return nullptr;
3073     NamedChain[i++] = cast<NamedDecl>(D);
3074   }
3075
3076   IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3077       Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3078       NamedChain, D->getChainingSize());
3079
3080   for (const auto *Attr : D->attrs())
3081     ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3082
3083   ToIndirectField->setAccess(D->getAccess());
3084   ToIndirectField->setLexicalDeclContext(LexicalDC);
3085   Importer.Imported(D, ToIndirectField);
3086   LexicalDC->addDeclInternal(ToIndirectField);
3087   return ToIndirectField;
3088 }
3089
3090 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3091   // Import the major distinguishing characteristics of an ivar.
3092   DeclContext *DC, *LexicalDC;
3093   DeclarationName Name;
3094   SourceLocation Loc;
3095   NamedDecl *ToD;
3096   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3097     return nullptr;
3098   if (ToD)
3099     return ToD;
3100
3101   // Determine whether we've already imported this ivar 
3102   SmallVector<NamedDecl *, 2> FoundDecls;
3103   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3104   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3105     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3106       if (Importer.IsStructurallyEquivalent(D->getType(), 
3107                                             FoundIvar->getType())) {
3108         Importer.Imported(D, FoundIvar);
3109         return FoundIvar;
3110       }
3111
3112       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3113         << Name << D->getType() << FoundIvar->getType();
3114       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3115         << FoundIvar->getType();
3116       return nullptr;
3117     }
3118   }
3119
3120   // Import the type.
3121   QualType T = Importer.Import(D->getType());
3122   if (T.isNull())
3123     return nullptr;
3124
3125   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3126   Expr *BitWidth = Importer.Import(D->getBitWidth());
3127   if (!BitWidth && D->getBitWidth())
3128     return nullptr;
3129
3130   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3131                                               cast<ObjCContainerDecl>(DC),
3132                                        Importer.Import(D->getInnerLocStart()),
3133                                               Loc, Name.getAsIdentifierInfo(),
3134                                               T, TInfo, D->getAccessControl(),
3135                                               BitWidth, D->getSynthesize());
3136   ToIvar->setLexicalDeclContext(LexicalDC);
3137   Importer.Imported(D, ToIvar);
3138   LexicalDC->addDeclInternal(ToIvar);
3139   return ToIvar;
3140   
3141 }
3142
3143 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3144   // Import the major distinguishing characteristics of a variable.
3145   DeclContext *DC, *LexicalDC;
3146   DeclarationName Name;
3147   SourceLocation Loc;
3148   NamedDecl *ToD;
3149   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3150     return nullptr;
3151   if (ToD)
3152     return ToD;
3153
3154   // Try to find a variable in our own ("to") context with the same name and
3155   // in the same context as the variable we're importing.
3156   if (D->isFileVarDecl()) {
3157     VarDecl *MergeWithVar = nullptr;
3158     SmallVector<NamedDecl *, 4> ConflictingDecls;
3159     unsigned IDNS = Decl::IDNS_Ordinary;
3160     SmallVector<NamedDecl *, 2> FoundDecls;
3161     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3162     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3163       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3164         continue;
3165       
3166       if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3167         // We have found a variable that we may need to merge with. Check it.
3168         if (FoundVar->hasExternalFormalLinkage() &&
3169             D->hasExternalFormalLinkage()) {
3170           if (Importer.IsStructurallyEquivalent(D->getType(), 
3171                                                 FoundVar->getType())) {
3172             MergeWithVar = FoundVar;
3173             break;
3174           }
3175
3176           const ArrayType *FoundArray
3177             = Importer.getToContext().getAsArrayType(FoundVar->getType());
3178           const ArrayType *TArray
3179             = Importer.getToContext().getAsArrayType(D->getType());
3180           if (FoundArray && TArray) {
3181             if (isa<IncompleteArrayType>(FoundArray) &&
3182                 isa<ConstantArrayType>(TArray)) {
3183               // Import the type.
3184               QualType T = Importer.Import(D->getType());
3185               if (T.isNull())
3186                 return nullptr;
3187
3188               FoundVar->setType(T);
3189               MergeWithVar = FoundVar;
3190               break;
3191             } else if (isa<IncompleteArrayType>(TArray) &&
3192                        isa<ConstantArrayType>(FoundArray)) {
3193               MergeWithVar = FoundVar;
3194               break;
3195             }
3196           }
3197
3198           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3199             << Name << D->getType() << FoundVar->getType();
3200           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3201             << FoundVar->getType();
3202         }
3203       }
3204       
3205       ConflictingDecls.push_back(FoundDecls[I]);
3206     }
3207
3208     if (MergeWithVar) {
3209       // An equivalent variable with external linkage has been found. Link 
3210       // the two declarations, then merge them.
3211       Importer.Imported(D, MergeWithVar);
3212       
3213       if (VarDecl *DDef = D->getDefinition()) {
3214         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3215           Importer.ToDiag(ExistingDef->getLocation(), 
3216                           diag::err_odr_variable_multiple_def)
3217             << Name;
3218           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3219         } else {
3220           Expr *Init = Importer.Import(DDef->getInit());
3221           MergeWithVar->setInit(Init);
3222           if (DDef->isInitKnownICE()) {
3223             EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3224             Eval->CheckedICE = true;
3225             Eval->IsICE = DDef->isInitICE();
3226           }
3227         }
3228       }
3229       
3230       return MergeWithVar;
3231     }
3232     
3233     if (!ConflictingDecls.empty()) {
3234       Name = Importer.HandleNameConflict(Name, DC, IDNS,
3235                                          ConflictingDecls.data(), 
3236                                          ConflictingDecls.size());
3237       if (!Name)
3238         return nullptr;
3239     }
3240   }
3241     
3242   // Import the type.
3243   QualType T = Importer.Import(D->getType());
3244   if (T.isNull())
3245     return nullptr;
3246
3247   // Create the imported variable.
3248   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3249   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3250                                    Importer.Import(D->getInnerLocStart()),
3251                                    Loc, Name.getAsIdentifierInfo(),
3252                                    T, TInfo,
3253                                    D->getStorageClass());
3254   ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3255   ToVar->setAccess(D->getAccess());
3256   ToVar->setLexicalDeclContext(LexicalDC);
3257   Importer.Imported(D, ToVar);
3258   LexicalDC->addDeclInternal(ToVar);
3259
3260   if (!D->isFileVarDecl() &&
3261       D->isUsed())
3262     ToVar->setIsUsed();
3263
3264   // Merge the initializer.
3265   if (ImportDefinition(D, ToVar))
3266     return nullptr;
3267
3268   return ToVar;
3269 }
3270
3271 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3272   // Parameters are created in the translation unit's context, then moved
3273   // into the function declaration's context afterward.
3274   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3275   
3276   // Import the name of this declaration.
3277   DeclarationName Name = Importer.Import(D->getDeclName());
3278   if (D->getDeclName() && !Name)
3279     return nullptr;
3280
3281   // Import the location of this declaration.
3282   SourceLocation Loc = Importer.Import(D->getLocation());
3283   
3284   // Import the parameter's type.
3285   QualType T = Importer.Import(D->getType());
3286   if (T.isNull())
3287     return nullptr;
3288
3289   // Create the imported parameter.
3290   ImplicitParamDecl *ToParm
3291     = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3292                                 Loc, Name.getAsIdentifierInfo(),
3293                                 T);
3294   return Importer.Imported(D, ToParm);
3295 }
3296
3297 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3298   // Parameters are created in the translation unit's context, then moved
3299   // into the function declaration's context afterward.
3300   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3301   
3302   // Import the name of this declaration.
3303   DeclarationName Name = Importer.Import(D->getDeclName());
3304   if (D->getDeclName() && !Name)
3305     return nullptr;
3306
3307   // Import the location of this declaration.
3308   SourceLocation Loc = Importer.Import(D->getLocation());
3309   
3310   // Import the parameter's type.
3311   QualType T = Importer.Import(D->getType());
3312   if (T.isNull())
3313     return nullptr;
3314
3315   // Create the imported parameter.
3316   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3317   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3318                                      Importer.Import(D->getInnerLocStart()),
3319                                             Loc, Name.getAsIdentifierInfo(),
3320                                             T, TInfo, D->getStorageClass(),
3321                                             /*FIXME: Default argument*/nullptr);
3322   ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3323
3324   if (D->isUsed())
3325     ToParm->setIsUsed();
3326
3327   return Importer.Imported(D, ToParm);
3328 }
3329
3330 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3331   // Import the major distinguishing characteristics of a method.
3332   DeclContext *DC, *LexicalDC;
3333   DeclarationName Name;
3334   SourceLocation Loc;
3335   NamedDecl *ToD;
3336   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3337     return nullptr;
3338   if (ToD)
3339     return ToD;
3340
3341   SmallVector<NamedDecl *, 2> FoundDecls;
3342   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3343   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3344     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3345       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3346         continue;
3347
3348       // Check return types.
3349       if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3350                                              FoundMethod->getReturnType())) {
3351         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3352             << D->isInstanceMethod() << Name << D->getReturnType()
3353             << FoundMethod->getReturnType();
3354         Importer.ToDiag(FoundMethod->getLocation(), 
3355                         diag::note_odr_objc_method_here)
3356           << D->isInstanceMethod() << Name;
3357         return nullptr;
3358       }
3359
3360       // Check the number of parameters.
3361       if (D->param_size() != FoundMethod->param_size()) {
3362         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3363           << D->isInstanceMethod() << Name
3364           << D->param_size() << FoundMethod->param_size();
3365         Importer.ToDiag(FoundMethod->getLocation(), 
3366                         diag::note_odr_objc_method_here)
3367           << D->isInstanceMethod() << Name;
3368         return nullptr;
3369       }
3370
3371       // Check parameter types.
3372       for (ObjCMethodDecl::param_iterator P = D->param_begin(), 
3373              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3374            P != PEnd; ++P, ++FoundP) {
3375         if (!Importer.IsStructurallyEquivalent((*P)->getType(), 
3376                                                (*FoundP)->getType())) {
3377           Importer.FromDiag((*P)->getLocation(), 
3378                             diag::err_odr_objc_method_param_type_inconsistent)
3379             << D->isInstanceMethod() << Name
3380             << (*P)->getType() << (*FoundP)->getType();
3381           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3382             << (*FoundP)->getType();
3383           return nullptr;
3384         }
3385       }
3386
3387       // Check variadic/non-variadic.
3388       // Check the number of parameters.
3389       if (D->isVariadic() != FoundMethod->isVariadic()) {
3390         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3391           << D->isInstanceMethod() << Name;
3392         Importer.ToDiag(FoundMethod->getLocation(), 
3393                         diag::note_odr_objc_method_here)
3394           << D->isInstanceMethod() << Name;
3395         return nullptr;
3396       }
3397
3398       // FIXME: Any other bits we need to merge?
3399       return Importer.Imported(D, FoundMethod);
3400     }
3401   }
3402
3403   // Import the result type.
3404   QualType ResultTy = Importer.Import(D->getReturnType());
3405   if (ResultTy.isNull())
3406     return nullptr;
3407
3408   TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3409
3410   ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3411       Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3412       Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3413       D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3414       D->getImplementationControl(), D->hasRelatedResultType());
3415
3416   // FIXME: When we decide to merge method definitions, we'll need to
3417   // deal with implicit parameters.
3418
3419   // Import the parameters
3420   SmallVector<ParmVarDecl *, 5> ToParams;
3421   for (auto *FromP : D->params()) {
3422     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3423     if (!ToP)
3424       return nullptr;
3425
3426     ToParams.push_back(ToP);
3427   }
3428   
3429   // Set the parameters.
3430   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3431     ToParams[I]->setOwningFunction(ToMethod);
3432     ToMethod->addDeclInternal(ToParams[I]);
3433   }
3434   SmallVector<SourceLocation, 12> SelLocs;
3435   D->getSelectorLocs(SelLocs);
3436   ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs); 
3437
3438   ToMethod->setLexicalDeclContext(LexicalDC);
3439   Importer.Imported(D, ToMethod);
3440   LexicalDC->addDeclInternal(ToMethod);
3441   return ToMethod;
3442 }
3443
3444 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3445   // Import the major distinguishing characteristics of a category.
3446   DeclContext *DC, *LexicalDC;
3447   DeclarationName Name;
3448   SourceLocation Loc;
3449   NamedDecl *ToD;
3450   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3451     return nullptr;
3452   if (ToD)
3453     return ToD;
3454
3455   TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3456   if (!BoundInfo)
3457     return nullptr;
3458
3459   ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3460                                 Importer.getToContext(), DC,
3461                                 D->getVariance(),
3462                                 Importer.Import(D->getVarianceLoc()),
3463                                 D->getIndex(),
3464                                 Importer.Import(D->getLocation()),
3465                                 Name.getAsIdentifierInfo(),
3466                                 Importer.Import(D->getColonLoc()),
3467                                 BoundInfo);
3468   Importer.Imported(D, Result);
3469   Result->setLexicalDeclContext(LexicalDC);
3470   return Result;
3471 }
3472
3473 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3474   // Import the major distinguishing characteristics of a category.
3475   DeclContext *DC, *LexicalDC;
3476   DeclarationName Name;
3477   SourceLocation Loc;
3478   NamedDecl *ToD;
3479   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3480     return nullptr;
3481   if (ToD)
3482     return ToD;
3483
3484   ObjCInterfaceDecl *ToInterface
3485     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3486   if (!ToInterface)
3487     return nullptr;
3488
3489   // Determine if we've already encountered this category.
3490   ObjCCategoryDecl *MergeWithCategory
3491     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3492   ObjCCategoryDecl *ToCategory = MergeWithCategory;
3493   if (!ToCategory) {
3494     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3495                                           Importer.Import(D->getAtStartLoc()),
3496                                           Loc, 
3497                                        Importer.Import(D->getCategoryNameLoc()), 
3498                                           Name.getAsIdentifierInfo(),
3499                                           ToInterface,
3500                                           /*TypeParamList=*/nullptr,
3501                                        Importer.Import(D->getIvarLBraceLoc()),
3502                                        Importer.Import(D->getIvarRBraceLoc()));
3503     ToCategory->setLexicalDeclContext(LexicalDC);
3504     LexicalDC->addDeclInternal(ToCategory);
3505     Importer.Imported(D, ToCategory);
3506     // Import the type parameter list after calling Imported, to avoid
3507     // loops when bringing in their DeclContext.
3508     ToCategory->setTypeParamList(ImportObjCTypeParamList(
3509                                    D->getTypeParamList()));
3510     
3511     // Import protocols
3512     SmallVector<ObjCProtocolDecl *, 4> Protocols;
3513     SmallVector<SourceLocation, 4> ProtocolLocs;
3514     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3515       = D->protocol_loc_begin();
3516     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3517                                           FromProtoEnd = D->protocol_end();
3518          FromProto != FromProtoEnd;
3519          ++FromProto, ++FromProtoLoc) {
3520       ObjCProtocolDecl *ToProto
3521         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3522       if (!ToProto)
3523         return nullptr;
3524       Protocols.push_back(ToProto);
3525       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3526     }
3527     
3528     // FIXME: If we're merging, make sure that the protocol list is the same.
3529     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3530                                 ProtocolLocs.data(), Importer.getToContext());
3531     
3532   } else {
3533     Importer.Imported(D, ToCategory);
3534   }
3535   
3536   // Import all of the members of this category.
3537   ImportDeclContext(D);
3538  
3539   // If we have an implementation, import it as well.
3540   if (D->getImplementation()) {
3541     ObjCCategoryImplDecl *Impl
3542       = cast_or_null<ObjCCategoryImplDecl>(
3543                                        Importer.Import(D->getImplementation()));
3544     if (!Impl)
3545       return nullptr;
3546
3547     ToCategory->setImplementation(Impl);
3548   }
3549   
3550   return ToCategory;
3551 }
3552
3553 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, 
3554                                        ObjCProtocolDecl *To,
3555                                        ImportDefinitionKind Kind) {
3556   if (To->getDefinition()) {
3557     if (shouldForceImportDeclContext(Kind))
3558       ImportDeclContext(From);
3559     return false;
3560   }
3561
3562   // Start the protocol definition
3563   To->startDefinition();
3564   
3565   // Import protocols
3566   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3567   SmallVector<SourceLocation, 4> ProtocolLocs;
3568   ObjCProtocolDecl::protocol_loc_iterator 
3569   FromProtoLoc = From->protocol_loc_begin();
3570   for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3571                                         FromProtoEnd = From->protocol_end();
3572        FromProto != FromProtoEnd;
3573        ++FromProto, ++FromProtoLoc) {
3574     ObjCProtocolDecl *ToProto
3575       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3576     if (!ToProto)
3577       return true;
3578     Protocols.push_back(ToProto);
3579     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3580   }
3581   
3582   // FIXME: If we're merging, make sure that the protocol list is the same.
3583   To->setProtocolList(Protocols.data(), Protocols.size(),
3584                       ProtocolLocs.data(), Importer.getToContext());
3585
3586   if (shouldForceImportDeclContext(Kind)) {
3587     // Import all of the members of this protocol.
3588     ImportDeclContext(From, /*ForceImport=*/true);
3589   }
3590   return false;
3591 }
3592
3593 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3594   // If this protocol has a definition in the translation unit we're coming 
3595   // from, but this particular declaration is not that definition, import the
3596   // definition and map to that.
3597   ObjCProtocolDecl *Definition = D->getDefinition();
3598   if (Definition && Definition != D) {
3599     Decl *ImportedDef = Importer.Import(Definition);
3600     if (!ImportedDef)
3601       return nullptr;
3602
3603     return Importer.Imported(D, ImportedDef);
3604   }
3605
3606   // Import the major distinguishing characteristics of a protocol.
3607   DeclContext *DC, *LexicalDC;
3608   DeclarationName Name;
3609   SourceLocation Loc;
3610   NamedDecl *ToD;
3611   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3612     return nullptr;
3613   if (ToD)
3614     return ToD;
3615
3616   ObjCProtocolDecl *MergeWithProtocol = nullptr;
3617   SmallVector<NamedDecl *, 2> FoundDecls;
3618   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3619   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3620     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3621       continue;
3622     
3623     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3624       break;
3625   }
3626   
3627   ObjCProtocolDecl *ToProto = MergeWithProtocol;
3628   if (!ToProto) {
3629     ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3630                                        Name.getAsIdentifierInfo(), Loc,
3631                                        Importer.Import(D->getAtStartLoc()),
3632                                        /*PrevDecl=*/nullptr);
3633     ToProto->setLexicalDeclContext(LexicalDC);
3634     LexicalDC->addDeclInternal(ToProto);
3635   }
3636     
3637   Importer.Imported(D, ToProto);
3638
3639   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3640     return nullptr;
3641
3642   return ToProto;
3643 }
3644
3645 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3646   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3647   DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3648
3649   SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3650   SourceLocation LangLoc = Importer.Import(D->getLocation());
3651
3652   bool HasBraces = D->hasBraces();
3653  
3654   LinkageSpecDecl *ToLinkageSpec =
3655     LinkageSpecDecl::Create(Importer.getToContext(),
3656                             DC,
3657                             ExternLoc,
3658                             LangLoc,
3659                             D->getLanguage(),
3660                             HasBraces);
3661
3662   if (HasBraces) {
3663     SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3664     ToLinkageSpec->setRBraceLoc(RBraceLoc);
3665   }
3666
3667   ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3668   LexicalDC->addDeclInternal(ToLinkageSpec);
3669
3670   Importer.Imported(D, ToLinkageSpec);
3671
3672   return ToLinkageSpec;
3673 }
3674
3675 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, 
3676                                        ObjCInterfaceDecl *To,
3677                                        ImportDefinitionKind Kind) {
3678   if (To->getDefinition()) {
3679     // Check consistency of superclass.
3680     ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3681     if (FromSuper) {
3682       FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3683       if (!FromSuper)
3684         return true;
3685     }
3686     
3687     ObjCInterfaceDecl *ToSuper = To->getSuperClass();    
3688     if ((bool)FromSuper != (bool)ToSuper ||
3689         (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3690       Importer.ToDiag(To->getLocation(), 
3691                       diag::err_odr_objc_superclass_inconsistent)
3692         << To->getDeclName();
3693       if (ToSuper)
3694         Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3695           << To->getSuperClass()->getDeclName();
3696       else
3697         Importer.ToDiag(To->getLocation(), 
3698                         diag::note_odr_objc_missing_superclass);
3699       if (From->getSuperClass())
3700         Importer.FromDiag(From->getSuperClassLoc(), 
3701                           diag::note_odr_objc_superclass)
3702         << From->getSuperClass()->getDeclName();
3703       else
3704         Importer.FromDiag(From->getLocation(), 
3705                           diag::note_odr_objc_missing_superclass);        
3706     }
3707     
3708     if (shouldForceImportDeclContext(Kind))
3709       ImportDeclContext(From);
3710     return false;
3711   }
3712   
3713   // Start the definition.
3714   To->startDefinition();
3715   
3716   // If this class has a superclass, import it.
3717   if (From->getSuperClass()) {
3718     TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3719     if (!SuperTInfo)
3720       return true;
3721
3722     To->setSuperClass(SuperTInfo);
3723   }
3724   
3725   // Import protocols
3726   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3727   SmallVector<SourceLocation, 4> ProtocolLocs;
3728   ObjCInterfaceDecl::protocol_loc_iterator 
3729   FromProtoLoc = From->protocol_loc_begin();
3730   
3731   for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3732                                          FromProtoEnd = From->protocol_end();
3733        FromProto != FromProtoEnd;
3734        ++FromProto, ++FromProtoLoc) {
3735     ObjCProtocolDecl *ToProto
3736       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3737     if (!ToProto)
3738       return true;
3739     Protocols.push_back(ToProto);
3740     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3741   }
3742   
3743   // FIXME: If we're merging, make sure that the protocol list is the same.
3744   To->setProtocolList(Protocols.data(), Protocols.size(),
3745                       ProtocolLocs.data(), Importer.getToContext());
3746   
3747   // Import categories. When the categories themselves are imported, they'll
3748   // hook themselves into this interface.
3749   for (auto *Cat : From->known_categories())
3750     Importer.Import(Cat);
3751   
3752   // If we have an @implementation, import it as well.
3753   if (From->getImplementation()) {
3754     ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3755                                      Importer.Import(From->getImplementation()));
3756     if (!Impl)
3757       return true;
3758     
3759     To->setImplementation(Impl);
3760   }
3761
3762   if (shouldForceImportDeclContext(Kind)) {
3763     // Import all of the members of this class.
3764     ImportDeclContext(From, /*ForceImport=*/true);
3765   }
3766   return false;
3767 }
3768
3769 ObjCTypeParamList *
3770 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
3771   if (!list)
3772     return nullptr;
3773
3774   SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
3775   for (auto fromTypeParam : *list) {
3776     auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3777                          Importer.Import(fromTypeParam));
3778     if (!toTypeParam)
3779       return nullptr;
3780
3781     toTypeParams.push_back(toTypeParam);
3782   }
3783
3784   return ObjCTypeParamList::create(Importer.getToContext(),
3785                                    Importer.Import(list->getLAngleLoc()),
3786                                    toTypeParams,
3787                                    Importer.Import(list->getRAngleLoc()));
3788 }
3789
3790 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3791   // If this class has a definition in the translation unit we're coming from,
3792   // but this particular declaration is not that definition, import the
3793   // definition and map to that.
3794   ObjCInterfaceDecl *Definition = D->getDefinition();
3795   if (Definition && Definition != D) {
3796     Decl *ImportedDef = Importer.Import(Definition);
3797     if (!ImportedDef)
3798       return nullptr;
3799
3800     return Importer.Imported(D, ImportedDef);
3801   }
3802
3803   // Import the major distinguishing characteristics of an @interface.
3804   DeclContext *DC, *LexicalDC;
3805   DeclarationName Name;
3806   SourceLocation Loc;
3807   NamedDecl *ToD;
3808   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3809     return nullptr;
3810   if (ToD)
3811     return ToD;
3812
3813   // Look for an existing interface with the same name.
3814   ObjCInterfaceDecl *MergeWithIface = nullptr;
3815   SmallVector<NamedDecl *, 2> FoundDecls;
3816   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3817   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3818     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3819       continue;
3820     
3821     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3822       break;
3823   }
3824   
3825   // Create an interface declaration, if one does not already exist.
3826   ObjCInterfaceDecl *ToIface = MergeWithIface;
3827   if (!ToIface) {
3828     ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3829                                         Importer.Import(D->getAtStartLoc()),
3830                                         Name.getAsIdentifierInfo(),
3831                                         /*TypeParamList=*/nullptr,
3832                                         /*PrevDecl=*/nullptr, Loc,
3833                                         D->isImplicitInterfaceDecl());
3834     ToIface->setLexicalDeclContext(LexicalDC);
3835     LexicalDC->addDeclInternal(ToIface);
3836   }
3837   Importer.Imported(D, ToIface);
3838   // Import the type parameter list after calling Imported, to avoid
3839   // loops when bringing in their DeclContext.
3840   ToIface->setTypeParamList(ImportObjCTypeParamList(
3841                               D->getTypeParamListAsWritten()));
3842   
3843   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3844     return nullptr;
3845
3846   return ToIface;
3847 }
3848
3849 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3850   ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3851                                         Importer.Import(D->getCategoryDecl()));
3852   if (!Category)
3853     return nullptr;
3854
3855   ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3856   if (!ToImpl) {
3857     DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3858     if (!DC)
3859       return nullptr;
3860
3861     SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3862     ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3863                                           Importer.Import(D->getIdentifier()),
3864                                           Category->getClassInterface(),
3865                                           Importer.Import(D->getLocation()),
3866                                           Importer.Import(D->getAtStartLoc()),
3867                                           CategoryNameLoc);
3868     
3869     DeclContext *LexicalDC = DC;
3870     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3871       LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3872       if (!LexicalDC)
3873         return nullptr;
3874
3875       ToImpl->setLexicalDeclContext(LexicalDC);
3876     }
3877     
3878     LexicalDC->addDeclInternal(ToImpl);
3879     Category->setImplementation(ToImpl);
3880   }
3881   
3882   Importer.Imported(D, ToImpl);
3883   ImportDeclContext(D);
3884   return ToImpl;
3885 }
3886
3887 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3888   // Find the corresponding interface.
3889   ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3890                                        Importer.Import(D->getClassInterface()));
3891   if (!Iface)
3892     return nullptr;
3893
3894   // Import the superclass, if any.
3895   ObjCInterfaceDecl *Super = nullptr;
3896   if (D->getSuperClass()) {
3897     Super = cast_or_null<ObjCInterfaceDecl>(
3898                                           Importer.Import(D->getSuperClass()));
3899     if (!Super)
3900       return nullptr;
3901   }
3902
3903   ObjCImplementationDecl *Impl = Iface->getImplementation();
3904   if (!Impl) {
3905     // We haven't imported an implementation yet. Create a new @implementation
3906     // now.
3907     Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3908                                   Importer.ImportContext(D->getDeclContext()),
3909                                           Iface, Super,
3910                                           Importer.Import(D->getLocation()),
3911                                           Importer.Import(D->getAtStartLoc()),
3912                                           Importer.Import(D->getSuperClassLoc()),
3913                                           Importer.Import(D->getIvarLBraceLoc()),
3914                                           Importer.Import(D->getIvarRBraceLoc()));
3915     
3916     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3917       DeclContext *LexicalDC
3918         = Importer.ImportContext(D->getLexicalDeclContext());
3919       if (!LexicalDC)
3920         return nullptr;
3921       Impl->setLexicalDeclContext(LexicalDC);
3922     }
3923     
3924     // Associate the implementation with the class it implements.
3925     Iface->setImplementation(Impl);
3926     Importer.Imported(D, Iface->getImplementation());
3927   } else {
3928     Importer.Imported(D, Iface->getImplementation());
3929
3930     // Verify that the existing @implementation has the same superclass.
3931     if ((Super && !Impl->getSuperClass()) ||
3932         (!Super && Impl->getSuperClass()) ||
3933         (Super && Impl->getSuperClass() &&
3934          !declaresSameEntity(Super->getCanonicalDecl(),
3935                              Impl->getSuperClass()))) {
3936       Importer.ToDiag(Impl->getLocation(),
3937                       diag::err_odr_objc_superclass_inconsistent)
3938         << Iface->getDeclName();
3939       // FIXME: It would be nice to have the location of the superclass
3940       // below.
3941       if (Impl->getSuperClass())
3942         Importer.ToDiag(Impl->getLocation(),
3943                         diag::note_odr_objc_superclass)
3944         << Impl->getSuperClass()->getDeclName();
3945       else
3946         Importer.ToDiag(Impl->getLocation(),
3947                         diag::note_odr_objc_missing_superclass);
3948       if (D->getSuperClass())
3949         Importer.FromDiag(D->getLocation(),
3950                           diag::note_odr_objc_superclass)
3951         << D->getSuperClass()->getDeclName();
3952       else
3953         Importer.FromDiag(D->getLocation(),
3954                           diag::note_odr_objc_missing_superclass);
3955       return nullptr;
3956     }
3957   }
3958     
3959   // Import all of the members of this @implementation.
3960   ImportDeclContext(D);
3961
3962   return Impl;
3963 }
3964
3965 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3966   // Import the major distinguishing characteristics of an @property.
3967   DeclContext *DC, *LexicalDC;
3968   DeclarationName Name;
3969   SourceLocation Loc;
3970   NamedDecl *ToD;
3971   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3972     return nullptr;
3973   if (ToD)
3974     return ToD;
3975
3976   // Check whether we have already imported this property.
3977   SmallVector<NamedDecl *, 2> FoundDecls;
3978   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3979   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3980     if (ObjCPropertyDecl *FoundProp
3981                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3982       // Check property types.
3983       if (!Importer.IsStructurallyEquivalent(D->getType(), 
3984                                              FoundProp->getType())) {
3985         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3986           << Name << D->getType() << FoundProp->getType();
3987         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3988           << FoundProp->getType();
3989         return nullptr;
3990       }
3991
3992       // FIXME: Check property attributes, getters, setters, etc.?
3993
3994       // Consider these properties to be equivalent.
3995       Importer.Imported(D, FoundProp);
3996       return FoundProp;
3997     }
3998   }
3999
4000   // Import the type.
4001   TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4002   if (!TSI)
4003     return nullptr;
4004
4005   // Create the new property.
4006   ObjCPropertyDecl *ToProperty
4007     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
4008                                Name.getAsIdentifierInfo(), 
4009                                Importer.Import(D->getAtLoc()),
4010                                Importer.Import(D->getLParenLoc()),
4011                                Importer.Import(D->getType()),
4012                                TSI,
4013                                D->getPropertyImplementation());
4014   Importer.Imported(D, ToProperty);
4015   ToProperty->setLexicalDeclContext(LexicalDC);
4016   LexicalDC->addDeclInternal(ToProperty);
4017
4018   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4019   ToProperty->setPropertyAttributesAsWritten(
4020                                       D->getPropertyAttributesAsWritten());
4021   ToProperty->setGetterName(Importer.Import(D->getGetterName()));
4022   ToProperty->setSetterName(Importer.Import(D->getSetterName()));
4023   ToProperty->setGetterMethodDecl(
4024      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4025   ToProperty->setSetterMethodDecl(
4026      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4027   ToProperty->setPropertyIvarDecl(
4028        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4029   return ToProperty;
4030 }
4031
4032 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4033   ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
4034                                         Importer.Import(D->getPropertyDecl()));
4035   if (!Property)
4036     return nullptr;
4037
4038   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4039   if (!DC)
4040     return nullptr;
4041
4042   // Import the lexical declaration context.
4043   DeclContext *LexicalDC = DC;
4044   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4045     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4046     if (!LexicalDC)
4047       return nullptr;
4048   }
4049
4050   ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4051   if (!InImpl)
4052     return nullptr;
4053
4054   // Import the ivar (for an @synthesize).
4055   ObjCIvarDecl *Ivar = nullptr;
4056   if (D->getPropertyIvarDecl()) {
4057     Ivar = cast_or_null<ObjCIvarDecl>(
4058                                     Importer.Import(D->getPropertyIvarDecl()));
4059     if (!Ivar)
4060       return nullptr;
4061   }
4062
4063   ObjCPropertyImplDecl *ToImpl
4064     = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4065                                    Property->getQueryKind());
4066   if (!ToImpl) {    
4067     ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
4068                                           Importer.Import(D->getLocStart()),
4069                                           Importer.Import(D->getLocation()),
4070                                           Property,
4071                                           D->getPropertyImplementation(),
4072                                           Ivar, 
4073                                   Importer.Import(D->getPropertyIvarDeclLoc()));
4074     ToImpl->setLexicalDeclContext(LexicalDC);
4075     Importer.Imported(D, ToImpl);
4076     LexicalDC->addDeclInternal(ToImpl);
4077   } else {
4078     // Check that we have the same kind of property implementation (@synthesize
4079     // vs. @dynamic).
4080     if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4081       Importer.ToDiag(ToImpl->getLocation(), 
4082                       diag::err_odr_objc_property_impl_kind_inconsistent)
4083         << Property->getDeclName() 
4084         << (ToImpl->getPropertyImplementation() 
4085                                               == ObjCPropertyImplDecl::Dynamic);
4086       Importer.FromDiag(D->getLocation(),
4087                         diag::note_odr_objc_property_impl_kind)
4088         << D->getPropertyDecl()->getDeclName()
4089         << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4090       return nullptr;
4091     }
4092     
4093     // For @synthesize, check that we have the same 
4094     if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4095         Ivar != ToImpl->getPropertyIvarDecl()) {
4096       Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), 
4097                       diag::err_odr_objc_synthesize_ivar_inconsistent)
4098         << Property->getDeclName()
4099         << ToImpl->getPropertyIvarDecl()->getDeclName()
4100         << Ivar->getDeclName();
4101       Importer.FromDiag(D->getPropertyIvarDeclLoc(), 
4102                         diag::note_odr_objc_synthesize_ivar_here)
4103         << D->getPropertyIvarDecl()->getDeclName();
4104       return nullptr;
4105     }
4106     
4107     // Merge the existing implementation with the new implementation.
4108     Importer.Imported(D, ToImpl);
4109   }
4110   
4111   return ToImpl;
4112 }
4113
4114 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4115   // For template arguments, we adopt the translation unit as our declaration
4116   // context. This context will be fixed when the actual template declaration
4117   // is created.
4118   
4119   // FIXME: Import default argument.
4120   return TemplateTypeParmDecl::Create(Importer.getToContext(),
4121                               Importer.getToContext().getTranslationUnitDecl(),
4122                                       Importer.Import(D->getLocStart()),
4123                                       Importer.Import(D->getLocation()),
4124                                       D->getDepth(),
4125                                       D->getIndex(), 
4126                                       Importer.Import(D->getIdentifier()),
4127                                       D->wasDeclaredWithTypename(),
4128                                       D->isParameterPack());
4129 }
4130
4131 Decl *
4132 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4133   // Import the name of this declaration.
4134   DeclarationName Name = Importer.Import(D->getDeclName());
4135   if (D->getDeclName() && !Name)
4136     return nullptr;
4137
4138   // Import the location of this declaration.
4139   SourceLocation Loc = Importer.Import(D->getLocation());
4140
4141   // Import the type of this declaration.
4142   QualType T = Importer.Import(D->getType());
4143   if (T.isNull())
4144     return nullptr;
4145
4146   // Import type-source information.
4147   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4148   if (D->getTypeSourceInfo() && !TInfo)
4149     return nullptr;
4150
4151   // FIXME: Import default argument.
4152   
4153   return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4154                                Importer.getToContext().getTranslationUnitDecl(),
4155                                          Importer.Import(D->getInnerLocStart()),
4156                                          Loc, D->getDepth(), D->getPosition(),
4157                                          Name.getAsIdentifierInfo(),
4158                                          T, D->isParameterPack(), TInfo);
4159 }
4160
4161 Decl *
4162 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4163   // Import the name of this declaration.
4164   DeclarationName Name = Importer.Import(D->getDeclName());
4165   if (D->getDeclName() && !Name)
4166     return nullptr;
4167
4168   // Import the location of this declaration.
4169   SourceLocation Loc = Importer.Import(D->getLocation());
4170   
4171   // Import template parameters.
4172   TemplateParameterList *TemplateParams
4173     = ImportTemplateParameterList(D->getTemplateParameters());
4174   if (!TemplateParams)
4175     return nullptr;
4176
4177   // FIXME: Import default argument.
4178   
4179   return TemplateTemplateParmDecl::Create(Importer.getToContext(), 
4180                               Importer.getToContext().getTranslationUnitDecl(), 
4181                                           Loc, D->getDepth(), D->getPosition(),
4182                                           D->isParameterPack(),
4183                                           Name.getAsIdentifierInfo(), 
4184                                           TemplateParams);
4185 }
4186
4187 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4188   // If this record has a definition in the translation unit we're coming from,
4189   // but this particular declaration is not that definition, import the
4190   // definition and map to that.
4191   CXXRecordDecl *Definition 
4192     = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4193   if (Definition && Definition != D->getTemplatedDecl()) {
4194     Decl *ImportedDef
4195       = Importer.Import(Definition->getDescribedClassTemplate());
4196     if (!ImportedDef)
4197       return nullptr;
4198
4199     return Importer.Imported(D, ImportedDef);
4200   }
4201   
4202   // Import the major distinguishing characteristics of this class template.
4203   DeclContext *DC, *LexicalDC;
4204   DeclarationName Name;
4205   SourceLocation Loc;
4206   NamedDecl *ToD;
4207   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4208     return nullptr;
4209   if (ToD)
4210     return ToD;
4211
4212   // We may already have a template of the same name; try to find and match it.
4213   if (!DC->isFunctionOrMethod()) {
4214     SmallVector<NamedDecl *, 4> ConflictingDecls;
4215     SmallVector<NamedDecl *, 2> FoundDecls;
4216     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4217     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4218       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4219         continue;
4220       
4221       Decl *Found = FoundDecls[I];
4222       if (ClassTemplateDecl *FoundTemplate 
4223                                         = dyn_cast<ClassTemplateDecl>(Found)) {
4224         if (IsStructuralMatch(D, FoundTemplate)) {
4225           // The class templates structurally match; call it the same template.
4226           // FIXME: We may be filling in a forward declaration here. Handle
4227           // this case!
4228           Importer.Imported(D->getTemplatedDecl(), 
4229                             FoundTemplate->getTemplatedDecl());
4230           return Importer.Imported(D, FoundTemplate);
4231         }         
4232       }
4233       
4234       ConflictingDecls.push_back(FoundDecls[I]);
4235     }
4236     
4237     if (!ConflictingDecls.empty()) {
4238       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4239                                          ConflictingDecls.data(), 
4240                                          ConflictingDecls.size());
4241     }
4242     
4243     if (!Name)
4244       return nullptr;
4245   }
4246
4247   CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4248   
4249   // Create the declaration that is being templated.
4250   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4251   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4252   CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4253                                                      DTemplated->getTagKind(),
4254                                                      DC, StartLoc, IdLoc,
4255                                                    Name.getAsIdentifierInfo());
4256   D2Templated->setAccess(DTemplated->getAccess());
4257   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4258   D2Templated->setLexicalDeclContext(LexicalDC);
4259   
4260   // Create the class template declaration itself.
4261   TemplateParameterList *TemplateParams
4262     = ImportTemplateParameterList(D->getTemplateParameters());
4263   if (!TemplateParams)
4264     return nullptr;
4265
4266   ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC, 
4267                                                     Loc, Name, TemplateParams, 
4268                                                     D2Templated, 
4269                                                     /*PrevDecl=*/nullptr);
4270   D2Templated->setDescribedClassTemplate(D2);    
4271   
4272   D2->setAccess(D->getAccess());
4273   D2->setLexicalDeclContext(LexicalDC);
4274   LexicalDC->addDeclInternal(D2);
4275   
4276   // Note the relationship between the class templates.
4277   Importer.Imported(D, D2);
4278   Importer.Imported(DTemplated, D2Templated);
4279
4280   if (DTemplated->isCompleteDefinition() &&
4281       !D2Templated->isCompleteDefinition()) {
4282     // FIXME: Import definition!
4283   }
4284   
4285   return D2;
4286 }
4287
4288 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4289                                           ClassTemplateSpecializationDecl *D) {
4290   // If this record has a definition in the translation unit we're coming from,
4291   // but this particular declaration is not that definition, import the
4292   // definition and map to that.
4293   TagDecl *Definition = D->getDefinition();
4294   if (Definition && Definition != D) {
4295     Decl *ImportedDef = Importer.Import(Definition);
4296     if (!ImportedDef)
4297       return nullptr;
4298
4299     return Importer.Imported(D, ImportedDef);
4300   }
4301
4302   ClassTemplateDecl *ClassTemplate
4303     = cast_or_null<ClassTemplateDecl>(Importer.Import(
4304                                                  D->getSpecializedTemplate()));
4305   if (!ClassTemplate)
4306     return nullptr;
4307
4308   // Import the context of this declaration.
4309   DeclContext *DC = ClassTemplate->getDeclContext();
4310   if (!DC)
4311     return nullptr;
4312
4313   DeclContext *LexicalDC = DC;
4314   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4315     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4316     if (!LexicalDC)
4317       return nullptr;
4318   }
4319   
4320   // Import the location of this declaration.
4321   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4322   SourceLocation IdLoc = Importer.Import(D->getLocation());
4323
4324   // Import template arguments.
4325   SmallVector<TemplateArgument, 2> TemplateArgs;
4326   if (ImportTemplateArguments(D->getTemplateArgs().data(), 
4327                               D->getTemplateArgs().size(),
4328                               TemplateArgs))
4329     return nullptr;
4330
4331   // Try to find an existing specialization with these template arguments.
4332   void *InsertPos = nullptr;
4333   ClassTemplateSpecializationDecl *D2
4334     = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4335   if (D2) {
4336     // We already have a class template specialization with these template
4337     // arguments.
4338     
4339     // FIXME: Check for specialization vs. instantiation errors.
4340     
4341     if (RecordDecl *FoundDef = D2->getDefinition()) {
4342       if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4343         // The record types structurally match, or the "from" translation
4344         // unit only had a forward declaration anyway; call it the same
4345         // function.
4346         return Importer.Imported(D, FoundDef);
4347       }
4348     }
4349   } else {
4350     // Create a new specialization.
4351     D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(), 
4352                                                  D->getTagKind(), DC, 
4353                                                  StartLoc, IdLoc,
4354                                                  ClassTemplate,
4355                                                  TemplateArgs.data(), 
4356                                                  TemplateArgs.size(), 
4357                                                  /*PrevDecl=*/nullptr);
4358     D2->setSpecializationKind(D->getSpecializationKind());
4359
4360     // Add this specialization to the class template.
4361     ClassTemplate->AddSpecialization(D2, InsertPos);
4362     
4363     // Import the qualifier, if any.
4364     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4365     
4366     // Add the specialization to this context.
4367     D2->setLexicalDeclContext(LexicalDC);
4368     LexicalDC->addDeclInternal(D2);
4369   }
4370   Importer.Imported(D, D2);
4371   
4372   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4373     return nullptr;
4374
4375   return D2;
4376 }
4377
4378 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4379   // If this variable has a definition in the translation unit we're coming
4380   // from,
4381   // but this particular declaration is not that definition, import the
4382   // definition and map to that.
4383   VarDecl *Definition =
4384       cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4385   if (Definition && Definition != D->getTemplatedDecl()) {
4386     Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4387     if (!ImportedDef)
4388       return nullptr;
4389
4390     return Importer.Imported(D, ImportedDef);
4391   }
4392
4393   // Import the major distinguishing characteristics of this variable template.
4394   DeclContext *DC, *LexicalDC;
4395   DeclarationName Name;
4396   SourceLocation Loc;
4397   NamedDecl *ToD;
4398   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4399     return nullptr;
4400   if (ToD)
4401     return ToD;
4402
4403   // We may already have a template of the same name; try to find and match it.
4404   assert(!DC->isFunctionOrMethod() &&
4405          "Variable templates cannot be declared at function scope");
4406   SmallVector<NamedDecl *, 4> ConflictingDecls;
4407   SmallVector<NamedDecl *, 2> FoundDecls;
4408   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4409   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4410     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4411       continue;
4412
4413     Decl *Found = FoundDecls[I];
4414     if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4415       if (IsStructuralMatch(D, FoundTemplate)) {
4416         // The variable templates structurally match; call it the same template.
4417         Importer.Imported(D->getTemplatedDecl(),
4418                           FoundTemplate->getTemplatedDecl());
4419         return Importer.Imported(D, FoundTemplate);
4420       }
4421     }
4422
4423     ConflictingDecls.push_back(FoundDecls[I]);
4424   }
4425
4426   if (!ConflictingDecls.empty()) {
4427     Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4428                                        ConflictingDecls.data(),
4429                                        ConflictingDecls.size());
4430   }
4431
4432   if (!Name)
4433     return nullptr;
4434
4435   VarDecl *DTemplated = D->getTemplatedDecl();
4436
4437   // Import the type.
4438   QualType T = Importer.Import(DTemplated->getType());
4439   if (T.isNull())
4440     return nullptr;
4441
4442   // Create the declaration that is being templated.
4443   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4444   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4445   TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4446   VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4447                                          IdLoc, Name.getAsIdentifierInfo(), T,
4448                                          TInfo, DTemplated->getStorageClass());
4449   D2Templated->setAccess(DTemplated->getAccess());
4450   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4451   D2Templated->setLexicalDeclContext(LexicalDC);
4452
4453   // Importer.Imported(DTemplated, D2Templated);
4454   // LexicalDC->addDeclInternal(D2Templated);
4455
4456   // Merge the initializer.
4457   if (ImportDefinition(DTemplated, D2Templated))
4458     return nullptr;
4459
4460   // Create the variable template declaration itself.
4461   TemplateParameterList *TemplateParams =
4462       ImportTemplateParameterList(D->getTemplateParameters());
4463   if (!TemplateParams)
4464     return nullptr;
4465
4466   VarTemplateDecl *D2 = VarTemplateDecl::Create(
4467       Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4468   D2Templated->setDescribedVarTemplate(D2);
4469
4470   D2->setAccess(D->getAccess());
4471   D2->setLexicalDeclContext(LexicalDC);
4472   LexicalDC->addDeclInternal(D2);
4473
4474   // Note the relationship between the variable templates.
4475   Importer.Imported(D, D2);
4476   Importer.Imported(DTemplated, D2Templated);
4477
4478   if (DTemplated->isThisDeclarationADefinition() &&
4479       !D2Templated->isThisDeclarationADefinition()) {
4480     // FIXME: Import definition!
4481   }
4482
4483   return D2;
4484 }
4485
4486 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4487     VarTemplateSpecializationDecl *D) {
4488   // If this record has a definition in the translation unit we're coming from,
4489   // but this particular declaration is not that definition, import the
4490   // definition and map to that.
4491   VarDecl *Definition = D->getDefinition();
4492   if (Definition && Definition != D) {
4493     Decl *ImportedDef = Importer.Import(Definition);
4494     if (!ImportedDef)
4495       return nullptr;
4496
4497     return Importer.Imported(D, ImportedDef);
4498   }
4499
4500   VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4501       Importer.Import(D->getSpecializedTemplate()));
4502   if (!VarTemplate)
4503     return nullptr;
4504
4505   // Import the context of this declaration.
4506   DeclContext *DC = VarTemplate->getDeclContext();
4507   if (!DC)
4508     return nullptr;
4509
4510   DeclContext *LexicalDC = DC;
4511   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4512     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4513     if (!LexicalDC)
4514       return nullptr;
4515   }
4516
4517   // Import the location of this declaration.
4518   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4519   SourceLocation IdLoc = Importer.Import(D->getLocation());
4520
4521   // Import template arguments.
4522   SmallVector<TemplateArgument, 2> TemplateArgs;
4523   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4524                               D->getTemplateArgs().size(), TemplateArgs))
4525     return nullptr;
4526
4527   // Try to find an existing specialization with these template arguments.
4528   void *InsertPos = nullptr;
4529   VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4530       TemplateArgs, InsertPos);
4531   if (D2) {
4532     // We already have a variable template specialization with these template
4533     // arguments.
4534
4535     // FIXME: Check for specialization vs. instantiation errors.
4536
4537     if (VarDecl *FoundDef = D2->getDefinition()) {
4538       if (!D->isThisDeclarationADefinition() ||
4539           IsStructuralMatch(D, FoundDef)) {
4540         // The record types structurally match, or the "from" translation
4541         // unit only had a forward declaration anyway; call it the same
4542         // variable.
4543         return Importer.Imported(D, FoundDef);
4544       }
4545     }
4546   } else {
4547
4548     // Import the type.
4549     QualType T = Importer.Import(D->getType());
4550     if (T.isNull())
4551       return nullptr;
4552     TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4553
4554     // Create a new specialization.
4555     D2 = VarTemplateSpecializationDecl::Create(
4556         Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4557         D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4558     D2->setSpecializationKind(D->getSpecializationKind());
4559     D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4560
4561     // Add this specialization to the class template.
4562     VarTemplate->AddSpecialization(D2, InsertPos);
4563
4564     // Import the qualifier, if any.
4565     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4566
4567     // Add the specialization to this context.
4568     D2->setLexicalDeclContext(LexicalDC);
4569     LexicalDC->addDeclInternal(D2);
4570   }
4571   Importer.Imported(D, D2);
4572
4573   if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4574     return nullptr;
4575
4576   return D2;
4577 }
4578
4579 //----------------------------------------------------------------------------
4580 // Import Statements
4581 //----------------------------------------------------------------------------
4582
4583 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4584   if (DG.isNull())
4585     return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4586   size_t NumDecls = DG.end() - DG.begin();
4587   SmallVector<Decl *, 1> ToDecls(NumDecls);
4588   auto &_Importer = this->Importer;
4589   std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4590     [&_Importer](Decl *D) -> Decl * {
4591       return _Importer.Import(D);
4592     });
4593   return DeclGroupRef::Create(Importer.getToContext(),
4594                               ToDecls.begin(),
4595                               NumDecls);
4596 }
4597
4598  Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4599    Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4600      << S->getStmtClassName();
4601    return nullptr;
4602  }
4603  
4604 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4605   DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4606   for (Decl *ToD : ToDG) {
4607     if (!ToD)
4608       return nullptr;
4609   }
4610   SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4611   SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4612   return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4613 }
4614
4615 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4616   SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4617   return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4618                                                 S->hasLeadingEmptyMacro());
4619 }
4620
4621 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4622   SmallVector<Stmt *, 4> ToStmts(S->size());
4623   auto &_Importer = this->Importer;
4624   std::transform(S->body_begin(), S->body_end(), ToStmts.begin(),
4625     [&_Importer](Stmt *CS) -> Stmt * {
4626       return _Importer.Import(CS);
4627     });
4628   for (Stmt *ToS : ToStmts) {
4629     if (!ToS)
4630       return nullptr;
4631   }
4632   SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4633   SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4634   return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
4635                                                     ToStmts,
4636                                                     ToLBraceLoc, ToRBraceLoc);
4637 }
4638
4639 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4640   Expr *ToLHS = Importer.Import(S->getLHS());
4641   if (!ToLHS)
4642     return nullptr;
4643   Expr *ToRHS = Importer.Import(S->getRHS());
4644   if (!ToRHS && S->getRHS())
4645     return nullptr;
4646   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4647   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4648   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4649   return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
4650                                                 ToCaseLoc, ToEllipsisLoc,
4651                                                 ToColonLoc);
4652 }
4653
4654 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4655   SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4656   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4657   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4658   if (!ToSubStmt && S->getSubStmt())
4659     return nullptr;
4660   return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4661                                                    ToSubStmt);
4662 }
4663
4664 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4665   SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4666   LabelDecl *ToLabelDecl =
4667     cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4668   if (!ToLabelDecl && S->getDecl())
4669     return nullptr;
4670   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4671   if (!ToSubStmt && S->getSubStmt())
4672     return nullptr;
4673   return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4674                                                  ToSubStmt);
4675 }
4676
4677 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4678   SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4679   ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4680   SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4681   ASTContext &_ToContext = Importer.getToContext();
4682   std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4683     [&_ToContext](const Attr *A) -> const Attr * {
4684       return A->clone(_ToContext);
4685     });
4686   for (const Attr *ToA : ToAttrs) {
4687     if (!ToA)
4688       return nullptr;
4689   }
4690   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4691   if (!ToSubStmt && S->getSubStmt())
4692     return nullptr;
4693   return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4694                                 ToAttrs, ToSubStmt);
4695 }
4696
4697 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4698   SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4699   VarDecl *ToConditionVariable = nullptr;
4700   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4701     ToConditionVariable =
4702       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4703     if (!ToConditionVariable)
4704       return nullptr;
4705   }
4706   Expr *ToCondition = Importer.Import(S->getCond());
4707   if (!ToCondition && S->getCond())
4708     return nullptr;
4709   Stmt *ToThenStmt = Importer.Import(S->getThen());
4710   if (!ToThenStmt && S->getThen())
4711     return nullptr;
4712   SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4713   Stmt *ToElseStmt = Importer.Import(S->getElse());
4714   if (!ToElseStmt && S->getElse())
4715     return nullptr;
4716   return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4717                                               ToIfLoc, ToConditionVariable,
4718                                               ToCondition, ToThenStmt,
4719                                               ToElseLoc, ToElseStmt);
4720 }
4721
4722 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4723   VarDecl *ToConditionVariable = nullptr;
4724   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4725     ToConditionVariable =
4726       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4727     if (!ToConditionVariable)
4728       return nullptr;
4729   }
4730   Expr *ToCondition = Importer.Import(S->getCond());
4731   if (!ToCondition && S->getCond())
4732     return nullptr;
4733   SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
4734                          Importer.getToContext(), ToConditionVariable,
4735                          ToCondition);
4736   Stmt *ToBody = Importer.Import(S->getBody());
4737   if (!ToBody && S->getBody())
4738     return nullptr;
4739   ToStmt->setBody(ToBody);
4740   ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
4741   // Now we have to re-chain the cases.
4742   SwitchCase *LastChainedSwitchCase = nullptr;
4743   for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
4744        SC = SC->getNextSwitchCase()) {
4745     SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
4746     if (!ToSC)
4747       return nullptr;
4748     if (LastChainedSwitchCase)
4749       LastChainedSwitchCase->setNextSwitchCase(ToSC);
4750     else
4751       ToStmt->setSwitchCaseList(ToSC);
4752     LastChainedSwitchCase = ToSC;
4753   }
4754   return ToStmt;
4755 }
4756
4757 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
4758   VarDecl *ToConditionVariable = nullptr;
4759   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4760     ToConditionVariable =
4761       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4762     if (!ToConditionVariable)
4763       return nullptr;
4764   }
4765   Expr *ToCondition = Importer.Import(S->getCond());
4766   if (!ToCondition && S->getCond())
4767     return nullptr;
4768   Stmt *ToBody = Importer.Import(S->getBody());
4769   if (!ToBody && S->getBody())
4770     return nullptr;
4771   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4772   return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
4773                                                  ToConditionVariable,
4774                                                  ToCondition, ToBody,
4775                                                  ToWhileLoc);
4776 }
4777
4778 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
4779   Stmt *ToBody = Importer.Import(S->getBody());
4780   if (!ToBody && S->getBody())
4781     return nullptr;
4782   Expr *ToCondition = Importer.Import(S->getCond());
4783   if (!ToCondition && S->getCond())
4784     return nullptr;
4785   SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
4786   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4787   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4788   return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
4789                                               ToDoLoc, ToWhileLoc,
4790                                               ToRParenLoc);
4791 }
4792
4793 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
4794   Stmt *ToInit = Importer.Import(S->getInit());
4795   if (!ToInit && S->getInit())
4796     return nullptr;
4797   Expr *ToCondition = Importer.Import(S->getCond());
4798   if (!ToCondition && S->getCond())
4799     return nullptr;
4800   VarDecl *ToConditionVariable = nullptr;
4801   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4802     ToConditionVariable =
4803       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4804     if (!ToConditionVariable)
4805       return nullptr;
4806   }
4807   Expr *ToInc = Importer.Import(S->getInc());
4808   if (!ToInc && S->getInc())
4809     return nullptr;
4810   Stmt *ToBody = Importer.Import(S->getBody());
4811   if (!ToBody && S->getBody())
4812     return nullptr;
4813   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4814   SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
4815   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4816   return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
4817                                                ToInit, ToCondition,
4818                                                ToConditionVariable,
4819                                                ToInc, ToBody,
4820                                                ToForLoc, ToLParenLoc,
4821                                                ToRParenLoc);
4822 }
4823
4824 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
4825   LabelDecl *ToLabel = nullptr;
4826   if (LabelDecl *FromLabel = S->getLabel()) {
4827     ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
4828     if (!ToLabel)
4829       return nullptr;
4830   }
4831   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4832   SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
4833   return new (Importer.getToContext()) GotoStmt(ToLabel,
4834                                                 ToGotoLoc, ToLabelLoc);
4835 }
4836
4837 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
4838   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4839   SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
4840   Expr *ToTarget = Importer.Import(S->getTarget());
4841   if (!ToTarget && S->getTarget())
4842     return nullptr;
4843   return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
4844                                                         ToTarget);
4845 }
4846
4847 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
4848   SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
4849   return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
4850 }
4851
4852 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
4853   SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
4854   return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
4855 }
4856
4857 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
4858   SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
4859   Expr *ToRetExpr = Importer.Import(S->getRetValue());
4860   if (!ToRetExpr && S->getRetValue())
4861     return nullptr;
4862   VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
4863   VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
4864   if (!ToNRVOCandidate && NRVOCandidate)
4865     return nullptr;
4866   return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
4867                                                   ToNRVOCandidate);
4868 }
4869
4870 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
4871   SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
4872   VarDecl *ToExceptionDecl = nullptr;
4873   if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
4874     ToExceptionDecl =
4875       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4876     if (!ToExceptionDecl)
4877       return nullptr;
4878   }
4879   Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
4880   if (!ToHandlerBlock && S->getHandlerBlock())
4881     return nullptr;
4882   return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
4883                                                     ToExceptionDecl,
4884                                                     ToHandlerBlock);
4885 }
4886
4887 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
4888   SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
4889   Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
4890   if (!ToTryBlock && S->getTryBlock())
4891     return nullptr;
4892   SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
4893   for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
4894     CXXCatchStmt *FromHandler = S->getHandler(HI);
4895     if (Stmt *ToHandler = Importer.Import(FromHandler))
4896       ToHandlers[HI] = ToHandler;
4897     else
4898       return nullptr;
4899   }
4900   return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
4901                             ToHandlers);
4902 }
4903
4904 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4905   DeclStmt *ToRange =
4906     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
4907   if (!ToRange && S->getRangeStmt())
4908     return nullptr;
4909   DeclStmt *ToBeginEnd =
4910     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginEndStmt()));
4911   if (!ToBeginEnd && S->getBeginEndStmt())
4912     return nullptr;
4913   Expr *ToCond = Importer.Import(S->getCond());
4914   if (!ToCond && S->getCond())
4915     return nullptr;
4916   Expr *ToInc = Importer.Import(S->getInc());
4917   if (!ToInc && S->getInc())
4918     return nullptr;
4919   DeclStmt *ToLoopVar =
4920     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
4921   if (!ToLoopVar && S->getLoopVarStmt())
4922     return nullptr;
4923   Stmt *ToBody = Importer.Import(S->getBody());
4924   if (!ToBody && S->getBody())
4925     return nullptr;
4926   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4927   SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
4928   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4929   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4930   return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBeginEnd,
4931                                                        ToCond, ToInc,
4932                                                        ToLoopVar, ToBody,
4933                                                        ToForLoc, ToCoawaitLoc,
4934                                                        ToColonLoc, ToRParenLoc);
4935 }
4936
4937 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
4938   Stmt *ToElem = Importer.Import(S->getElement());
4939   if (!ToElem && S->getElement())
4940     return nullptr;
4941   Expr *ToCollect = Importer.Import(S->getCollection());
4942   if (!ToCollect && S->getCollection())
4943     return nullptr;
4944   Stmt *ToBody = Importer.Import(S->getBody());
4945   if (!ToBody && S->getBody())
4946     return nullptr;
4947   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4948   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4949   return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
4950                                                              ToCollect,
4951                                                              ToBody, ToForLoc,
4952                                                              ToRParenLoc);
4953 }
4954
4955 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4956   SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
4957   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4958   VarDecl *ToExceptionDecl = nullptr;
4959   if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
4960     ToExceptionDecl =
4961       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4962     if (!ToExceptionDecl)
4963       return nullptr;
4964   }
4965   Stmt *ToBody = Importer.Import(S->getCatchBody());
4966   if (!ToBody && S->getCatchBody())
4967     return nullptr;
4968   return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
4969                                                        ToRParenLoc,
4970                                                        ToExceptionDecl,
4971                                                        ToBody);
4972 }
4973
4974 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
4975   SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
4976   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
4977   if (!ToAtFinallyStmt && S->getFinallyBody())
4978     return nullptr;
4979   return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
4980                                                          ToAtFinallyStmt);
4981 }
4982
4983 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
4984   SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
4985   Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
4986   if (!ToAtTryStmt && S->getTryBody())
4987     return nullptr;
4988   SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
4989   for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
4990     ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
4991     if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
4992       ToCatchStmts[CI] = ToCatchStmt;
4993     else
4994       return nullptr;
4995   }
4996   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
4997   if (!ToAtFinallyStmt && S->getFinallyStmt())
4998     return nullptr;
4999   return ObjCAtTryStmt::Create(Importer.getToContext(),
5000                                ToAtTryLoc, ToAtTryStmt,
5001                                ToCatchStmts.begin(), ToCatchStmts.size(),
5002                                ToAtFinallyStmt);
5003 }
5004
5005 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5006   (ObjCAtSynchronizedStmt *S) {
5007   SourceLocation ToAtSynchronizedLoc =
5008     Importer.Import(S->getAtSynchronizedLoc());
5009   Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5010   if (!ToSynchExpr && S->getSynchExpr())
5011     return nullptr;
5012   Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5013   if (!ToSynchBody && S->getSynchBody())
5014     return nullptr;
5015   return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5016     ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5017 }
5018
5019 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5020   SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5021   Expr *ToThrow = Importer.Import(S->getThrowExpr());
5022   if (!ToThrow && S->getThrowExpr())
5023     return nullptr;
5024   return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5025 }
5026
5027 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5028   (ObjCAutoreleasePoolStmt *S) {
5029   SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5030   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5031   if (!ToSubStmt && S->getSubStmt())
5032     return nullptr;
5033   return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5034                                                                ToSubStmt);
5035 }
5036
5037 //----------------------------------------------------------------------------
5038 // Import Expressions
5039 //----------------------------------------------------------------------------
5040 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5041   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5042     << E->getStmtClassName();
5043   return nullptr;
5044 }
5045
5046 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5047   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5048   if (!ToD)
5049     return nullptr;
5050
5051   NamedDecl *FoundD = nullptr;
5052   if (E->getDecl() != E->getFoundDecl()) {
5053     FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5054     if (!FoundD)
5055       return nullptr;
5056   }
5057   
5058   QualType T = Importer.Import(E->getType());
5059   if (T.isNull())
5060     return nullptr;
5061
5062   DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), 
5063                                          Importer.Import(E->getQualifierLoc()),
5064                                    Importer.Import(E->getTemplateKeywordLoc()),
5065                                          ToD,
5066                                         E->refersToEnclosingVariableOrCapture(),
5067                                          Importer.Import(E->getLocation()),
5068                                          T, E->getValueKind(),
5069                                          FoundD,
5070                                          /*FIXME:TemplateArgs=*/nullptr);
5071   if (E->hadMultipleCandidates())
5072     DRE->setHadMultipleCandidates(true);
5073   return DRE;
5074 }
5075
5076 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5077   QualType T = Importer.Import(E->getType());
5078   if (T.isNull())
5079     return nullptr;
5080
5081   return IntegerLiteral::Create(Importer.getToContext(), 
5082                                 E->getValue(), T,
5083                                 Importer.Import(E->getLocation()));
5084 }
5085
5086 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5087   QualType T = Importer.Import(E->getType());
5088   if (T.isNull())
5089     return nullptr;
5090
5091   return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5092                                                         E->getKind(), T,
5093                                           Importer.Import(E->getLocation()));
5094 }
5095
5096 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5097   Expr *SubExpr = Importer.Import(E->getSubExpr());
5098   if (!SubExpr)
5099     return nullptr;
5100
5101   return new (Importer.getToContext()) 
5102                                   ParenExpr(Importer.Import(E->getLParen()),
5103                                             Importer.Import(E->getRParen()),
5104                                             SubExpr);
5105 }
5106
5107 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5108   QualType T = Importer.Import(E->getType());
5109   if (T.isNull())
5110     return nullptr;
5111
5112   Expr *SubExpr = Importer.Import(E->getSubExpr());
5113   if (!SubExpr)
5114     return nullptr;
5115
5116   return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5117                                                      T, E->getValueKind(),
5118                                                      E->getObjectKind(),
5119                                          Importer.Import(E->getOperatorLoc()));                                        
5120 }
5121
5122 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5123                                             UnaryExprOrTypeTraitExpr *E) {
5124   QualType ResultType = Importer.Import(E->getType());
5125   
5126   if (E->isArgumentType()) {
5127     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5128     if (!TInfo)
5129       return nullptr;
5130
5131     return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5132                                            TInfo, ResultType,
5133                                            Importer.Import(E->getOperatorLoc()),
5134                                            Importer.Import(E->getRParenLoc()));
5135   }
5136   
5137   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5138   if (!SubExpr)
5139     return nullptr;
5140
5141   return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5142                                           SubExpr, ResultType,
5143                                           Importer.Import(E->getOperatorLoc()),
5144                                           Importer.Import(E->getRParenLoc()));
5145 }
5146
5147 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5148   QualType T = Importer.Import(E->getType());
5149   if (T.isNull())
5150     return nullptr;
5151
5152   Expr *LHS = Importer.Import(E->getLHS());
5153   if (!LHS)
5154     return nullptr;
5155
5156   Expr *RHS = Importer.Import(E->getRHS());
5157   if (!RHS)
5158     return nullptr;
5159
5160   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5161                                                       T, E->getValueKind(),
5162                                                       E->getObjectKind(),
5163                                            Importer.Import(E->getOperatorLoc()),
5164                                                       E->isFPContractable());
5165 }
5166
5167 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5168   QualType T = Importer.Import(E->getType());
5169   if (T.isNull())
5170     return nullptr;
5171
5172   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5173   if (CompLHSType.isNull())
5174     return nullptr;
5175
5176   QualType CompResultType = Importer.Import(E->getComputationResultType());
5177   if (CompResultType.isNull())
5178     return nullptr;
5179
5180   Expr *LHS = Importer.Import(E->getLHS());
5181   if (!LHS)
5182     return nullptr;
5183
5184   Expr *RHS = Importer.Import(E->getRHS());
5185   if (!RHS)
5186     return nullptr;
5187
5188   return new (Importer.getToContext()) 
5189                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5190                                                T, E->getValueKind(),
5191                                                E->getObjectKind(),
5192                                                CompLHSType, CompResultType,
5193                                            Importer.Import(E->getOperatorLoc()),
5194                                                E->isFPContractable());
5195 }
5196
5197 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
5198   if (E->path_empty()) return false;
5199
5200   // TODO: import cast paths
5201   return true;
5202 }
5203
5204 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5205   QualType T = Importer.Import(E->getType());
5206   if (T.isNull())
5207     return nullptr;
5208
5209   Expr *SubExpr = Importer.Import(E->getSubExpr());
5210   if (!SubExpr)
5211     return nullptr;
5212
5213   CXXCastPath BasePath;
5214   if (ImportCastPath(E, BasePath))
5215     return nullptr;
5216
5217   return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5218                                   SubExpr, &BasePath, E->getValueKind());
5219 }
5220
5221 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
5222   QualType T = Importer.Import(E->getType());
5223   if (T.isNull())
5224     return nullptr;
5225
5226   Expr *SubExpr = Importer.Import(E->getSubExpr());
5227   if (!SubExpr)
5228     return nullptr;
5229
5230   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5231   if (!TInfo && E->getTypeInfoAsWritten())
5232     return nullptr;
5233
5234   CXXCastPath BasePath;
5235   if (ImportCastPath(E, BasePath))
5236     return nullptr;
5237
5238   return CStyleCastExpr::Create(Importer.getToContext(), T,
5239                                 E->getValueKind(), E->getCastKind(),
5240                                 SubExpr, &BasePath, TInfo,
5241                                 Importer.Import(E->getLParenLoc()),
5242                                 Importer.Import(E->getRParenLoc()));
5243 }
5244
5245 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5246   QualType T = Importer.Import(E->getType());
5247   if (T.isNull())
5248     return nullptr;
5249
5250   CXXConstructorDecl *ToCCD =
5251     dyn_cast<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5252   if (!ToCCD && E->getConstructor())
5253     return nullptr;
5254
5255   size_t NumArgs = E->getNumArgs();
5256   SmallVector<Expr *, 1> ToArgs(NumArgs);
5257   ASTImporter &_Importer = Importer;
5258   std::transform(E->arg_begin(), E->arg_end(), ToArgs.begin(),
5259     [&_Importer](Expr *AE) -> Expr * {
5260       return _Importer.Import(AE);
5261     });
5262   for (Expr *ToA : ToArgs) {
5263     if (!ToA)
5264       return nullptr;
5265   }
5266
5267   return CXXConstructExpr::Create(Importer.getToContext(), T,
5268                                   Importer.Import(E->getLocation()),
5269                                   ToCCD, E->isElidable(),
5270                                   ToArgs, E->hadMultipleCandidates(),
5271                                   E->isListInitialization(),
5272                                   E->isStdInitListInitialization(),
5273                                   E->requiresZeroInitialization(),
5274                                   E->getConstructionKind(),
5275                                   Importer.Import(E->getParenOrBraceRange()));
5276 }
5277
5278 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5279   QualType T = Importer.Import(E->getType());
5280   if (T.isNull())
5281     return nullptr;
5282
5283   Expr *ToBase = Importer.Import(E->getBase());
5284   if (!ToBase && E->getBase())
5285     return nullptr;
5286
5287   ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5288   if (!ToMember && E->getMemberDecl())
5289     return nullptr;
5290
5291   DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5292     dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5293     E->getFoundDecl().getAccess());
5294
5295   DeclarationNameInfo ToMemberNameInfo(
5296     Importer.Import(E->getMemberNameInfo().getName()),
5297     Importer.Import(E->getMemberNameInfo().getLoc()));
5298
5299   if (E->hasExplicitTemplateArgs()) {
5300     return nullptr; // FIXME: handle template arguments
5301   }
5302
5303   return MemberExpr::Create(Importer.getToContext(), ToBase,
5304                             E->isArrow(),
5305                             Importer.Import(E->getOperatorLoc()),
5306                             Importer.Import(E->getQualifierLoc()),
5307                             Importer.Import(E->getTemplateKeywordLoc()),
5308                             ToMember, ToFoundDecl, ToMemberNameInfo,
5309                             nullptr, T, E->getValueKind(),
5310                             E->getObjectKind());
5311 }
5312
5313 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5314   QualType T = Importer.Import(E->getType());
5315   if (T.isNull())
5316     return nullptr;
5317
5318   Expr *ToCallee = Importer.Import(E->getCallee());
5319   if (!ToCallee && E->getCallee())
5320     return nullptr;
5321
5322   unsigned NumArgs = E->getNumArgs();
5323
5324   llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5325
5326   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5327     Expr *FromArg = E->getArg(ai);
5328     Expr *ToArg = Importer.Import(FromArg);
5329     if (!ToArg)
5330       return nullptr;
5331     ToArgs[ai] = ToArg;
5332   }
5333
5334   Expr **ToArgs_Copied = new (Importer.getToContext()) 
5335     Expr*[NumArgs];
5336
5337   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5338     ToArgs_Copied[ai] = ToArgs[ai];
5339
5340   return new (Importer.getToContext())
5341     CallExpr(Importer.getToContext(), ToCallee, 
5342              llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5343              Importer.Import(E->getRParenLoc()));
5344 }
5345
5346 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
5347                          ASTContext &FromContext, FileManager &FromFileManager,
5348                          bool MinimalImport)
5349   : ToContext(ToContext), FromContext(FromContext),
5350     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
5351     Minimal(MinimalImport), LastDiagFromFrom(false)
5352 {
5353   ImportedDecls[FromContext.getTranslationUnitDecl()]
5354     = ToContext.getTranslationUnitDecl();
5355 }
5356
5357 ASTImporter::~ASTImporter() { }
5358
5359 QualType ASTImporter::Import(QualType FromT) {
5360   if (FromT.isNull())
5361     return QualType();
5362
5363   const Type *fromTy = FromT.getTypePtr();
5364   
5365   // Check whether we've already imported this type.  
5366   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5367     = ImportedTypes.find(fromTy);
5368   if (Pos != ImportedTypes.end())
5369     return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
5370   
5371   // Import the type
5372   ASTNodeImporter Importer(*this);
5373   QualType ToT = Importer.Visit(fromTy);
5374   if (ToT.isNull())
5375     return ToT;
5376   
5377   // Record the imported type.
5378   ImportedTypes[fromTy] = ToT.getTypePtr();
5379   
5380   return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
5381 }
5382
5383 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
5384   if (!FromTSI)
5385     return FromTSI;
5386
5387   // FIXME: For now we just create a "trivial" type source info based
5388   // on the type and a single location. Implement a real version of this.
5389   QualType T = Import(FromTSI->getType());
5390   if (T.isNull())
5391     return nullptr;
5392
5393   return ToContext.getTrivialTypeSourceInfo(T, 
5394            Import(FromTSI->getTypeLoc().getLocStart()));
5395 }
5396
5397 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
5398   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5399   if (Pos != ImportedDecls.end()) {
5400     Decl *ToD = Pos->second;
5401     ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
5402     return ToD;
5403   } else {
5404     return nullptr;
5405   }
5406 }
5407
5408 Decl *ASTImporter::Import(Decl *FromD) {
5409   if (!FromD)
5410     return nullptr;
5411
5412   ASTNodeImporter Importer(*this);
5413
5414   // Check whether we've already imported this declaration.  
5415   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5416   if (Pos != ImportedDecls.end()) {
5417     Decl *ToD = Pos->second;
5418     Importer.ImportDefinitionIfNeeded(FromD, ToD);
5419     return ToD;
5420   }
5421   
5422   // Import the type
5423   Decl *ToD = Importer.Visit(FromD);
5424   if (!ToD)
5425     return nullptr;
5426
5427   // Record the imported declaration.
5428   ImportedDecls[FromD] = ToD;
5429   
5430   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
5431     // Keep track of anonymous tags that have an associated typedef.
5432     if (FromTag->getTypedefNameForAnonDecl())
5433       AnonTagsWithPendingTypedefs.push_back(FromTag);
5434   } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
5435     // When we've finished transforming a typedef, see whether it was the
5436     // typedef for an anonymous tag.
5437     for (SmallVectorImpl<TagDecl *>::iterator
5438                FromTag = AnonTagsWithPendingTypedefs.begin(), 
5439             FromTagEnd = AnonTagsWithPendingTypedefs.end();
5440          FromTag != FromTagEnd; ++FromTag) {
5441       if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
5442         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
5443           // We found the typedef for an anonymous tag; link them.
5444           ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
5445           AnonTagsWithPendingTypedefs.erase(FromTag);
5446           break;
5447         }
5448       }
5449     }
5450   }
5451   
5452   return ToD;
5453 }
5454
5455 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
5456   if (!FromDC)
5457     return FromDC;
5458
5459   DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
5460   if (!ToDC)
5461     return nullptr;
5462
5463   // When we're using a record/enum/Objective-C class/protocol as a context, we 
5464   // need it to have a definition.
5465   if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
5466     RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
5467     if (ToRecord->isCompleteDefinition()) {
5468       // Do nothing.
5469     } else if (FromRecord->isCompleteDefinition()) {
5470       ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
5471                                               ASTNodeImporter::IDK_Basic);
5472     } else {
5473       CompleteDecl(ToRecord);
5474     }
5475   } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
5476     EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
5477     if (ToEnum->isCompleteDefinition()) {
5478       // Do nothing.
5479     } else if (FromEnum->isCompleteDefinition()) {
5480       ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
5481                                               ASTNodeImporter::IDK_Basic);
5482     } else {
5483       CompleteDecl(ToEnum);
5484     }    
5485   } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
5486     ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
5487     if (ToClass->getDefinition()) {
5488       // Do nothing.
5489     } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
5490       ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
5491                                               ASTNodeImporter::IDK_Basic);
5492     } else {
5493       CompleteDecl(ToClass);
5494     }
5495   } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
5496     ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
5497     if (ToProto->getDefinition()) {
5498       // Do nothing.
5499     } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
5500       ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
5501                                               ASTNodeImporter::IDK_Basic);
5502     } else {
5503       CompleteDecl(ToProto);
5504     }    
5505   }
5506   
5507   return ToDC;
5508 }
5509
5510 Expr *ASTImporter::Import(Expr *FromE) {
5511   if (!FromE)
5512     return nullptr;
5513
5514   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
5515 }
5516
5517 Stmt *ASTImporter::Import(Stmt *FromS) {
5518   if (!FromS)
5519     return nullptr;
5520
5521   // Check whether we've already imported this declaration.  
5522   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
5523   if (Pos != ImportedStmts.end())
5524     return Pos->second;
5525   
5526   // Import the type
5527   ASTNodeImporter Importer(*this);
5528   Stmt *ToS = Importer.Visit(FromS);
5529   if (!ToS)
5530     return nullptr;
5531
5532   // Record the imported declaration.
5533   ImportedStmts[FromS] = ToS;
5534   return ToS;
5535 }
5536
5537 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
5538   if (!FromNNS)
5539     return nullptr;
5540
5541   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
5542
5543   switch (FromNNS->getKind()) {
5544   case NestedNameSpecifier::Identifier:
5545     if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
5546       return NestedNameSpecifier::Create(ToContext, prefix, II);
5547     }
5548     return nullptr;
5549
5550   case NestedNameSpecifier::Namespace:
5551     if (NamespaceDecl *NS = 
5552           cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
5553       return NestedNameSpecifier::Create(ToContext, prefix, NS);
5554     }
5555     return nullptr;
5556
5557   case NestedNameSpecifier::NamespaceAlias:
5558     if (NamespaceAliasDecl *NSAD = 
5559           cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
5560       return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
5561     }
5562     return nullptr;
5563
5564   case NestedNameSpecifier::Global:
5565     return NestedNameSpecifier::GlobalSpecifier(ToContext);
5566
5567   case NestedNameSpecifier::Super:
5568     if (CXXRecordDecl *RD =
5569             cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
5570       return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
5571     }
5572     return nullptr;
5573
5574   case NestedNameSpecifier::TypeSpec:
5575   case NestedNameSpecifier::TypeSpecWithTemplate: {
5576       QualType T = Import(QualType(FromNNS->getAsType(), 0u));
5577       if (!T.isNull()) {
5578         bool bTemplate = FromNNS->getKind() == 
5579                          NestedNameSpecifier::TypeSpecWithTemplate;
5580         return NestedNameSpecifier::Create(ToContext, prefix, 
5581                                            bTemplate, T.getTypePtr());
5582       }
5583     }
5584       return nullptr;
5585   }
5586
5587   llvm_unreachable("Invalid nested name specifier kind");
5588 }
5589
5590 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
5591   // FIXME: Implement!
5592   return NestedNameSpecifierLoc();
5593 }
5594
5595 TemplateName ASTImporter::Import(TemplateName From) {
5596   switch (From.getKind()) {
5597   case TemplateName::Template:
5598     if (TemplateDecl *ToTemplate
5599                 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5600       return TemplateName(ToTemplate);
5601       
5602     return TemplateName();
5603       
5604   case TemplateName::OverloadedTemplate: {
5605     OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
5606     UnresolvedSet<2> ToTemplates;
5607     for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
5608                                              E = FromStorage->end();
5609          I != E; ++I) {
5610       if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I))) 
5611         ToTemplates.addDecl(To);
5612       else
5613         return TemplateName();
5614     }
5615     return ToContext.getOverloadedTemplateName(ToTemplates.begin(), 
5616                                                ToTemplates.end());
5617   }
5618       
5619   case TemplateName::QualifiedTemplate: {
5620     QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
5621     NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
5622     if (!Qualifier)
5623       return TemplateName();
5624     
5625     if (TemplateDecl *ToTemplate
5626         = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5627       return ToContext.getQualifiedTemplateName(Qualifier, 
5628                                                 QTN->hasTemplateKeyword(), 
5629                                                 ToTemplate);
5630     
5631     return TemplateName();
5632   }
5633   
5634   case TemplateName::DependentTemplate: {
5635     DependentTemplateName *DTN = From.getAsDependentTemplateName();
5636     NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
5637     if (!Qualifier)
5638       return TemplateName();
5639     
5640     if (DTN->isIdentifier()) {
5641       return ToContext.getDependentTemplateName(Qualifier, 
5642                                                 Import(DTN->getIdentifier()));
5643     }
5644     
5645     return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
5646   }
5647
5648   case TemplateName::SubstTemplateTemplateParm: {
5649     SubstTemplateTemplateParmStorage *subst
5650       = From.getAsSubstTemplateTemplateParm();
5651     TemplateTemplateParmDecl *param
5652       = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
5653     if (!param)
5654       return TemplateName();
5655
5656     TemplateName replacement = Import(subst->getReplacement());
5657     if (replacement.isNull()) return TemplateName();
5658     
5659     return ToContext.getSubstTemplateTemplateParm(param, replacement);
5660   }
5661       
5662   case TemplateName::SubstTemplateTemplateParmPack: {
5663     SubstTemplateTemplateParmPackStorage *SubstPack
5664       = From.getAsSubstTemplateTemplateParmPack();
5665     TemplateTemplateParmDecl *Param
5666       = cast_or_null<TemplateTemplateParmDecl>(
5667                                         Import(SubstPack->getParameterPack()));
5668     if (!Param)
5669       return TemplateName();
5670     
5671     ASTNodeImporter Importer(*this);
5672     TemplateArgument ArgPack 
5673       = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
5674     if (ArgPack.isNull())
5675       return TemplateName();
5676     
5677     return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
5678   }
5679   }
5680   
5681   llvm_unreachable("Invalid template name kind");
5682 }
5683
5684 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
5685   if (FromLoc.isInvalid())
5686     return SourceLocation();
5687
5688   SourceManager &FromSM = FromContext.getSourceManager();
5689   
5690   // For now, map everything down to its spelling location, so that we
5691   // don't have to import macro expansions.
5692   // FIXME: Import macro expansions!
5693   FromLoc = FromSM.getSpellingLoc(FromLoc);
5694   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
5695   SourceManager &ToSM = ToContext.getSourceManager();
5696   FileID ToFileID = Import(Decomposed.first);
5697   if (ToFileID.isInvalid())
5698     return SourceLocation();
5699   SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
5700                            .getLocWithOffset(Decomposed.second);
5701   return ret;
5702 }
5703
5704 SourceRange ASTImporter::Import(SourceRange FromRange) {
5705   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
5706 }
5707
5708 FileID ASTImporter::Import(FileID FromID) {
5709   llvm::DenseMap<FileID, FileID>::iterator Pos
5710     = ImportedFileIDs.find(FromID);
5711   if (Pos != ImportedFileIDs.end())
5712     return Pos->second;
5713   
5714   SourceManager &FromSM = FromContext.getSourceManager();
5715   SourceManager &ToSM = ToContext.getSourceManager();
5716   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
5717   assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
5718   
5719   // Include location of this file.
5720   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
5721   
5722   // Map the FileID for to the "to" source manager.
5723   FileID ToID;
5724   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
5725   if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
5726     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
5727     // disk again
5728     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
5729     // than mmap the files several times.
5730     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
5731     if (!Entry)
5732       return FileID();
5733     ToID = ToSM.createFileID(Entry, ToIncludeLoc, 
5734                              FromSLoc.getFile().getFileCharacteristic());
5735   } else {
5736     // FIXME: We want to re-use the existing MemoryBuffer!
5737     const llvm::MemoryBuffer *
5738         FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
5739     std::unique_ptr<llvm::MemoryBuffer> ToBuf
5740       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
5741                                              FromBuf->getBufferIdentifier());
5742     ToID = ToSM.createFileID(std::move(ToBuf),
5743                              FromSLoc.getFile().getFileCharacteristic());
5744   }
5745   
5746   
5747   ImportedFileIDs[FromID] = ToID;
5748   return ToID;
5749 }
5750
5751 void ASTImporter::ImportDefinition(Decl *From) {
5752   Decl *To = Import(From);
5753   if (!To)
5754     return;
5755   
5756   if (DeclContext *FromDC = cast<DeclContext>(From)) {
5757     ASTNodeImporter Importer(*this);
5758       
5759     if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
5760       if (!ToRecord->getDefinition()) {
5761         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, 
5762                                   ASTNodeImporter::IDK_Everything);
5763         return;
5764       }      
5765     }
5766
5767     if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
5768       if (!ToEnum->getDefinition()) {
5769         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, 
5770                                   ASTNodeImporter::IDK_Everything);
5771         return;
5772       }      
5773     }
5774     
5775     if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
5776       if (!ToIFace->getDefinition()) {
5777         Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
5778                                   ASTNodeImporter::IDK_Everything);
5779         return;
5780       }
5781     }
5782
5783     if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
5784       if (!ToProto->getDefinition()) {
5785         Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
5786                                   ASTNodeImporter::IDK_Everything);
5787         return;
5788       }
5789     }
5790     
5791     Importer.ImportDeclContext(FromDC, true);
5792   }
5793 }
5794
5795 DeclarationName ASTImporter::Import(DeclarationName FromName) {
5796   if (!FromName)
5797     return DeclarationName();
5798
5799   switch (FromName.getNameKind()) {
5800   case DeclarationName::Identifier:
5801     return Import(FromName.getAsIdentifierInfo());
5802
5803   case DeclarationName::ObjCZeroArgSelector:
5804   case DeclarationName::ObjCOneArgSelector:
5805   case DeclarationName::ObjCMultiArgSelector:
5806     return Import(FromName.getObjCSelector());
5807
5808   case DeclarationName::CXXConstructorName: {
5809     QualType T = Import(FromName.getCXXNameType());
5810     if (T.isNull())
5811       return DeclarationName();
5812
5813     return ToContext.DeclarationNames.getCXXConstructorName(
5814                                                ToContext.getCanonicalType(T));
5815   }
5816
5817   case DeclarationName::CXXDestructorName: {
5818     QualType T = Import(FromName.getCXXNameType());
5819     if (T.isNull())
5820       return DeclarationName();
5821
5822     return ToContext.DeclarationNames.getCXXDestructorName(
5823                                                ToContext.getCanonicalType(T));
5824   }
5825
5826   case DeclarationName::CXXConversionFunctionName: {
5827     QualType T = Import(FromName.getCXXNameType());
5828     if (T.isNull())
5829       return DeclarationName();
5830
5831     return ToContext.DeclarationNames.getCXXConversionFunctionName(
5832                                                ToContext.getCanonicalType(T));
5833   }
5834
5835   case DeclarationName::CXXOperatorName:
5836     return ToContext.DeclarationNames.getCXXOperatorName(
5837                                           FromName.getCXXOverloadedOperator());
5838
5839   case DeclarationName::CXXLiteralOperatorName:
5840     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5841                                    Import(FromName.getCXXLiteralIdentifier()));
5842
5843   case DeclarationName::CXXUsingDirective:
5844     // FIXME: STATICS!
5845     return DeclarationName::getUsingDirectiveName();
5846   }
5847
5848   llvm_unreachable("Invalid DeclarationName Kind!");
5849 }
5850
5851 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5852   if (!FromId)
5853     return nullptr;
5854
5855   return &ToContext.Idents.get(FromId->getName());
5856 }
5857
5858 Selector ASTImporter::Import(Selector FromSel) {
5859   if (FromSel.isNull())
5860     return Selector();
5861
5862   SmallVector<IdentifierInfo *, 4> Idents;
5863   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5864   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5865     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5866   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5867 }
5868
5869 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5870                                                 DeclContext *DC,
5871                                                 unsigned IDNS,
5872                                                 NamedDecl **Decls,
5873                                                 unsigned NumDecls) {
5874   return Name;
5875 }
5876
5877 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5878   if (LastDiagFromFrom)
5879     ToContext.getDiagnostics().notePriorDiagnosticFrom(
5880       FromContext.getDiagnostics());
5881   LastDiagFromFrom = false;
5882   return ToContext.getDiagnostics().Report(Loc, DiagID);
5883 }
5884
5885 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5886   if (!LastDiagFromFrom)
5887     FromContext.getDiagnostics().notePriorDiagnosticFrom(
5888       ToContext.getDiagnostics());
5889   LastDiagFromFrom = true;
5890   return FromContext.getDiagnostics().Report(Loc, DiagID);
5891 }
5892
5893 void ASTImporter::CompleteDecl (Decl *D) {
5894   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5895     if (!ID->getDefinition())
5896       ID->startDefinition();
5897   }
5898   else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5899     if (!PD->getDefinition())
5900       PD->startDefinition();
5901   }
5902   else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5903     if (!TD->getDefinition() && !TD->isBeingDefined()) {
5904       TD->startDefinition();
5905       TD->setCompleteDefinition(true);
5906     }
5907   }
5908   else {
5909     assert (0 && "CompleteDecl called on a Decl that can't be completed");
5910   }
5911 }
5912
5913 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5914   ImportedDecls[From] = To;
5915   return To;
5916 }
5917
5918 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5919                                            bool Complain) {
5920   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5921    = ImportedTypes.find(From.getTypePtr());
5922   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5923     return true;
5924       
5925   StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5926                                    false, Complain);
5927   return Ctx.IsStructurallyEquivalent(From, To);
5928 }