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