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