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:
ASTNodeImporter(ASTImporter & Importer)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     // FIXME: DependentDecltypeType
68     QualType VisitRecordType(const RecordType *T);
69     QualType VisitEnumType(const EnumType *T);
70     QualType VisitAttributedType(const AttributedType *T);
71     // FIXME: TemplateTypeParmType
72     // FIXME: SubstTemplateTypeParmType
73     QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
74     QualType VisitElaboratedType(const ElaboratedType *T);
75     // FIXME: DependentNameType
76     // FIXME: DependentTemplateSpecializationType
77     QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
78     QualType VisitObjCObjectType(const ObjCObjectType *T);
79     QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
80 
81     // Importing declarations
82     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
83                          DeclContext *&LexicalDC, DeclarationName &Name,
84                          SourceLocation &Loc);
85     void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
86     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87                                   DeclarationNameInfo& To);
88     void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89 
90     /// \brief What we should import from the definition.
91     enum ImportDefinitionKind {
92       /// \brief Import the default subset of the definition, which might be
93       /// nothing (if minimal import is set) or might be everything (if minimal
94       /// import is not set).
95       IDK_Default,
96       /// \brief Import everything.
97       IDK_Everything,
98       /// \brief Import only the bare bones needed to establish a valid
99       /// DeclContext.
100       IDK_Basic
101     };
102 
shouldForceImportDeclContext(ImportDefinitionKind IDK)103     bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
104       return IDK == IDK_Everything ||
105              (IDK == IDK_Default && !Importer.isMinimalImport());
106     }
107 
108     bool ImportDefinition(RecordDecl *From, RecordDecl *To,
109                           ImportDefinitionKind Kind = IDK_Default);
110     bool ImportDefinition(VarDecl *From, VarDecl *To,
111                           ImportDefinitionKind Kind = IDK_Default);
112     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
113                           ImportDefinitionKind Kind = IDK_Default);
114     bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
115                           ImportDefinitionKind Kind = IDK_Default);
116     bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
117                           ImportDefinitionKind Kind = IDK_Default);
118     TemplateParameterList *ImportTemplateParameterList(
119                                                  TemplateParameterList *Params);
120     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
121     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
122                                  unsigned NumFromArgs,
123                                SmallVectorImpl<TemplateArgument> &ToArgs);
124     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
125                            bool Complain = true);
126     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
127                            bool Complain = true);
128     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
129     bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
130     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
131     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
132     Decl *VisitDecl(Decl *D);
133     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
134     Decl *VisitNamespaceDecl(NamespaceDecl *D);
135     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
136     Decl *VisitTypedefDecl(TypedefDecl *D);
137     Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
138     Decl *VisitEnumDecl(EnumDecl *D);
139     Decl *VisitRecordDecl(RecordDecl *D);
140     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
141     Decl *VisitFunctionDecl(FunctionDecl *D);
142     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
143     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
144     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
145     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
146     Decl *VisitFieldDecl(FieldDecl *D);
147     Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
148     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
149     Decl *VisitVarDecl(VarDecl *D);
150     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
151     Decl *VisitParmVarDecl(ParmVarDecl *D);
152     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
153     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
154     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
155     Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
156     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
157     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
158     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
159     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
160     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
161     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
162     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
163     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
164     Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
165     Decl *VisitClassTemplateSpecializationDecl(
166                                             ClassTemplateSpecializationDecl *D);
167     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
168     Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
169 
170     // Importing statements
171     Stmt *VisitStmt(Stmt *S);
172 
173     // Importing expressions
174     Expr *VisitExpr(Expr *E);
175     Expr *VisitDeclRefExpr(DeclRefExpr *E);
176     Expr *VisitIntegerLiteral(IntegerLiteral *E);
177     Expr *VisitCharacterLiteral(CharacterLiteral *E);
178     Expr *VisitParenExpr(ParenExpr *E);
179     Expr *VisitUnaryOperator(UnaryOperator *E);
180     Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
181     Expr *VisitBinaryOperator(BinaryOperator *E);
182     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
183     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
184     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
185   };
186 }
187 using namespace clang;
188 
189 //----------------------------------------------------------------------------
190 // Structural Equivalence
191 //----------------------------------------------------------------------------
192 
193 namespace {
194   struct StructuralEquivalenceContext {
195     /// \brief AST contexts for which we are checking structural equivalence.
196     ASTContext &C1, &C2;
197 
198     /// \brief The set of "tentative" equivalences between two canonical
199     /// declarations, mapping from a declaration in the first context to the
200     /// declaration in the second context that we believe to be equivalent.
201     llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
202 
203     /// \brief Queue of declarations in the first context whose equivalence
204     /// with a declaration in the second context still needs to be verified.
205     std::deque<Decl *> DeclsToCheck;
206 
207     /// \brief Declaration (from, to) pairs that are known not to be equivalent
208     /// (which we have already complained about).
209     llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
210 
211     /// \brief Whether we're being strict about the spelling of types when
212     /// unifying two types.
213     bool StrictTypeSpelling;
214 
215     /// \brief Whether to complain about failures.
216     bool Complain;
217 
218     /// \brief \c true if the last diagnostic came from C2.
219     bool LastDiagFromC2;
220 
StructuralEquivalenceContext__anone728b20d0111::StructuralEquivalenceContext221     StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
222                llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
223                                  bool StrictTypeSpelling = false,
224                                  bool Complain = true)
225       : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
226         StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
227         LastDiagFromC2(false) {}
228 
229     /// \brief Determine whether the two declarations are structurally
230     /// equivalent.
231     bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
232 
233     /// \brief Determine whether the two types are structurally equivalent.
234     bool IsStructurallyEquivalent(QualType T1, QualType T2);
235 
236   private:
237     /// \brief Finish checking all of the structural equivalences.
238     ///
239     /// \returns true if an error occurred, false otherwise.
240     bool Finish();
241 
242   public:
Diag1__anone728b20d0111::StructuralEquivalenceContext243     DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
244       assert(Complain && "Not allowed to complain");
245       if (LastDiagFromC2)
246         C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
247       LastDiagFromC2 = false;
248       return C1.getDiagnostics().Report(Loc, DiagID);
249     }
250 
Diag2__anone728b20d0111::StructuralEquivalenceContext251     DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
252       assert(Complain && "Not allowed to complain");
253       if (!LastDiagFromC2)
254         C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
255       LastDiagFromC2 = true;
256       return C2.getDiagnostics().Report(Loc, DiagID);
257     }
258   };
259 }
260 
261 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
262                                      QualType T1, QualType T2);
263 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
264                                      Decl *D1, Decl *D2);
265 
266 /// \brief Determine structural equivalence of two expressions.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Expr * E1,Expr * E2)267 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
268                                      Expr *E1, Expr *E2) {
269   if (!E1 || !E2)
270     return E1 == E2;
271 
272   // FIXME: Actually perform a structural comparison!
273   return true;
274 }
275 
276 /// \brief Determine whether two identifiers are equivalent.
IsStructurallyEquivalent(const IdentifierInfo * Name1,const IdentifierInfo * Name2)277 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
278                                      const IdentifierInfo *Name2) {
279   if (!Name1 || !Name2)
280     return Name1 == Name2;
281 
282   return Name1->getName() == Name2->getName();
283 }
284 
285 /// \brief Determine whether two nested-name-specifiers are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NestedNameSpecifier * NNS1,NestedNameSpecifier * NNS2)286 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
287                                      NestedNameSpecifier *NNS1,
288                                      NestedNameSpecifier *NNS2) {
289   // FIXME: Implement!
290   return true;
291 }
292 
293 /// \brief Determine whether two template arguments are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,const TemplateArgument & Arg1,const TemplateArgument & Arg2)294 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
295                                      const TemplateArgument &Arg1,
296                                      const TemplateArgument &Arg2) {
297   if (Arg1.getKind() != Arg2.getKind())
298     return false;
299 
300   switch (Arg1.getKind()) {
301   case TemplateArgument::Null:
302     return true;
303 
304   case TemplateArgument::Type:
305     return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
306 
307   case TemplateArgument::Integral:
308     if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
309                                           Arg2.getIntegralType()))
310       return false;
311 
312     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
313 
314   case TemplateArgument::Declaration:
315     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
316 
317   case TemplateArgument::NullPtr:
318     return true; // FIXME: Is this correct?
319 
320   case TemplateArgument::Template:
321     return IsStructurallyEquivalent(Context,
322                                     Arg1.getAsTemplate(),
323                                     Arg2.getAsTemplate());
324 
325   case TemplateArgument::TemplateExpansion:
326     return IsStructurallyEquivalent(Context,
327                                     Arg1.getAsTemplateOrTemplatePattern(),
328                                     Arg2.getAsTemplateOrTemplatePattern());
329 
330   case TemplateArgument::Expression:
331     return IsStructurallyEquivalent(Context,
332                                     Arg1.getAsExpr(), Arg2.getAsExpr());
333 
334   case TemplateArgument::Pack:
335     if (Arg1.pack_size() != Arg2.pack_size())
336       return false;
337 
338     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
339       if (!IsStructurallyEquivalent(Context,
340                                     Arg1.pack_begin()[I],
341                                     Arg2.pack_begin()[I]))
342         return false;
343 
344     return true;
345   }
346 
347   llvm_unreachable("Invalid template argument kind");
348 }
349 
350 /// \brief Determine structural equivalence for the common part of array
351 /// types.
IsArrayStructurallyEquivalent(StructuralEquivalenceContext & Context,const ArrayType * Array1,const ArrayType * Array2)352 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
353                                           const ArrayType *Array1,
354                                           const ArrayType *Array2) {
355   if (!IsStructurallyEquivalent(Context,
356                                 Array1->getElementType(),
357                                 Array2->getElementType()))
358     return false;
359   if (Array1->getSizeModifier() != Array2->getSizeModifier())
360     return false;
361   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
362     return false;
363 
364   return true;
365 }
366 
367 /// \brief Determine structural equivalence of two types.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,QualType T1,QualType T2)368 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
369                                      QualType T1, QualType T2) {
370   if (T1.isNull() || T2.isNull())
371     return T1.isNull() && T2.isNull();
372 
373   if (!Context.StrictTypeSpelling) {
374     // We aren't being strict about token-to-token equivalence of types,
375     // so map down to the canonical type.
376     T1 = Context.C1.getCanonicalType(T1);
377     T2 = Context.C2.getCanonicalType(T2);
378   }
379 
380   if (T1.getQualifiers() != T2.getQualifiers())
381     return false;
382 
383   Type::TypeClass TC = T1->getTypeClass();
384 
385   if (T1->getTypeClass() != T2->getTypeClass()) {
386     // Compare function types with prototypes vs. without prototypes as if
387     // both did not have prototypes.
388     if (T1->getTypeClass() == Type::FunctionProto &&
389         T2->getTypeClass() == Type::FunctionNoProto)
390       TC = Type::FunctionNoProto;
391     else if (T1->getTypeClass() == Type::FunctionNoProto &&
392              T2->getTypeClass() == Type::FunctionProto)
393       TC = Type::FunctionNoProto;
394     else
395       return false;
396   }
397 
398   switch (TC) {
399   case Type::Builtin:
400     // FIXME: Deal with Char_S/Char_U.
401     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
402       return false;
403     break;
404 
405   case Type::Complex:
406     if (!IsStructurallyEquivalent(Context,
407                                   cast<ComplexType>(T1)->getElementType(),
408                                   cast<ComplexType>(T2)->getElementType()))
409       return false;
410     break;
411 
412   case Type::Adjusted:
413   case Type::Decayed:
414     if (!IsStructurallyEquivalent(Context,
415                                   cast<AdjustedType>(T1)->getOriginalType(),
416                                   cast<AdjustedType>(T2)->getOriginalType()))
417       return false;
418     break;
419 
420   case Type::Pointer:
421     if (!IsStructurallyEquivalent(Context,
422                                   cast<PointerType>(T1)->getPointeeType(),
423                                   cast<PointerType>(T2)->getPointeeType()))
424       return false;
425     break;
426 
427   case Type::BlockPointer:
428     if (!IsStructurallyEquivalent(Context,
429                                   cast<BlockPointerType>(T1)->getPointeeType(),
430                                   cast<BlockPointerType>(T2)->getPointeeType()))
431       return false;
432     break;
433 
434   case Type::LValueReference:
435   case Type::RValueReference: {
436     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
437     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
438     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
439       return false;
440     if (Ref1->isInnerRef() != Ref2->isInnerRef())
441       return false;
442     if (!IsStructurallyEquivalent(Context,
443                                   Ref1->getPointeeTypeAsWritten(),
444                                   Ref2->getPointeeTypeAsWritten()))
445       return false;
446     break;
447   }
448 
449   case Type::MemberPointer: {
450     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
451     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
452     if (!IsStructurallyEquivalent(Context,
453                                   MemPtr1->getPointeeType(),
454                                   MemPtr2->getPointeeType()))
455       return false;
456     if (!IsStructurallyEquivalent(Context,
457                                   QualType(MemPtr1->getClass(), 0),
458                                   QualType(MemPtr2->getClass(), 0)))
459       return false;
460     break;
461   }
462 
463   case Type::ConstantArray: {
464     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
465     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
466     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
467       return false;
468 
469     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
470       return false;
471     break;
472   }
473 
474   case Type::IncompleteArray:
475     if (!IsArrayStructurallyEquivalent(Context,
476                                        cast<ArrayType>(T1),
477                                        cast<ArrayType>(T2)))
478       return false;
479     break;
480 
481   case Type::VariableArray: {
482     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
483     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
484     if (!IsStructurallyEquivalent(Context,
485                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
486       return false;
487 
488     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
489       return false;
490 
491     break;
492   }
493 
494   case Type::DependentSizedArray: {
495     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
496     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
497     if (!IsStructurallyEquivalent(Context,
498                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
499       return false;
500 
501     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
502       return false;
503 
504     break;
505   }
506 
507   case Type::DependentSizedExtVector: {
508     const DependentSizedExtVectorType *Vec1
509       = cast<DependentSizedExtVectorType>(T1);
510     const DependentSizedExtVectorType *Vec2
511       = cast<DependentSizedExtVectorType>(T2);
512     if (!IsStructurallyEquivalent(Context,
513                                   Vec1->getSizeExpr(), Vec2->getSizeExpr()))
514       return false;
515     if (!IsStructurallyEquivalent(Context,
516                                   Vec1->getElementType(),
517                                   Vec2->getElementType()))
518       return false;
519     break;
520   }
521 
522   case Type::Vector:
523   case Type::ExtVector: {
524     const VectorType *Vec1 = cast<VectorType>(T1);
525     const VectorType *Vec2 = cast<VectorType>(T2);
526     if (!IsStructurallyEquivalent(Context,
527                                   Vec1->getElementType(),
528                                   Vec2->getElementType()))
529       return false;
530     if (Vec1->getNumElements() != Vec2->getNumElements())
531       return false;
532     if (Vec1->getVectorKind() != Vec2->getVectorKind())
533       return false;
534     break;
535   }
536 
537   case Type::FunctionProto: {
538     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
539     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
540     if (Proto1->getNumParams() != Proto2->getNumParams())
541       return false;
542     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
543       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
544                                     Proto2->getParamType(I)))
545         return false;
546     }
547     if (Proto1->isVariadic() != Proto2->isVariadic())
548       return false;
549     if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
550       return false;
551     if (Proto1->getExceptionSpecType() == EST_Dynamic) {
552       if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
553         return false;
554       for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
555         if (!IsStructurallyEquivalent(Context,
556                                       Proto1->getExceptionType(I),
557                                       Proto2->getExceptionType(I)))
558           return false;
559       }
560     } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
561       if (!IsStructurallyEquivalent(Context,
562                                     Proto1->getNoexceptExpr(),
563                                     Proto2->getNoexceptExpr()))
564         return false;
565     }
566     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
567       return false;
568 
569     // Fall through to check the bits common with FunctionNoProtoType.
570   }
571 
572   case Type::FunctionNoProto: {
573     const FunctionType *Function1 = cast<FunctionType>(T1);
574     const FunctionType *Function2 = cast<FunctionType>(T2);
575     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
576                                   Function2->getReturnType()))
577       return false;
578       if (Function1->getExtInfo() != Function2->getExtInfo())
579         return false;
580     break;
581   }
582 
583   case Type::UnresolvedUsing:
584     if (!IsStructurallyEquivalent(Context,
585                                   cast<UnresolvedUsingType>(T1)->getDecl(),
586                                   cast<UnresolvedUsingType>(T2)->getDecl()))
587       return false;
588 
589     break;
590 
591   case Type::Attributed:
592     if (!IsStructurallyEquivalent(Context,
593                                   cast<AttributedType>(T1)->getModifiedType(),
594                                   cast<AttributedType>(T2)->getModifiedType()))
595       return false;
596     if (!IsStructurallyEquivalent(Context,
597                                 cast<AttributedType>(T1)->getEquivalentType(),
598                                 cast<AttributedType>(T2)->getEquivalentType()))
599       return false;
600     break;
601 
602   case Type::Paren:
603     if (!IsStructurallyEquivalent(Context,
604                                   cast<ParenType>(T1)->getInnerType(),
605                                   cast<ParenType>(T2)->getInnerType()))
606       return false;
607     break;
608 
609   case Type::Typedef:
610     if (!IsStructurallyEquivalent(Context,
611                                   cast<TypedefType>(T1)->getDecl(),
612                                   cast<TypedefType>(T2)->getDecl()))
613       return false;
614     break;
615 
616   case Type::TypeOfExpr:
617     if (!IsStructurallyEquivalent(Context,
618                                 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
619                                 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
620       return false;
621     break;
622 
623   case Type::TypeOf:
624     if (!IsStructurallyEquivalent(Context,
625                                   cast<TypeOfType>(T1)->getUnderlyingType(),
626                                   cast<TypeOfType>(T2)->getUnderlyingType()))
627       return false;
628     break;
629 
630   case Type::UnaryTransform:
631     if (!IsStructurallyEquivalent(Context,
632                              cast<UnaryTransformType>(T1)->getUnderlyingType(),
633                              cast<UnaryTransformType>(T1)->getUnderlyingType()))
634       return false;
635     break;
636 
637   case Type::Decltype:
638     if (!IsStructurallyEquivalent(Context,
639                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
640                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
641       return false;
642     break;
643 
644   case Type::Auto:
645     if (!IsStructurallyEquivalent(Context,
646                                   cast<AutoType>(T1)->getDeducedType(),
647                                   cast<AutoType>(T2)->getDeducedType()))
648       return false;
649     break;
650 
651   case Type::Record:
652   case Type::Enum:
653     if (!IsStructurallyEquivalent(Context,
654                                   cast<TagType>(T1)->getDecl(),
655                                   cast<TagType>(T2)->getDecl()))
656       return false;
657     break;
658 
659   case Type::TemplateTypeParm: {
660     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
661     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
662     if (Parm1->getDepth() != Parm2->getDepth())
663       return false;
664     if (Parm1->getIndex() != Parm2->getIndex())
665       return false;
666     if (Parm1->isParameterPack() != Parm2->isParameterPack())
667       return false;
668 
669     // Names of template type parameters are never significant.
670     break;
671   }
672 
673   case Type::SubstTemplateTypeParm: {
674     const SubstTemplateTypeParmType *Subst1
675       = cast<SubstTemplateTypeParmType>(T1);
676     const SubstTemplateTypeParmType *Subst2
677       = cast<SubstTemplateTypeParmType>(T2);
678     if (!IsStructurallyEquivalent(Context,
679                                   QualType(Subst1->getReplacedParameter(), 0),
680                                   QualType(Subst2->getReplacedParameter(), 0)))
681       return false;
682     if (!IsStructurallyEquivalent(Context,
683                                   Subst1->getReplacementType(),
684                                   Subst2->getReplacementType()))
685       return false;
686     break;
687   }
688 
689   case Type::SubstTemplateTypeParmPack: {
690     const SubstTemplateTypeParmPackType *Subst1
691       = cast<SubstTemplateTypeParmPackType>(T1);
692     const SubstTemplateTypeParmPackType *Subst2
693       = cast<SubstTemplateTypeParmPackType>(T2);
694     if (!IsStructurallyEquivalent(Context,
695                                   QualType(Subst1->getReplacedParameter(), 0),
696                                   QualType(Subst2->getReplacedParameter(), 0)))
697       return false;
698     if (!IsStructurallyEquivalent(Context,
699                                   Subst1->getArgumentPack(),
700                                   Subst2->getArgumentPack()))
701       return false;
702     break;
703   }
704   case Type::TemplateSpecialization: {
705     const TemplateSpecializationType *Spec1
706       = cast<TemplateSpecializationType>(T1);
707     const TemplateSpecializationType *Spec2
708       = cast<TemplateSpecializationType>(T2);
709     if (!IsStructurallyEquivalent(Context,
710                                   Spec1->getTemplateName(),
711                                   Spec2->getTemplateName()))
712       return false;
713     if (Spec1->getNumArgs() != Spec2->getNumArgs())
714       return false;
715     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
716       if (!IsStructurallyEquivalent(Context,
717                                     Spec1->getArg(I), Spec2->getArg(I)))
718         return false;
719     }
720     break;
721   }
722 
723   case Type::Elaborated: {
724     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
725     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
726     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
727     if (Elab1->getKeyword() != Elab2->getKeyword())
728       return false;
729     if (!IsStructurallyEquivalent(Context,
730                                   Elab1->getQualifier(),
731                                   Elab2->getQualifier()))
732       return false;
733     if (!IsStructurallyEquivalent(Context,
734                                   Elab1->getNamedType(),
735                                   Elab2->getNamedType()))
736       return false;
737     break;
738   }
739 
740   case Type::InjectedClassName: {
741     const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
742     const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
743     if (!IsStructurallyEquivalent(Context,
744                                   Inj1->getInjectedSpecializationType(),
745                                   Inj2->getInjectedSpecializationType()))
746       return false;
747     break;
748   }
749 
750   case Type::DependentName: {
751     const DependentNameType *Typename1 = cast<DependentNameType>(T1);
752     const DependentNameType *Typename2 = cast<DependentNameType>(T2);
753     if (!IsStructurallyEquivalent(Context,
754                                   Typename1->getQualifier(),
755                                   Typename2->getQualifier()))
756       return false;
757     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
758                                   Typename2->getIdentifier()))
759       return false;
760 
761     break;
762   }
763 
764   case Type::DependentTemplateSpecialization: {
765     const DependentTemplateSpecializationType *Spec1 =
766       cast<DependentTemplateSpecializationType>(T1);
767     const DependentTemplateSpecializationType *Spec2 =
768       cast<DependentTemplateSpecializationType>(T2);
769     if (!IsStructurallyEquivalent(Context,
770                                   Spec1->getQualifier(),
771                                   Spec2->getQualifier()))
772       return false;
773     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
774                                   Spec2->getIdentifier()))
775       return false;
776     if (Spec1->getNumArgs() != Spec2->getNumArgs())
777       return false;
778     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
779       if (!IsStructurallyEquivalent(Context,
780                                     Spec1->getArg(I), Spec2->getArg(I)))
781         return false;
782     }
783     break;
784   }
785 
786   case Type::PackExpansion:
787     if (!IsStructurallyEquivalent(Context,
788                                   cast<PackExpansionType>(T1)->getPattern(),
789                                   cast<PackExpansionType>(T2)->getPattern()))
790       return false;
791     break;
792 
793   case Type::ObjCInterface: {
794     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
795     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
796     if (!IsStructurallyEquivalent(Context,
797                                   Iface1->getDecl(), Iface2->getDecl()))
798       return false;
799     break;
800   }
801 
802   case Type::ObjCObject: {
803     const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
804     const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
805     if (!IsStructurallyEquivalent(Context,
806                                   Obj1->getBaseType(),
807                                   Obj2->getBaseType()))
808       return false;
809     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
810       return false;
811     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
812       if (!IsStructurallyEquivalent(Context,
813                                     Obj1->getProtocol(I),
814                                     Obj2->getProtocol(I)))
815         return false;
816     }
817     break;
818   }
819 
820   case Type::ObjCObjectPointer: {
821     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
822     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
823     if (!IsStructurallyEquivalent(Context,
824                                   Ptr1->getPointeeType(),
825                                   Ptr2->getPointeeType()))
826       return false;
827     break;
828   }
829 
830   case Type::Atomic: {
831     if (!IsStructurallyEquivalent(Context,
832                                   cast<AtomicType>(T1)->getValueType(),
833                                   cast<AtomicType>(T2)->getValueType()))
834       return false;
835     break;
836   }
837 
838   } // end switch
839 
840   return true;
841 }
842 
843 /// \brief Determine structural equivalence of two fields.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,FieldDecl * Field1,FieldDecl * Field2)844 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
845                                      FieldDecl *Field1, FieldDecl *Field2) {
846   RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
847 
848   // For anonymous structs/unions, match up the anonymous struct/union type
849   // declarations directly, so that we don't go off searching for anonymous
850   // types
851   if (Field1->isAnonymousStructOrUnion() &&
852       Field2->isAnonymousStructOrUnion()) {
853     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
854     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
855     return IsStructurallyEquivalent(Context, D1, D2);
856   }
857 
858   // Check for equivalent field names.
859   IdentifierInfo *Name1 = Field1->getIdentifier();
860   IdentifierInfo *Name2 = Field2->getIdentifier();
861   if (!::IsStructurallyEquivalent(Name1, Name2))
862     return false;
863 
864   if (!IsStructurallyEquivalent(Context,
865                                 Field1->getType(), Field2->getType())) {
866     if (Context.Complain) {
867       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
868         << Context.C2.getTypeDeclType(Owner2);
869       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
870         << Field2->getDeclName() << Field2->getType();
871       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
872         << Field1->getDeclName() << Field1->getType();
873     }
874     return false;
875   }
876 
877   if (Field1->isBitField() != Field2->isBitField()) {
878     if (Context.Complain) {
879       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
880         << Context.C2.getTypeDeclType(Owner2);
881       if (Field1->isBitField()) {
882         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
883         << Field1->getDeclName() << Field1->getType()
884         << Field1->getBitWidthValue(Context.C1);
885         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
886         << Field2->getDeclName();
887       } else {
888         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
889         << Field2->getDeclName() << Field2->getType()
890         << Field2->getBitWidthValue(Context.C2);
891         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
892         << Field1->getDeclName();
893       }
894     }
895     return false;
896   }
897 
898   if (Field1->isBitField()) {
899     // Make sure that the bit-fields are the same length.
900     unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
901     unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
902 
903     if (Bits1 != Bits2) {
904       if (Context.Complain) {
905         Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
906           << Context.C2.getTypeDeclType(Owner2);
907         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
908           << Field2->getDeclName() << Field2->getType() << Bits2;
909         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
910           << Field1->getDeclName() << Field1->getType() << Bits1;
911       }
912       return false;
913     }
914   }
915 
916   return true;
917 }
918 
919 /// \brief Find the index of the given anonymous struct/union within its
920 /// context.
921 ///
922 /// \returns Returns the index of this anonymous struct/union in its context,
923 /// including the next assigned index (if none of them match). Returns an
924 /// empty option if the context is not a record, i.e.. if the anonymous
925 /// struct/union is at namespace or block scope.
findAnonymousStructOrUnionIndex(RecordDecl * Anon)926 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
927   ASTContext &Context = Anon->getASTContext();
928   QualType AnonTy = Context.getRecordType(Anon);
929 
930   RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
931   if (!Owner)
932     return None;
933 
934   unsigned Index = 0;
935   for (const auto *D : Owner->noload_decls()) {
936     const auto *F = dyn_cast<FieldDecl>(D);
937     if (!F || !F->isAnonymousStructOrUnion())
938       continue;
939 
940     if (Context.hasSameType(F->getType(), AnonTy))
941       break;
942 
943     ++Index;
944   }
945 
946   return Index;
947 }
948 
949 /// \brief Determine structural equivalence of two records.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,RecordDecl * D1,RecordDecl * D2)950 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
951                                      RecordDecl *D1, RecordDecl *D2) {
952   if (D1->isUnion() != D2->isUnion()) {
953     if (Context.Complain) {
954       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
955         << Context.C2.getTypeDeclType(D2);
956       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
957         << D1->getDeclName() << (unsigned)D1->getTagKind();
958     }
959     return false;
960   }
961 
962   if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
963     // If both anonymous structs/unions are in a record context, make sure
964     // they occur in the same location in the context records.
965     if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
966       if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
967         if (*Index1 != *Index2)
968           return false;
969       }
970     }
971   }
972 
973   // If both declarations are class template specializations, we know
974   // the ODR applies, so check the template and template arguments.
975   ClassTemplateSpecializationDecl *Spec1
976     = dyn_cast<ClassTemplateSpecializationDecl>(D1);
977   ClassTemplateSpecializationDecl *Spec2
978     = dyn_cast<ClassTemplateSpecializationDecl>(D2);
979   if (Spec1 && Spec2) {
980     // Check that the specialized templates are the same.
981     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
982                                   Spec2->getSpecializedTemplate()))
983       return false;
984 
985     // Check that the template arguments are the same.
986     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
987       return false;
988 
989     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
990       if (!IsStructurallyEquivalent(Context,
991                                     Spec1->getTemplateArgs().get(I),
992                                     Spec2->getTemplateArgs().get(I)))
993         return false;
994   }
995   // If one is a class template specialization and the other is not, these
996   // structures are different.
997   else if (Spec1 || Spec2)
998     return false;
999 
1000   // Compare the definitions of these two records. If either or both are
1001   // incomplete, we assume that they are equivalent.
1002   D1 = D1->getDefinition();
1003   D2 = D2->getDefinition();
1004   if (!D1 || !D2)
1005     return true;
1006 
1007   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1008     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1009       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1010         if (Context.Complain) {
1011           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1012             << Context.C2.getTypeDeclType(D2);
1013           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1014             << D2CXX->getNumBases();
1015           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1016             << D1CXX->getNumBases();
1017         }
1018         return false;
1019       }
1020 
1021       // Check the base classes.
1022       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1023                                            BaseEnd1 = D1CXX->bases_end(),
1024                                                 Base2 = D2CXX->bases_begin();
1025            Base1 != BaseEnd1;
1026            ++Base1, ++Base2) {
1027         if (!IsStructurallyEquivalent(Context,
1028                                       Base1->getType(), Base2->getType())) {
1029           if (Context.Complain) {
1030             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1031               << Context.C2.getTypeDeclType(D2);
1032             Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1033               << Base2->getType()
1034               << Base2->getSourceRange();
1035             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1036               << Base1->getType()
1037               << Base1->getSourceRange();
1038           }
1039           return false;
1040         }
1041 
1042         // Check virtual vs. non-virtual inheritance mismatch.
1043         if (Base1->isVirtual() != Base2->isVirtual()) {
1044           if (Context.Complain) {
1045             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1046               << Context.C2.getTypeDeclType(D2);
1047             Context.Diag2(Base2->getLocStart(),
1048                           diag::note_odr_virtual_base)
1049               << Base2->isVirtual() << Base2->getSourceRange();
1050             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1051               << Base1->isVirtual()
1052               << Base1->getSourceRange();
1053           }
1054           return false;
1055         }
1056       }
1057     } else if (D1CXX->getNumBases() > 0) {
1058       if (Context.Complain) {
1059         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1060           << Context.C2.getTypeDeclType(D2);
1061         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1062         Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1063           << Base1->getType()
1064           << Base1->getSourceRange();
1065         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1066       }
1067       return false;
1068     }
1069   }
1070 
1071   // Check the fields for consistency.
1072   RecordDecl::field_iterator Field2 = D2->field_begin(),
1073                              Field2End = D2->field_end();
1074   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1075                                   Field1End = D1->field_end();
1076        Field1 != Field1End;
1077        ++Field1, ++Field2) {
1078     if (Field2 == Field2End) {
1079       if (Context.Complain) {
1080         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1081           << Context.C2.getTypeDeclType(D2);
1082         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1083           << Field1->getDeclName() << Field1->getType();
1084         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1085       }
1086       return false;
1087     }
1088 
1089     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1090       return false;
1091   }
1092 
1093   if (Field2 != Field2End) {
1094     if (Context.Complain) {
1095       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1096         << Context.C2.getTypeDeclType(D2);
1097       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1098         << Field2->getDeclName() << Field2->getType();
1099       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1100     }
1101     return false;
1102   }
1103 
1104   return true;
1105 }
1106 
1107 /// \brief Determine structural equivalence of two enums.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,EnumDecl * D1,EnumDecl * D2)1108 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1109                                      EnumDecl *D1, EnumDecl *D2) {
1110   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1111                              EC2End = D2->enumerator_end();
1112   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1113                                   EC1End = D1->enumerator_end();
1114        EC1 != EC1End; ++EC1, ++EC2) {
1115     if (EC2 == EC2End) {
1116       if (Context.Complain) {
1117         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1118           << Context.C2.getTypeDeclType(D2);
1119         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1120           << EC1->getDeclName()
1121           << EC1->getInitVal().toString(10);
1122         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1123       }
1124       return false;
1125     }
1126 
1127     llvm::APSInt Val1 = EC1->getInitVal();
1128     llvm::APSInt Val2 = EC2->getInitVal();
1129     if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1130         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1131       if (Context.Complain) {
1132         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1133           << Context.C2.getTypeDeclType(D2);
1134         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1135           << EC2->getDeclName()
1136           << EC2->getInitVal().toString(10);
1137         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1138           << EC1->getDeclName()
1139           << EC1->getInitVal().toString(10);
1140       }
1141       return false;
1142     }
1143   }
1144 
1145   if (EC2 != EC2End) {
1146     if (Context.Complain) {
1147       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1148         << Context.C2.getTypeDeclType(D2);
1149       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1150         << EC2->getDeclName()
1151         << EC2->getInitVal().toString(10);
1152       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1153     }
1154     return false;
1155   }
1156 
1157   return true;
1158 }
1159 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateParameterList * Params1,TemplateParameterList * Params2)1160 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1161                                      TemplateParameterList *Params1,
1162                                      TemplateParameterList *Params2) {
1163   if (Params1->size() != Params2->size()) {
1164     if (Context.Complain) {
1165       Context.Diag2(Params2->getTemplateLoc(),
1166                     diag::err_odr_different_num_template_parameters)
1167         << Params1->size() << Params2->size();
1168       Context.Diag1(Params1->getTemplateLoc(),
1169                     diag::note_odr_template_parameter_list);
1170     }
1171     return false;
1172   }
1173 
1174   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1175     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1176       if (Context.Complain) {
1177         Context.Diag2(Params2->getParam(I)->getLocation(),
1178                       diag::err_odr_different_template_parameter_kind);
1179         Context.Diag1(Params1->getParam(I)->getLocation(),
1180                       diag::note_odr_template_parameter_here);
1181       }
1182       return false;
1183     }
1184 
1185     if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1186                                           Params2->getParam(I))) {
1187 
1188       return false;
1189     }
1190   }
1191 
1192   return true;
1193 }
1194 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTypeParmDecl * D1,TemplateTypeParmDecl * D2)1195 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1196                                      TemplateTypeParmDecl *D1,
1197                                      TemplateTypeParmDecl *D2) {
1198   if (D1->isParameterPack() != D2->isParameterPack()) {
1199     if (Context.Complain) {
1200       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1201         << D2->isParameterPack();
1202       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1203         << D1->isParameterPack();
1204     }
1205     return false;
1206   }
1207 
1208   return true;
1209 }
1210 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NonTypeTemplateParmDecl * D1,NonTypeTemplateParmDecl * D2)1211 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1212                                      NonTypeTemplateParmDecl *D1,
1213                                      NonTypeTemplateParmDecl *D2) {
1214   if (D1->isParameterPack() != D2->isParameterPack()) {
1215     if (Context.Complain) {
1216       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1217         << D2->isParameterPack();
1218       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1219         << D1->isParameterPack();
1220     }
1221     return false;
1222   }
1223 
1224   // Check types.
1225   if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1226     if (Context.Complain) {
1227       Context.Diag2(D2->getLocation(),
1228                     diag::err_odr_non_type_parameter_type_inconsistent)
1229         << D2->getType() << D1->getType();
1230       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1231         << D1->getType();
1232     }
1233     return false;
1234   }
1235 
1236   return true;
1237 }
1238 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTemplateParmDecl * D1,TemplateTemplateParmDecl * D2)1239 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1240                                      TemplateTemplateParmDecl *D1,
1241                                      TemplateTemplateParmDecl *D2) {
1242   if (D1->isParameterPack() != D2->isParameterPack()) {
1243     if (Context.Complain) {
1244       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1245         << D2->isParameterPack();
1246       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1247         << D1->isParameterPack();
1248     }
1249     return false;
1250   }
1251 
1252   // Check template parameter lists.
1253   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1254                                   D2->getTemplateParameters());
1255 }
1256 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,ClassTemplateDecl * D1,ClassTemplateDecl * D2)1257 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1258                                      ClassTemplateDecl *D1,
1259                                      ClassTemplateDecl *D2) {
1260   // Check template parameters.
1261   if (!IsStructurallyEquivalent(Context,
1262                                 D1->getTemplateParameters(),
1263                                 D2->getTemplateParameters()))
1264     return false;
1265 
1266   // Check the templated declaration.
1267   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1268                                           D2->getTemplatedDecl());
1269 }
1270 
1271 /// \brief Determine structural equivalence of two declarations.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Decl * D1,Decl * D2)1272 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1273                                      Decl *D1, Decl *D2) {
1274   // FIXME: Check for known structural equivalences via a callback of some sort.
1275 
1276   // Check whether we already know that these two declarations are not
1277   // structurally equivalent.
1278   if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1279                                                       D2->getCanonicalDecl())))
1280     return false;
1281 
1282   // Determine whether we've already produced a tentative equivalence for D1.
1283   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1284   if (EquivToD1)
1285     return EquivToD1 == D2->getCanonicalDecl();
1286 
1287   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1288   EquivToD1 = D2->getCanonicalDecl();
1289   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1290   return true;
1291 }
1292 
IsStructurallyEquivalent(Decl * D1,Decl * D2)1293 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1294                                                             Decl *D2) {
1295   if (!::IsStructurallyEquivalent(*this, D1, D2))
1296     return false;
1297 
1298   return !Finish();
1299 }
1300 
IsStructurallyEquivalent(QualType T1,QualType T2)1301 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1302                                                             QualType T2) {
1303   if (!::IsStructurallyEquivalent(*this, T1, T2))
1304     return false;
1305 
1306   return !Finish();
1307 }
1308 
Finish()1309 bool StructuralEquivalenceContext::Finish() {
1310   while (!DeclsToCheck.empty()) {
1311     // Check the next declaration.
1312     Decl *D1 = DeclsToCheck.front();
1313     DeclsToCheck.pop_front();
1314 
1315     Decl *D2 = TentativeEquivalences[D1];
1316     assert(D2 && "Unrecorded tentative equivalence?");
1317 
1318     bool Equivalent = true;
1319 
1320     // FIXME: Switch on all declaration kinds. For now, we're just going to
1321     // check the obvious ones.
1322     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1323       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1324         // Check for equivalent structure names.
1325         IdentifierInfo *Name1 = Record1->getIdentifier();
1326         if (!Name1 && Record1->getTypedefNameForAnonDecl())
1327           Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1328         IdentifierInfo *Name2 = Record2->getIdentifier();
1329         if (!Name2 && Record2->getTypedefNameForAnonDecl())
1330           Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1331         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1332             !::IsStructurallyEquivalent(*this, Record1, Record2))
1333           Equivalent = false;
1334       } else {
1335         // Record/non-record mismatch.
1336         Equivalent = false;
1337       }
1338     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1339       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1340         // Check for equivalent enum names.
1341         IdentifierInfo *Name1 = Enum1->getIdentifier();
1342         if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1343           Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1344         IdentifierInfo *Name2 = Enum2->getIdentifier();
1345         if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1346           Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1347         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1348             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1349           Equivalent = false;
1350       } else {
1351         // Enum/non-enum mismatch
1352         Equivalent = false;
1353       }
1354     } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1355       if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1356         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1357                                         Typedef2->getIdentifier()) ||
1358             !::IsStructurallyEquivalent(*this,
1359                                         Typedef1->getUnderlyingType(),
1360                                         Typedef2->getUnderlyingType()))
1361           Equivalent = false;
1362       } else {
1363         // Typedef/non-typedef mismatch.
1364         Equivalent = false;
1365       }
1366     } else if (ClassTemplateDecl *ClassTemplate1
1367                                            = dyn_cast<ClassTemplateDecl>(D1)) {
1368       if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1369         if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1370                                         ClassTemplate2->getIdentifier()) ||
1371             !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1372           Equivalent = false;
1373       } else {
1374         // Class template/non-class-template mismatch.
1375         Equivalent = false;
1376       }
1377     } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1378       if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1379         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1380           Equivalent = false;
1381       } else {
1382         // Kind mismatch.
1383         Equivalent = false;
1384       }
1385     } else if (NonTypeTemplateParmDecl *NTTP1
1386                                      = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1387       if (NonTypeTemplateParmDecl *NTTP2
1388                                       = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1389         if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1390           Equivalent = false;
1391       } else {
1392         // Kind mismatch.
1393         Equivalent = false;
1394       }
1395     } else if (TemplateTemplateParmDecl *TTP1
1396                                   = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1397       if (TemplateTemplateParmDecl *TTP2
1398                                     = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1399         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1400           Equivalent = false;
1401       } else {
1402         // Kind mismatch.
1403         Equivalent = false;
1404       }
1405     }
1406 
1407     if (!Equivalent) {
1408       // Note that these two declarations are not equivalent (and we already
1409       // know about it).
1410       NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1411                                                D2->getCanonicalDecl()));
1412       return true;
1413     }
1414     // FIXME: Check other declaration kinds!
1415   }
1416 
1417   return false;
1418 }
1419 
1420 //----------------------------------------------------------------------------
1421 // Import Types
1422 //----------------------------------------------------------------------------
1423 
VisitType(const Type * T)1424 QualType ASTNodeImporter::VisitType(const Type *T) {
1425   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1426     << T->getTypeClassName();
1427   return QualType();
1428 }
1429 
VisitBuiltinType(const BuiltinType * T)1430 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1431   switch (T->getKind()) {
1432 #define SHARED_SINGLETON_TYPE(Expansion)
1433 #define BUILTIN_TYPE(Id, SingletonId) \
1434   case BuiltinType::Id: return Importer.getToContext().SingletonId;
1435 #include "clang/AST/BuiltinTypes.def"
1436 
1437   // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1438   // context supports C++.
1439 
1440   // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1441   // context supports ObjC.
1442 
1443   case BuiltinType::Char_U:
1444     // The context we're importing from has an unsigned 'char'. If we're
1445     // importing into a context with a signed 'char', translate to
1446     // 'unsigned char' instead.
1447     if (Importer.getToContext().getLangOpts().CharIsSigned)
1448       return Importer.getToContext().UnsignedCharTy;
1449 
1450     return Importer.getToContext().CharTy;
1451 
1452   case BuiltinType::Char_S:
1453     // The context we're importing from has an unsigned 'char'. If we're
1454     // importing into a context with a signed 'char', translate to
1455     // 'unsigned char' instead.
1456     if (!Importer.getToContext().getLangOpts().CharIsSigned)
1457       return Importer.getToContext().SignedCharTy;
1458 
1459     return Importer.getToContext().CharTy;
1460 
1461   case BuiltinType::WChar_S:
1462   case BuiltinType::WChar_U:
1463     // FIXME: If not in C++, shall we translate to the C equivalent of
1464     // wchar_t?
1465     return Importer.getToContext().WCharTy;
1466   }
1467 
1468   llvm_unreachable("Invalid BuiltinType Kind!");
1469 }
1470 
VisitComplexType(const ComplexType * T)1471 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1472   QualType ToElementType = Importer.Import(T->getElementType());
1473   if (ToElementType.isNull())
1474     return QualType();
1475 
1476   return Importer.getToContext().getComplexType(ToElementType);
1477 }
1478 
VisitPointerType(const PointerType * T)1479 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1480   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1481   if (ToPointeeType.isNull())
1482     return QualType();
1483 
1484   return Importer.getToContext().getPointerType(ToPointeeType);
1485 }
1486 
VisitBlockPointerType(const BlockPointerType * T)1487 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1488   // FIXME: Check for blocks support in "to" context.
1489   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1490   if (ToPointeeType.isNull())
1491     return QualType();
1492 
1493   return Importer.getToContext().getBlockPointerType(ToPointeeType);
1494 }
1495 
1496 QualType
VisitLValueReferenceType(const LValueReferenceType * T)1497 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1498   // FIXME: Check for C++ support in "to" context.
1499   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1500   if (ToPointeeType.isNull())
1501     return QualType();
1502 
1503   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1504 }
1505 
1506 QualType
VisitRValueReferenceType(const RValueReferenceType * T)1507 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1508   // FIXME: Check for C++0x support in "to" context.
1509   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1510   if (ToPointeeType.isNull())
1511     return QualType();
1512 
1513   return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1514 }
1515 
VisitMemberPointerType(const MemberPointerType * T)1516 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1517   // FIXME: Check for C++ support in "to" context.
1518   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1519   if (ToPointeeType.isNull())
1520     return QualType();
1521 
1522   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1523   return Importer.getToContext().getMemberPointerType(ToPointeeType,
1524                                                       ClassType.getTypePtr());
1525 }
1526 
VisitConstantArrayType(const ConstantArrayType * T)1527 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1528   QualType ToElementType = Importer.Import(T->getElementType());
1529   if (ToElementType.isNull())
1530     return QualType();
1531 
1532   return Importer.getToContext().getConstantArrayType(ToElementType,
1533                                                       T->getSize(),
1534                                                       T->getSizeModifier(),
1535                                                T->getIndexTypeCVRQualifiers());
1536 }
1537 
1538 QualType
VisitIncompleteArrayType(const IncompleteArrayType * T)1539 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1540   QualType ToElementType = Importer.Import(T->getElementType());
1541   if (ToElementType.isNull())
1542     return QualType();
1543 
1544   return Importer.getToContext().getIncompleteArrayType(ToElementType,
1545                                                         T->getSizeModifier(),
1546                                                 T->getIndexTypeCVRQualifiers());
1547 }
1548 
VisitVariableArrayType(const VariableArrayType * T)1549 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1550   QualType ToElementType = Importer.Import(T->getElementType());
1551   if (ToElementType.isNull())
1552     return QualType();
1553 
1554   Expr *Size = Importer.Import(T->getSizeExpr());
1555   if (!Size)
1556     return QualType();
1557 
1558   SourceRange Brackets = Importer.Import(T->getBracketsRange());
1559   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1560                                                       T->getSizeModifier(),
1561                                                 T->getIndexTypeCVRQualifiers(),
1562                                                       Brackets);
1563 }
1564 
VisitVectorType(const VectorType * T)1565 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1566   QualType ToElementType = Importer.Import(T->getElementType());
1567   if (ToElementType.isNull())
1568     return QualType();
1569 
1570   return Importer.getToContext().getVectorType(ToElementType,
1571                                                T->getNumElements(),
1572                                                T->getVectorKind());
1573 }
1574 
VisitExtVectorType(const ExtVectorType * T)1575 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1576   QualType ToElementType = Importer.Import(T->getElementType());
1577   if (ToElementType.isNull())
1578     return QualType();
1579 
1580   return Importer.getToContext().getExtVectorType(ToElementType,
1581                                                   T->getNumElements());
1582 }
1583 
1584 QualType
VisitFunctionNoProtoType(const FunctionNoProtoType * T)1585 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1586   // FIXME: What happens if we're importing a function without a prototype
1587   // into C++? Should we make it variadic?
1588   QualType ToResultType = Importer.Import(T->getReturnType());
1589   if (ToResultType.isNull())
1590     return QualType();
1591 
1592   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1593                                                         T->getExtInfo());
1594 }
1595 
VisitFunctionProtoType(const FunctionProtoType * T)1596 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1597   QualType ToResultType = Importer.Import(T->getReturnType());
1598   if (ToResultType.isNull())
1599     return QualType();
1600 
1601   // Import argument types
1602   SmallVector<QualType, 4> ArgTypes;
1603   for (const auto &A : T->param_types()) {
1604     QualType ArgType = Importer.Import(A);
1605     if (ArgType.isNull())
1606       return QualType();
1607     ArgTypes.push_back(ArgType);
1608   }
1609 
1610   // Import exception types
1611   SmallVector<QualType, 4> ExceptionTypes;
1612   for (const auto &E : T->exceptions()) {
1613     QualType ExceptionType = Importer.Import(E);
1614     if (ExceptionType.isNull())
1615       return QualType();
1616     ExceptionTypes.push_back(ExceptionType);
1617   }
1618 
1619   FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1620   FunctionProtoType::ExtProtoInfo ToEPI;
1621 
1622   ToEPI.ExtInfo = FromEPI.ExtInfo;
1623   ToEPI.Variadic = FromEPI.Variadic;
1624   ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1625   ToEPI.TypeQuals = FromEPI.TypeQuals;
1626   ToEPI.RefQualifier = FromEPI.RefQualifier;
1627   ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1628   ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1629   ToEPI.ExceptionSpec.NoexceptExpr =
1630       Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1631   ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1632       Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1633   ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1634       Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1635 
1636   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1637 }
1638 
VisitParenType(const ParenType * T)1639 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1640   QualType ToInnerType = Importer.Import(T->getInnerType());
1641   if (ToInnerType.isNull())
1642     return QualType();
1643 
1644   return Importer.getToContext().getParenType(ToInnerType);
1645 }
1646 
VisitTypedefType(const TypedefType * T)1647 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1648   TypedefNameDecl *ToDecl
1649              = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1650   if (!ToDecl)
1651     return QualType();
1652 
1653   return Importer.getToContext().getTypeDeclType(ToDecl);
1654 }
1655 
VisitTypeOfExprType(const TypeOfExprType * T)1656 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1657   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1658   if (!ToExpr)
1659     return QualType();
1660 
1661   return Importer.getToContext().getTypeOfExprType(ToExpr);
1662 }
1663 
VisitTypeOfType(const TypeOfType * T)1664 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1665   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1666   if (ToUnderlyingType.isNull())
1667     return QualType();
1668 
1669   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1670 }
1671 
VisitDecltypeType(const DecltypeType * T)1672 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1673   // FIXME: Make sure that the "to" context supports C++0x!
1674   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1675   if (!ToExpr)
1676     return QualType();
1677 
1678   QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1679   if (UnderlyingType.isNull())
1680     return QualType();
1681 
1682   return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1683 }
1684 
VisitUnaryTransformType(const UnaryTransformType * T)1685 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1686   QualType ToBaseType = Importer.Import(T->getBaseType());
1687   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1688   if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1689     return QualType();
1690 
1691   return Importer.getToContext().getUnaryTransformType(ToBaseType,
1692                                                        ToUnderlyingType,
1693                                                        T->getUTTKind());
1694 }
1695 
VisitAutoType(const AutoType * T)1696 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1697   // FIXME: Make sure that the "to" context supports C++11!
1698   QualType FromDeduced = T->getDeducedType();
1699   QualType ToDeduced;
1700   if (!FromDeduced.isNull()) {
1701     ToDeduced = Importer.Import(FromDeduced);
1702     if (ToDeduced.isNull())
1703       return QualType();
1704   }
1705 
1706   return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto(),
1707                                              /*IsDependent*/false);
1708 }
1709 
VisitRecordType(const RecordType * T)1710 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1711   RecordDecl *ToDecl
1712     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1713   if (!ToDecl)
1714     return QualType();
1715 
1716   return Importer.getToContext().getTagDeclType(ToDecl);
1717 }
1718 
VisitEnumType(const EnumType * T)1719 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1720   EnumDecl *ToDecl
1721     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1722   if (!ToDecl)
1723     return QualType();
1724 
1725   return Importer.getToContext().getTagDeclType(ToDecl);
1726 }
1727 
VisitAttributedType(const AttributedType * T)1728 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1729   QualType FromModifiedType = T->getModifiedType();
1730   QualType FromEquivalentType = T->getEquivalentType();
1731   QualType ToModifiedType;
1732   QualType ToEquivalentType;
1733 
1734   if (!FromModifiedType.isNull()) {
1735     ToModifiedType = Importer.Import(FromModifiedType);
1736     if (ToModifiedType.isNull())
1737       return QualType();
1738   }
1739   if (!FromEquivalentType.isNull()) {
1740     ToEquivalentType = Importer.Import(FromEquivalentType);
1741     if (ToEquivalentType.isNull())
1742       return QualType();
1743   }
1744 
1745   return Importer.getToContext().getAttributedType(T->getAttrKind(),
1746     ToModifiedType, ToEquivalentType);
1747 }
1748 
VisitTemplateSpecializationType(const TemplateSpecializationType * T)1749 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1750                                        const TemplateSpecializationType *T) {
1751   TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1752   if (ToTemplate.isNull())
1753     return QualType();
1754 
1755   SmallVector<TemplateArgument, 2> ToTemplateArgs;
1756   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1757     return QualType();
1758 
1759   QualType ToCanonType;
1760   if (!QualType(T, 0).isCanonical()) {
1761     QualType FromCanonType
1762       = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1763     ToCanonType =Importer.Import(FromCanonType);
1764     if (ToCanonType.isNull())
1765       return QualType();
1766   }
1767   return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1768                                                          ToTemplateArgs.data(),
1769                                                          ToTemplateArgs.size(),
1770                                                                ToCanonType);
1771 }
1772 
VisitElaboratedType(const ElaboratedType * T)1773 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1774   NestedNameSpecifier *ToQualifier = nullptr;
1775   // Note: the qualifier in an ElaboratedType is optional.
1776   if (T->getQualifier()) {
1777     ToQualifier = Importer.Import(T->getQualifier());
1778     if (!ToQualifier)
1779       return QualType();
1780   }
1781 
1782   QualType ToNamedType = Importer.Import(T->getNamedType());
1783   if (ToNamedType.isNull())
1784     return QualType();
1785 
1786   return Importer.getToContext().getElaboratedType(T->getKeyword(),
1787                                                    ToQualifier, ToNamedType);
1788 }
1789 
VisitObjCInterfaceType(const ObjCInterfaceType * T)1790 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1791   ObjCInterfaceDecl *Class
1792     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1793   if (!Class)
1794     return QualType();
1795 
1796   return Importer.getToContext().getObjCInterfaceType(Class);
1797 }
1798 
VisitObjCObjectType(const ObjCObjectType * T)1799 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1800   QualType ToBaseType = Importer.Import(T->getBaseType());
1801   if (ToBaseType.isNull())
1802     return QualType();
1803 
1804   SmallVector<ObjCProtocolDecl *, 4> Protocols;
1805   for (auto *P : T->quals()) {
1806     ObjCProtocolDecl *Protocol
1807       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1808     if (!Protocol)
1809       return QualType();
1810     Protocols.push_back(Protocol);
1811   }
1812 
1813   return Importer.getToContext().getObjCObjectType(ToBaseType,
1814                                                    Protocols.data(),
1815                                                    Protocols.size());
1816 }
1817 
1818 QualType
VisitObjCObjectPointerType(const ObjCObjectPointerType * T)1819 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1820   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1821   if (ToPointeeType.isNull())
1822     return QualType();
1823 
1824   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1825 }
1826 
1827 //----------------------------------------------------------------------------
1828 // Import Declarations
1829 //----------------------------------------------------------------------------
ImportDeclParts(NamedDecl * D,DeclContext * & DC,DeclContext * & LexicalDC,DeclarationName & Name,SourceLocation & Loc)1830 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1831                                       DeclContext *&LexicalDC,
1832                                       DeclarationName &Name,
1833                                       SourceLocation &Loc) {
1834   // Import the context of this declaration.
1835   DC = Importer.ImportContext(D->getDeclContext());
1836   if (!DC)
1837     return true;
1838 
1839   LexicalDC = DC;
1840   if (D->getDeclContext() != D->getLexicalDeclContext()) {
1841     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1842     if (!LexicalDC)
1843       return true;
1844   }
1845 
1846   // Import the name of this declaration.
1847   Name = Importer.Import(D->getDeclName());
1848   if (D->getDeclName() && !Name)
1849     return true;
1850 
1851   // Import the location of this declaration.
1852   Loc = Importer.Import(D->getLocation());
1853   return false;
1854 }
1855 
ImportDefinitionIfNeeded(Decl * FromD,Decl * ToD)1856 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1857   if (!FromD)
1858     return;
1859 
1860   if (!ToD) {
1861     ToD = Importer.Import(FromD);
1862     if (!ToD)
1863       return;
1864   }
1865 
1866   if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1867     if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1868       if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1869         ImportDefinition(FromRecord, ToRecord);
1870       }
1871     }
1872     return;
1873   }
1874 
1875   if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1876     if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1877       if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1878         ImportDefinition(FromEnum, ToEnum);
1879       }
1880     }
1881     return;
1882   }
1883 }
1884 
1885 void
ImportDeclarationNameLoc(const DeclarationNameInfo & From,DeclarationNameInfo & To)1886 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1887                                           DeclarationNameInfo& To) {
1888   // NOTE: To.Name and To.Loc are already imported.
1889   // We only have to import To.LocInfo.
1890   switch (To.getName().getNameKind()) {
1891   case DeclarationName::Identifier:
1892   case DeclarationName::ObjCZeroArgSelector:
1893   case DeclarationName::ObjCOneArgSelector:
1894   case DeclarationName::ObjCMultiArgSelector:
1895   case DeclarationName::CXXUsingDirective:
1896     return;
1897 
1898   case DeclarationName::CXXOperatorName: {
1899     SourceRange Range = From.getCXXOperatorNameRange();
1900     To.setCXXOperatorNameRange(Importer.Import(Range));
1901     return;
1902   }
1903   case DeclarationName::CXXLiteralOperatorName: {
1904     SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1905     To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1906     return;
1907   }
1908   case DeclarationName::CXXConstructorName:
1909   case DeclarationName::CXXDestructorName:
1910   case DeclarationName::CXXConversionFunctionName: {
1911     TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1912     To.setNamedTypeInfo(Importer.Import(FromTInfo));
1913     return;
1914   }
1915   }
1916   llvm_unreachable("Unknown name kind.");
1917 }
1918 
ImportDeclContext(DeclContext * FromDC,bool ForceImport)1919 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1920   if (Importer.isMinimalImport() && !ForceImport) {
1921     Importer.ImportContext(FromDC);
1922     return;
1923   }
1924 
1925   for (auto *From : FromDC->decls())
1926     Importer.Import(From);
1927 }
1928 
ImportDefinition(RecordDecl * From,RecordDecl * To,ImportDefinitionKind Kind)1929 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1930                                        ImportDefinitionKind Kind) {
1931   if (To->getDefinition() || To->isBeingDefined()) {
1932     if (Kind == IDK_Everything)
1933       ImportDeclContext(From, /*ForceImport=*/true);
1934 
1935     return false;
1936   }
1937 
1938   To->startDefinition();
1939 
1940   // Add base classes.
1941   if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1942     CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1943 
1944     struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1945     struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1946     ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1947     ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1948     ToData.Aggregate = FromData.Aggregate;
1949     ToData.PlainOldData = FromData.PlainOldData;
1950     ToData.Empty = FromData.Empty;
1951     ToData.Polymorphic = FromData.Polymorphic;
1952     ToData.Abstract = FromData.Abstract;
1953     ToData.IsStandardLayout = FromData.IsStandardLayout;
1954     ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
1955     ToData.HasPrivateFields = FromData.HasPrivateFields;
1956     ToData.HasProtectedFields = FromData.HasProtectedFields;
1957     ToData.HasPublicFields = FromData.HasPublicFields;
1958     ToData.HasMutableFields = FromData.HasMutableFields;
1959     ToData.HasVariantMembers = FromData.HasVariantMembers;
1960     ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1961     ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1962     ToData.HasUninitializedReferenceMember
1963       = FromData.HasUninitializedReferenceMember;
1964     ToData.NeedOverloadResolutionForMoveConstructor
1965       = FromData.NeedOverloadResolutionForMoveConstructor;
1966     ToData.NeedOverloadResolutionForMoveAssignment
1967       = FromData.NeedOverloadResolutionForMoveAssignment;
1968     ToData.NeedOverloadResolutionForDestructor
1969       = FromData.NeedOverloadResolutionForDestructor;
1970     ToData.DefaultedMoveConstructorIsDeleted
1971       = FromData.DefaultedMoveConstructorIsDeleted;
1972     ToData.DefaultedMoveAssignmentIsDeleted
1973       = FromData.DefaultedMoveAssignmentIsDeleted;
1974     ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1975     ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1976     ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1977     ToData.HasConstexprNonCopyMoveConstructor
1978       = FromData.HasConstexprNonCopyMoveConstructor;
1979     ToData.DefaultedDefaultConstructorIsConstexpr
1980       = FromData.DefaultedDefaultConstructorIsConstexpr;
1981     ToData.HasConstexprDefaultConstructor
1982       = FromData.HasConstexprDefaultConstructor;
1983     ToData.HasNonLiteralTypeFieldsOrBases
1984       = FromData.HasNonLiteralTypeFieldsOrBases;
1985     // ComputedVisibleConversions not imported.
1986     ToData.UserProvidedDefaultConstructor
1987       = FromData.UserProvidedDefaultConstructor;
1988     ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1989     ToData.ImplicitCopyConstructorHasConstParam
1990       = FromData.ImplicitCopyConstructorHasConstParam;
1991     ToData.ImplicitCopyAssignmentHasConstParam
1992       = FromData.ImplicitCopyAssignmentHasConstParam;
1993     ToData.HasDeclaredCopyConstructorWithConstParam
1994       = FromData.HasDeclaredCopyConstructorWithConstParam;
1995     ToData.HasDeclaredCopyAssignmentWithConstParam
1996       = FromData.HasDeclaredCopyAssignmentWithConstParam;
1997     ToData.IsLambda = FromData.IsLambda;
1998 
1999     SmallVector<CXXBaseSpecifier *, 4> Bases;
2000     for (const auto &Base1 : FromCXX->bases()) {
2001       QualType T = Importer.Import(Base1.getType());
2002       if (T.isNull())
2003         return true;
2004 
2005       SourceLocation EllipsisLoc;
2006       if (Base1.isPackExpansion())
2007         EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2008 
2009       // Ensure that we have a definition for the base.
2010       ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2011 
2012       Bases.push_back(
2013                     new (Importer.getToContext())
2014                       CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2015                                        Base1.isVirtual(),
2016                                        Base1.isBaseOfClass(),
2017                                        Base1.getAccessSpecifierAsWritten(),
2018                                    Importer.Import(Base1.getTypeSourceInfo()),
2019                                        EllipsisLoc));
2020     }
2021     if (!Bases.empty())
2022       ToCXX->setBases(Bases.data(), Bases.size());
2023   }
2024 
2025   if (shouldForceImportDeclContext(Kind))
2026     ImportDeclContext(From, /*ForceImport=*/true);
2027 
2028   To->completeDefinition();
2029   return false;
2030 }
2031 
ImportDefinition(VarDecl * From,VarDecl * To,ImportDefinitionKind Kind)2032 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2033                                        ImportDefinitionKind Kind) {
2034   if (To->getDefinition())
2035     return false;
2036 
2037   // FIXME: Can we really import any initializer? Alternatively, we could force
2038   // ourselves to import every declaration of a variable and then only use
2039   // getInit() here.
2040   To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2041 
2042   // FIXME: Other bits to merge?
2043 
2044   return false;
2045 }
2046 
ImportDefinition(EnumDecl * From,EnumDecl * To,ImportDefinitionKind Kind)2047 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2048                                        ImportDefinitionKind Kind) {
2049   if (To->getDefinition() || To->isBeingDefined()) {
2050     if (Kind == IDK_Everything)
2051       ImportDeclContext(From, /*ForceImport=*/true);
2052     return false;
2053   }
2054 
2055   To->startDefinition();
2056 
2057   QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2058   if (T.isNull())
2059     return true;
2060 
2061   QualType ToPromotionType = Importer.Import(From->getPromotionType());
2062   if (ToPromotionType.isNull())
2063     return true;
2064 
2065   if (shouldForceImportDeclContext(Kind))
2066     ImportDeclContext(From, /*ForceImport=*/true);
2067 
2068   // FIXME: we might need to merge the number of positive or negative bits
2069   // if the enumerator lists don't match.
2070   To->completeDefinition(T, ToPromotionType,
2071                          From->getNumPositiveBits(),
2072                          From->getNumNegativeBits());
2073   return false;
2074 }
2075 
ImportTemplateParameterList(TemplateParameterList * Params)2076 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2077                                                 TemplateParameterList *Params) {
2078   SmallVector<NamedDecl *, 4> ToParams;
2079   ToParams.reserve(Params->size());
2080   for (TemplateParameterList::iterator P = Params->begin(),
2081                                     PEnd = Params->end();
2082        P != PEnd; ++P) {
2083     Decl *To = Importer.Import(*P);
2084     if (!To)
2085       return nullptr;
2086 
2087     ToParams.push_back(cast<NamedDecl>(To));
2088   }
2089 
2090   return TemplateParameterList::Create(Importer.getToContext(),
2091                                        Importer.Import(Params->getTemplateLoc()),
2092                                        Importer.Import(Params->getLAngleLoc()),
2093                                        ToParams.data(), ToParams.size(),
2094                                        Importer.Import(Params->getRAngleLoc()));
2095 }
2096 
2097 TemplateArgument
ImportTemplateArgument(const TemplateArgument & From)2098 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2099   switch (From.getKind()) {
2100   case TemplateArgument::Null:
2101     return TemplateArgument();
2102 
2103   case TemplateArgument::Type: {
2104     QualType ToType = Importer.Import(From.getAsType());
2105     if (ToType.isNull())
2106       return TemplateArgument();
2107     return TemplateArgument(ToType);
2108   }
2109 
2110   case TemplateArgument::Integral: {
2111     QualType ToType = Importer.Import(From.getIntegralType());
2112     if (ToType.isNull())
2113       return TemplateArgument();
2114     return TemplateArgument(From, ToType);
2115   }
2116 
2117   case TemplateArgument::Declaration: {
2118     ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2119     QualType ToType = Importer.Import(From.getParamTypeForDecl());
2120     if (!To || ToType.isNull())
2121       return TemplateArgument();
2122     return TemplateArgument(To, ToType);
2123   }
2124 
2125   case TemplateArgument::NullPtr: {
2126     QualType ToType = Importer.Import(From.getNullPtrType());
2127     if (ToType.isNull())
2128       return TemplateArgument();
2129     return TemplateArgument(ToType, /*isNullPtr*/true);
2130   }
2131 
2132   case TemplateArgument::Template: {
2133     TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2134     if (ToTemplate.isNull())
2135       return TemplateArgument();
2136 
2137     return TemplateArgument(ToTemplate);
2138   }
2139 
2140   case TemplateArgument::TemplateExpansion: {
2141     TemplateName ToTemplate
2142       = Importer.Import(From.getAsTemplateOrTemplatePattern());
2143     if (ToTemplate.isNull())
2144       return TemplateArgument();
2145 
2146     return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2147   }
2148 
2149   case TemplateArgument::Expression:
2150     if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2151       return TemplateArgument(ToExpr);
2152     return TemplateArgument();
2153 
2154   case TemplateArgument::Pack: {
2155     SmallVector<TemplateArgument, 2> ToPack;
2156     ToPack.reserve(From.pack_size());
2157     if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2158       return TemplateArgument();
2159 
2160     TemplateArgument *ToArgs
2161       = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
2162     std::copy(ToPack.begin(), ToPack.end(), ToArgs);
2163     return TemplateArgument(ToArgs, ToPack.size());
2164   }
2165   }
2166 
2167   llvm_unreachable("Invalid template argument kind");
2168 }
2169 
ImportTemplateArguments(const TemplateArgument * FromArgs,unsigned NumFromArgs,SmallVectorImpl<TemplateArgument> & ToArgs)2170 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2171                                               unsigned NumFromArgs,
2172                               SmallVectorImpl<TemplateArgument> &ToArgs) {
2173   for (unsigned I = 0; I != NumFromArgs; ++I) {
2174     TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2175     if (To.isNull() && !FromArgs[I].isNull())
2176       return true;
2177 
2178     ToArgs.push_back(To);
2179   }
2180 
2181   return false;
2182 }
2183 
IsStructuralMatch(RecordDecl * FromRecord,RecordDecl * ToRecord,bool Complain)2184 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2185                                         RecordDecl *ToRecord, bool Complain) {
2186   // Eliminate a potential failure point where we attempt to re-import
2187   // something we're trying to import while completing ToRecord.
2188   Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2189   if (ToOrigin) {
2190     RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2191     if (ToOriginRecord)
2192       ToRecord = ToOriginRecord;
2193   }
2194 
2195   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2196                                    ToRecord->getASTContext(),
2197                                    Importer.getNonEquivalentDecls(),
2198                                    false, Complain);
2199   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2200 }
2201 
IsStructuralMatch(VarDecl * FromVar,VarDecl * ToVar,bool Complain)2202 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2203                                         bool Complain) {
2204   StructuralEquivalenceContext Ctx(
2205       Importer.getFromContext(), Importer.getToContext(),
2206       Importer.getNonEquivalentDecls(), false, Complain);
2207   return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2208 }
2209 
IsStructuralMatch(EnumDecl * FromEnum,EnumDecl * ToEnum)2210 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2211   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2212                                    Importer.getToContext(),
2213                                    Importer.getNonEquivalentDecls());
2214   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2215 }
2216 
IsStructuralMatch(EnumConstantDecl * FromEC,EnumConstantDecl * ToEC)2217 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2218                                         EnumConstantDecl *ToEC)
2219 {
2220   const llvm::APSInt &FromVal = FromEC->getInitVal();
2221   const llvm::APSInt &ToVal = ToEC->getInitVal();
2222 
2223   return FromVal.isSigned() == ToVal.isSigned() &&
2224          FromVal.getBitWidth() == ToVal.getBitWidth() &&
2225          FromVal == ToVal;
2226 }
2227 
IsStructuralMatch(ClassTemplateDecl * From,ClassTemplateDecl * To)2228 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2229                                         ClassTemplateDecl *To) {
2230   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2231                                    Importer.getToContext(),
2232                                    Importer.getNonEquivalentDecls());
2233   return Ctx.IsStructurallyEquivalent(From, To);
2234 }
2235 
IsStructuralMatch(VarTemplateDecl * From,VarTemplateDecl * To)2236 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2237                                         VarTemplateDecl *To) {
2238   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2239                                    Importer.getToContext(),
2240                                    Importer.getNonEquivalentDecls());
2241   return Ctx.IsStructurallyEquivalent(From, To);
2242 }
2243 
VisitDecl(Decl * D)2244 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2245   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2246     << D->getDeclKindName();
2247   return nullptr;
2248 }
2249 
VisitTranslationUnitDecl(TranslationUnitDecl * D)2250 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2251   TranslationUnitDecl *ToD =
2252     Importer.getToContext().getTranslationUnitDecl();
2253 
2254   Importer.Imported(D, ToD);
2255 
2256   return ToD;
2257 }
2258 
VisitNamespaceDecl(NamespaceDecl * D)2259 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2260   // Import the major distinguishing characteristics of this namespace.
2261   DeclContext *DC, *LexicalDC;
2262   DeclarationName Name;
2263   SourceLocation Loc;
2264   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2265     return nullptr;
2266 
2267   NamespaceDecl *MergeWithNamespace = nullptr;
2268   if (!Name) {
2269     // This is an anonymous namespace. Adopt an existing anonymous
2270     // namespace if we can.
2271     // FIXME: Not testable.
2272     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2273       MergeWithNamespace = TU->getAnonymousNamespace();
2274     else
2275       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2276   } else {
2277     SmallVector<NamedDecl *, 4> ConflictingDecls;
2278     SmallVector<NamedDecl *, 2> FoundDecls;
2279     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2280     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2281       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2282         continue;
2283 
2284       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2285         MergeWithNamespace = FoundNS;
2286         ConflictingDecls.clear();
2287         break;
2288       }
2289 
2290       ConflictingDecls.push_back(FoundDecls[I]);
2291     }
2292 
2293     if (!ConflictingDecls.empty()) {
2294       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2295                                          ConflictingDecls.data(),
2296                                          ConflictingDecls.size());
2297     }
2298   }
2299 
2300   // Create the "to" namespace, if needed.
2301   NamespaceDecl *ToNamespace = MergeWithNamespace;
2302   if (!ToNamespace) {
2303     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2304                                         D->isInline(),
2305                                         Importer.Import(D->getLocStart()),
2306                                         Loc, Name.getAsIdentifierInfo(),
2307                                         /*PrevDecl=*/nullptr);
2308     ToNamespace->setLexicalDeclContext(LexicalDC);
2309     LexicalDC->addDeclInternal(ToNamespace);
2310 
2311     // If this is an anonymous namespace, register it as the anonymous
2312     // namespace within its context.
2313     if (!Name) {
2314       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2315         TU->setAnonymousNamespace(ToNamespace);
2316       else
2317         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2318     }
2319   }
2320   Importer.Imported(D, ToNamespace);
2321 
2322   ImportDeclContext(D);
2323 
2324   return ToNamespace;
2325 }
2326 
VisitTypedefNameDecl(TypedefNameDecl * D,bool IsAlias)2327 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2328   // Import the major distinguishing characteristics of this typedef.
2329   DeclContext *DC, *LexicalDC;
2330   DeclarationName Name;
2331   SourceLocation Loc;
2332   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2333     return nullptr;
2334 
2335   // If this typedef is not in block scope, determine whether we've
2336   // seen a typedef with the same name (that we can merge with) or any
2337   // other entity by that name (which name lookup could conflict with).
2338   if (!DC->isFunctionOrMethod()) {
2339     SmallVector<NamedDecl *, 4> ConflictingDecls;
2340     unsigned IDNS = Decl::IDNS_Ordinary;
2341     SmallVector<NamedDecl *, 2> FoundDecls;
2342     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2343     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2344       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2345         continue;
2346       if (TypedefNameDecl *FoundTypedef =
2347             dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2348         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2349                                             FoundTypedef->getUnderlyingType()))
2350           return Importer.Imported(D, FoundTypedef);
2351       }
2352 
2353       ConflictingDecls.push_back(FoundDecls[I]);
2354     }
2355 
2356     if (!ConflictingDecls.empty()) {
2357       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2358                                          ConflictingDecls.data(),
2359                                          ConflictingDecls.size());
2360       if (!Name)
2361         return nullptr;
2362     }
2363   }
2364 
2365   // Import the underlying type of this typedef;
2366   QualType T = Importer.Import(D->getUnderlyingType());
2367   if (T.isNull())
2368     return nullptr;
2369 
2370   // Create the new typedef node.
2371   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2372   SourceLocation StartL = Importer.Import(D->getLocStart());
2373   TypedefNameDecl *ToTypedef;
2374   if (IsAlias)
2375     ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2376                                       StartL, Loc,
2377                                       Name.getAsIdentifierInfo(),
2378                                       TInfo);
2379   else
2380     ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2381                                     StartL, Loc,
2382                                     Name.getAsIdentifierInfo(),
2383                                     TInfo);
2384 
2385   ToTypedef->setAccess(D->getAccess());
2386   ToTypedef->setLexicalDeclContext(LexicalDC);
2387   Importer.Imported(D, ToTypedef);
2388   LexicalDC->addDeclInternal(ToTypedef);
2389 
2390   return ToTypedef;
2391 }
2392 
VisitTypedefDecl(TypedefDecl * D)2393 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2394   return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2395 }
2396 
VisitTypeAliasDecl(TypeAliasDecl * D)2397 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2398   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2399 }
2400 
VisitEnumDecl(EnumDecl * D)2401 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2402   // Import the major distinguishing characteristics of this enum.
2403   DeclContext *DC, *LexicalDC;
2404   DeclarationName Name;
2405   SourceLocation Loc;
2406   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2407     return nullptr;
2408 
2409   // Figure out what enum name we're looking for.
2410   unsigned IDNS = Decl::IDNS_Tag;
2411   DeclarationName SearchName = Name;
2412   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2413     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2414     IDNS = Decl::IDNS_Ordinary;
2415   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2416     IDNS |= Decl::IDNS_Ordinary;
2417 
2418   // We may already have an enum of the same name; try to find and match it.
2419   if (!DC->isFunctionOrMethod() && SearchName) {
2420     SmallVector<NamedDecl *, 4> ConflictingDecls;
2421     SmallVector<NamedDecl *, 2> FoundDecls;
2422     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2423     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2424       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2425         continue;
2426 
2427       Decl *Found = FoundDecls[I];
2428       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2429         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2430           Found = Tag->getDecl();
2431       }
2432 
2433       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2434         if (IsStructuralMatch(D, FoundEnum))
2435           return Importer.Imported(D, FoundEnum);
2436       }
2437 
2438       ConflictingDecls.push_back(FoundDecls[I]);
2439     }
2440 
2441     if (!ConflictingDecls.empty()) {
2442       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2443                                          ConflictingDecls.data(),
2444                                          ConflictingDecls.size());
2445     }
2446   }
2447 
2448   // Create the enum declaration.
2449   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2450                                   Importer.Import(D->getLocStart()),
2451                                   Loc, Name.getAsIdentifierInfo(), nullptr,
2452                                   D->isScoped(), D->isScopedUsingClassTag(),
2453                                   D->isFixed());
2454   // Import the qualifier, if any.
2455   D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2456   D2->setAccess(D->getAccess());
2457   D2->setLexicalDeclContext(LexicalDC);
2458   Importer.Imported(D, D2);
2459   LexicalDC->addDeclInternal(D2);
2460 
2461   // Import the integer type.
2462   QualType ToIntegerType = Importer.Import(D->getIntegerType());
2463   if (ToIntegerType.isNull())
2464     return nullptr;
2465   D2->setIntegerType(ToIntegerType);
2466 
2467   // Import the definition
2468   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2469     return nullptr;
2470 
2471   return D2;
2472 }
2473 
VisitRecordDecl(RecordDecl * D)2474 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2475   // If this record has a definition in the translation unit we're coming from,
2476   // but this particular declaration is not that definition, import the
2477   // definition and map to that.
2478   TagDecl *Definition = D->getDefinition();
2479   if (Definition && Definition != D) {
2480     Decl *ImportedDef = Importer.Import(Definition);
2481     if (!ImportedDef)
2482       return nullptr;
2483 
2484     return Importer.Imported(D, ImportedDef);
2485   }
2486 
2487   // Import the major distinguishing characteristics of this record.
2488   DeclContext *DC, *LexicalDC;
2489   DeclarationName Name;
2490   SourceLocation Loc;
2491   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2492     return nullptr;
2493 
2494   // Figure out what structure name we're looking for.
2495   unsigned IDNS = Decl::IDNS_Tag;
2496   DeclarationName SearchName = Name;
2497   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2498     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2499     IDNS = Decl::IDNS_Ordinary;
2500   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2501     IDNS |= Decl::IDNS_Ordinary;
2502 
2503   // We may already have a record of the same name; try to find and match it.
2504   RecordDecl *AdoptDecl = nullptr;
2505   if (!DC->isFunctionOrMethod()) {
2506     SmallVector<NamedDecl *, 4> ConflictingDecls;
2507     SmallVector<NamedDecl *, 2> FoundDecls;
2508     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2509     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2510       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2511         continue;
2512 
2513       Decl *Found = FoundDecls[I];
2514       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2515         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2516           Found = Tag->getDecl();
2517       }
2518 
2519       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2520         if (D->isAnonymousStructOrUnion() &&
2521             FoundRecord->isAnonymousStructOrUnion()) {
2522           // If both anonymous structs/unions are in a record context, make sure
2523           // they occur in the same location in the context records.
2524           if (Optional<unsigned> Index1
2525               = findAnonymousStructOrUnionIndex(D)) {
2526             if (Optional<unsigned> Index2 =
2527                     findAnonymousStructOrUnionIndex(FoundRecord)) {
2528               if (*Index1 != *Index2)
2529                 continue;
2530             }
2531           }
2532         }
2533 
2534         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2535           if ((SearchName && !D->isCompleteDefinition())
2536               || (D->isCompleteDefinition() &&
2537                   D->isAnonymousStructOrUnion()
2538                     == FoundDef->isAnonymousStructOrUnion() &&
2539                   IsStructuralMatch(D, FoundDef))) {
2540             // The record types structurally match, or the "from" translation
2541             // unit only had a forward declaration anyway; call it the same
2542             // function.
2543             // FIXME: For C++, we should also merge methods here.
2544             return Importer.Imported(D, FoundDef);
2545           }
2546         } else if (!D->isCompleteDefinition()) {
2547           // We have a forward declaration of this type, so adopt that forward
2548           // declaration rather than building a new one.
2549 
2550           // If one or both can be completed from external storage then try one
2551           // last time to complete and compare them before doing this.
2552 
2553           if (FoundRecord->hasExternalLexicalStorage() &&
2554               !FoundRecord->isCompleteDefinition())
2555             FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2556           if (D->hasExternalLexicalStorage())
2557             D->getASTContext().getExternalSource()->CompleteType(D);
2558 
2559           if (FoundRecord->isCompleteDefinition() &&
2560               D->isCompleteDefinition() &&
2561               !IsStructuralMatch(D, FoundRecord))
2562             continue;
2563 
2564           AdoptDecl = FoundRecord;
2565           continue;
2566         } else if (!SearchName) {
2567           continue;
2568         }
2569       }
2570 
2571       ConflictingDecls.push_back(FoundDecls[I]);
2572     }
2573 
2574     if (!ConflictingDecls.empty() && SearchName) {
2575       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2576                                          ConflictingDecls.data(),
2577                                          ConflictingDecls.size());
2578     }
2579   }
2580 
2581   // Create the record declaration.
2582   RecordDecl *D2 = AdoptDecl;
2583   SourceLocation StartLoc = Importer.Import(D->getLocStart());
2584   if (!D2) {
2585     if (isa<CXXRecordDecl>(D)) {
2586       CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2587                                                    D->getTagKind(),
2588                                                    DC, StartLoc, Loc,
2589                                                    Name.getAsIdentifierInfo());
2590       D2 = D2CXX;
2591       D2->setAccess(D->getAccess());
2592     } else {
2593       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2594                               DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2595     }
2596 
2597     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2598     D2->setLexicalDeclContext(LexicalDC);
2599     LexicalDC->addDeclInternal(D2);
2600     if (D->isAnonymousStructOrUnion())
2601       D2->setAnonymousStructOrUnion(true);
2602   }
2603 
2604   Importer.Imported(D, D2);
2605 
2606   if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2607     return nullptr;
2608 
2609   return D2;
2610 }
2611 
VisitEnumConstantDecl(EnumConstantDecl * D)2612 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2613   // Import the major distinguishing characteristics of this enumerator.
2614   DeclContext *DC, *LexicalDC;
2615   DeclarationName Name;
2616   SourceLocation Loc;
2617   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2618     return nullptr;
2619 
2620   QualType T = Importer.Import(D->getType());
2621   if (T.isNull())
2622     return nullptr;
2623 
2624   // Determine whether there are any other declarations with the same name and
2625   // in the same context.
2626   if (!LexicalDC->isFunctionOrMethod()) {
2627     SmallVector<NamedDecl *, 4> ConflictingDecls;
2628     unsigned IDNS = Decl::IDNS_Ordinary;
2629     SmallVector<NamedDecl *, 2> FoundDecls;
2630     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2631     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2632       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2633         continue;
2634 
2635       if (EnumConstantDecl *FoundEnumConstant
2636             = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2637         if (IsStructuralMatch(D, FoundEnumConstant))
2638           return Importer.Imported(D, FoundEnumConstant);
2639       }
2640 
2641       ConflictingDecls.push_back(FoundDecls[I]);
2642     }
2643 
2644     if (!ConflictingDecls.empty()) {
2645       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2646                                          ConflictingDecls.data(),
2647                                          ConflictingDecls.size());
2648       if (!Name)
2649         return nullptr;
2650     }
2651   }
2652 
2653   Expr *Init = Importer.Import(D->getInitExpr());
2654   if (D->getInitExpr() && !Init)
2655     return nullptr;
2656 
2657   EnumConstantDecl *ToEnumerator
2658     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2659                                Name.getAsIdentifierInfo(), T,
2660                                Init, D->getInitVal());
2661   ToEnumerator->setAccess(D->getAccess());
2662   ToEnumerator->setLexicalDeclContext(LexicalDC);
2663   Importer.Imported(D, ToEnumerator);
2664   LexicalDC->addDeclInternal(ToEnumerator);
2665   return ToEnumerator;
2666 }
2667 
VisitFunctionDecl(FunctionDecl * D)2668 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2669   // Import the major distinguishing characteristics of this function.
2670   DeclContext *DC, *LexicalDC;
2671   DeclarationName Name;
2672   SourceLocation Loc;
2673   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2674     return nullptr;
2675 
2676   // Try to find a function in our own ("to") context with the same name, same
2677   // type, and in the same context as the function we're importing.
2678   if (!LexicalDC->isFunctionOrMethod()) {
2679     SmallVector<NamedDecl *, 4> ConflictingDecls;
2680     unsigned IDNS = Decl::IDNS_Ordinary;
2681     SmallVector<NamedDecl *, 2> FoundDecls;
2682     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2683     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2684       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2685         continue;
2686 
2687       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2688         if (FoundFunction->hasExternalFormalLinkage() &&
2689             D->hasExternalFormalLinkage()) {
2690           if (Importer.IsStructurallyEquivalent(D->getType(),
2691                                                 FoundFunction->getType())) {
2692             // FIXME: Actually try to merge the body and other attributes.
2693             return Importer.Imported(D, FoundFunction);
2694           }
2695 
2696           // FIXME: Check for overloading more carefully, e.g., by boosting
2697           // Sema::IsOverload out to the AST library.
2698 
2699           // Function overloading is okay in C++.
2700           if (Importer.getToContext().getLangOpts().CPlusPlus)
2701             continue;
2702 
2703           // Complain about inconsistent function types.
2704           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2705             << Name << D->getType() << FoundFunction->getType();
2706           Importer.ToDiag(FoundFunction->getLocation(),
2707                           diag::note_odr_value_here)
2708             << FoundFunction->getType();
2709         }
2710       }
2711 
2712       ConflictingDecls.push_back(FoundDecls[I]);
2713     }
2714 
2715     if (!ConflictingDecls.empty()) {
2716       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2717                                          ConflictingDecls.data(),
2718                                          ConflictingDecls.size());
2719       if (!Name)
2720         return nullptr;
2721     }
2722   }
2723 
2724   DeclarationNameInfo NameInfo(Name, Loc);
2725   // Import additional name location/type info.
2726   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2727 
2728   QualType FromTy = D->getType();
2729   bool usedDifferentExceptionSpec = false;
2730 
2731   if (const FunctionProtoType *
2732         FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2733     FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2734     // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2735     // FunctionDecl that we are importing the FunctionProtoType for.
2736     // To avoid an infinite recursion when importing, create the FunctionDecl
2737     // with a simplified function type and update it afterwards.
2738     if (FromEPI.ExceptionSpec.SourceDecl ||
2739         FromEPI.ExceptionSpec.SourceTemplate ||
2740         FromEPI.ExceptionSpec.NoexceptExpr) {
2741       FunctionProtoType::ExtProtoInfo DefaultEPI;
2742       FromTy = Importer.getFromContext().getFunctionType(
2743           FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2744       usedDifferentExceptionSpec = true;
2745     }
2746   }
2747 
2748   // Import the type.
2749   QualType T = Importer.Import(FromTy);
2750   if (T.isNull())
2751     return nullptr;
2752 
2753   // Import the function parameters.
2754   SmallVector<ParmVarDecl *, 8> Parameters;
2755   for (auto P : D->params()) {
2756     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2757     if (!ToP)
2758       return nullptr;
2759 
2760     Parameters.push_back(ToP);
2761   }
2762 
2763   // Create the imported function.
2764   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2765   FunctionDecl *ToFunction = nullptr;
2766   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2767     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2768                                             cast<CXXRecordDecl>(DC),
2769                                             D->getInnerLocStart(),
2770                                             NameInfo, T, TInfo,
2771                                             FromConstructor->isExplicit(),
2772                                             D->isInlineSpecified(),
2773                                             D->isImplicit(),
2774                                             D->isConstexpr());
2775   } else if (isa<CXXDestructorDecl>(D)) {
2776     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2777                                            cast<CXXRecordDecl>(DC),
2778                                            D->getInnerLocStart(),
2779                                            NameInfo, T, TInfo,
2780                                            D->isInlineSpecified(),
2781                                            D->isImplicit());
2782   } else if (CXXConversionDecl *FromConversion
2783                                            = dyn_cast<CXXConversionDecl>(D)) {
2784     ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2785                                            cast<CXXRecordDecl>(DC),
2786                                            D->getInnerLocStart(),
2787                                            NameInfo, T, TInfo,
2788                                            D->isInlineSpecified(),
2789                                            FromConversion->isExplicit(),
2790                                            D->isConstexpr(),
2791                                            Importer.Import(D->getLocEnd()));
2792   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2793     ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2794                                        cast<CXXRecordDecl>(DC),
2795                                        D->getInnerLocStart(),
2796                                        NameInfo, T, TInfo,
2797                                        Method->getStorageClass(),
2798                                        Method->isInlineSpecified(),
2799                                        D->isConstexpr(),
2800                                        Importer.Import(D->getLocEnd()));
2801   } else {
2802     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2803                                       D->getInnerLocStart(),
2804                                       NameInfo, T, TInfo, D->getStorageClass(),
2805                                       D->isInlineSpecified(),
2806                                       D->hasWrittenPrototype(),
2807                                       D->isConstexpr());
2808   }
2809 
2810   // Import the qualifier, if any.
2811   ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2812   ToFunction->setAccess(D->getAccess());
2813   ToFunction->setLexicalDeclContext(LexicalDC);
2814   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2815   ToFunction->setTrivial(D->isTrivial());
2816   ToFunction->setPure(D->isPure());
2817   Importer.Imported(D, ToFunction);
2818 
2819   // Set the parameters.
2820   for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2821     Parameters[I]->setOwningFunction(ToFunction);
2822     ToFunction->addDeclInternal(Parameters[I]);
2823   }
2824   ToFunction->setParams(Parameters);
2825 
2826   if (usedDifferentExceptionSpec) {
2827     // Update FunctionProtoType::ExtProtoInfo.
2828     QualType T = Importer.Import(D->getType());
2829     if (T.isNull())
2830       return nullptr;
2831     ToFunction->setType(T);
2832   }
2833 
2834   // FIXME: Other bits to merge?
2835 
2836   // Add this function to the lexical context.
2837   LexicalDC->addDeclInternal(ToFunction);
2838 
2839   return ToFunction;
2840 }
2841 
VisitCXXMethodDecl(CXXMethodDecl * D)2842 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2843   return VisitFunctionDecl(D);
2844 }
2845 
VisitCXXConstructorDecl(CXXConstructorDecl * D)2846 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2847   return VisitCXXMethodDecl(D);
2848 }
2849 
VisitCXXDestructorDecl(CXXDestructorDecl * D)2850 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2851   return VisitCXXMethodDecl(D);
2852 }
2853 
VisitCXXConversionDecl(CXXConversionDecl * D)2854 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2855   return VisitCXXMethodDecl(D);
2856 }
2857 
getFieldIndex(Decl * F)2858 static unsigned getFieldIndex(Decl *F) {
2859   RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2860   if (!Owner)
2861     return 0;
2862 
2863   unsigned Index = 1;
2864   for (const auto *D : Owner->noload_decls()) {
2865     if (D == F)
2866       return Index;
2867 
2868     if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2869       ++Index;
2870   }
2871 
2872   return Index;
2873 }
2874 
VisitFieldDecl(FieldDecl * D)2875 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2876   // Import the major distinguishing characteristics of a variable.
2877   DeclContext *DC, *LexicalDC;
2878   DeclarationName Name;
2879   SourceLocation Loc;
2880   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2881     return nullptr;
2882 
2883   // Determine whether we've already imported this field.
2884   SmallVector<NamedDecl *, 2> FoundDecls;
2885   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2886   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2887     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2888       // For anonymous fields, match up by index.
2889       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2890         continue;
2891 
2892       if (Importer.IsStructurallyEquivalent(D->getType(),
2893                                             FoundField->getType())) {
2894         Importer.Imported(D, FoundField);
2895         return FoundField;
2896       }
2897 
2898       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2899         << Name << D->getType() << FoundField->getType();
2900       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2901         << FoundField->getType();
2902       return nullptr;
2903     }
2904   }
2905 
2906   // Import the type.
2907   QualType T = Importer.Import(D->getType());
2908   if (T.isNull())
2909     return nullptr;
2910 
2911   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2912   Expr *BitWidth = Importer.Import(D->getBitWidth());
2913   if (!BitWidth && D->getBitWidth())
2914     return nullptr;
2915 
2916   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2917                                          Importer.Import(D->getInnerLocStart()),
2918                                          Loc, Name.getAsIdentifierInfo(),
2919                                          T, TInfo, BitWidth, D->isMutable(),
2920                                          D->getInClassInitStyle());
2921   ToField->setAccess(D->getAccess());
2922   ToField->setLexicalDeclContext(LexicalDC);
2923   if (ToField->hasInClassInitializer())
2924     ToField->setInClassInitializer(D->getInClassInitializer());
2925   ToField->setImplicit(D->isImplicit());
2926   Importer.Imported(D, ToField);
2927   LexicalDC->addDeclInternal(ToField);
2928   return ToField;
2929 }
2930 
VisitIndirectFieldDecl(IndirectFieldDecl * D)2931 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2932   // Import the major distinguishing characteristics of a variable.
2933   DeclContext *DC, *LexicalDC;
2934   DeclarationName Name;
2935   SourceLocation Loc;
2936   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2937     return nullptr;
2938 
2939   // Determine whether we've already imported this field.
2940   SmallVector<NamedDecl *, 2> FoundDecls;
2941   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2942   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2943     if (IndirectFieldDecl *FoundField
2944                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2945       // For anonymous indirect fields, match up by index.
2946       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2947         continue;
2948 
2949       if (Importer.IsStructurallyEquivalent(D->getType(),
2950                                             FoundField->getType(),
2951                                             !Name.isEmpty())) {
2952         Importer.Imported(D, FoundField);
2953         return FoundField;
2954       }
2955 
2956       // If there are more anonymous fields to check, continue.
2957       if (!Name && I < N-1)
2958         continue;
2959 
2960       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2961         << Name << D->getType() << FoundField->getType();
2962       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2963         << FoundField->getType();
2964       return nullptr;
2965     }
2966   }
2967 
2968   // Import the type.
2969   QualType T = Importer.Import(D->getType());
2970   if (T.isNull())
2971     return nullptr;
2972 
2973   NamedDecl **NamedChain =
2974     new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2975 
2976   unsigned i = 0;
2977   for (auto *PI : D->chain()) {
2978     Decl *D = Importer.Import(PI);
2979     if (!D)
2980       return nullptr;
2981     NamedChain[i++] = cast<NamedDecl>(D);
2982   }
2983 
2984   IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2985       Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
2986       NamedChain, D->getChainingSize());
2987 
2988   for (const auto *Attr : D->attrs())
2989     ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
2990 
2991   ToIndirectField->setAccess(D->getAccess());
2992   ToIndirectField->setLexicalDeclContext(LexicalDC);
2993   Importer.Imported(D, ToIndirectField);
2994   LexicalDC->addDeclInternal(ToIndirectField);
2995   return ToIndirectField;
2996 }
2997 
VisitObjCIvarDecl(ObjCIvarDecl * D)2998 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2999   // Import the major distinguishing characteristics of an ivar.
3000   DeclContext *DC, *LexicalDC;
3001   DeclarationName Name;
3002   SourceLocation Loc;
3003   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3004     return nullptr;
3005 
3006   // Determine whether we've already imported this ivar
3007   SmallVector<NamedDecl *, 2> FoundDecls;
3008   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3009   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3010     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3011       if (Importer.IsStructurallyEquivalent(D->getType(),
3012                                             FoundIvar->getType())) {
3013         Importer.Imported(D, FoundIvar);
3014         return FoundIvar;
3015       }
3016 
3017       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3018         << Name << D->getType() << FoundIvar->getType();
3019       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3020         << FoundIvar->getType();
3021       return nullptr;
3022     }
3023   }
3024 
3025   // Import the type.
3026   QualType T = Importer.Import(D->getType());
3027   if (T.isNull())
3028     return nullptr;
3029 
3030   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3031   Expr *BitWidth = Importer.Import(D->getBitWidth());
3032   if (!BitWidth && D->getBitWidth())
3033     return nullptr;
3034 
3035   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3036                                               cast<ObjCContainerDecl>(DC),
3037                                        Importer.Import(D->getInnerLocStart()),
3038                                               Loc, Name.getAsIdentifierInfo(),
3039                                               T, TInfo, D->getAccessControl(),
3040                                               BitWidth, D->getSynthesize());
3041   ToIvar->setLexicalDeclContext(LexicalDC);
3042   Importer.Imported(D, ToIvar);
3043   LexicalDC->addDeclInternal(ToIvar);
3044   return ToIvar;
3045 
3046 }
3047 
VisitVarDecl(VarDecl * D)3048 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3049   // Import the major distinguishing characteristics of a variable.
3050   DeclContext *DC, *LexicalDC;
3051   DeclarationName Name;
3052   SourceLocation Loc;
3053   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3054     return nullptr;
3055 
3056   // Try to find a variable in our own ("to") context with the same name and
3057   // in the same context as the variable we're importing.
3058   if (D->isFileVarDecl()) {
3059     VarDecl *MergeWithVar = nullptr;
3060     SmallVector<NamedDecl *, 4> ConflictingDecls;
3061     unsigned IDNS = Decl::IDNS_Ordinary;
3062     SmallVector<NamedDecl *, 2> FoundDecls;
3063     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3064     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3065       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3066         continue;
3067 
3068       if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3069         // We have found a variable that we may need to merge with. Check it.
3070         if (FoundVar->hasExternalFormalLinkage() &&
3071             D->hasExternalFormalLinkage()) {
3072           if (Importer.IsStructurallyEquivalent(D->getType(),
3073                                                 FoundVar->getType())) {
3074             MergeWithVar = FoundVar;
3075             break;
3076           }
3077 
3078           const ArrayType *FoundArray
3079             = Importer.getToContext().getAsArrayType(FoundVar->getType());
3080           const ArrayType *TArray
3081             = Importer.getToContext().getAsArrayType(D->getType());
3082           if (FoundArray && TArray) {
3083             if (isa<IncompleteArrayType>(FoundArray) &&
3084                 isa<ConstantArrayType>(TArray)) {
3085               // Import the type.
3086               QualType T = Importer.Import(D->getType());
3087               if (T.isNull())
3088                 return nullptr;
3089 
3090               FoundVar->setType(T);
3091               MergeWithVar = FoundVar;
3092               break;
3093             } else if (isa<IncompleteArrayType>(TArray) &&
3094                        isa<ConstantArrayType>(FoundArray)) {
3095               MergeWithVar = FoundVar;
3096               break;
3097             }
3098           }
3099 
3100           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3101             << Name << D->getType() << FoundVar->getType();
3102           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3103             << FoundVar->getType();
3104         }
3105       }
3106 
3107       ConflictingDecls.push_back(FoundDecls[I]);
3108     }
3109 
3110     if (MergeWithVar) {
3111       // An equivalent variable with external linkage has been found. Link
3112       // the two declarations, then merge them.
3113       Importer.Imported(D, MergeWithVar);
3114 
3115       if (VarDecl *DDef = D->getDefinition()) {
3116         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3117           Importer.ToDiag(ExistingDef->getLocation(),
3118                           diag::err_odr_variable_multiple_def)
3119             << Name;
3120           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3121         } else {
3122           Expr *Init = Importer.Import(DDef->getInit());
3123           MergeWithVar->setInit(Init);
3124           if (DDef->isInitKnownICE()) {
3125             EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3126             Eval->CheckedICE = true;
3127             Eval->IsICE = DDef->isInitICE();
3128           }
3129         }
3130       }
3131 
3132       return MergeWithVar;
3133     }
3134 
3135     if (!ConflictingDecls.empty()) {
3136       Name = Importer.HandleNameConflict(Name, DC, IDNS,
3137                                          ConflictingDecls.data(),
3138                                          ConflictingDecls.size());
3139       if (!Name)
3140         return nullptr;
3141     }
3142   }
3143 
3144   // Import the type.
3145   QualType T = Importer.Import(D->getType());
3146   if (T.isNull())
3147     return nullptr;
3148 
3149   // Create the imported variable.
3150   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3151   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3152                                    Importer.Import(D->getInnerLocStart()),
3153                                    Loc, Name.getAsIdentifierInfo(),
3154                                    T, TInfo,
3155                                    D->getStorageClass());
3156   ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3157   ToVar->setAccess(D->getAccess());
3158   ToVar->setLexicalDeclContext(LexicalDC);
3159   Importer.Imported(D, ToVar);
3160   LexicalDC->addDeclInternal(ToVar);
3161 
3162   // Merge the initializer.
3163   if (ImportDefinition(D, ToVar))
3164     return nullptr;
3165 
3166   return ToVar;
3167 }
3168 
VisitImplicitParamDecl(ImplicitParamDecl * D)3169 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3170   // Parameters are created in the translation unit's context, then moved
3171   // into the function declaration's context afterward.
3172   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3173 
3174   // Import the name of this declaration.
3175   DeclarationName Name = Importer.Import(D->getDeclName());
3176   if (D->getDeclName() && !Name)
3177     return nullptr;
3178 
3179   // Import the location of this declaration.
3180   SourceLocation Loc = Importer.Import(D->getLocation());
3181 
3182   // Import the parameter's type.
3183   QualType T = Importer.Import(D->getType());
3184   if (T.isNull())
3185     return nullptr;
3186 
3187   // Create the imported parameter.
3188   ImplicitParamDecl *ToParm
3189     = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3190                                 Loc, Name.getAsIdentifierInfo(),
3191                                 T);
3192   return Importer.Imported(D, ToParm);
3193 }
3194 
VisitParmVarDecl(ParmVarDecl * D)3195 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3196   // Parameters are created in the translation unit's context, then moved
3197   // into the function declaration's context afterward.
3198   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3199 
3200   // Import the name of this declaration.
3201   DeclarationName Name = Importer.Import(D->getDeclName());
3202   if (D->getDeclName() && !Name)
3203     return nullptr;
3204 
3205   // Import the location of this declaration.
3206   SourceLocation Loc = Importer.Import(D->getLocation());
3207 
3208   // Import the parameter's type.
3209   QualType T = Importer.Import(D->getType());
3210   if (T.isNull())
3211     return nullptr;
3212 
3213   // Create the imported parameter.
3214   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3215   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3216                                      Importer.Import(D->getInnerLocStart()),
3217                                             Loc, Name.getAsIdentifierInfo(),
3218                                             T, TInfo, D->getStorageClass(),
3219                                             /*FIXME: Default argument*/nullptr);
3220   ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3221   return Importer.Imported(D, ToParm);
3222 }
3223 
VisitObjCMethodDecl(ObjCMethodDecl * D)3224 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3225   // Import the major distinguishing characteristics of a method.
3226   DeclContext *DC, *LexicalDC;
3227   DeclarationName Name;
3228   SourceLocation Loc;
3229   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3230     return nullptr;
3231 
3232   SmallVector<NamedDecl *, 2> FoundDecls;
3233   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3234   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3235     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3236       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3237         continue;
3238 
3239       // Check return types.
3240       if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3241                                              FoundMethod->getReturnType())) {
3242         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3243             << D->isInstanceMethod() << Name << D->getReturnType()
3244             << FoundMethod->getReturnType();
3245         Importer.ToDiag(FoundMethod->getLocation(),
3246                         diag::note_odr_objc_method_here)
3247           << D->isInstanceMethod() << Name;
3248         return nullptr;
3249       }
3250 
3251       // Check the number of parameters.
3252       if (D->param_size() != FoundMethod->param_size()) {
3253         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3254           << D->isInstanceMethod() << Name
3255           << D->param_size() << FoundMethod->param_size();
3256         Importer.ToDiag(FoundMethod->getLocation(),
3257                         diag::note_odr_objc_method_here)
3258           << D->isInstanceMethod() << Name;
3259         return nullptr;
3260       }
3261 
3262       // Check parameter types.
3263       for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3264              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3265            P != PEnd; ++P, ++FoundP) {
3266         if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3267                                                (*FoundP)->getType())) {
3268           Importer.FromDiag((*P)->getLocation(),
3269                             diag::err_odr_objc_method_param_type_inconsistent)
3270             << D->isInstanceMethod() << Name
3271             << (*P)->getType() << (*FoundP)->getType();
3272           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3273             << (*FoundP)->getType();
3274           return nullptr;
3275         }
3276       }
3277 
3278       // Check variadic/non-variadic.
3279       // Check the number of parameters.
3280       if (D->isVariadic() != FoundMethod->isVariadic()) {
3281         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3282           << D->isInstanceMethod() << Name;
3283         Importer.ToDiag(FoundMethod->getLocation(),
3284                         diag::note_odr_objc_method_here)
3285           << D->isInstanceMethod() << Name;
3286         return nullptr;
3287       }
3288 
3289       // FIXME: Any other bits we need to merge?
3290       return Importer.Imported(D, FoundMethod);
3291     }
3292   }
3293 
3294   // Import the result type.
3295   QualType ResultTy = Importer.Import(D->getReturnType());
3296   if (ResultTy.isNull())
3297     return nullptr;
3298 
3299   TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3300 
3301   ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3302       Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3303       Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3304       D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3305       D->getImplementationControl(), D->hasRelatedResultType());
3306 
3307   // FIXME: When we decide to merge method definitions, we'll need to
3308   // deal with implicit parameters.
3309 
3310   // Import the parameters
3311   SmallVector<ParmVarDecl *, 5> ToParams;
3312   for (auto *FromP : D->params()) {
3313     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3314     if (!ToP)
3315       return nullptr;
3316 
3317     ToParams.push_back(ToP);
3318   }
3319 
3320   // Set the parameters.
3321   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3322     ToParams[I]->setOwningFunction(ToMethod);
3323     ToMethod->addDeclInternal(ToParams[I]);
3324   }
3325   SmallVector<SourceLocation, 12> SelLocs;
3326   D->getSelectorLocs(SelLocs);
3327   ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3328 
3329   ToMethod->setLexicalDeclContext(LexicalDC);
3330   Importer.Imported(D, ToMethod);
3331   LexicalDC->addDeclInternal(ToMethod);
3332   return ToMethod;
3333 }
3334 
VisitObjCCategoryDecl(ObjCCategoryDecl * D)3335 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3336   // Import the major distinguishing characteristics of a category.
3337   DeclContext *DC, *LexicalDC;
3338   DeclarationName Name;
3339   SourceLocation Loc;
3340   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3341     return nullptr;
3342 
3343   ObjCInterfaceDecl *ToInterface
3344     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3345   if (!ToInterface)
3346     return nullptr;
3347 
3348   // Determine if we've already encountered this category.
3349   ObjCCategoryDecl *MergeWithCategory
3350     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3351   ObjCCategoryDecl *ToCategory = MergeWithCategory;
3352   if (!ToCategory) {
3353     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3354                                           Importer.Import(D->getAtStartLoc()),
3355                                           Loc,
3356                                        Importer.Import(D->getCategoryNameLoc()),
3357                                           Name.getAsIdentifierInfo(),
3358                                           ToInterface,
3359                                        Importer.Import(D->getIvarLBraceLoc()),
3360                                        Importer.Import(D->getIvarRBraceLoc()));
3361     ToCategory->setLexicalDeclContext(LexicalDC);
3362     LexicalDC->addDeclInternal(ToCategory);
3363     Importer.Imported(D, ToCategory);
3364 
3365     // Import protocols
3366     SmallVector<ObjCProtocolDecl *, 4> Protocols;
3367     SmallVector<SourceLocation, 4> ProtocolLocs;
3368     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3369       = D->protocol_loc_begin();
3370     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3371                                           FromProtoEnd = D->protocol_end();
3372          FromProto != FromProtoEnd;
3373          ++FromProto, ++FromProtoLoc) {
3374       ObjCProtocolDecl *ToProto
3375         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3376       if (!ToProto)
3377         return nullptr;
3378       Protocols.push_back(ToProto);
3379       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3380     }
3381 
3382     // FIXME: If we're merging, make sure that the protocol list is the same.
3383     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3384                                 ProtocolLocs.data(), Importer.getToContext());
3385 
3386   } else {
3387     Importer.Imported(D, ToCategory);
3388   }
3389 
3390   // Import all of the members of this category.
3391   ImportDeclContext(D);
3392 
3393   // If we have an implementation, import it as well.
3394   if (D->getImplementation()) {
3395     ObjCCategoryImplDecl *Impl
3396       = cast_or_null<ObjCCategoryImplDecl>(
3397                                        Importer.Import(D->getImplementation()));
3398     if (!Impl)
3399       return nullptr;
3400 
3401     ToCategory->setImplementation(Impl);
3402   }
3403 
3404   return ToCategory;
3405 }
3406 
ImportDefinition(ObjCProtocolDecl * From,ObjCProtocolDecl * To,ImportDefinitionKind Kind)3407 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3408                                        ObjCProtocolDecl *To,
3409                                        ImportDefinitionKind Kind) {
3410   if (To->getDefinition()) {
3411     if (shouldForceImportDeclContext(Kind))
3412       ImportDeclContext(From);
3413     return false;
3414   }
3415 
3416   // Start the protocol definition
3417   To->startDefinition();
3418 
3419   // Import protocols
3420   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3421   SmallVector<SourceLocation, 4> ProtocolLocs;
3422   ObjCProtocolDecl::protocol_loc_iterator
3423   FromProtoLoc = From->protocol_loc_begin();
3424   for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3425                                         FromProtoEnd = From->protocol_end();
3426        FromProto != FromProtoEnd;
3427        ++FromProto, ++FromProtoLoc) {
3428     ObjCProtocolDecl *ToProto
3429       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3430     if (!ToProto)
3431       return true;
3432     Protocols.push_back(ToProto);
3433     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3434   }
3435 
3436   // FIXME: If we're merging, make sure that the protocol list is the same.
3437   To->setProtocolList(Protocols.data(), Protocols.size(),
3438                       ProtocolLocs.data(), Importer.getToContext());
3439 
3440   if (shouldForceImportDeclContext(Kind)) {
3441     // Import all of the members of this protocol.
3442     ImportDeclContext(From, /*ForceImport=*/true);
3443   }
3444   return false;
3445 }
3446 
VisitObjCProtocolDecl(ObjCProtocolDecl * D)3447 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3448   // If this protocol has a definition in the translation unit we're coming
3449   // from, but this particular declaration is not that definition, import the
3450   // definition and map to that.
3451   ObjCProtocolDecl *Definition = D->getDefinition();
3452   if (Definition && Definition != D) {
3453     Decl *ImportedDef = Importer.Import(Definition);
3454     if (!ImportedDef)
3455       return nullptr;
3456 
3457     return Importer.Imported(D, ImportedDef);
3458   }
3459 
3460   // Import the major distinguishing characteristics of a protocol.
3461   DeclContext *DC, *LexicalDC;
3462   DeclarationName Name;
3463   SourceLocation Loc;
3464   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3465     return nullptr;
3466 
3467   ObjCProtocolDecl *MergeWithProtocol = nullptr;
3468   SmallVector<NamedDecl *, 2> FoundDecls;
3469   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3470   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3471     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3472       continue;
3473 
3474     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3475       break;
3476   }
3477 
3478   ObjCProtocolDecl *ToProto = MergeWithProtocol;
3479   if (!ToProto) {
3480     ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3481                                        Name.getAsIdentifierInfo(), Loc,
3482                                        Importer.Import(D->getAtStartLoc()),
3483                                        /*PrevDecl=*/nullptr);
3484     ToProto->setLexicalDeclContext(LexicalDC);
3485     LexicalDC->addDeclInternal(ToProto);
3486   }
3487 
3488   Importer.Imported(D, ToProto);
3489 
3490   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3491     return nullptr;
3492 
3493   return ToProto;
3494 }
3495 
VisitLinkageSpecDecl(LinkageSpecDecl * D)3496 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3497   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3498   DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3499 
3500   SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3501   SourceLocation LangLoc = Importer.Import(D->getLocation());
3502 
3503   bool HasBraces = D->hasBraces();
3504 
3505   LinkageSpecDecl *ToLinkageSpec =
3506     LinkageSpecDecl::Create(Importer.getToContext(),
3507                             DC,
3508                             ExternLoc,
3509                             LangLoc,
3510                             D->getLanguage(),
3511                             HasBraces);
3512 
3513   if (HasBraces) {
3514     SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3515     ToLinkageSpec->setRBraceLoc(RBraceLoc);
3516   }
3517 
3518   ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3519   LexicalDC->addDeclInternal(ToLinkageSpec);
3520 
3521   Importer.Imported(D, ToLinkageSpec);
3522 
3523   return ToLinkageSpec;
3524 }
3525 
ImportDefinition(ObjCInterfaceDecl * From,ObjCInterfaceDecl * To,ImportDefinitionKind Kind)3526 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3527                                        ObjCInterfaceDecl *To,
3528                                        ImportDefinitionKind Kind) {
3529   if (To->getDefinition()) {
3530     // Check consistency of superclass.
3531     ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3532     if (FromSuper) {
3533       FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3534       if (!FromSuper)
3535         return true;
3536     }
3537 
3538     ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3539     if ((bool)FromSuper != (bool)ToSuper ||
3540         (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3541       Importer.ToDiag(To->getLocation(),
3542                       diag::err_odr_objc_superclass_inconsistent)
3543         << To->getDeclName();
3544       if (ToSuper)
3545         Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3546           << To->getSuperClass()->getDeclName();
3547       else
3548         Importer.ToDiag(To->getLocation(),
3549                         diag::note_odr_objc_missing_superclass);
3550       if (From->getSuperClass())
3551         Importer.FromDiag(From->getSuperClassLoc(),
3552                           diag::note_odr_objc_superclass)
3553         << From->getSuperClass()->getDeclName();
3554       else
3555         Importer.FromDiag(From->getLocation(),
3556                           diag::note_odr_objc_missing_superclass);
3557     }
3558 
3559     if (shouldForceImportDeclContext(Kind))
3560       ImportDeclContext(From);
3561     return false;
3562   }
3563 
3564   // Start the definition.
3565   To->startDefinition();
3566 
3567   // If this class has a superclass, import it.
3568   if (From->getSuperClass()) {
3569     ObjCInterfaceDecl *Super = cast_or_null<ObjCInterfaceDecl>(
3570                                  Importer.Import(From->getSuperClass()));
3571     if (!Super)
3572       return true;
3573 
3574     To->setSuperClass(Super);
3575     To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
3576   }
3577 
3578   // Import protocols
3579   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3580   SmallVector<SourceLocation, 4> ProtocolLocs;
3581   ObjCInterfaceDecl::protocol_loc_iterator
3582   FromProtoLoc = From->protocol_loc_begin();
3583 
3584   for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3585                                          FromProtoEnd = From->protocol_end();
3586        FromProto != FromProtoEnd;
3587        ++FromProto, ++FromProtoLoc) {
3588     ObjCProtocolDecl *ToProto
3589       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3590     if (!ToProto)
3591       return true;
3592     Protocols.push_back(ToProto);
3593     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3594   }
3595 
3596   // FIXME: If we're merging, make sure that the protocol list is the same.
3597   To->setProtocolList(Protocols.data(), Protocols.size(),
3598                       ProtocolLocs.data(), Importer.getToContext());
3599 
3600   // Import categories. When the categories themselves are imported, they'll
3601   // hook themselves into this interface.
3602   for (auto *Cat : From->known_categories())
3603     Importer.Import(Cat);
3604 
3605   // If we have an @implementation, import it as well.
3606   if (From->getImplementation()) {
3607     ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3608                                      Importer.Import(From->getImplementation()));
3609     if (!Impl)
3610       return true;
3611 
3612     To->setImplementation(Impl);
3613   }
3614 
3615   if (shouldForceImportDeclContext(Kind)) {
3616     // Import all of the members of this class.
3617     ImportDeclContext(From, /*ForceImport=*/true);
3618   }
3619   return false;
3620 }
3621 
VisitObjCInterfaceDecl(ObjCInterfaceDecl * D)3622 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3623   // If this class has a definition in the translation unit we're coming from,
3624   // but this particular declaration is not that definition, import the
3625   // definition and map to that.
3626   ObjCInterfaceDecl *Definition = D->getDefinition();
3627   if (Definition && Definition != D) {
3628     Decl *ImportedDef = Importer.Import(Definition);
3629     if (!ImportedDef)
3630       return nullptr;
3631 
3632     return Importer.Imported(D, ImportedDef);
3633   }
3634 
3635   // Import the major distinguishing characteristics of an @interface.
3636   DeclContext *DC, *LexicalDC;
3637   DeclarationName Name;
3638   SourceLocation Loc;
3639   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3640     return nullptr;
3641 
3642   // Look for an existing interface with the same name.
3643   ObjCInterfaceDecl *MergeWithIface = nullptr;
3644   SmallVector<NamedDecl *, 2> FoundDecls;
3645   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3646   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3647     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3648       continue;
3649 
3650     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3651       break;
3652   }
3653 
3654   // Create an interface declaration, if one does not already exist.
3655   ObjCInterfaceDecl *ToIface = MergeWithIface;
3656   if (!ToIface) {
3657     ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3658                                         Importer.Import(D->getAtStartLoc()),
3659                                         Name.getAsIdentifierInfo(),
3660                                         /*PrevDecl=*/nullptr, Loc,
3661                                         D->isImplicitInterfaceDecl());
3662     ToIface->setLexicalDeclContext(LexicalDC);
3663     LexicalDC->addDeclInternal(ToIface);
3664   }
3665   Importer.Imported(D, ToIface);
3666 
3667   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3668     return nullptr;
3669 
3670   return ToIface;
3671 }
3672 
VisitObjCCategoryImplDecl(ObjCCategoryImplDecl * D)3673 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3674   ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3675                                         Importer.Import(D->getCategoryDecl()));
3676   if (!Category)
3677     return nullptr;
3678 
3679   ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3680   if (!ToImpl) {
3681     DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3682     if (!DC)
3683       return nullptr;
3684 
3685     SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3686     ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3687                                           Importer.Import(D->getIdentifier()),
3688                                           Category->getClassInterface(),
3689                                           Importer.Import(D->getLocation()),
3690                                           Importer.Import(D->getAtStartLoc()),
3691                                           CategoryNameLoc);
3692 
3693     DeclContext *LexicalDC = DC;
3694     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3695       LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3696       if (!LexicalDC)
3697         return nullptr;
3698 
3699       ToImpl->setLexicalDeclContext(LexicalDC);
3700     }
3701 
3702     LexicalDC->addDeclInternal(ToImpl);
3703     Category->setImplementation(ToImpl);
3704   }
3705 
3706   Importer.Imported(D, ToImpl);
3707   ImportDeclContext(D);
3708   return ToImpl;
3709 }
3710 
VisitObjCImplementationDecl(ObjCImplementationDecl * D)3711 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3712   // Find the corresponding interface.
3713   ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3714                                        Importer.Import(D->getClassInterface()));
3715   if (!Iface)
3716     return nullptr;
3717 
3718   // Import the superclass, if any.
3719   ObjCInterfaceDecl *Super = nullptr;
3720   if (D->getSuperClass()) {
3721     Super = cast_or_null<ObjCInterfaceDecl>(
3722                                           Importer.Import(D->getSuperClass()));
3723     if (!Super)
3724       return nullptr;
3725   }
3726 
3727   ObjCImplementationDecl *Impl = Iface->getImplementation();
3728   if (!Impl) {
3729     // We haven't imported an implementation yet. Create a new @implementation
3730     // now.
3731     Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3732                                   Importer.ImportContext(D->getDeclContext()),
3733                                           Iface, Super,
3734                                           Importer.Import(D->getLocation()),
3735                                           Importer.Import(D->getAtStartLoc()),
3736                                           Importer.Import(D->getSuperClassLoc()),
3737                                           Importer.Import(D->getIvarLBraceLoc()),
3738                                           Importer.Import(D->getIvarRBraceLoc()));
3739 
3740     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3741       DeclContext *LexicalDC
3742         = Importer.ImportContext(D->getLexicalDeclContext());
3743       if (!LexicalDC)
3744         return nullptr;
3745       Impl->setLexicalDeclContext(LexicalDC);
3746     }
3747 
3748     // Associate the implementation with the class it implements.
3749     Iface->setImplementation(Impl);
3750     Importer.Imported(D, Iface->getImplementation());
3751   } else {
3752     Importer.Imported(D, Iface->getImplementation());
3753 
3754     // Verify that the existing @implementation has the same superclass.
3755     if ((Super && !Impl->getSuperClass()) ||
3756         (!Super && Impl->getSuperClass()) ||
3757         (Super && Impl->getSuperClass() &&
3758          !declaresSameEntity(Super->getCanonicalDecl(),
3759                              Impl->getSuperClass()))) {
3760       Importer.ToDiag(Impl->getLocation(),
3761                       diag::err_odr_objc_superclass_inconsistent)
3762         << Iface->getDeclName();
3763       // FIXME: It would be nice to have the location of the superclass
3764       // below.
3765       if (Impl->getSuperClass())
3766         Importer.ToDiag(Impl->getLocation(),
3767                         diag::note_odr_objc_superclass)
3768         << Impl->getSuperClass()->getDeclName();
3769       else
3770         Importer.ToDiag(Impl->getLocation(),
3771                         diag::note_odr_objc_missing_superclass);
3772       if (D->getSuperClass())
3773         Importer.FromDiag(D->getLocation(),
3774                           diag::note_odr_objc_superclass)
3775         << D->getSuperClass()->getDeclName();
3776       else
3777         Importer.FromDiag(D->getLocation(),
3778                           diag::note_odr_objc_missing_superclass);
3779       return nullptr;
3780     }
3781   }
3782 
3783   // Import all of the members of this @implementation.
3784   ImportDeclContext(D);
3785 
3786   return Impl;
3787 }
3788 
VisitObjCPropertyDecl(ObjCPropertyDecl * D)3789 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3790   // Import the major distinguishing characteristics of an @property.
3791   DeclContext *DC, *LexicalDC;
3792   DeclarationName Name;
3793   SourceLocation Loc;
3794   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3795     return nullptr;
3796 
3797   // Check whether we have already imported this property.
3798   SmallVector<NamedDecl *, 2> FoundDecls;
3799   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3800   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3801     if (ObjCPropertyDecl *FoundProp
3802                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3803       // Check property types.
3804       if (!Importer.IsStructurallyEquivalent(D->getType(),
3805                                              FoundProp->getType())) {
3806         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3807           << Name << D->getType() << FoundProp->getType();
3808         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3809           << FoundProp->getType();
3810         return nullptr;
3811       }
3812 
3813       // FIXME: Check property attributes, getters, setters, etc.?
3814 
3815       // Consider these properties to be equivalent.
3816       Importer.Imported(D, FoundProp);
3817       return FoundProp;
3818     }
3819   }
3820 
3821   // Import the type.
3822   TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
3823   if (!T)
3824     return nullptr;
3825 
3826   // Create the new property.
3827   ObjCPropertyDecl *ToProperty
3828     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3829                                Name.getAsIdentifierInfo(),
3830                                Importer.Import(D->getAtLoc()),
3831                                Importer.Import(D->getLParenLoc()),
3832                                T,
3833                                D->getPropertyImplementation());
3834   Importer.Imported(D, ToProperty);
3835   ToProperty->setLexicalDeclContext(LexicalDC);
3836   LexicalDC->addDeclInternal(ToProperty);
3837 
3838   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3839   ToProperty->setPropertyAttributesAsWritten(
3840                                       D->getPropertyAttributesAsWritten());
3841   ToProperty->setGetterName(Importer.Import(D->getGetterName()));
3842   ToProperty->setSetterName(Importer.Import(D->getSetterName()));
3843   ToProperty->setGetterMethodDecl(
3844      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3845   ToProperty->setSetterMethodDecl(
3846      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3847   ToProperty->setPropertyIvarDecl(
3848        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3849   return ToProperty;
3850 }
3851 
VisitObjCPropertyImplDecl(ObjCPropertyImplDecl * D)3852 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3853   ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3854                                         Importer.Import(D->getPropertyDecl()));
3855   if (!Property)
3856     return nullptr;
3857 
3858   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3859   if (!DC)
3860     return nullptr;
3861 
3862   // Import the lexical declaration context.
3863   DeclContext *LexicalDC = DC;
3864   if (D->getDeclContext() != D->getLexicalDeclContext()) {
3865     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3866     if (!LexicalDC)
3867       return nullptr;
3868   }
3869 
3870   ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3871   if (!InImpl)
3872     return nullptr;
3873 
3874   // Import the ivar (for an @synthesize).
3875   ObjCIvarDecl *Ivar = nullptr;
3876   if (D->getPropertyIvarDecl()) {
3877     Ivar = cast_or_null<ObjCIvarDecl>(
3878                                     Importer.Import(D->getPropertyIvarDecl()));
3879     if (!Ivar)
3880       return nullptr;
3881   }
3882 
3883   ObjCPropertyImplDecl *ToImpl
3884     = InImpl->FindPropertyImplDecl(Property->getIdentifier());
3885   if (!ToImpl) {
3886     ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3887                                           Importer.Import(D->getLocStart()),
3888                                           Importer.Import(D->getLocation()),
3889                                           Property,
3890                                           D->getPropertyImplementation(),
3891                                           Ivar,
3892                                   Importer.Import(D->getPropertyIvarDeclLoc()));
3893     ToImpl->setLexicalDeclContext(LexicalDC);
3894     Importer.Imported(D, ToImpl);
3895     LexicalDC->addDeclInternal(ToImpl);
3896   } else {
3897     // Check that we have the same kind of property implementation (@synthesize
3898     // vs. @dynamic).
3899     if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3900       Importer.ToDiag(ToImpl->getLocation(),
3901                       diag::err_odr_objc_property_impl_kind_inconsistent)
3902         << Property->getDeclName()
3903         << (ToImpl->getPropertyImplementation()
3904                                               == ObjCPropertyImplDecl::Dynamic);
3905       Importer.FromDiag(D->getLocation(),
3906                         diag::note_odr_objc_property_impl_kind)
3907         << D->getPropertyDecl()->getDeclName()
3908         << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3909       return nullptr;
3910     }
3911 
3912     // For @synthesize, check that we have the same
3913     if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3914         Ivar != ToImpl->getPropertyIvarDecl()) {
3915       Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3916                       diag::err_odr_objc_synthesize_ivar_inconsistent)
3917         << Property->getDeclName()
3918         << ToImpl->getPropertyIvarDecl()->getDeclName()
3919         << Ivar->getDeclName();
3920       Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3921                         diag::note_odr_objc_synthesize_ivar_here)
3922         << D->getPropertyIvarDecl()->getDeclName();
3923       return nullptr;
3924     }
3925 
3926     // Merge the existing implementation with the new implementation.
3927     Importer.Imported(D, ToImpl);
3928   }
3929 
3930   return ToImpl;
3931 }
3932 
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)3933 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3934   // For template arguments, we adopt the translation unit as our declaration
3935   // context. This context will be fixed when the actual template declaration
3936   // is created.
3937 
3938   // FIXME: Import default argument.
3939   return TemplateTypeParmDecl::Create(Importer.getToContext(),
3940                               Importer.getToContext().getTranslationUnitDecl(),
3941                                       Importer.Import(D->getLocStart()),
3942                                       Importer.Import(D->getLocation()),
3943                                       D->getDepth(),
3944                                       D->getIndex(),
3945                                       Importer.Import(D->getIdentifier()),
3946                                       D->wasDeclaredWithTypename(),
3947                                       D->isParameterPack());
3948 }
3949 
3950 Decl *
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)3951 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3952   // Import the name of this declaration.
3953   DeclarationName Name = Importer.Import(D->getDeclName());
3954   if (D->getDeclName() && !Name)
3955     return nullptr;
3956 
3957   // Import the location of this declaration.
3958   SourceLocation Loc = Importer.Import(D->getLocation());
3959 
3960   // Import the type of this declaration.
3961   QualType T = Importer.Import(D->getType());
3962   if (T.isNull())
3963     return nullptr;
3964 
3965   // Import type-source information.
3966   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3967   if (D->getTypeSourceInfo() && !TInfo)
3968     return nullptr;
3969 
3970   // FIXME: Import default argument.
3971 
3972   return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3973                                Importer.getToContext().getTranslationUnitDecl(),
3974                                          Importer.Import(D->getInnerLocStart()),
3975                                          Loc, D->getDepth(), D->getPosition(),
3976                                          Name.getAsIdentifierInfo(),
3977                                          T, D->isParameterPack(), TInfo);
3978 }
3979 
3980 Decl *
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)3981 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3982   // Import the name of this declaration.
3983   DeclarationName Name = Importer.Import(D->getDeclName());
3984   if (D->getDeclName() && !Name)
3985     return nullptr;
3986 
3987   // Import the location of this declaration.
3988   SourceLocation Loc = Importer.Import(D->getLocation());
3989 
3990   // Import template parameters.
3991   TemplateParameterList *TemplateParams
3992     = ImportTemplateParameterList(D->getTemplateParameters());
3993   if (!TemplateParams)
3994     return nullptr;
3995 
3996   // FIXME: Import default argument.
3997 
3998   return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3999                               Importer.getToContext().getTranslationUnitDecl(),
4000                                           Loc, D->getDepth(), D->getPosition(),
4001                                           D->isParameterPack(),
4002                                           Name.getAsIdentifierInfo(),
4003                                           TemplateParams);
4004 }
4005 
VisitClassTemplateDecl(ClassTemplateDecl * D)4006 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4007   // If this record has a definition in the translation unit we're coming from,
4008   // but this particular declaration is not that definition, import the
4009   // definition and map to that.
4010   CXXRecordDecl *Definition
4011     = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4012   if (Definition && Definition != D->getTemplatedDecl()) {
4013     Decl *ImportedDef
4014       = Importer.Import(Definition->getDescribedClassTemplate());
4015     if (!ImportedDef)
4016       return nullptr;
4017 
4018     return Importer.Imported(D, ImportedDef);
4019   }
4020 
4021   // Import the major distinguishing characteristics of this class template.
4022   DeclContext *DC, *LexicalDC;
4023   DeclarationName Name;
4024   SourceLocation Loc;
4025   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
4026     return nullptr;
4027 
4028   // We may already have a template of the same name; try to find and match it.
4029   if (!DC->isFunctionOrMethod()) {
4030     SmallVector<NamedDecl *, 4> ConflictingDecls;
4031     SmallVector<NamedDecl *, 2> FoundDecls;
4032     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4033     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4034       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4035         continue;
4036 
4037       Decl *Found = FoundDecls[I];
4038       if (ClassTemplateDecl *FoundTemplate
4039                                         = dyn_cast<ClassTemplateDecl>(Found)) {
4040         if (IsStructuralMatch(D, FoundTemplate)) {
4041           // The class templates structurally match; call it the same template.
4042           // FIXME: We may be filling in a forward declaration here. Handle
4043           // this case!
4044           Importer.Imported(D->getTemplatedDecl(),
4045                             FoundTemplate->getTemplatedDecl());
4046           return Importer.Imported(D, FoundTemplate);
4047         }
4048       }
4049 
4050       ConflictingDecls.push_back(FoundDecls[I]);
4051     }
4052 
4053     if (!ConflictingDecls.empty()) {
4054       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4055                                          ConflictingDecls.data(),
4056                                          ConflictingDecls.size());
4057     }
4058 
4059     if (!Name)
4060       return nullptr;
4061   }
4062 
4063   CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4064 
4065   // Create the declaration that is being templated.
4066   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4067   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4068   CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4069                                                      DTemplated->getTagKind(),
4070                                                      DC, StartLoc, IdLoc,
4071                                                    Name.getAsIdentifierInfo());
4072   D2Templated->setAccess(DTemplated->getAccess());
4073   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4074   D2Templated->setLexicalDeclContext(LexicalDC);
4075 
4076   // Create the class template declaration itself.
4077   TemplateParameterList *TemplateParams
4078     = ImportTemplateParameterList(D->getTemplateParameters());
4079   if (!TemplateParams)
4080     return nullptr;
4081 
4082   ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4083                                                     Loc, Name, TemplateParams,
4084                                                     D2Templated,
4085                                                     /*PrevDecl=*/nullptr);
4086   D2Templated->setDescribedClassTemplate(D2);
4087 
4088   D2->setAccess(D->getAccess());
4089   D2->setLexicalDeclContext(LexicalDC);
4090   LexicalDC->addDeclInternal(D2);
4091 
4092   // Note the relationship between the class templates.
4093   Importer.Imported(D, D2);
4094   Importer.Imported(DTemplated, D2Templated);
4095 
4096   if (DTemplated->isCompleteDefinition() &&
4097       !D2Templated->isCompleteDefinition()) {
4098     // FIXME: Import definition!
4099   }
4100 
4101   return D2;
4102 }
4103 
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)4104 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4105                                           ClassTemplateSpecializationDecl *D) {
4106   // If this record has a definition in the translation unit we're coming from,
4107   // but this particular declaration is not that definition, import the
4108   // definition and map to that.
4109   TagDecl *Definition = D->getDefinition();
4110   if (Definition && Definition != D) {
4111     Decl *ImportedDef = Importer.Import(Definition);
4112     if (!ImportedDef)
4113       return nullptr;
4114 
4115     return Importer.Imported(D, ImportedDef);
4116   }
4117 
4118   ClassTemplateDecl *ClassTemplate
4119     = cast_or_null<ClassTemplateDecl>(Importer.Import(
4120                                                  D->getSpecializedTemplate()));
4121   if (!ClassTemplate)
4122     return nullptr;
4123 
4124   // Import the context of this declaration.
4125   DeclContext *DC = ClassTemplate->getDeclContext();
4126   if (!DC)
4127     return nullptr;
4128 
4129   DeclContext *LexicalDC = DC;
4130   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4131     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4132     if (!LexicalDC)
4133       return nullptr;
4134   }
4135 
4136   // Import the location of this declaration.
4137   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4138   SourceLocation IdLoc = Importer.Import(D->getLocation());
4139 
4140   // Import template arguments.
4141   SmallVector<TemplateArgument, 2> TemplateArgs;
4142   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4143                               D->getTemplateArgs().size(),
4144                               TemplateArgs))
4145     return nullptr;
4146 
4147   // Try to find an existing specialization with these template arguments.
4148   void *InsertPos = nullptr;
4149   ClassTemplateSpecializationDecl *D2
4150     = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4151   if (D2) {
4152     // We already have a class template specialization with these template
4153     // arguments.
4154 
4155     // FIXME: Check for specialization vs. instantiation errors.
4156 
4157     if (RecordDecl *FoundDef = D2->getDefinition()) {
4158       if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4159         // The record types structurally match, or the "from" translation
4160         // unit only had a forward declaration anyway; call it the same
4161         // function.
4162         return Importer.Imported(D, FoundDef);
4163       }
4164     }
4165   } else {
4166     // Create a new specialization.
4167     D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4168                                                  D->getTagKind(), DC,
4169                                                  StartLoc, IdLoc,
4170                                                  ClassTemplate,
4171                                                  TemplateArgs.data(),
4172                                                  TemplateArgs.size(),
4173                                                  /*PrevDecl=*/nullptr);
4174     D2->setSpecializationKind(D->getSpecializationKind());
4175 
4176     // Add this specialization to the class template.
4177     ClassTemplate->AddSpecialization(D2, InsertPos);
4178 
4179     // Import the qualifier, if any.
4180     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4181 
4182     // Add the specialization to this context.
4183     D2->setLexicalDeclContext(LexicalDC);
4184     LexicalDC->addDeclInternal(D2);
4185   }
4186   Importer.Imported(D, D2);
4187 
4188   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4189     return nullptr;
4190 
4191   return D2;
4192 }
4193 
VisitVarTemplateDecl(VarTemplateDecl * D)4194 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4195   // If this variable has a definition in the translation unit we're coming
4196   // from,
4197   // but this particular declaration is not that definition, import the
4198   // definition and map to that.
4199   VarDecl *Definition =
4200       cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4201   if (Definition && Definition != D->getTemplatedDecl()) {
4202     Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4203     if (!ImportedDef)
4204       return nullptr;
4205 
4206     return Importer.Imported(D, ImportedDef);
4207   }
4208 
4209   // Import the major distinguishing characteristics of this variable template.
4210   DeclContext *DC, *LexicalDC;
4211   DeclarationName Name;
4212   SourceLocation Loc;
4213   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
4214     return nullptr;
4215 
4216   // We may already have a template of the same name; try to find and match it.
4217   assert(!DC->isFunctionOrMethod() &&
4218          "Variable templates cannot be declared at function scope");
4219   SmallVector<NamedDecl *, 4> ConflictingDecls;
4220   SmallVector<NamedDecl *, 2> FoundDecls;
4221   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4222   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4223     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4224       continue;
4225 
4226     Decl *Found = FoundDecls[I];
4227     if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4228       if (IsStructuralMatch(D, FoundTemplate)) {
4229         // The variable templates structurally match; call it the same template.
4230         Importer.Imported(D->getTemplatedDecl(),
4231                           FoundTemplate->getTemplatedDecl());
4232         return Importer.Imported(D, FoundTemplate);
4233       }
4234     }
4235 
4236     ConflictingDecls.push_back(FoundDecls[I]);
4237   }
4238 
4239   if (!ConflictingDecls.empty()) {
4240     Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4241                                        ConflictingDecls.data(),
4242                                        ConflictingDecls.size());
4243   }
4244 
4245   if (!Name)
4246     return nullptr;
4247 
4248   VarDecl *DTemplated = D->getTemplatedDecl();
4249 
4250   // Import the type.
4251   QualType T = Importer.Import(DTemplated->getType());
4252   if (T.isNull())
4253     return nullptr;
4254 
4255   // Create the declaration that is being templated.
4256   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4257   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4258   TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4259   VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4260                                          IdLoc, Name.getAsIdentifierInfo(), T,
4261                                          TInfo, DTemplated->getStorageClass());
4262   D2Templated->setAccess(DTemplated->getAccess());
4263   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4264   D2Templated->setLexicalDeclContext(LexicalDC);
4265 
4266   // Importer.Imported(DTemplated, D2Templated);
4267   // LexicalDC->addDeclInternal(D2Templated);
4268 
4269   // Merge the initializer.
4270   if (ImportDefinition(DTemplated, D2Templated))
4271     return nullptr;
4272 
4273   // Create the variable template declaration itself.
4274   TemplateParameterList *TemplateParams =
4275       ImportTemplateParameterList(D->getTemplateParameters());
4276   if (!TemplateParams)
4277     return nullptr;
4278 
4279   VarTemplateDecl *D2 = VarTemplateDecl::Create(
4280       Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4281   D2Templated->setDescribedVarTemplate(D2);
4282 
4283   D2->setAccess(D->getAccess());
4284   D2->setLexicalDeclContext(LexicalDC);
4285   LexicalDC->addDeclInternal(D2);
4286 
4287   // Note the relationship between the variable templates.
4288   Importer.Imported(D, D2);
4289   Importer.Imported(DTemplated, D2Templated);
4290 
4291   if (DTemplated->isThisDeclarationADefinition() &&
4292       !D2Templated->isThisDeclarationADefinition()) {
4293     // FIXME: Import definition!
4294   }
4295 
4296   return D2;
4297 }
4298 
VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl * D)4299 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4300     VarTemplateSpecializationDecl *D) {
4301   // If this record has a definition in the translation unit we're coming from,
4302   // but this particular declaration is not that definition, import the
4303   // definition and map to that.
4304   VarDecl *Definition = D->getDefinition();
4305   if (Definition && Definition != D) {
4306     Decl *ImportedDef = Importer.Import(Definition);
4307     if (!ImportedDef)
4308       return nullptr;
4309 
4310     return Importer.Imported(D, ImportedDef);
4311   }
4312 
4313   VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4314       Importer.Import(D->getSpecializedTemplate()));
4315   if (!VarTemplate)
4316     return nullptr;
4317 
4318   // Import the context of this declaration.
4319   DeclContext *DC = VarTemplate->getDeclContext();
4320   if (!DC)
4321     return nullptr;
4322 
4323   DeclContext *LexicalDC = DC;
4324   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4325     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4326     if (!LexicalDC)
4327       return nullptr;
4328   }
4329 
4330   // Import the location of this declaration.
4331   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4332   SourceLocation IdLoc = Importer.Import(D->getLocation());
4333 
4334   // Import template arguments.
4335   SmallVector<TemplateArgument, 2> TemplateArgs;
4336   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4337                               D->getTemplateArgs().size(), TemplateArgs))
4338     return nullptr;
4339 
4340   // Try to find an existing specialization with these template arguments.
4341   void *InsertPos = nullptr;
4342   VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4343       TemplateArgs, InsertPos);
4344   if (D2) {
4345     // We already have a variable template specialization with these template
4346     // arguments.
4347 
4348     // FIXME: Check for specialization vs. instantiation errors.
4349 
4350     if (VarDecl *FoundDef = D2->getDefinition()) {
4351       if (!D->isThisDeclarationADefinition() ||
4352           IsStructuralMatch(D, FoundDef)) {
4353         // The record types structurally match, or the "from" translation
4354         // unit only had a forward declaration anyway; call it the same
4355         // variable.
4356         return Importer.Imported(D, FoundDef);
4357       }
4358     }
4359   } else {
4360 
4361     // Import the type.
4362     QualType T = Importer.Import(D->getType());
4363     if (T.isNull())
4364       return nullptr;
4365     TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4366 
4367     // Create a new specialization.
4368     D2 = VarTemplateSpecializationDecl::Create(
4369         Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4370         D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4371     D2->setSpecializationKind(D->getSpecializationKind());
4372     D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4373 
4374     // Add this specialization to the class template.
4375     VarTemplate->AddSpecialization(D2, InsertPos);
4376 
4377     // Import the qualifier, if any.
4378     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4379 
4380     // Add the specialization to this context.
4381     D2->setLexicalDeclContext(LexicalDC);
4382     LexicalDC->addDeclInternal(D2);
4383   }
4384   Importer.Imported(D, D2);
4385 
4386   if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4387     return nullptr;
4388 
4389   return D2;
4390 }
4391 
4392 //----------------------------------------------------------------------------
4393 // Import Statements
4394 //----------------------------------------------------------------------------
4395 
VisitStmt(Stmt * S)4396 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4397   Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4398     << S->getStmtClassName();
4399   return nullptr;
4400 }
4401 
4402 //----------------------------------------------------------------------------
4403 // Import Expressions
4404 //----------------------------------------------------------------------------
VisitExpr(Expr * E)4405 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
4406   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
4407     << E->getStmtClassName();
4408   return nullptr;
4409 }
4410 
VisitDeclRefExpr(DeclRefExpr * E)4411 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
4412   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
4413   if (!ToD)
4414     return nullptr;
4415 
4416   NamedDecl *FoundD = nullptr;
4417   if (E->getDecl() != E->getFoundDecl()) {
4418     FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
4419     if (!FoundD)
4420       return nullptr;
4421   }
4422 
4423   QualType T = Importer.Import(E->getType());
4424   if (T.isNull())
4425     return nullptr;
4426 
4427   DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
4428                                          Importer.Import(E->getQualifierLoc()),
4429                                    Importer.Import(E->getTemplateKeywordLoc()),
4430                                          ToD,
4431                                         E->refersToEnclosingVariableOrCapture(),
4432                                          Importer.Import(E->getLocation()),
4433                                          T, E->getValueKind(),
4434                                          FoundD,
4435                                          /*FIXME:TemplateArgs=*/nullptr);
4436   if (E->hadMultipleCandidates())
4437     DRE->setHadMultipleCandidates(true);
4438   return DRE;
4439 }
4440 
VisitIntegerLiteral(IntegerLiteral * E)4441 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
4442   QualType T = Importer.Import(E->getType());
4443   if (T.isNull())
4444     return nullptr;
4445 
4446   return IntegerLiteral::Create(Importer.getToContext(),
4447                                 E->getValue(), T,
4448                                 Importer.Import(E->getLocation()));
4449 }
4450 
VisitCharacterLiteral(CharacterLiteral * E)4451 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
4452   QualType T = Importer.Import(E->getType());
4453   if (T.isNull())
4454     return nullptr;
4455 
4456   return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
4457                                                         E->getKind(), T,
4458                                           Importer.Import(E->getLocation()));
4459 }
4460 
VisitParenExpr(ParenExpr * E)4461 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
4462   Expr *SubExpr = Importer.Import(E->getSubExpr());
4463   if (!SubExpr)
4464     return nullptr;
4465 
4466   return new (Importer.getToContext())
4467                                   ParenExpr(Importer.Import(E->getLParen()),
4468                                             Importer.Import(E->getRParen()),
4469                                             SubExpr);
4470 }
4471 
VisitUnaryOperator(UnaryOperator * E)4472 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
4473   QualType T = Importer.Import(E->getType());
4474   if (T.isNull())
4475     return nullptr;
4476 
4477   Expr *SubExpr = Importer.Import(E->getSubExpr());
4478   if (!SubExpr)
4479     return nullptr;
4480 
4481   return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
4482                                                      T, E->getValueKind(),
4483                                                      E->getObjectKind(),
4484                                          Importer.Import(E->getOperatorLoc()));
4485 }
4486 
VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * E)4487 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
4488                                             UnaryExprOrTypeTraitExpr *E) {
4489   QualType ResultType = Importer.Import(E->getType());
4490 
4491   if (E->isArgumentType()) {
4492     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
4493     if (!TInfo)
4494       return nullptr;
4495 
4496     return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4497                                            TInfo, ResultType,
4498                                            Importer.Import(E->getOperatorLoc()),
4499                                            Importer.Import(E->getRParenLoc()));
4500   }
4501 
4502   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
4503   if (!SubExpr)
4504     return nullptr;
4505 
4506   return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4507                                           SubExpr, ResultType,
4508                                           Importer.Import(E->getOperatorLoc()),
4509                                           Importer.Import(E->getRParenLoc()));
4510 }
4511 
VisitBinaryOperator(BinaryOperator * E)4512 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
4513   QualType T = Importer.Import(E->getType());
4514   if (T.isNull())
4515     return nullptr;
4516 
4517   Expr *LHS = Importer.Import(E->getLHS());
4518   if (!LHS)
4519     return nullptr;
4520 
4521   Expr *RHS = Importer.Import(E->getRHS());
4522   if (!RHS)
4523     return nullptr;
4524 
4525   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
4526                                                       T, E->getValueKind(),
4527                                                       E->getObjectKind(),
4528                                            Importer.Import(E->getOperatorLoc()),
4529                                                       E->isFPContractable());
4530 }
4531 
VisitCompoundAssignOperator(CompoundAssignOperator * E)4532 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
4533   QualType T = Importer.Import(E->getType());
4534   if (T.isNull())
4535     return nullptr;
4536 
4537   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
4538   if (CompLHSType.isNull())
4539     return nullptr;
4540 
4541   QualType CompResultType = Importer.Import(E->getComputationResultType());
4542   if (CompResultType.isNull())
4543     return nullptr;
4544 
4545   Expr *LHS = Importer.Import(E->getLHS());
4546   if (!LHS)
4547     return nullptr;
4548 
4549   Expr *RHS = Importer.Import(E->getRHS());
4550   if (!RHS)
4551     return nullptr;
4552 
4553   return new (Importer.getToContext())
4554                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
4555                                                T, E->getValueKind(),
4556                                                E->getObjectKind(),
4557                                                CompLHSType, CompResultType,
4558                                            Importer.Import(E->getOperatorLoc()),
4559                                                E->isFPContractable());
4560 }
4561 
ImportCastPath(CastExpr * E,CXXCastPath & Path)4562 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
4563   if (E->path_empty()) return false;
4564 
4565   // TODO: import cast paths
4566   return true;
4567 }
4568 
VisitImplicitCastExpr(ImplicitCastExpr * E)4569 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
4570   QualType T = Importer.Import(E->getType());
4571   if (T.isNull())
4572     return nullptr;
4573 
4574   Expr *SubExpr = Importer.Import(E->getSubExpr());
4575   if (!SubExpr)
4576     return nullptr;
4577 
4578   CXXCastPath BasePath;
4579   if (ImportCastPath(E, BasePath))
4580     return nullptr;
4581 
4582   return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
4583                                   SubExpr, &BasePath, E->getValueKind());
4584 }
4585 
VisitCStyleCastExpr(CStyleCastExpr * E)4586 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
4587   QualType T = Importer.Import(E->getType());
4588   if (T.isNull())
4589     return nullptr;
4590 
4591   Expr *SubExpr = Importer.Import(E->getSubExpr());
4592   if (!SubExpr)
4593     return nullptr;
4594 
4595   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
4596   if (!TInfo && E->getTypeInfoAsWritten())
4597     return nullptr;
4598 
4599   CXXCastPath BasePath;
4600   if (ImportCastPath(E, BasePath))
4601     return nullptr;
4602 
4603   return CStyleCastExpr::Create(Importer.getToContext(), T,
4604                                 E->getValueKind(), E->getCastKind(),
4605                                 SubExpr, &BasePath, TInfo,
4606                                 Importer.Import(E->getLParenLoc()),
4607                                 Importer.Import(E->getRParenLoc()));
4608 }
4609 
ASTImporter(ASTContext & ToContext,FileManager & ToFileManager,ASTContext & FromContext,FileManager & FromFileManager,bool MinimalImport)4610 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
4611                          ASTContext &FromContext, FileManager &FromFileManager,
4612                          bool MinimalImport)
4613   : ToContext(ToContext), FromContext(FromContext),
4614     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
4615     Minimal(MinimalImport), LastDiagFromFrom(false)
4616 {
4617   ImportedDecls[FromContext.getTranslationUnitDecl()]
4618     = ToContext.getTranslationUnitDecl();
4619 }
4620 
~ASTImporter()4621 ASTImporter::~ASTImporter() { }
4622 
Import(QualType FromT)4623 QualType ASTImporter::Import(QualType FromT) {
4624   if (FromT.isNull())
4625     return QualType();
4626 
4627   const Type *fromTy = FromT.getTypePtr();
4628 
4629   // Check whether we've already imported this type.
4630   llvm::DenseMap<const Type *, const Type *>::iterator Pos
4631     = ImportedTypes.find(fromTy);
4632   if (Pos != ImportedTypes.end())
4633     return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
4634 
4635   // Import the type
4636   ASTNodeImporter Importer(*this);
4637   QualType ToT = Importer.Visit(fromTy);
4638   if (ToT.isNull())
4639     return ToT;
4640 
4641   // Record the imported type.
4642   ImportedTypes[fromTy] = ToT.getTypePtr();
4643 
4644   return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
4645 }
4646 
Import(TypeSourceInfo * FromTSI)4647 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
4648   if (!FromTSI)
4649     return FromTSI;
4650 
4651   // FIXME: For now we just create a "trivial" type source info based
4652   // on the type and a single location. Implement a real version of this.
4653   QualType T = Import(FromTSI->getType());
4654   if (T.isNull())
4655     return nullptr;
4656 
4657   return ToContext.getTrivialTypeSourceInfo(T,
4658                         FromTSI->getTypeLoc().getLocStart());
4659 }
4660 
Import(Decl * FromD)4661 Decl *ASTImporter::Import(Decl *FromD) {
4662   if (!FromD)
4663     return nullptr;
4664 
4665   ASTNodeImporter Importer(*this);
4666 
4667   // Check whether we've already imported this declaration.
4668   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
4669   if (Pos != ImportedDecls.end()) {
4670     Decl *ToD = Pos->second;
4671     Importer.ImportDefinitionIfNeeded(FromD, ToD);
4672     return ToD;
4673   }
4674 
4675   // Import the type
4676   Decl *ToD = Importer.Visit(FromD);
4677   if (!ToD)
4678     return nullptr;
4679 
4680   // Record the imported declaration.
4681   ImportedDecls[FromD] = ToD;
4682 
4683   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
4684     // Keep track of anonymous tags that have an associated typedef.
4685     if (FromTag->getTypedefNameForAnonDecl())
4686       AnonTagsWithPendingTypedefs.push_back(FromTag);
4687   } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
4688     // When we've finished transforming a typedef, see whether it was the
4689     // typedef for an anonymous tag.
4690     for (SmallVectorImpl<TagDecl *>::iterator
4691                FromTag = AnonTagsWithPendingTypedefs.begin(),
4692             FromTagEnd = AnonTagsWithPendingTypedefs.end();
4693          FromTag != FromTagEnd; ++FromTag) {
4694       if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
4695         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
4696           // We found the typedef for an anonymous tag; link them.
4697           ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
4698           AnonTagsWithPendingTypedefs.erase(FromTag);
4699           break;
4700         }
4701       }
4702     }
4703   }
4704 
4705   return ToD;
4706 }
4707 
ImportContext(DeclContext * FromDC)4708 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
4709   if (!FromDC)
4710     return FromDC;
4711 
4712   DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
4713   if (!ToDC)
4714     return nullptr;
4715 
4716   // When we're using a record/enum/Objective-C class/protocol as a context, we
4717   // need it to have a definition.
4718   if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
4719     RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
4720     if (ToRecord->isCompleteDefinition()) {
4721       // Do nothing.
4722     } else if (FromRecord->isCompleteDefinition()) {
4723       ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
4724                                               ASTNodeImporter::IDK_Basic);
4725     } else {
4726       CompleteDecl(ToRecord);
4727     }
4728   } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
4729     EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
4730     if (ToEnum->isCompleteDefinition()) {
4731       // Do nothing.
4732     } else if (FromEnum->isCompleteDefinition()) {
4733       ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
4734                                               ASTNodeImporter::IDK_Basic);
4735     } else {
4736       CompleteDecl(ToEnum);
4737     }
4738   } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
4739     ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
4740     if (ToClass->getDefinition()) {
4741       // Do nothing.
4742     } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
4743       ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
4744                                               ASTNodeImporter::IDK_Basic);
4745     } else {
4746       CompleteDecl(ToClass);
4747     }
4748   } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
4749     ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
4750     if (ToProto->getDefinition()) {
4751       // Do nothing.
4752     } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
4753       ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
4754                                               ASTNodeImporter::IDK_Basic);
4755     } else {
4756       CompleteDecl(ToProto);
4757     }
4758   }
4759 
4760   return ToDC;
4761 }
4762 
Import(Expr * FromE)4763 Expr *ASTImporter::Import(Expr *FromE) {
4764   if (!FromE)
4765     return nullptr;
4766 
4767   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
4768 }
4769 
Import(Stmt * FromS)4770 Stmt *ASTImporter::Import(Stmt *FromS) {
4771   if (!FromS)
4772     return nullptr;
4773 
4774   // Check whether we've already imported this declaration.
4775   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
4776   if (Pos != ImportedStmts.end())
4777     return Pos->second;
4778 
4779   // Import the type
4780   ASTNodeImporter Importer(*this);
4781   Stmt *ToS = Importer.Visit(FromS);
4782   if (!ToS)
4783     return nullptr;
4784 
4785   // Record the imported declaration.
4786   ImportedStmts[FromS] = ToS;
4787   return ToS;
4788 }
4789 
Import(NestedNameSpecifier * FromNNS)4790 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
4791   if (!FromNNS)
4792     return nullptr;
4793 
4794   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
4795 
4796   switch (FromNNS->getKind()) {
4797   case NestedNameSpecifier::Identifier:
4798     if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
4799       return NestedNameSpecifier::Create(ToContext, prefix, II);
4800     }
4801     return nullptr;
4802 
4803   case NestedNameSpecifier::Namespace:
4804     if (NamespaceDecl *NS =
4805           cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
4806       return NestedNameSpecifier::Create(ToContext, prefix, NS);
4807     }
4808     return nullptr;
4809 
4810   case NestedNameSpecifier::NamespaceAlias:
4811     if (NamespaceAliasDecl *NSAD =
4812           cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
4813       return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
4814     }
4815     return nullptr;
4816 
4817   case NestedNameSpecifier::Global:
4818     return NestedNameSpecifier::GlobalSpecifier(ToContext);
4819 
4820   case NestedNameSpecifier::Super:
4821     if (CXXRecordDecl *RD =
4822             cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
4823       return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
4824     }
4825     return nullptr;
4826 
4827   case NestedNameSpecifier::TypeSpec:
4828   case NestedNameSpecifier::TypeSpecWithTemplate: {
4829       QualType T = Import(QualType(FromNNS->getAsType(), 0u));
4830       if (!T.isNull()) {
4831         bool bTemplate = FromNNS->getKind() ==
4832                          NestedNameSpecifier::TypeSpecWithTemplate;
4833         return NestedNameSpecifier::Create(ToContext, prefix,
4834                                            bTemplate, T.getTypePtr());
4835       }
4836     }
4837       return nullptr;
4838   }
4839 
4840   llvm_unreachable("Invalid nested name specifier kind");
4841 }
4842 
Import(NestedNameSpecifierLoc FromNNS)4843 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
4844   // FIXME: Implement!
4845   return NestedNameSpecifierLoc();
4846 }
4847 
Import(TemplateName From)4848 TemplateName ASTImporter::Import(TemplateName From) {
4849   switch (From.getKind()) {
4850   case TemplateName::Template:
4851     if (TemplateDecl *ToTemplate
4852                 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4853       return TemplateName(ToTemplate);
4854 
4855     return TemplateName();
4856 
4857   case TemplateName::OverloadedTemplate: {
4858     OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
4859     UnresolvedSet<2> ToTemplates;
4860     for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
4861                                              E = FromStorage->end();
4862          I != E; ++I) {
4863       if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
4864         ToTemplates.addDecl(To);
4865       else
4866         return TemplateName();
4867     }
4868     return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
4869                                                ToTemplates.end());
4870   }
4871 
4872   case TemplateName::QualifiedTemplate: {
4873     QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
4874     NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
4875     if (!Qualifier)
4876       return TemplateName();
4877 
4878     if (TemplateDecl *ToTemplate
4879         = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4880       return ToContext.getQualifiedTemplateName(Qualifier,
4881                                                 QTN->hasTemplateKeyword(),
4882                                                 ToTemplate);
4883 
4884     return TemplateName();
4885   }
4886 
4887   case TemplateName::DependentTemplate: {
4888     DependentTemplateName *DTN = From.getAsDependentTemplateName();
4889     NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
4890     if (!Qualifier)
4891       return TemplateName();
4892 
4893     if (DTN->isIdentifier()) {
4894       return ToContext.getDependentTemplateName(Qualifier,
4895                                                 Import(DTN->getIdentifier()));
4896     }
4897 
4898     return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
4899   }
4900 
4901   case TemplateName::SubstTemplateTemplateParm: {
4902     SubstTemplateTemplateParmStorage *subst
4903       = From.getAsSubstTemplateTemplateParm();
4904     TemplateTemplateParmDecl *param
4905       = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
4906     if (!param)
4907       return TemplateName();
4908 
4909     TemplateName replacement = Import(subst->getReplacement());
4910     if (replacement.isNull()) return TemplateName();
4911 
4912     return ToContext.getSubstTemplateTemplateParm(param, replacement);
4913   }
4914 
4915   case TemplateName::SubstTemplateTemplateParmPack: {
4916     SubstTemplateTemplateParmPackStorage *SubstPack
4917       = From.getAsSubstTemplateTemplateParmPack();
4918     TemplateTemplateParmDecl *Param
4919       = cast_or_null<TemplateTemplateParmDecl>(
4920                                         Import(SubstPack->getParameterPack()));
4921     if (!Param)
4922       return TemplateName();
4923 
4924     ASTNodeImporter Importer(*this);
4925     TemplateArgument ArgPack
4926       = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
4927     if (ArgPack.isNull())
4928       return TemplateName();
4929 
4930     return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
4931   }
4932   }
4933 
4934   llvm_unreachable("Invalid template name kind");
4935 }
4936 
Import(SourceLocation FromLoc)4937 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
4938   if (FromLoc.isInvalid())
4939     return SourceLocation();
4940 
4941   SourceManager &FromSM = FromContext.getSourceManager();
4942 
4943   // For now, map everything down to its spelling location, so that we
4944   // don't have to import macro expansions.
4945   // FIXME: Import macro expansions!
4946   FromLoc = FromSM.getSpellingLoc(FromLoc);
4947   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
4948   SourceManager &ToSM = ToContext.getSourceManager();
4949   FileID ToFileID = Import(Decomposed.first);
4950   if (ToFileID.isInvalid())
4951     return SourceLocation();
4952   return ToSM.getLocForStartOfFile(ToFileID)
4953              .getLocWithOffset(Decomposed.second);
4954 }
4955 
Import(SourceRange FromRange)4956 SourceRange ASTImporter::Import(SourceRange FromRange) {
4957   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
4958 }
4959 
Import(FileID FromID)4960 FileID ASTImporter::Import(FileID FromID) {
4961   llvm::DenseMap<FileID, FileID>::iterator Pos
4962     = ImportedFileIDs.find(FromID);
4963   if (Pos != ImportedFileIDs.end())
4964     return Pos->second;
4965 
4966   SourceManager &FromSM = FromContext.getSourceManager();
4967   SourceManager &ToSM = ToContext.getSourceManager();
4968   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
4969   assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
4970 
4971   // Include location of this file.
4972   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
4973 
4974   // Map the FileID for to the "to" source manager.
4975   FileID ToID;
4976   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
4977   if (Cache->OrigEntry) {
4978     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
4979     // disk again
4980     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
4981     // than mmap the files several times.
4982     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
4983     if (!Entry)
4984       return FileID();
4985     ToID = ToSM.createFileID(Entry, ToIncludeLoc,
4986                              FromSLoc.getFile().getFileCharacteristic());
4987   } else {
4988     // FIXME: We want to re-use the existing MemoryBuffer!
4989     const llvm::MemoryBuffer *
4990         FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
4991     std::unique_ptr<llvm::MemoryBuffer> ToBuf
4992       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
4993                                              FromBuf->getBufferIdentifier());
4994     ToID = ToSM.createFileID(std::move(ToBuf),
4995                              FromSLoc.getFile().getFileCharacteristic());
4996   }
4997 
4998 
4999   ImportedFileIDs[FromID] = ToID;
5000   return ToID;
5001 }
5002 
ImportDefinition(Decl * From)5003 void ASTImporter::ImportDefinition(Decl *From) {
5004   Decl *To = Import(From);
5005   if (!To)
5006     return;
5007 
5008   if (DeclContext *FromDC = cast<DeclContext>(From)) {
5009     ASTNodeImporter Importer(*this);
5010 
5011     if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
5012       if (!ToRecord->getDefinition()) {
5013         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
5014                                   ASTNodeImporter::IDK_Everything);
5015         return;
5016       }
5017     }
5018 
5019     if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
5020       if (!ToEnum->getDefinition()) {
5021         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
5022                                   ASTNodeImporter::IDK_Everything);
5023         return;
5024       }
5025     }
5026 
5027     if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
5028       if (!ToIFace->getDefinition()) {
5029         Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
5030                                   ASTNodeImporter::IDK_Everything);
5031         return;
5032       }
5033     }
5034 
5035     if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
5036       if (!ToProto->getDefinition()) {
5037         Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
5038                                   ASTNodeImporter::IDK_Everything);
5039         return;
5040       }
5041     }
5042 
5043     Importer.ImportDeclContext(FromDC, true);
5044   }
5045 }
5046 
Import(DeclarationName FromName)5047 DeclarationName ASTImporter::Import(DeclarationName FromName) {
5048   if (!FromName)
5049     return DeclarationName();
5050 
5051   switch (FromName.getNameKind()) {
5052   case DeclarationName::Identifier:
5053     return Import(FromName.getAsIdentifierInfo());
5054 
5055   case DeclarationName::ObjCZeroArgSelector:
5056   case DeclarationName::ObjCOneArgSelector:
5057   case DeclarationName::ObjCMultiArgSelector:
5058     return Import(FromName.getObjCSelector());
5059 
5060   case DeclarationName::CXXConstructorName: {
5061     QualType T = Import(FromName.getCXXNameType());
5062     if (T.isNull())
5063       return DeclarationName();
5064 
5065     return ToContext.DeclarationNames.getCXXConstructorName(
5066                                                ToContext.getCanonicalType(T));
5067   }
5068 
5069   case DeclarationName::CXXDestructorName: {
5070     QualType T = Import(FromName.getCXXNameType());
5071     if (T.isNull())
5072       return DeclarationName();
5073 
5074     return ToContext.DeclarationNames.getCXXDestructorName(
5075                                                ToContext.getCanonicalType(T));
5076   }
5077 
5078   case DeclarationName::CXXConversionFunctionName: {
5079     QualType T = Import(FromName.getCXXNameType());
5080     if (T.isNull())
5081       return DeclarationName();
5082 
5083     return ToContext.DeclarationNames.getCXXConversionFunctionName(
5084                                                ToContext.getCanonicalType(T));
5085   }
5086 
5087   case DeclarationName::CXXOperatorName:
5088     return ToContext.DeclarationNames.getCXXOperatorName(
5089                                           FromName.getCXXOverloadedOperator());
5090 
5091   case DeclarationName::CXXLiteralOperatorName:
5092     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5093                                    Import(FromName.getCXXLiteralIdentifier()));
5094 
5095   case DeclarationName::CXXUsingDirective:
5096     // FIXME: STATICS!
5097     return DeclarationName::getUsingDirectiveName();
5098   }
5099 
5100   llvm_unreachable("Invalid DeclarationName Kind!");
5101 }
5102 
Import(const IdentifierInfo * FromId)5103 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5104   if (!FromId)
5105     return nullptr;
5106 
5107   return &ToContext.Idents.get(FromId->getName());
5108 }
5109 
Import(Selector FromSel)5110 Selector ASTImporter::Import(Selector FromSel) {
5111   if (FromSel.isNull())
5112     return Selector();
5113 
5114   SmallVector<IdentifierInfo *, 4> Idents;
5115   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5116   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5117     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5118   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5119 }
5120 
HandleNameConflict(DeclarationName Name,DeclContext * DC,unsigned IDNS,NamedDecl ** Decls,unsigned NumDecls)5121 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5122                                                 DeclContext *DC,
5123                                                 unsigned IDNS,
5124                                                 NamedDecl **Decls,
5125                                                 unsigned NumDecls) {
5126   return Name;
5127 }
5128 
ToDiag(SourceLocation Loc,unsigned DiagID)5129 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5130   if (LastDiagFromFrom)
5131     ToContext.getDiagnostics().notePriorDiagnosticFrom(
5132       FromContext.getDiagnostics());
5133   LastDiagFromFrom = false;
5134   return ToContext.getDiagnostics().Report(Loc, DiagID);
5135 }
5136 
FromDiag(SourceLocation Loc,unsigned DiagID)5137 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5138   if (!LastDiagFromFrom)
5139     FromContext.getDiagnostics().notePriorDiagnosticFrom(
5140       ToContext.getDiagnostics());
5141   LastDiagFromFrom = true;
5142   return FromContext.getDiagnostics().Report(Loc, DiagID);
5143 }
5144 
CompleteDecl(Decl * D)5145 void ASTImporter::CompleteDecl (Decl *D) {
5146   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5147     if (!ID->getDefinition())
5148       ID->startDefinition();
5149   }
5150   else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5151     if (!PD->getDefinition())
5152       PD->startDefinition();
5153   }
5154   else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5155     if (!TD->getDefinition() && !TD->isBeingDefined()) {
5156       TD->startDefinition();
5157       TD->setCompleteDefinition(true);
5158     }
5159   }
5160   else {
5161     assert (0 && "CompleteDecl called on a Decl that can't be completed");
5162   }
5163 }
5164 
Imported(Decl * From,Decl * To)5165 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5166   ImportedDecls[From] = To;
5167   return To;
5168 }
5169 
IsStructurallyEquivalent(QualType From,QualType To,bool Complain)5170 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5171                                            bool Complain) {
5172   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5173    = ImportedTypes.find(From.getTypePtr());
5174   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5175     return true;
5176 
5177   StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5178                                    false, Complain);
5179   return Ctx.IsStructurallyEquivalent(From, To);
5180 }
5181