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