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