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