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