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