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