clang  8.0.0svn
ASTImporter.cpp
Go to the documentation of this file.
1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
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 
15 #include "clang/AST/ASTImporter.h"
16 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclVisitor.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExprObjC.h"
37 #include "clang/AST/Stmt.h"
38 #include "clang/AST/StmtCXX.h"
39 #include "clang/AST/StmtObjC.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TemplateBase.h"
42 #include "clang/AST/TemplateName.h"
43 #include "clang/AST/Type.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/AST/TypeVisitor.h"
50 #include "clang/Basic/LLVM.h"
54 #include "clang/Basic/Specifiers.h"
55 #include "llvm/ADT/APSInt.h"
56 #include "llvm/ADT/ArrayRef.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/None.h"
59 #include "llvm/ADT/Optional.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstddef>
68 #include <memory>
69 #include <type_traits>
70 #include <utility>
71 
72 namespace clang {
73 
75  assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
76  "Try to get field index for non-field.");
77 
78  auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
79  if (!Owner)
80  return 0;
81 
82  unsigned Index = 1;
83  for (const auto *D : Owner->decls()) {
84  if (D == F)
85  return Index;
86 
87  if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
88  ++Index;
89  }
90 
91  llvm_unreachable("Field was not found in its parent context.");
92 
93  return 0;
94  }
95 
96  template <class T>
99  SmallVector<Decl*, 2> Redecls;
100  for (auto *R : D->getFirstDecl()->redecls()) {
101  if (R != D->getFirstDecl())
102  Redecls.push_back(R);
103  }
104  Redecls.push_back(D->getFirstDecl());
105  std::reverse(Redecls.begin(), Redecls.end());
106  return Redecls;
107  }
108 
110  if (auto *FD = dyn_cast<FunctionDecl>(D))
111  return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
112  if (auto *VD = dyn_cast<VarDecl>(D))
113  return getCanonicalForwardRedeclChain<VarDecl>(VD);
114  llvm_unreachable("Bad declaration kind");
115  }
116 
117  void updateFlags(const Decl *From, Decl *To) {
118  // Check if some flags or attrs are new in 'From' and copy into 'To'.
119  // FIXME: Other flags or attrs?
120  if (From->isUsed(false) && !To->isUsed(false))
121  To->setIsUsed();
122  }
123 
124  class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
125  public DeclVisitor<ASTNodeImporter, Decl *>,
126  public StmtVisitor<ASTNodeImporter, Stmt *> {
127  ASTImporter &Importer;
128 
129  // Wrapper for an overload set.
130  template <typename ToDeclT> struct CallOverloadedCreateFun {
131  template <typename... Args>
132  auto operator()(Args &&... args)
133  -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) {
134  return ToDeclT::Create(std::forward<Args>(args)...);
135  }
136  };
137 
138  // Always use these functions to create a Decl during import. There are
139  // certain tasks which must be done after the Decl was created, e.g. we
140  // must immediately register that as an imported Decl. The parameter `ToD`
141  // will be set to the newly created Decl or if had been imported before
142  // then to the already imported Decl. Returns a bool value set to true if
143  // the `FromD` had been imported before.
144  template <typename ToDeclT, typename FromDeclT, typename... Args>
145  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
146  Args &&... args) {
147  // There may be several overloads of ToDeclT::Create. We must make sure
148  // to call the one which would be chosen by the arguments, thus we use a
149  // wrapper for the overload set.
150  CallOverloadedCreateFun<ToDeclT> OC;
151  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
152  std::forward<Args>(args)...);
153  }
154  // Use this overload if a special Type is needed to be created. E.g if we
155  // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
156  // then:
157  // TypedefNameDecl *ToTypedef;
158  // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
159  template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
160  typename... Args>
161  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
162  Args &&... args) {
163  CallOverloadedCreateFun<NewDeclT> OC;
164  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
165  std::forward<Args>(args)...);
166  }
167  // Use this version if a special create function must be
168  // used, e.g. CXXRecordDecl::CreateLambda .
169  template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
170  typename... Args>
171  LLVM_NODISCARD bool
172  GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
173  FromDeclT *FromD, Args &&... args) {
174  ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
175  if (ToD)
176  return true; // Already imported.
177  ToD = CreateFun(std::forward<Args>(args)...);
178  InitializeImportedDecl(FromD, ToD);
179  return false; // A new Decl is created.
180  }
181 
182  void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
183  Importer.MapImported(FromD, ToD);
185  if (FromD->hasAttrs())
186  for (const Attr *FromAttr : FromD->getAttrs())
187  ToD->addAttr(Importer.Import(FromAttr));
188  if (FromD->isUsed())
189  ToD->setIsUsed();
190  if (FromD->isImplicit())
191  ToD->setImplicit();
192  }
193 
194  public:
195  explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
196 
200 
201  // Importing types
202  QualType VisitType(const Type *T);
203  QualType VisitAtomicType(const AtomicType *T);
204  QualType VisitBuiltinType(const BuiltinType *T);
205  QualType VisitDecayedType(const DecayedType *T);
206  QualType VisitComplexType(const ComplexType *T);
207  QualType VisitPointerType(const PointerType *T);
208  QualType VisitBlockPointerType(const BlockPointerType *T);
209  QualType VisitLValueReferenceType(const LValueReferenceType *T);
210  QualType VisitRValueReferenceType(const RValueReferenceType *T);
211  QualType VisitMemberPointerType(const MemberPointerType *T);
212  QualType VisitConstantArrayType(const ConstantArrayType *T);
213  QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
214  QualType VisitVariableArrayType(const VariableArrayType *T);
215  QualType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
216  // FIXME: DependentSizedExtVectorType
217  QualType VisitVectorType(const VectorType *T);
218  QualType VisitExtVectorType(const ExtVectorType *T);
219  QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
220  QualType VisitFunctionProtoType(const FunctionProtoType *T);
221  QualType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
222  QualType VisitParenType(const ParenType *T);
223  QualType VisitTypedefType(const TypedefType *T);
224  QualType VisitTypeOfExprType(const TypeOfExprType *T);
225  // FIXME: DependentTypeOfExprType
226  QualType VisitTypeOfType(const TypeOfType *T);
227  QualType VisitDecltypeType(const DecltypeType *T);
228  QualType VisitUnaryTransformType(const UnaryTransformType *T);
229  QualType VisitAutoType(const AutoType *T);
230  QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
231  // FIXME: DependentDecltypeType
232  QualType VisitRecordType(const RecordType *T);
233  QualType VisitEnumType(const EnumType *T);
234  QualType VisitAttributedType(const AttributedType *T);
235  QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
236  QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T);
237  QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
238  QualType VisitElaboratedType(const ElaboratedType *T);
239  QualType VisitDependentNameType(const DependentNameType *T);
240  QualType VisitPackExpansionType(const PackExpansionType *T);
241  QualType VisitDependentTemplateSpecializationType(
243  QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
244  QualType VisitObjCObjectType(const ObjCObjectType *T);
245  QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
246 
247  // Importing declarations
248  bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
249  DeclContext *&LexicalDC, DeclarationName &Name,
250  NamedDecl *&ToD, SourceLocation &Loc);
251  void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
252  void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
253  DeclarationNameInfo& To);
254  void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
255  void ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
256 
257  bool ImportCastPath(CastExpr *E, CXXCastPath &Path);
258 
260 
261  Designator ImportDesignator(const Designator &D);
262 
263  Optional<LambdaCapture> ImportLambdaCapture(const LambdaCapture &From);
264 
265  /// What we should import from the definition.
267  /// Import the default subset of the definition, which might be
268  /// nothing (if minimal import is set) or might be everything (if minimal
269  /// import is not set).
271 
272  /// Import everything.
274 
275  /// Import only the bare bones needed to establish a valid
276  /// DeclContext.
277  IDK_Basic
278  };
279 
281  return IDK == IDK_Everything ||
282  (IDK == IDK_Default && !Importer.isMinimalImport());
283  }
284 
285  bool ImportInitializer(VarDecl *From, VarDecl *To);
286  bool ImportDefinition(RecordDecl *From, RecordDecl *To,
287  ImportDefinitionKind Kind = IDK_Default);
288  bool ImportDefinition(EnumDecl *From, EnumDecl *To,
289  ImportDefinitionKind Kind = IDK_Default);
291  ImportDefinitionKind Kind = IDK_Default);
293  ImportDefinitionKind Kind = IDK_Default);
294  TemplateParameterList *ImportTemplateParameterList(
295  TemplateParameterList *Params);
296  TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
297  Optional<TemplateArgumentLoc> ImportTemplateArgumentLoc(
298  const TemplateArgumentLoc &TALoc);
299  bool ImportTemplateArguments(const TemplateArgument *FromArgs,
300  unsigned NumFromArgs,
302 
303  template <typename InContainerTy>
304  bool ImportTemplateArgumentListInfo(const InContainerTy &Container,
305  TemplateArgumentListInfo &ToTAInfo);
306 
307  template<typename InContainerTy>
308  bool ImportTemplateArgumentListInfo(SourceLocation FromLAngleLoc,
309  SourceLocation FromRAngleLoc,
310  const InContainerTy &Container,
312 
315  std::tuple<FunctionTemplateDecl *, OptionalTemplateArgsTy>
316  ImportFunctionTemplateWithTemplateArgsFromSpecialization(
317  FunctionDecl *FromFD);
318 
319  bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
320 
321  bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
322  bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
323  bool Complain = true);
324  bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
325  bool Complain = true);
326  bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
327  bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
328  bool IsStructuralMatch(FunctionTemplateDecl *From,
330  bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
331  bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
332  bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
333  Decl *VisitDecl(Decl *D);
334  Decl *VisitEmptyDecl(EmptyDecl *D);
335  Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
336  Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
337  Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
338  Decl *VisitNamespaceDecl(NamespaceDecl *D);
339  Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
340  Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
341  Decl *VisitTypedefDecl(TypedefDecl *D);
342  Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
343  Decl *VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
344  Decl *VisitLabelDecl(LabelDecl *D);
345  Decl *VisitEnumDecl(EnumDecl *D);
346  Decl *VisitRecordDecl(RecordDecl *D);
347  Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
348  Decl *VisitFunctionDecl(FunctionDecl *D);
349  Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
350  Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
351  Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
352  Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
353  Decl *VisitFieldDecl(FieldDecl *D);
354  Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
355  Decl *VisitFriendDecl(FriendDecl *D);
356  Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
357  Decl *VisitVarDecl(VarDecl *D);
358  Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
359  Decl *VisitParmVarDecl(ParmVarDecl *D);
360  Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
361  Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
362  Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
363  Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
364  Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
365  Decl *VisitUsingDecl(UsingDecl *D);
366  Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
367  Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
368  Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
369  Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
370 
371  ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
372  Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
373  Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
374  Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
375  Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
376  Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
377  Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
378  Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
379  Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
380  Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
381  Decl *VisitClassTemplateSpecializationDecl(
383  Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
384  Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
385  Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
386 
387  // Importing statements
388  DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
389 
390  Stmt *VisitStmt(Stmt *S);
391  Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
392  Stmt *VisitDeclStmt(DeclStmt *S);
393  Stmt *VisitNullStmt(NullStmt *S);
394  Stmt *VisitCompoundStmt(CompoundStmt *S);
395  Stmt *VisitCaseStmt(CaseStmt *S);
396  Stmt *VisitDefaultStmt(DefaultStmt *S);
397  Stmt *VisitLabelStmt(LabelStmt *S);
398  Stmt *VisitAttributedStmt(AttributedStmt *S);
399  Stmt *VisitIfStmt(IfStmt *S);
400  Stmt *VisitSwitchStmt(SwitchStmt *S);
401  Stmt *VisitWhileStmt(WhileStmt *S);
402  Stmt *VisitDoStmt(DoStmt *S);
403  Stmt *VisitForStmt(ForStmt *S);
404  Stmt *VisitGotoStmt(GotoStmt *S);
405  Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
406  Stmt *VisitContinueStmt(ContinueStmt *S);
407  Stmt *VisitBreakStmt(BreakStmt *S);
408  Stmt *VisitReturnStmt(ReturnStmt *S);
409  // FIXME: MSAsmStmt
410  // FIXME: SEHExceptStmt
411  // FIXME: SEHFinallyStmt
412  // FIXME: SEHTryStmt
413  // FIXME: SEHLeaveStmt
414  // FIXME: CapturedStmt
415  Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
416  Stmt *VisitCXXTryStmt(CXXTryStmt *S);
417  Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
418  // FIXME: MSDependentExistsStmt
419  Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
420  Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
421  Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
422  Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
423  Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
424  Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
425  Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
426 
427  // Importing expressions
428  Expr *VisitExpr(Expr *E);
429  Expr *VisitVAArgExpr(VAArgExpr *E);
430  Expr *VisitGNUNullExpr(GNUNullExpr *E);
431  Expr *VisitPredefinedExpr(PredefinedExpr *E);
432  Expr *VisitDeclRefExpr(DeclRefExpr *E);
433  Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
434  Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
435  Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
436  Expr *VisitIntegerLiteral(IntegerLiteral *E);
437  Expr *VisitFloatingLiteral(FloatingLiteral *E);
438  Expr *VisitImaginaryLiteral(ImaginaryLiteral *E);
439  Expr *VisitCharacterLiteral(CharacterLiteral *E);
440  Expr *VisitStringLiteral(StringLiteral *E);
441  Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
442  Expr *VisitAtomicExpr(AtomicExpr *E);
443  Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
444  Expr *VisitParenExpr(ParenExpr *E);
445  Expr *VisitParenListExpr(ParenListExpr *E);
446  Expr *VisitStmtExpr(StmtExpr *E);
447  Expr *VisitUnaryOperator(UnaryOperator *E);
448  Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
449  Expr *VisitBinaryOperator(BinaryOperator *E);
450  Expr *VisitConditionalOperator(ConditionalOperator *E);
451  Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
452  Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
453  Expr *VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
454  Expr *VisitExpressionTraitExpr(ExpressionTraitExpr *E);
455  Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
456  Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
457  Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
458  Expr *VisitExplicitCastExpr(ExplicitCastExpr *E);
459  Expr *VisitOffsetOfExpr(OffsetOfExpr *OE);
460  Expr *VisitCXXThrowExpr(CXXThrowExpr *E);
461  Expr *VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
462  Expr *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
463  Expr *VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
464  Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
465  Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
466  Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
467  Expr *VisitPackExpansionExpr(PackExpansionExpr *E);
468  Expr *VisitSizeOfPackExpr(SizeOfPackExpr *E);
469  Expr *VisitCXXNewExpr(CXXNewExpr *CE);
470  Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
471  Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
472  Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
473  Expr *VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
474  Expr *VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
475  Expr *VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *CE);
476  Expr *VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
477  Expr *VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
478  Expr *VisitExprWithCleanups(ExprWithCleanups *EWC);
479  Expr *VisitCXXThisExpr(CXXThisExpr *E);
480  Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
481  Expr *VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
482  Expr *VisitMemberExpr(MemberExpr *E);
483  Expr *VisitCallExpr(CallExpr *E);
484  Expr *VisitLambdaExpr(LambdaExpr *LE);
485  Expr *VisitInitListExpr(InitListExpr *E);
486  Expr *VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
487  Expr *VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
488  Expr *VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
489  Expr *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
490  Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
491  Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
492  Expr *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
493  Expr *VisitTypeTraitExpr(TypeTraitExpr *E);
494  Expr *VisitCXXTypeidExpr(CXXTypeidExpr *E);
495 
496  template<typename IIter, typename OIter>
497  void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
498  using ItemT = typename std::remove_reference<decltype(*Obegin)>::type;
499 
500  ASTImporter &ImporterRef = Importer;
501  std::transform(Ibegin, Iend, Obegin,
502  [&ImporterRef](ItemT From) -> ItemT {
503  return ImporterRef.Import(From);
504  });
505  }
506 
507  template<typename IIter, typename OIter>
508  bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
510 
511  ASTImporter &ImporterRef = Importer;
512  bool Failed = false;
513  std::transform(Ibegin, Iend, Obegin,
514  [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
515  auto *To = cast_or_null<ItemT>(ImporterRef.Import(From));
516  if (!To && From)
517  Failed = true;
518  return To;
519  });
520  return Failed;
521  }
522 
523  template<typename InContainerTy, typename OutContainerTy>
524  bool ImportContainerChecked(const InContainerTy &InContainer,
525  OutContainerTy &OutContainer) {
526  return ImportArrayChecked(InContainer.begin(), InContainer.end(),
527  OutContainer.begin());
528  }
529 
530  template<typename InContainerTy, typename OIter>
531  bool ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
532  return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
533  }
534 
535  // Importing overrides.
536  void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod);
537 
538  FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl *FromFD);
539  };
540 
541 template <typename InContainerTy>
543  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
544  const InContainerTy &Container, TemplateArgumentListInfo &Result) {
545  TemplateArgumentListInfo ToTAInfo(Importer.Import(FromLAngleLoc),
546  Importer.Import(FromRAngleLoc));
547  if (ImportTemplateArgumentListInfo(Container, ToTAInfo))
548  return true;
549  Result = ToTAInfo;
550  return false;
551 }
552 
553 template <>
554 bool ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
556  return ImportTemplateArgumentListInfo(
557  From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
558 }
559 
560 template <>
564  return ImportTemplateArgumentListInfo(From.LAngleLoc, From.RAngleLoc,
565  From.arguments(), Result);
566 }
567 
568 std::tuple<FunctionTemplateDecl *, ASTNodeImporter::OptionalTemplateArgsTy>
570  FunctionDecl *FromFD) {
571  assert(FromFD->getTemplatedKind() ==
573  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
574  auto *Template = cast_or_null<FunctionTemplateDecl>(
575  Importer.Import(FTSInfo->getTemplate()));
576 
577  // Import template arguments.
578  auto TemplArgs = FTSInfo->TemplateArguments->asArray();
579  TemplateArgsTy ToTemplArgs;
580  if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
581  ToTemplArgs)) // Error during import.
582  return std::make_tuple(Template, OptionalTemplateArgsTy());
583 
584  return std::make_tuple(Template, ToTemplArgs);
585 }
586 
587 } // namespace clang
588 
589 //----------------------------------------------------------------------------
590 // Import Types
591 //----------------------------------------------------------------------------
592 
593 using namespace clang;
594 
596  Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
597  << T->getTypeClassName();
598  return {};
599 }
600 
602  QualType UnderlyingType = Importer.Import(T->getValueType());
603  if(UnderlyingType.isNull())
604  return {};
605 
606  return Importer.getToContext().getAtomicType(UnderlyingType);
607 }
608 
610  switch (T->getKind()) {
611 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
612  case BuiltinType::Id: \
613  return Importer.getToContext().SingletonId;
614 #include "clang/Basic/OpenCLImageTypes.def"
615 #define SHARED_SINGLETON_TYPE(Expansion)
616 #define BUILTIN_TYPE(Id, SingletonId) \
617  case BuiltinType::Id: return Importer.getToContext().SingletonId;
618 #include "clang/AST/BuiltinTypes.def"
619 
620  // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
621  // context supports C++.
622 
623  // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
624  // context supports ObjC.
625 
626  case BuiltinType::Char_U:
627  // The context we're importing from has an unsigned 'char'. If we're
628  // importing into a context with a signed 'char', translate to
629  // 'unsigned char' instead.
630  if (Importer.getToContext().getLangOpts().CharIsSigned)
631  return Importer.getToContext().UnsignedCharTy;
632 
633  return Importer.getToContext().CharTy;
634 
635  case BuiltinType::Char_S:
636  // The context we're importing from has an unsigned 'char'. If we're
637  // importing into a context with a signed 'char', translate to
638  // 'unsigned char' instead.
639  if (!Importer.getToContext().getLangOpts().CharIsSigned)
640  return Importer.getToContext().SignedCharTy;
641 
642  return Importer.getToContext().CharTy;
643 
644  case BuiltinType::WChar_S:
645  case BuiltinType::WChar_U:
646  // FIXME: If not in C++, shall we translate to the C equivalent of
647  // wchar_t?
648  return Importer.getToContext().WCharTy;
649  }
650 
651  llvm_unreachable("Invalid BuiltinType Kind!");
652 }
653 
655  QualType OrigT = Importer.Import(T->getOriginalType());
656  if (OrigT.isNull())
657  return {};
658 
659  return Importer.getToContext().getDecayedType(OrigT);
660 }
661 
663  QualType ToElementType = Importer.Import(T->getElementType());
664  if (ToElementType.isNull())
665  return {};
666 
667  return Importer.getToContext().getComplexType(ToElementType);
668 }
669 
671  QualType ToPointeeType = Importer.Import(T->getPointeeType());
672  if (ToPointeeType.isNull())
673  return {};
674 
675  return Importer.getToContext().getPointerType(ToPointeeType);
676 }
677 
679  // FIXME: Check for blocks support in "to" context.
680  QualType ToPointeeType = Importer.Import(T->getPointeeType());
681  if (ToPointeeType.isNull())
682  return {};
683 
684  return Importer.getToContext().getBlockPointerType(ToPointeeType);
685 }
686 
687 QualType
689  // FIXME: Check for C++ support in "to" context.
690  QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
691  if (ToPointeeType.isNull())
692  return {};
693 
694  return Importer.getToContext().getLValueReferenceType(ToPointeeType);
695 }
696 
697 QualType
699  // FIXME: Check for C++0x support in "to" context.
700  QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
701  if (ToPointeeType.isNull())
702  return {};
703 
704  return Importer.getToContext().getRValueReferenceType(ToPointeeType);
705 }
706 
708  // FIXME: Check for C++ support in "to" context.
709  QualType ToPointeeType = Importer.Import(T->getPointeeType());
710  if (ToPointeeType.isNull())
711  return {};
712 
713  QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
714  return Importer.getToContext().getMemberPointerType(ToPointeeType,
715  ClassType.getTypePtr());
716 }
717 
719  QualType ToElementType = Importer.Import(T->getElementType());
720  if (ToElementType.isNull())
721  return {};
722 
723  return Importer.getToContext().getConstantArrayType(ToElementType,
724  T->getSize(),
725  T->getSizeModifier(),
727 }
728 
729 QualType
731  QualType ToElementType = Importer.Import(T->getElementType());
732  if (ToElementType.isNull())
733  return {};
734 
735  return Importer.getToContext().getIncompleteArrayType(ToElementType,
736  T->getSizeModifier(),
738 }
739 
741  QualType ToElementType = Importer.Import(T->getElementType());
742  if (ToElementType.isNull())
743  return {};
744 
745  Expr *Size = Importer.Import(T->getSizeExpr());
746  if (!Size)
747  return {};
748 
749  SourceRange Brackets = Importer.Import(T->getBracketsRange());
750  return Importer.getToContext().getVariableArrayType(ToElementType, Size,
751  T->getSizeModifier(),
753  Brackets);
754 }
755 
757  const DependentSizedArrayType *T) {
758  QualType ToElementType = Importer.Import(T->getElementType());
759  if (ToElementType.isNull())
760  return {};
761 
762  // SizeExpr may be null if size is not specified directly.
763  // For example, 'int a[]'.
764  Expr *Size = Importer.Import(T->getSizeExpr());
765  if (!Size && T->getSizeExpr())
766  return {};
767 
768  SourceRange Brackets = Importer.Import(T->getBracketsRange());
769  return Importer.getToContext().getDependentSizedArrayType(
770  ToElementType, Size, T->getSizeModifier(), T->getIndexTypeCVRQualifiers(),
771  Brackets);
772 }
773 
775  QualType ToElementType = Importer.Import(T->getElementType());
776  if (ToElementType.isNull())
777  return {};
778 
779  return Importer.getToContext().getVectorType(ToElementType,
780  T->getNumElements(),
781  T->getVectorKind());
782 }
783 
785  QualType ToElementType = Importer.Import(T->getElementType());
786  if (ToElementType.isNull())
787  return {};
788 
789  return Importer.getToContext().getExtVectorType(ToElementType,
790  T->getNumElements());
791 }
792 
793 QualType
795  // FIXME: What happens if we're importing a function without a prototype
796  // into C++? Should we make it variadic?
797  QualType ToResultType = Importer.Import(T->getReturnType());
798  if (ToResultType.isNull())
799  return {};
800 
801  return Importer.getToContext().getFunctionNoProtoType(ToResultType,
802  T->getExtInfo());
803 }
804 
806  QualType ToResultType = Importer.Import(T->getReturnType());
807  if (ToResultType.isNull())
808  return {};
809 
810  // Import argument types
811  SmallVector<QualType, 4> ArgTypes;
812  for (const auto &A : T->param_types()) {
813  QualType ArgType = Importer.Import(A);
814  if (ArgType.isNull())
815  return {};
816  ArgTypes.push_back(ArgType);
817  }
818 
819  // Import exception types
820  SmallVector<QualType, 4> ExceptionTypes;
821  for (const auto &E : T->exceptions()) {
822  QualType ExceptionType = Importer.Import(E);
823  if (ExceptionType.isNull())
824  return {};
825  ExceptionTypes.push_back(ExceptionType);
826  }
827 
830 
831  ToEPI.ExtInfo = FromEPI.ExtInfo;
832  ToEPI.Variadic = FromEPI.Variadic;
833  ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
834  ToEPI.TypeQuals = FromEPI.TypeQuals;
835  ToEPI.RefQualifier = FromEPI.RefQualifier;
836  ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
837  ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
839  Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
840  ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
841  Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
842  ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
843  Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
844 
845  return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
846 }
847 
849  const UnresolvedUsingType *T) {
850  const auto *ToD =
851  cast_or_null<UnresolvedUsingTypenameDecl>(Importer.Import(T->getDecl()));
852  if (!ToD)
853  return {};
854 
855  auto *ToPrevD =
856  cast_or_null<UnresolvedUsingTypenameDecl>(
857  Importer.Import(T->getDecl()->getPreviousDecl()));
858  if (!ToPrevD && T->getDecl()->getPreviousDecl())
859  return {};
860 
861  return Importer.getToContext().getTypeDeclType(ToD, ToPrevD);
862 }
863 
865  QualType ToInnerType = Importer.Import(T->getInnerType());
866  if (ToInnerType.isNull())
867  return {};
868 
869  return Importer.getToContext().getParenType(ToInnerType);
870 }
871 
873  auto *ToDecl =
874  dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
875  if (!ToDecl)
876  return {};
877 
878  return Importer.getToContext().getTypeDeclType(ToDecl);
879 }
880 
882  Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
883  if (!ToExpr)
884  return {};
885 
886  return Importer.getToContext().getTypeOfExprType(ToExpr);
887 }
888 
890  QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
891  if (ToUnderlyingType.isNull())
892  return {};
893 
894  return Importer.getToContext().getTypeOfType(ToUnderlyingType);
895 }
896 
898  // FIXME: Make sure that the "to" context supports C++0x!
899  Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
900  if (!ToExpr)
901  return {};
902 
903  QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
904  if (UnderlyingType.isNull())
905  return {};
906 
907  return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
908 }
909 
911  QualType ToBaseType = Importer.Import(T->getBaseType());
912  QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
913  if (ToBaseType.isNull() || ToUnderlyingType.isNull())
914  return {};
915 
916  return Importer.getToContext().getUnaryTransformType(ToBaseType,
917  ToUnderlyingType,
918  T->getUTTKind());
919 }
920 
922  // FIXME: Make sure that the "to" context supports C++11!
923  QualType FromDeduced = T->getDeducedType();
924  QualType ToDeduced;
925  if (!FromDeduced.isNull()) {
926  ToDeduced = Importer.Import(FromDeduced);
927  if (ToDeduced.isNull())
928  return {};
929  }
930 
931  return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
932  /*IsDependent*/false);
933 }
934 
936  const InjectedClassNameType *T) {
937  auto *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
938  if (!D)
939  return {};
940 
941  QualType InjType = Importer.Import(T->getInjectedSpecializationType());
942  if (InjType.isNull())
943  return {};
944 
945  // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
946  // See comments in InjectedClassNameType definition for details
947  // return Importer.getToContext().getInjectedClassNameType(D, InjType);
948  enum {
951  };
952 
953  return QualType(new (Importer.getToContext(), TypeAlignment)
954  InjectedClassNameType(D, InjType), 0);
955 }
956 
958  auto *ToDecl = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
959  if (!ToDecl)
960  return {};
961 
962  return Importer.getToContext().getTagDeclType(ToDecl);
963 }
964 
966  auto *ToDecl = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
967  if (!ToDecl)
968  return {};
969 
970  return Importer.getToContext().getTagDeclType(ToDecl);
971 }
972 
974  QualType FromModifiedType = T->getModifiedType();
975  QualType FromEquivalentType = T->getEquivalentType();
976  QualType ToModifiedType;
977  QualType ToEquivalentType;
978 
979  if (!FromModifiedType.isNull()) {
980  ToModifiedType = Importer.Import(FromModifiedType);
981  if (ToModifiedType.isNull())
982  return {};
983  }
984  if (!FromEquivalentType.isNull()) {
985  ToEquivalentType = Importer.Import(FromEquivalentType);
986  if (ToEquivalentType.isNull())
987  return {};
988  }
989 
990  return Importer.getToContext().getAttributedType(T->getAttrKind(),
991  ToModifiedType, ToEquivalentType);
992 }
993 
995  const TemplateTypeParmType *T) {
996  auto *ParmDecl =
997  cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
998  if (!ParmDecl && T->getDecl())
999  return {};
1000 
1001  return Importer.getToContext().getTemplateTypeParmType(
1002  T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
1003 }
1004 
1006  const SubstTemplateTypeParmType *T) {
1007  const auto *Replaced =
1008  cast_or_null<TemplateTypeParmType>(Importer.Import(
1009  QualType(T->getReplacedParameter(), 0)).getTypePtr());
1010  if (!Replaced)
1011  return {};
1012 
1013  QualType Replacement = Importer.Import(T->getReplacementType());
1014  if (Replacement.isNull())
1015  return {};
1016  Replacement = Replacement.getCanonicalType();
1017 
1018  return Importer.getToContext().getSubstTemplateTypeParmType(
1019  Replaced, Replacement);
1020 }
1021 
1023  const TemplateSpecializationType *T) {
1024  TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1025  if (ToTemplate.isNull())
1026  return {};
1027 
1028  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1029  if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1030  return {};
1031 
1032  QualType ToCanonType;
1033  if (!QualType(T, 0).isCanonical()) {
1034  QualType FromCanonType
1035  = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1036  ToCanonType =Importer.Import(FromCanonType);
1037  if (ToCanonType.isNull())
1038  return {};
1039  }
1040  return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1041  ToTemplateArgs,
1042  ToCanonType);
1043 }
1044 
1046  NestedNameSpecifier *ToQualifier = nullptr;
1047  // Note: the qualifier in an ElaboratedType is optional.
1048  if (T->getQualifier()) {
1049  ToQualifier = Importer.Import(T->getQualifier());
1050  if (!ToQualifier)
1051  return {};
1052  }
1053 
1054  QualType ToNamedType = Importer.Import(T->getNamedType());
1055  if (ToNamedType.isNull())
1056  return {};
1057 
1058  TagDecl *OwnedTagDecl =
1059  cast_or_null<TagDecl>(Importer.Import(T->getOwnedTagDecl()));
1060  if (!OwnedTagDecl && T->getOwnedTagDecl())
1061  return {};
1062 
1063  return Importer.getToContext().getElaboratedType(T->getKeyword(),
1064  ToQualifier, ToNamedType,
1065  OwnedTagDecl);
1066 }
1067 
1069  QualType Pattern = Importer.Import(T->getPattern());
1070  if (Pattern.isNull())
1071  return {};
1072 
1073  return Importer.getToContext().getPackExpansionType(Pattern,
1074  T->getNumExpansions());
1075 }
1076 
1079  NestedNameSpecifier *Qualifier = Importer.Import(T->getQualifier());
1080  if (!Qualifier && T->getQualifier())
1081  return {};
1082 
1083  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1084  if (!Name && T->getIdentifier())
1085  return {};
1086 
1088  ToPack.reserve(T->getNumArgs());
1089  if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToPack))
1090  return {};
1091 
1092  return Importer.getToContext().getDependentTemplateSpecializationType(
1093  T->getKeyword(), Qualifier, Name, ToPack);
1094 }
1095 
1097  NestedNameSpecifier *NNS = Importer.Import(T->getQualifier());
1098  if (!NNS && T->getQualifier())
1099  return QualType();
1100 
1101  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1102  if (!Name && T->getIdentifier())
1103  return QualType();
1104 
1105  QualType Canon = (T == T->getCanonicalTypeInternal().getTypePtr())
1106  ? QualType()
1107  : Importer.Import(T->getCanonicalTypeInternal());
1108  if (!Canon.isNull())
1109  Canon = Canon.getCanonicalType();
1110 
1111  return Importer.getToContext().getDependentNameType(T->getKeyword(), NNS,
1112  Name, Canon);
1113 }
1114 
1116  auto *Class =
1117  dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1118  if (!Class)
1119  return {};
1120 
1121  return Importer.getToContext().getObjCInterfaceType(Class);
1122 }
1123 
1125  QualType ToBaseType = Importer.Import(T->getBaseType());
1126  if (ToBaseType.isNull())
1127  return {};
1128 
1129  SmallVector<QualType, 4> TypeArgs;
1130  for (auto TypeArg : T->getTypeArgsAsWritten()) {
1131  QualType ImportedTypeArg = Importer.Import(TypeArg);
1132  if (ImportedTypeArg.isNull())
1133  return {};
1134 
1135  TypeArgs.push_back(ImportedTypeArg);
1136  }
1137 
1139  for (auto *P : T->quals()) {
1140  auto *Protocol = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1141  if (!Protocol)
1142  return {};
1143  Protocols.push_back(Protocol);
1144  }
1145 
1146  return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1147  Protocols,
1148  T->isKindOfTypeAsWritten());
1149 }
1150 
1151 QualType
1153  QualType ToPointeeType = Importer.Import(T->getPointeeType());
1154  if (ToPointeeType.isNull())
1155  return {};
1156 
1157  return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1158 }
1159 
1160 //----------------------------------------------------------------------------
1161 // Import Declarations
1162 //----------------------------------------------------------------------------
1164  DeclContext *&LexicalDC,
1165  DeclarationName &Name,
1166  NamedDecl *&ToD,
1167  SourceLocation &Loc) {
1168  // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1169  // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1170  DeclContext *OrigDC = D->getDeclContext();
1171  FunctionDecl *FunDecl;
1172  if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1173  FunDecl->hasBody()) {
1174  auto getLeafPointeeType = [](const Type *T) {
1175  while (T->isPointerType() || T->isArrayType()) {
1176  T = T->getPointeeOrArrayElementType();
1177  }
1178  return T;
1179  };
1180  for (const ParmVarDecl *P : FunDecl->parameters()) {
1181  const Type *LeafT =
1182  getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1183  auto *RT = dyn_cast<RecordType>(LeafT);
1184  if (RT && RT->getDecl() == D) {
1185  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1186  << D->getDeclKindName();
1187  return true;
1188  }
1189  }
1190  }
1191 
1192  // Import the context of this declaration.
1193  DC = Importer.ImportContext(OrigDC);
1194  if (!DC)
1195  return true;
1196 
1197  LexicalDC = DC;
1198  if (D->getDeclContext() != D->getLexicalDeclContext()) {
1199  LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1200  if (!LexicalDC)
1201  return true;
1202  }
1203 
1204  // Import the name of this declaration.
1205  Name = Importer.Import(D->getDeclName());
1206  if (D->getDeclName() && !Name)
1207  return true;
1208 
1209  // Import the location of this declaration.
1210  Loc = Importer.Import(D->getLocation());
1211  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1212  return false;
1213 }
1214 
1216  if (!FromD)
1217  return;
1218 
1219  if (!ToD) {
1220  ToD = Importer.Import(FromD);
1221  if (!ToD)
1222  return;
1223  }
1224 
1225  if (auto *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1226  if (auto *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1227  if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1228  ImportDefinition(FromRecord, ToRecord);
1229  }
1230  }
1231  return;
1232  }
1233 
1234  if (auto *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1235  if (auto *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1236  if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1237  ImportDefinition(FromEnum, ToEnum);
1238  }
1239  }
1240  return;
1241  }
1242 }
1243 
1244 void
1246  DeclarationNameInfo& To) {
1247  // NOTE: To.Name and To.Loc are already imported.
1248  // We only have to import To.LocInfo.
1249  switch (To.getName().getNameKind()) {
1256  return;
1257 
1259  SourceRange Range = From.getCXXOperatorNameRange();
1260  To.setCXXOperatorNameRange(Importer.Import(Range));
1261  return;
1262  }
1265  To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1266  return;
1267  }
1271  TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1272  To.setNamedTypeInfo(Importer.Import(FromTInfo));
1273  return;
1274  }
1275  }
1276  llvm_unreachable("Unknown name kind.");
1277 }
1278 
1279 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1280  if (Importer.isMinimalImport() && !ForceImport) {
1281  Importer.ImportContext(FromDC);
1282  return;
1283  }
1284 
1285  for (auto *From : FromDC->decls())
1286  Importer.Import(From);
1287 }
1288 
1290  const CXXRecordDecl *From, CXXRecordDecl *To) {
1291  assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1292  "Import implicit methods to or from non-definition");
1293 
1294  for (CXXMethodDecl *FromM : From->methods())
1295  if (FromM->isImplicit())
1296  Importer.Import(FromM);
1297 }
1298 
1300  ASTImporter &Importer) {
1301  if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1302  auto *ToTypedef =
1303  cast_or_null<TypedefNameDecl>(Importer.Import(FromTypedef));
1304  assert (ToTypedef && "Failed to import typedef of an anonymous structure");
1305 
1306  To->setTypedefNameForAnonDecl(ToTypedef);
1307  }
1308 }
1309 
1312  if (To->getDefinition() || To->isBeingDefined()) {
1313  if (Kind == IDK_Everything)
1314  ImportDeclContext(From, /*ForceImport=*/true);
1315 
1316  return false;
1317  }
1318 
1319  To->startDefinition();
1320 
1321  setTypedefNameForAnonDecl(From, To, Importer);
1322 
1323  // Add base classes.
1324  if (auto *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1325  auto *FromCXX = cast<CXXRecordDecl>(From);
1326 
1327  struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1328  struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1329  ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1330  ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1331  ToData.Aggregate = FromData.Aggregate;
1332  ToData.PlainOldData = FromData.PlainOldData;
1333  ToData.Empty = FromData.Empty;
1334  ToData.Polymorphic = FromData.Polymorphic;
1335  ToData.Abstract = FromData.Abstract;
1336  ToData.IsStandardLayout = FromData.IsStandardLayout;
1337  ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout;
1338  ToData.HasBasesWithFields = FromData.HasBasesWithFields;
1339  ToData.HasBasesWithNonStaticDataMembers =
1340  FromData.HasBasesWithNonStaticDataMembers;
1341  ToData.HasPrivateFields = FromData.HasPrivateFields;
1342  ToData.HasProtectedFields = FromData.HasProtectedFields;
1343  ToData.HasPublicFields = FromData.HasPublicFields;
1344  ToData.HasMutableFields = FromData.HasMutableFields;
1345  ToData.HasVariantMembers = FromData.HasVariantMembers;
1346  ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1347  ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1348  ToData.HasUninitializedReferenceMember
1349  = FromData.HasUninitializedReferenceMember;
1350  ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1351  ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1352  ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1353  ToData.NeedOverloadResolutionForCopyConstructor
1354  = FromData.NeedOverloadResolutionForCopyConstructor;
1355  ToData.NeedOverloadResolutionForMoveConstructor
1356  = FromData.NeedOverloadResolutionForMoveConstructor;
1357  ToData.NeedOverloadResolutionForMoveAssignment
1358  = FromData.NeedOverloadResolutionForMoveAssignment;
1359  ToData.NeedOverloadResolutionForDestructor
1360  = FromData.NeedOverloadResolutionForDestructor;
1361  ToData.DefaultedCopyConstructorIsDeleted
1362  = FromData.DefaultedCopyConstructorIsDeleted;
1363  ToData.DefaultedMoveConstructorIsDeleted
1364  = FromData.DefaultedMoveConstructorIsDeleted;
1365  ToData.DefaultedMoveAssignmentIsDeleted
1366  = FromData.DefaultedMoveAssignmentIsDeleted;
1367  ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1368  ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1369  ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1370  ToData.HasConstexprNonCopyMoveConstructor
1371  = FromData.HasConstexprNonCopyMoveConstructor;
1372  ToData.HasDefaultedDefaultConstructor
1373  = FromData.HasDefaultedDefaultConstructor;
1374  ToData.DefaultedDefaultConstructorIsConstexpr
1375  = FromData.DefaultedDefaultConstructorIsConstexpr;
1376  ToData.HasConstexprDefaultConstructor
1377  = FromData.HasConstexprDefaultConstructor;
1378  ToData.HasNonLiteralTypeFieldsOrBases
1379  = FromData.HasNonLiteralTypeFieldsOrBases;
1380  // ComputedVisibleConversions not imported.
1381  ToData.UserProvidedDefaultConstructor
1382  = FromData.UserProvidedDefaultConstructor;
1383  ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1384  ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1385  = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1386  ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1387  = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1388  ToData.ImplicitCopyAssignmentHasConstParam
1389  = FromData.ImplicitCopyAssignmentHasConstParam;
1390  ToData.HasDeclaredCopyConstructorWithConstParam
1391  = FromData.HasDeclaredCopyConstructorWithConstParam;
1392  ToData.HasDeclaredCopyAssignmentWithConstParam
1393  = FromData.HasDeclaredCopyAssignmentWithConstParam;
1394 
1396  for (const auto &Base1 : FromCXX->bases()) {
1397  QualType T = Importer.Import(Base1.getType());
1398  if (T.isNull())
1399  return true;
1400 
1401  SourceLocation EllipsisLoc;
1402  if (Base1.isPackExpansion())
1403  EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
1404 
1405  // Ensure that we have a definition for the base.
1406  ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
1407 
1408  Bases.push_back(
1409  new (Importer.getToContext())
1410  CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
1411  Base1.isVirtual(),
1412  Base1.isBaseOfClass(),
1413  Base1.getAccessSpecifierAsWritten(),
1414  Importer.Import(Base1.getTypeSourceInfo()),
1415  EllipsisLoc));
1416  }
1417  if (!Bases.empty())
1418  ToCXX->setBases(Bases.data(), Bases.size());
1419  }
1420 
1421  if (shouldForceImportDeclContext(Kind))
1422  ImportDeclContext(From, /*ForceImport=*/true);
1423 
1424  To->completeDefinition();
1425  return false;
1426 }
1427 
1429  if (To->getAnyInitializer())
1430  return false;
1431 
1432  Expr *FromInit = From->getInit();
1433  if (!FromInit)
1434  return false;
1435 
1436  Expr *ToInit = Importer.Import(const_cast<Expr *>(FromInit));
1437  if (!ToInit)
1438  return true;
1439 
1440  To->setInit(ToInit);
1441  if (From->isInitKnownICE()) {
1442  EvaluatedStmt *Eval = To->ensureEvaluatedStmt();
1443  Eval->CheckedICE = true;
1444  Eval->IsICE = From->isInitICE();
1445  }
1446 
1447  // FIXME: Other bits to merge?
1448  return false;
1449 }
1450 
1453  if (To->getDefinition() || To->isBeingDefined()) {
1454  if (Kind == IDK_Everything)
1455  ImportDeclContext(From, /*ForceImport=*/true);
1456  return false;
1457  }
1458 
1459  To->startDefinition();
1460 
1461  setTypedefNameForAnonDecl(From, To, Importer);
1462 
1463  QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
1464  if (T.isNull())
1465  return true;
1466 
1467  QualType ToPromotionType = Importer.Import(From->getPromotionType());
1468  if (ToPromotionType.isNull())
1469  return true;
1470 
1471  if (shouldForceImportDeclContext(Kind))
1472  ImportDeclContext(From, /*ForceImport=*/true);
1473 
1474  // FIXME: we might need to merge the number of positive or negative bits
1475  // if the enumerator lists don't match.
1476  To->completeDefinition(T, ToPromotionType,
1477  From->getNumPositiveBits(),
1478  From->getNumNegativeBits());
1479  return false;
1480 }
1481 
1483  TemplateParameterList *Params) {
1484  SmallVector<NamedDecl *, 4> ToParams(Params->size());
1485  if (ImportContainerChecked(*Params, ToParams))
1486  return nullptr;
1487 
1488  Expr *ToRequiresClause;
1489  if (Expr *const R = Params->getRequiresClause()) {
1490  ToRequiresClause = Importer.Import(R);
1491  if (!ToRequiresClause)
1492  return nullptr;
1493  } else {
1494  ToRequiresClause = nullptr;
1495  }
1496 
1497  return TemplateParameterList::Create(Importer.getToContext(),
1498  Importer.Import(Params->getTemplateLoc()),
1499  Importer.Import(Params->getLAngleLoc()),
1500  ToParams,
1501  Importer.Import(Params->getRAngleLoc()),
1502  ToRequiresClause);
1503 }
1504 
1507  switch (From.getKind()) {
1509  return TemplateArgument();
1510 
1511  case TemplateArgument::Type: {
1512  QualType ToType = Importer.Import(From.getAsType());
1513  if (ToType.isNull())
1514  return {};
1515  return TemplateArgument(ToType);
1516  }
1517 
1519  QualType ToType = Importer.Import(From.getIntegralType());
1520  if (ToType.isNull())
1521  return {};
1522  return TemplateArgument(From, ToType);
1523  }
1524 
1526  auto *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
1527  QualType ToType = Importer.Import(From.getParamTypeForDecl());
1528  if (!To || ToType.isNull())
1529  return {};
1530  return TemplateArgument(To, ToType);
1531  }
1532 
1534  QualType ToType = Importer.Import(From.getNullPtrType());
1535  if (ToType.isNull())
1536  return {};
1537  return TemplateArgument(ToType, /*isNullPtr*/true);
1538  }
1539 
1541  TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
1542  if (ToTemplate.isNull())
1543  return {};
1544 
1545  return TemplateArgument(ToTemplate);
1546  }
1547 
1549  TemplateName ToTemplate
1550  = Importer.Import(From.getAsTemplateOrTemplatePattern());
1551  if (ToTemplate.isNull())
1552  return {};
1553 
1554  return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
1555  }
1556 
1558  if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
1559  return TemplateArgument(ToExpr);
1560  return TemplateArgument();
1561 
1562  case TemplateArgument::Pack: {
1564  ToPack.reserve(From.pack_size());
1565  if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
1566  return {};
1567 
1568  return TemplateArgument(
1569  llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
1570  }
1571  }
1572 
1573  llvm_unreachable("Invalid template argument kind");
1574 }
1575 
1578  TemplateArgument Arg = ImportTemplateArgument(TALoc.getArgument());
1579  TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
1580  TemplateArgumentLocInfo ToInfo;
1581  if (Arg.getKind() == TemplateArgument::Expression) {
1582  Expr *E = Importer.Import(FromInfo.getAsExpr());
1583  ToInfo = TemplateArgumentLocInfo(E);
1584  if (!E)
1585  return None;
1586  } else if (Arg.getKind() == TemplateArgument::Type) {
1587  if (TypeSourceInfo *TSI = Importer.Import(FromInfo.getAsTypeSourceInfo()))
1588  ToInfo = TemplateArgumentLocInfo(TSI);
1589  else
1590  return None;
1591  } else {
1592  ToInfo = TemplateArgumentLocInfo(
1593  Importer.Import(FromInfo.getTemplateQualifierLoc()),
1594  Importer.Import(FromInfo.getTemplateNameLoc()),
1595  Importer.Import(FromInfo.getTemplateEllipsisLoc()));
1596  }
1597  return TemplateArgumentLoc(Arg, ToInfo);
1598 }
1599 
1601  unsigned NumFromArgs,
1603  for (unsigned I = 0; I != NumFromArgs; ++I) {
1604  TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
1605  if (To.isNull() && !FromArgs[I].isNull())
1606  return true;
1607 
1608  ToArgs.push_back(To);
1609  }
1610 
1611  return false;
1612 }
1613 
1614 // We cannot use Optional<> pattern here and below because
1615 // TemplateArgumentListInfo's operator new is declared as deleted so it cannot
1616 // be stored in Optional.
1617 template <typename InContainerTy>
1619  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1620  for (const auto &FromLoc : Container) {
1621  if (auto ToLoc = ImportTemplateArgumentLoc(FromLoc))
1622  ToTAInfo.addArgument(*ToLoc);
1623  else
1624  return true;
1625  }
1626  return false;
1627 }
1628 
1633 }
1634 
1635 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
1637  Importer.getFromContext(), Importer.getToContext(),
1638  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1639  false, Complain);
1640  return Ctx.IsEquivalent(From, To);
1641 }
1642 
1644  RecordDecl *ToRecord, bool Complain) {
1645  // Eliminate a potential failure point where we attempt to re-import
1646  // something we're trying to import while completing ToRecord.
1647  Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1648  if (ToOrigin) {
1649  auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1650  if (ToOriginRecord)
1651  ToRecord = ToOriginRecord;
1652  }
1653 
1654  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1655  ToRecord->getASTContext(),
1656  Importer.getNonEquivalentDecls(),
1657  getStructuralEquivalenceKind(Importer),
1658  false, Complain);
1659  return Ctx.IsEquivalent(FromRecord, ToRecord);
1660 }
1661 
1663  bool Complain) {
1665  Importer.getFromContext(), Importer.getToContext(),
1666  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1667  false, Complain);
1668  return Ctx.IsEquivalent(FromVar, ToVar);
1669 }
1670 
1673  Importer.getFromContext(), Importer.getToContext(),
1674  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
1675  return Ctx.IsEquivalent(FromEnum, ToEnum);
1676 }
1677 
1679  FunctionTemplateDecl *To) {
1681  Importer.getFromContext(), Importer.getToContext(),
1682  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1683  false, false);
1684  return Ctx.IsEquivalent(From, To);
1685 }
1686 
1689  Importer.getFromContext(), Importer.getToContext(),
1690  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1691  false, false);
1692  return Ctx.IsEquivalent(From, To);
1693 }
1694 
1696  EnumConstantDecl *ToEC) {
1697  const llvm::APSInt &FromVal = FromEC->getInitVal();
1698  const llvm::APSInt &ToVal = ToEC->getInitVal();
1699 
1700  return FromVal.isSigned() == ToVal.isSigned() &&
1701  FromVal.getBitWidth() == ToVal.getBitWidth() &&
1702  FromVal == ToVal;
1703 }
1704 
1706  ClassTemplateDecl *To) {
1707  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1708  Importer.getToContext(),
1709  Importer.getNonEquivalentDecls(),
1710  getStructuralEquivalenceKind(Importer));
1711  return Ctx.IsEquivalent(From, To);
1712 }
1713 
1715  VarTemplateDecl *To) {
1716  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1717  Importer.getToContext(),
1718  Importer.getNonEquivalentDecls(),
1719  getStructuralEquivalenceKind(Importer));
1720  return Ctx.IsEquivalent(From, To);
1721 }
1722 
1724  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1725  << D->getDeclKindName();
1726  return nullptr;
1727 }
1728 
1730  // Import the context of this declaration.
1731  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1732  if (!DC)
1733  return nullptr;
1734 
1735  DeclContext *LexicalDC = DC;
1736  if (D->getDeclContext() != D->getLexicalDeclContext()) {
1737  LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1738  if (!LexicalDC)
1739  return nullptr;
1740  }
1741 
1742  // Import the location of this declaration.
1743  SourceLocation Loc = Importer.Import(D->getLocation());
1744 
1745  EmptyDecl *ToD;
1746  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc))
1747  return ToD;
1748 
1749  ToD->setLexicalDeclContext(LexicalDC);
1750  LexicalDC->addDeclInternal(ToD);
1751  return ToD;
1752 }
1753 
1755  TranslationUnitDecl *ToD =
1756  Importer.getToContext().getTranslationUnitDecl();
1757 
1758  Importer.MapImported(D, ToD);
1759 
1760  return ToD;
1761 }
1762 
1764  SourceLocation Loc = Importer.Import(D->getLocation());
1765  SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
1766 
1767  // Import the context of this declaration.
1768  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1769  if (!DC)
1770  return nullptr;
1771 
1772  AccessSpecDecl *ToD;
1773  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
1774  DC, Loc, ColonLoc))
1775  return ToD;
1776 
1777  // Lexical DeclContext and Semantic DeclContext
1778  // is always the same for the accessSpec.
1779  ToD->setLexicalDeclContext(DC);
1780  DC->addDeclInternal(ToD);
1781 
1782  return ToD;
1783 }
1784 
1786  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1787  if (!DC)
1788  return nullptr;
1789 
1790  DeclContext *LexicalDC = DC;
1791 
1792  // Import the location of this declaration.
1793  SourceLocation Loc = Importer.Import(D->getLocation());
1794 
1795  Expr *AssertExpr = Importer.Import(D->getAssertExpr());
1796  if (!AssertExpr)
1797  return nullptr;
1798 
1799  StringLiteral *FromMsg = D->getMessage();
1800  auto *ToMsg = cast_or_null<StringLiteral>(Importer.Import(FromMsg));
1801  if (!ToMsg && FromMsg)
1802  return nullptr;
1803 
1804  StaticAssertDecl *ToD;
1805  if (GetImportedOrCreateDecl(
1806  ToD, D, Importer.getToContext(), DC, Loc, AssertExpr, ToMsg,
1807  Importer.Import(D->getRParenLoc()), D->isFailed()))
1808  return ToD;
1809 
1810  ToD->setLexicalDeclContext(LexicalDC);
1811  LexicalDC->addDeclInternal(ToD);
1812  return ToD;
1813 }
1814 
1816  // Import the major distinguishing characteristics of this namespace.
1817  DeclContext *DC, *LexicalDC;
1818  DeclarationName Name;
1819  SourceLocation Loc;
1820  NamedDecl *ToD;
1821  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1822  return nullptr;
1823  if (ToD)
1824  return ToD;
1825 
1826  NamespaceDecl *MergeWithNamespace = nullptr;
1827  if (!Name) {
1828  // This is an anonymous namespace. Adopt an existing anonymous
1829  // namespace if we can.
1830  // FIXME: Not testable.
1831  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
1832  MergeWithNamespace = TU->getAnonymousNamespace();
1833  else
1834  MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1835  } else {
1836  SmallVector<NamedDecl *, 4> ConflictingDecls;
1837  SmallVector<NamedDecl *, 2> FoundDecls;
1838  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1839  for (auto *FoundDecl : FoundDecls) {
1841  continue;
1842 
1843  if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
1844  MergeWithNamespace = FoundNS;
1845  ConflictingDecls.clear();
1846  break;
1847  }
1848 
1849  ConflictingDecls.push_back(FoundDecl);
1850  }
1851 
1852  if (!ConflictingDecls.empty()) {
1853  Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
1854  ConflictingDecls.data(),
1855  ConflictingDecls.size());
1856  }
1857  }
1858 
1859  // Create the "to" namespace, if needed.
1860  NamespaceDecl *ToNamespace = MergeWithNamespace;
1861  if (!ToNamespace) {
1862  if (GetImportedOrCreateDecl(
1863  ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
1864  Importer.Import(D->getBeginLoc()), Loc, Name.getAsIdentifierInfo(),
1865  /*PrevDecl=*/nullptr))
1866  return ToNamespace;
1867  ToNamespace->setLexicalDeclContext(LexicalDC);
1868  LexicalDC->addDeclInternal(ToNamespace);
1869 
1870  // If this is an anonymous namespace, register it as the anonymous
1871  // namespace within its context.
1872  if (!Name) {
1873  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
1874  TU->setAnonymousNamespace(ToNamespace);
1875  else
1876  cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
1877  }
1878  }
1879  Importer.MapImported(D, ToNamespace);
1880 
1881  ImportDeclContext(D);
1882 
1883  return ToNamespace;
1884 }
1885 
1887  // Import the major distinguishing characteristics of this namespace.
1888  DeclContext *DC, *LexicalDC;
1889  DeclarationName Name;
1890  SourceLocation Loc;
1891  NamedDecl *LookupD;
1892  if (ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
1893  return nullptr;
1894  if (LookupD)
1895  return LookupD;
1896 
1897  // NOTE: No conflict resolution is done for namespace aliases now.
1898 
1899  auto *TargetDecl = cast_or_null<NamespaceDecl>(
1900  Importer.Import(D->getNamespace()));
1901  if (!TargetDecl)
1902  return nullptr;
1903 
1904  IdentifierInfo *ToII = Importer.Import(D->getIdentifier());
1905  if (!ToII)
1906  return nullptr;
1907 
1908  NestedNameSpecifierLoc ToQLoc = Importer.Import(D->getQualifierLoc());
1909  if (D->getQualifierLoc() && !ToQLoc)
1910  return nullptr;
1911 
1912  NamespaceAliasDecl *ToD;
1913  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC,
1914  Importer.Import(D->getNamespaceLoc()),
1915  Importer.Import(D->getAliasLoc()), ToII, ToQLoc,
1916  Importer.Import(D->getTargetNameLoc()),
1917  TargetDecl))
1918  return ToD;
1919 
1920  ToD->setLexicalDeclContext(LexicalDC);
1921  LexicalDC->addDeclInternal(ToD);
1922 
1923  return ToD;
1924 }
1925 
1927  // Import the major distinguishing characteristics of this typedef.
1928  DeclContext *DC, *LexicalDC;
1929  DeclarationName Name;
1930  SourceLocation Loc;
1931  NamedDecl *ToD;
1932  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1933  return nullptr;
1934  if (ToD)
1935  return ToD;
1936 
1937  // If this typedef is not in block scope, determine whether we've
1938  // seen a typedef with the same name (that we can merge with) or any
1939  // other entity by that name (which name lookup could conflict with).
1940  if (!DC->isFunctionOrMethod()) {
1941  SmallVector<NamedDecl *, 4> ConflictingDecls;
1942  unsigned IDNS = Decl::IDNS_Ordinary;
1943  SmallVector<NamedDecl *, 2> FoundDecls;
1944  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1945  for (auto *FoundDecl : FoundDecls) {
1946  if (!FoundDecl->isInIdentifierNamespace(IDNS))
1947  continue;
1948  if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
1949  if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
1950  FoundTypedef->getUnderlyingType()))
1951  return Importer.MapImported(D, FoundTypedef);
1952  }
1953 
1954  ConflictingDecls.push_back(FoundDecl);
1955  }
1956 
1957  if (!ConflictingDecls.empty()) {
1958  Name = Importer.HandleNameConflict(Name, DC, IDNS,
1959  ConflictingDecls.data(),
1960  ConflictingDecls.size());
1961  if (!Name)
1962  return nullptr;
1963  }
1964  }
1965 
1966  // Import the underlying type of this typedef;
1967  QualType T = Importer.Import(D->getUnderlyingType());
1968  if (T.isNull())
1969  return nullptr;
1970 
1971  // Create the new typedef node.
1972  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1973  SourceLocation StartL = Importer.Import(D->getBeginLoc());
1974 
1975  TypedefNameDecl *ToTypedef;
1976  if (IsAlias) {
1977  if (GetImportedOrCreateDecl<TypeAliasDecl>(
1978  ToTypedef, D, Importer.getToContext(), DC, StartL, Loc,
1979  Name.getAsIdentifierInfo(), TInfo))
1980  return ToTypedef;
1981  } else if (GetImportedOrCreateDecl<TypedefDecl>(
1982  ToTypedef, D, Importer.getToContext(), DC, StartL, Loc,
1983  Name.getAsIdentifierInfo(), TInfo))
1984  return ToTypedef;
1985 
1986  ToTypedef->setAccess(D->getAccess());
1987  ToTypedef->setLexicalDeclContext(LexicalDC);
1988 
1989  // Templated declarations should not appear in DeclContext.
1990  TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
1991  if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
1992  LexicalDC->addDeclInternal(ToTypedef);
1993 
1994  return ToTypedef;
1995 }
1996 
1998  return VisitTypedefNameDecl(D, /*IsAlias=*/false);
1999 }
2000 
2002  return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2003 }
2004 
2006  // Import the major distinguishing characteristics of this typedef.
2007  DeclContext *DC, *LexicalDC;
2008  DeclarationName Name;
2009  SourceLocation Loc;
2010  NamedDecl *FoundD;
2011  if (ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2012  return nullptr;
2013  if (FoundD)
2014  return FoundD;
2015 
2016  // If this typedef is not in block scope, determine whether we've
2017  // seen a typedef with the same name (that we can merge with) or any
2018  // other entity by that name (which name lookup could conflict with).
2019  if (!DC->isFunctionOrMethod()) {
2020  SmallVector<NamedDecl *, 4> ConflictingDecls;
2021  unsigned IDNS = Decl::IDNS_Ordinary;
2022  SmallVector<NamedDecl *, 2> FoundDecls;
2023  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2024  for (auto *FoundDecl : FoundDecls) {
2025  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2026  continue;
2027  if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2028  return Importer.MapImported(D, FoundAlias);
2029  ConflictingDecls.push_back(FoundDecl);
2030  }
2031 
2032  if (!ConflictingDecls.empty()) {
2033  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2034  ConflictingDecls.data(),
2035  ConflictingDecls.size());
2036  if (!Name)
2037  return nullptr;
2038  }
2039  }
2040 
2041  TemplateParameterList *Params = ImportTemplateParameterList(
2042  D->getTemplateParameters());
2043  if (!Params)
2044  return nullptr;
2045 
2046  auto *TemplDecl = cast_or_null<TypeAliasDecl>(
2047  Importer.Import(D->getTemplatedDecl()));
2048  if (!TemplDecl)
2049  return nullptr;
2050 
2051  TypeAliasTemplateDecl *ToAlias;
2052  if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2053  Name, Params, TemplDecl))
2054  return ToAlias;
2055 
2056  TemplDecl->setDescribedAliasTemplate(ToAlias);
2057 
2058  ToAlias->setAccess(D->getAccess());
2059  ToAlias->setLexicalDeclContext(LexicalDC);
2060  LexicalDC->addDeclInternal(ToAlias);
2061  return ToAlias;
2062 }
2063 
2065  // Import the major distinguishing characteristics of this label.
2066  DeclContext *DC, *LexicalDC;
2067  DeclarationName Name;
2068  SourceLocation Loc;
2069  NamedDecl *ToD;
2070  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2071  return nullptr;
2072  if (ToD)
2073  return ToD;
2074 
2075  assert(LexicalDC->isFunctionOrMethod());
2076 
2077  LabelDecl *ToLabel;
2078  if (D->isGnuLocal()
2079  ? GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC,
2080  Importer.Import(D->getLocation()),
2081  Name.getAsIdentifierInfo(),
2082  Importer.Import(D->getBeginLoc()))
2083  : GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC,
2084  Importer.Import(D->getLocation()),
2085  Name.getAsIdentifierInfo()))
2086  return ToLabel;
2087 
2088  auto *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
2089  if (!Label)
2090  return nullptr;
2091 
2092  ToLabel->setStmt(Label);
2093  ToLabel->setLexicalDeclContext(LexicalDC);
2094  LexicalDC->addDeclInternal(ToLabel);
2095  return ToLabel;
2096 }
2097 
2099  // Import the major distinguishing characteristics of this enum.
2100  DeclContext *DC, *LexicalDC;
2101  DeclarationName Name;
2102  SourceLocation Loc;
2103  NamedDecl *ToD;
2104  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2105  return nullptr;
2106  if (ToD)
2107  return ToD;
2108 
2109  // Figure out what enum name we're looking for.
2110  unsigned IDNS = Decl::IDNS_Tag;
2111  DeclarationName SearchName = Name;
2112  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2113  SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2114  IDNS = Decl::IDNS_Ordinary;
2115  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2116  IDNS |= Decl::IDNS_Ordinary;
2117 
2118  // We may already have an enum of the same name; try to find and match it.
2119  if (!DC->isFunctionOrMethod() && SearchName) {
2120  SmallVector<NamedDecl *, 4> ConflictingDecls;
2121  SmallVector<NamedDecl *, 2> FoundDecls;
2122  DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
2123  for (auto *FoundDecl : FoundDecls) {
2124  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2125  continue;
2126 
2127  Decl *Found = FoundDecl;
2128  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2129  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2130  Found = Tag->getDecl();
2131  }
2132 
2133  if (auto *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2134  if (IsStructuralMatch(D, FoundEnum))
2135  return Importer.MapImported(D, FoundEnum);
2136  }
2137 
2138  ConflictingDecls.push_back(FoundDecl);
2139  }
2140 
2141  if (!ConflictingDecls.empty()) {
2142  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2143  ConflictingDecls.data(),
2144  ConflictingDecls.size());
2145  }
2146  }
2147 
2148  // Create the enum declaration.
2149  EnumDecl *D2;
2150  if (GetImportedOrCreateDecl(
2151  D2, D, Importer.getToContext(), DC, Importer.Import(D->getBeginLoc()),
2152  Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2153  D->isScopedUsingClassTag(), D->isFixed()))
2154  return D2;
2155 
2156  // Import the qualifier, if any.
2157  D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2158  D2->setAccess(D->getAccess());
2159  D2->setLexicalDeclContext(LexicalDC);
2160  LexicalDC->addDeclInternal(D2);
2161 
2162  // Import the integer type.
2163  QualType ToIntegerType = Importer.Import(D->getIntegerType());
2164  if (ToIntegerType.isNull())
2165  return nullptr;
2166  D2->setIntegerType(ToIntegerType);
2167 
2168  // Import the definition
2169  if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2170  return nullptr;
2171 
2172  return D2;
2173 }
2174 
2176  bool IsFriendTemplate = false;
2177  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2178  IsFriendTemplate =
2179  DCXX->getDescribedClassTemplate() &&
2180  DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2182  }
2183 
2184  // If this record has a definition in the translation unit we're coming from,
2185  // but this particular declaration is not that definition, import the
2186  // definition and map to that.
2187  TagDecl *Definition = D->getDefinition();
2188  if (Definition && Definition != D &&
2189  // Friend template declaration must be imported on its own.
2190  !IsFriendTemplate &&
2191  // In contrast to a normal CXXRecordDecl, the implicit
2192  // CXXRecordDecl of ClassTemplateSpecializationDecl is its redeclaration.
2193  // The definition of the implicit CXXRecordDecl in this case is the
2194  // ClassTemplateSpecializationDecl itself. Thus, we start with an extra
2195  // condition in order to be able to import the implict Decl.
2196  !D->isImplicit()) {
2197  Decl *ImportedDef = Importer.Import(Definition);
2198  if (!ImportedDef)
2199  return nullptr;
2200 
2201  return Importer.MapImported(D, ImportedDef);
2202  }
2203 
2204  // Import the major distinguishing characteristics of this record.
2205  DeclContext *DC, *LexicalDC;
2206  DeclarationName Name;
2207  SourceLocation Loc;
2208  NamedDecl *ToD;
2209  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2210  return nullptr;
2211  if (ToD)
2212  return ToD;
2213 
2214  // Figure out what structure name we're looking for.
2215  unsigned IDNS = Decl::IDNS_Tag;
2216  DeclarationName SearchName = Name;
2217  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2218  SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2219  IDNS = Decl::IDNS_Ordinary;
2220  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2221  IDNS |= Decl::IDNS_Ordinary;
2222 
2223  // We may already have a record of the same name; try to find and match it.
2224  RecordDecl *AdoptDecl = nullptr;
2225  RecordDecl *PrevDecl = nullptr;
2226  if (!DC->isFunctionOrMethod()) {
2227  SmallVector<NamedDecl *, 4> ConflictingDecls;
2228  SmallVector<NamedDecl *, 2> FoundDecls;
2229  DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
2230 
2231  if (!FoundDecls.empty()) {
2232  // We're going to have to compare D against potentially conflicting Decls, so complete it.
2235  }
2236 
2237  for (auto *FoundDecl : FoundDecls) {
2238  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2239  continue;
2240 
2241  Decl *Found = FoundDecl;
2242  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2243  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2244  Found = Tag->getDecl();
2245  }
2246 
2247  if (D->getDescribedTemplate()) {
2248  if (auto *Template = dyn_cast<ClassTemplateDecl>(Found))
2249  Found = Template->getTemplatedDecl();
2250  else
2251  continue;
2252  }
2253 
2254  if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2255  if (!SearchName) {
2256  if (!IsStructuralMatch(D, FoundRecord, false))
2257  continue;
2258  }
2259 
2260  PrevDecl = FoundRecord;
2261 
2262  if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2263  if ((SearchName && !D->isCompleteDefinition() && !IsFriendTemplate)
2264  || (D->isCompleteDefinition() &&
2266  == FoundDef->isAnonymousStructOrUnion() &&
2267  IsStructuralMatch(D, FoundDef))) {
2268  // The record types structurally match, or the "from" translation
2269  // unit only had a forward declaration anyway; call it the same
2270  // function.
2271  // FIXME: Structural equivalence check should check for same
2272  // user-defined methods.
2273  Importer.MapImported(D, FoundDef);
2274  if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2275  auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2276  assert(FoundCXX && "Record type mismatch");
2277 
2278  if (D->isCompleteDefinition() && !Importer.isMinimalImport())
2279  // FoundDef may not have every implicit method that D has
2280  // because implicit methods are created only if they are used.
2281  ImportImplicitMethods(DCXX, FoundCXX);
2282  }
2283  return FoundDef;
2284  }
2285  } else if (!D->isCompleteDefinition()) {
2286  // We have a forward declaration of this type, so adopt that forward
2287  // declaration rather than building a new one.
2288 
2289  // If one or both can be completed from external storage then try one
2290  // last time to complete and compare them before doing this.
2291 
2292  if (FoundRecord->hasExternalLexicalStorage() &&
2293  !FoundRecord->isCompleteDefinition())
2294  FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2295  if (D->hasExternalLexicalStorage())
2297 
2298  if (FoundRecord->isCompleteDefinition() &&
2299  D->isCompleteDefinition() &&
2300  !IsStructuralMatch(D, FoundRecord))
2301  continue;
2302 
2303  if (IsFriendTemplate)
2304  continue;
2305 
2306  AdoptDecl = FoundRecord;
2307  continue;
2308  } else if (!SearchName) {
2309  continue;
2310  }
2311  }
2312 
2313  ConflictingDecls.push_back(FoundDecl);
2314  }
2315 
2316  if (!ConflictingDecls.empty() && SearchName) {
2317  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2318  ConflictingDecls.data(),
2319  ConflictingDecls.size());
2320  }
2321  }
2322 
2323  // Create the record declaration.
2324  RecordDecl *D2 = AdoptDecl;
2325  SourceLocation StartLoc = Importer.Import(D->getBeginLoc());
2326  if (!D2) {
2327  CXXRecordDecl *D2CXX = nullptr;
2328  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2329  if (DCXX->isLambda()) {
2330  TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
2331  if (GetImportedOrCreateSpecialDecl(
2332  D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2333  DC, TInfo, Loc, DCXX->isDependentLambda(),
2334  DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2335  return D2CXX;
2336  Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
2337  if (DCXX->getLambdaContextDecl() && !CDecl)
2338  return nullptr;
2339  D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
2340  } else if (DCXX->isInjectedClassName()) {
2341  // We have to be careful to do a similar dance to the one in
2342  // Sema::ActOnStartCXXMemberDeclarations
2343  CXXRecordDecl *const PrevDecl = nullptr;
2344  const bool DelayTypeCreation = true;
2345  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2346  D->getTagKind(), DC, StartLoc, Loc,
2347  Name.getAsIdentifierInfo(), PrevDecl,
2348  DelayTypeCreation))
2349  return D2CXX;
2350  Importer.getToContext().getTypeDeclType(
2351  D2CXX, dyn_cast<CXXRecordDecl>(DC));
2352  } else {
2353  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2354  D->getTagKind(), DC, StartLoc, Loc,
2355  Name.getAsIdentifierInfo(),
2356  cast_or_null<CXXRecordDecl>(PrevDecl)))
2357  return D2CXX;
2358  }
2359 
2360  D2 = D2CXX;
2361  D2->setAccess(D->getAccess());
2362  D2->setLexicalDeclContext(LexicalDC);
2363  if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2364  LexicalDC->addDeclInternal(D2);
2365 
2366  if (ClassTemplateDecl *FromDescribed =
2367  DCXX->getDescribedClassTemplate()) {
2368  auto *ToDescribed = cast_or_null<ClassTemplateDecl>(
2369  Importer.Import(FromDescribed));
2370  if (!ToDescribed)
2371  return nullptr;
2372  D2CXX->setDescribedClassTemplate(ToDescribed);
2373  if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2374  // In a record describing a template the type should be an
2375  // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2376  // previously set type to the correct value here (ToDescribed is not
2377  // available at record create).
2378  // FIXME: The previous type is cleared but not removed from
2379  // ASTContext's internal storage.
2380  CXXRecordDecl *Injected = nullptr;
2381  for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2382  auto *Record = dyn_cast<CXXRecordDecl>(Found);
2383  if (Record && Record->isInjectedClassName()) {
2384  Injected = Record;
2385  break;
2386  }
2387  }
2388  D2CXX->setTypeForDecl(nullptr);
2389  Importer.getToContext().getInjectedClassNameType(D2CXX,
2390  ToDescribed->getInjectedClassNameSpecialization());
2391  if (Injected) {
2392  Injected->setTypeForDecl(nullptr);
2393  Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2394  }
2395  }
2396  } else if (MemberSpecializationInfo *MemberInfo =
2397  DCXX->getMemberSpecializationInfo()) {
2399  MemberInfo->getTemplateSpecializationKind();
2400  CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2401  auto *ToInst =
2402  cast_or_null<CXXRecordDecl>(Importer.Import(FromInst));
2403  if (FromInst && !ToInst)
2404  return nullptr;
2405  D2CXX->setInstantiationOfMemberClass(ToInst, SK);
2407  Importer.Import(MemberInfo->getPointOfInstantiation()));
2408  }
2409  } else {
2410  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2411  D->getTagKind(), DC, StartLoc, Loc,
2412  Name.getAsIdentifierInfo(), PrevDecl))
2413  return D2;
2414  D2->setLexicalDeclContext(LexicalDC);
2415  LexicalDC->addDeclInternal(D2);
2416  }
2417 
2418  D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2419  if (D->isAnonymousStructOrUnion())
2420  D2->setAnonymousStructOrUnion(true);
2421  }
2422 
2423  Importer.MapImported(D, D2);
2424 
2425  if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2426  return nullptr;
2427 
2428  return D2;
2429 }
2430 
2432  // Import the major distinguishing characteristics of this enumerator.
2433  DeclContext *DC, *LexicalDC;
2434  DeclarationName Name;
2435  SourceLocation Loc;
2436  NamedDecl *ToD;
2437  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2438  return nullptr;
2439  if (ToD)
2440  return ToD;
2441 
2442  QualType T = Importer.Import(D->getType());
2443  if (T.isNull())
2444  return nullptr;
2445 
2446  // Determine whether there are any other declarations with the same name and
2447  // in the same context.
2448  if (!LexicalDC->isFunctionOrMethod()) {
2449  SmallVector<NamedDecl *, 4> ConflictingDecls;
2450  unsigned IDNS = Decl::IDNS_Ordinary;
2451  SmallVector<NamedDecl *, 2> FoundDecls;
2452  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2453  for (auto *FoundDecl : FoundDecls) {
2454  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2455  continue;
2456 
2457  if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2458  if (IsStructuralMatch(D, FoundEnumConstant))
2459  return Importer.MapImported(D, FoundEnumConstant);
2460  }
2461 
2462  ConflictingDecls.push_back(FoundDecl);
2463  }
2464 
2465  if (!ConflictingDecls.empty()) {
2466  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2467  ConflictingDecls.data(),
2468  ConflictingDecls.size());
2469  if (!Name)
2470  return nullptr;
2471  }
2472  }
2473 
2474  Expr *Init = Importer.Import(D->getInitExpr());
2475  if (D->getInitExpr() && !Init)
2476  return nullptr;
2477 
2478  EnumConstantDecl *ToEnumerator;
2479  if (GetImportedOrCreateDecl(
2480  ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2481  Name.getAsIdentifierInfo(), T, Init, D->getInitVal()))
2482  return ToEnumerator;
2483 
2484  ToEnumerator->setAccess(D->getAccess());
2485  ToEnumerator->setLexicalDeclContext(LexicalDC);
2486  LexicalDC->addDeclInternal(ToEnumerator);
2487  return ToEnumerator;
2488 }
2489 
2491  FunctionDecl *ToFD) {
2492  switch (FromFD->getTemplatedKind()) {
2495  return false;
2496 
2498  auto *InstFD = cast_or_null<FunctionDecl>(
2499  Importer.Import(FromFD->getInstantiatedFromMemberFunction()));
2500  if (!InstFD)
2501  return true;
2502 
2504  SourceLocation POI = Importer.Import(
2506  ToFD->setInstantiationOfMemberFunction(InstFD, TSK);
2508  return false;
2509  }
2510 
2512  FunctionTemplateDecl* Template;
2513  OptionalTemplateArgsTy ToTemplArgs;
2514  std::tie(Template, ToTemplArgs) =
2515  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2516  if (!Template || !ToTemplArgs)
2517  return true;
2518 
2520  Importer.getToContext(), *ToTemplArgs);
2521 
2522  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2523  TemplateArgumentListInfo ToTAInfo;
2524  const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2525  if (FromTAArgsAsWritten)
2526  if (ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo))
2527  return true;
2528 
2529  SourceLocation POI = Importer.Import(FTSInfo->getPointOfInstantiation());
2530 
2531  TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2532  ToFD->setFunctionTemplateSpecialization(
2533  Template, ToTAList, /* InsertPos= */ nullptr,
2534  TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, POI);
2535  return false;
2536  }
2537 
2539  auto *FromInfo = FromFD->getDependentSpecializationInfo();
2540  UnresolvedSet<8> TemplDecls;
2541  unsigned NumTemplates = FromInfo->getNumTemplates();
2542  for (unsigned I = 0; I < NumTemplates; I++) {
2543  if (auto *ToFTD = cast_or_null<FunctionTemplateDecl>(
2544  Importer.Import(FromInfo->getTemplate(I))))
2545  TemplDecls.addDecl(ToFTD);
2546  else
2547  return true;
2548  }
2549 
2550  // Import TemplateArgumentListInfo.
2551  TemplateArgumentListInfo ToTAInfo;
2552  if (ImportTemplateArgumentListInfo(
2553  FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2554  llvm::makeArrayRef(FromInfo->getTemplateArgs(),
2555  FromInfo->getNumTemplateArgs()),
2556  ToTAInfo))
2557  return true;
2558 
2559  ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2560  TemplDecls, ToTAInfo);
2561  return false;
2562  }
2563  }
2564  llvm_unreachable("All cases should be covered!");
2565 }
2566 
2567 FunctionDecl *
2569  FunctionTemplateDecl* Template;
2570  OptionalTemplateArgsTy ToTemplArgs;
2571  std::tie(Template, ToTemplArgs) =
2572  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2573  if (!Template || !ToTemplArgs)
2574  return nullptr;
2575 
2576  void *InsertPos = nullptr;
2577  auto *FoundSpec = Template->findSpecialization(*ToTemplArgs, InsertPos);
2578  return FoundSpec;
2579 }
2580 
2582 
2584  auto RedeclIt = Redecls.begin();
2585  // Import the first part of the decl chain. I.e. import all previous
2586  // declarations starting from the canonical decl.
2587  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt)
2588  if (!Importer.Import(*RedeclIt))
2589  return nullptr;
2590  assert(*RedeclIt == D);
2591 
2592  // Import the major distinguishing characteristics of this function.
2593  DeclContext *DC, *LexicalDC;
2594  DeclarationName Name;
2595  SourceLocation Loc;
2596  NamedDecl *ToD;
2597  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2598  return nullptr;
2599  if (ToD)
2600  return ToD;
2601 
2602  const FunctionDecl *FoundByLookup = nullptr;
2604 
2605  // If this is a function template specialization, then try to find the same
2606  // existing specialization in the "to" context. The localUncachedLookup
2607  // below will not find any specialization, but would find the primary
2608  // template; thus, we have to skip normal lookup in case of specializations.
2609  // FIXME handle member function templates (TK_MemberSpecialization) similarly?
2610  if (D->getTemplatedKind() ==
2612  if (FunctionDecl *FoundFunction = FindFunctionTemplateSpecialization(D)) {
2613  if (D->doesThisDeclarationHaveABody() &&
2614  FoundFunction->hasBody())
2615  return Importer.Imported(D, FoundFunction);
2616  FoundByLookup = FoundFunction;
2617  }
2618  }
2619  // Try to find a function in our own ("to") context with the same name, same
2620  // type, and in the same context as the function we're importing.
2621  else if (!LexicalDC->isFunctionOrMethod()) {
2622  SmallVector<NamedDecl *, 4> ConflictingDecls;
2624  SmallVector<NamedDecl *, 2> FoundDecls;
2625  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2626  for (auto *FoundDecl : FoundDecls) {
2627  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2628  continue;
2629 
2630  // If template was found, look at the templated function.
2631  if (FromFT) {
2632  if (auto *Template = dyn_cast<FunctionTemplateDecl>(FoundDecl))
2633  FoundDecl = Template->getTemplatedDecl();
2634  else
2635  continue;
2636  }
2637 
2638  if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
2639  if (FoundFunction->hasExternalFormalLinkage() &&
2640  D->hasExternalFormalLinkage()) {
2641  if (IsStructuralMatch(D, FoundFunction)) {
2642  const FunctionDecl *Definition = nullptr;
2643  if (D->doesThisDeclarationHaveABody() &&
2644  FoundFunction->hasBody(Definition)) {
2645  return Importer.MapImported(
2646  D, const_cast<FunctionDecl *>(Definition));
2647  }
2648  FoundByLookup = FoundFunction;
2649  break;
2650  }
2651 
2652  // FIXME: Check for overloading more carefully, e.g., by boosting
2653  // Sema::IsOverload out to the AST library.
2654 
2655  // Function overloading is okay in C++.
2656  if (Importer.getToContext().getLangOpts().CPlusPlus)
2657  continue;
2658 
2659  // Complain about inconsistent function types.
2660  Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2661  << Name << D->getType() << FoundFunction->getType();
2662  Importer.ToDiag(FoundFunction->getLocation(),
2663  diag::note_odr_value_here)
2664  << FoundFunction->getType();
2665  }
2666  }
2667 
2668  ConflictingDecls.push_back(FoundDecl);
2669  }
2670 
2671  if (!ConflictingDecls.empty()) {
2672  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2673  ConflictingDecls.data(),
2674  ConflictingDecls.size());
2675  if (!Name)
2676  return nullptr;
2677  }
2678  }
2679 
2680  DeclarationNameInfo NameInfo(Name, Loc);
2681  // Import additional name location/type info.
2682  ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2683 
2684  QualType FromTy = D->getType();
2685  bool usedDifferentExceptionSpec = false;
2686 
2687  if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2688  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2689  // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2690  // FunctionDecl that we are importing the FunctionProtoType for.
2691  // To avoid an infinite recursion when importing, create the FunctionDecl
2692  // with a simplified function type and update it afterwards.
2693  if (FromEPI.ExceptionSpec.SourceDecl ||
2694  FromEPI.ExceptionSpec.SourceTemplate ||
2695  FromEPI.ExceptionSpec.NoexceptExpr) {
2697  FromTy = Importer.getFromContext().getFunctionType(
2698  FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2699  usedDifferentExceptionSpec = true;
2700  }
2701  }
2702 
2703  // Import the type.
2704  QualType T = Importer.Import(FromTy);
2705  if (T.isNull())
2706  return nullptr;
2707 
2708  // Import the function parameters.
2709  SmallVector<ParmVarDecl *, 8> Parameters;
2710  for (auto P : D->parameters()) {
2711  auto *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2712  if (!ToP)
2713  return nullptr;
2714 
2715  Parameters.push_back(ToP);
2716  }
2717 
2718  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2719  if (D->getTypeSourceInfo() && !TInfo)
2720  return nullptr;
2721 
2722  // Create the imported function.
2723  FunctionDecl *ToFunction = nullptr;
2724  SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2725  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2726  if (GetImportedOrCreateDecl<CXXConstructorDecl>(
2727  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2728  InnerLocStart, NameInfo, T, TInfo, FromConstructor->isExplicit(),
2729  D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()))
2730  return ToFunction;
2731  if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
2732  SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
2733  for (auto *I : FromConstructor->inits()) {
2734  auto *ToI = cast_or_null<CXXCtorInitializer>(Importer.Import(I));
2735  if (!ToI && I)
2736  return nullptr;
2737  CtorInitializers.push_back(ToI);
2738  }
2739  auto **Memory =
2740  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
2741  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
2742  auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
2743  ToCtor->setCtorInitializers(Memory);
2744  ToCtor->setNumCtorInitializers(NumInitializers);
2745  }
2746  } else if (isa<CXXDestructorDecl>(D)) {
2747  if (GetImportedOrCreateDecl<CXXDestructorDecl>(
2748  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2749  InnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
2750  D->isImplicit()))
2751  return ToFunction;
2752  } else if (CXXConversionDecl *FromConversion =
2753  dyn_cast<CXXConversionDecl>(D)) {
2754  if (GetImportedOrCreateDecl<CXXConversionDecl>(
2755  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2756  InnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
2757  FromConversion->isExplicit(), D->isConstexpr(), SourceLocation()))
2758  return ToFunction;
2759  } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2760  if (GetImportedOrCreateDecl<CXXMethodDecl>(
2761  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
2762  InnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
2763  Method->isInlineSpecified(), D->isConstexpr(), SourceLocation()))
2764  return ToFunction;
2765  } else {
2766  if (GetImportedOrCreateDecl(ToFunction, D, Importer.getToContext(), DC,
2767  InnerLocStart, NameInfo, T, TInfo,
2769  D->hasWrittenPrototype(), D->isConstexpr()))
2770  return ToFunction;
2771  }
2772 
2773  // Import the qualifier, if any.
2774  ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2775  ToFunction->setAccess(D->getAccess());
2776  ToFunction->setLexicalDeclContext(LexicalDC);
2777  ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2778  ToFunction->setTrivial(D->isTrivial());
2779  ToFunction->setPure(D->isPure());
2780  ToFunction->setRangeEnd(Importer.Import(D->getEndLoc()));
2781 
2782  // Set the parameters.
2783  for (auto *Param : Parameters) {
2784  Param->setOwningFunction(ToFunction);
2785  ToFunction->addDeclInternal(Param);
2786  }
2787  ToFunction->setParams(Parameters);
2788 
2789  if (FoundByLookup) {
2790  auto *Recent = const_cast<FunctionDecl *>(
2791  FoundByLookup->getMostRecentDecl());
2792  ToFunction->setPreviousDecl(Recent);
2793  }
2794 
2795  // We need to complete creation of FunctionProtoTypeLoc manually with setting
2796  // params it refers to.
2797  if (TInfo) {
2798  if (auto ProtoLoc =
2800  for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
2801  ProtoLoc.setParam(I, Parameters[I]);
2802  }
2803  }
2804 
2805  if (usedDifferentExceptionSpec) {
2806  // Update FunctionProtoType::ExtProtoInfo.
2807  QualType T = Importer.Import(D->getType());
2808  if (T.isNull())
2809  return nullptr;
2810  ToFunction->setType(T);
2811  }
2812 
2813  // Import the describing template function, if any.
2814  if (FromFT)
2815  if (!Importer.Import(FromFT))
2816  return nullptr;
2817 
2818  if (D->doesThisDeclarationHaveABody()) {
2819  if (Stmt *FromBody = D->getBody()) {
2820  if (Stmt *ToBody = Importer.Import(FromBody)) {
2821  ToFunction->setBody(ToBody);
2822  }
2823  }
2824  }
2825 
2826  // FIXME: Other bits to merge?
2827 
2828  // If it is a template, import all related things.
2829  if (ImportTemplateInformation(D, ToFunction))
2830  return nullptr;
2831 
2833 
2834  // TODO Can we generalize this approach to other AST nodes as well?
2835  if (D->getDeclContext()->containsDeclAndLoad(D))
2836  DC->addDeclInternal(ToFunction);
2837  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
2838  LexicalDC->addDeclInternal(ToFunction);
2839 
2840  // Friend declaration's lexical context is the befriending class, but the
2841  // semantic context is the enclosing scope of the befriending class.
2842  // We want the friend functions to be found in the semantic context by lookup.
2843  // FIXME should we handle this generically in VisitFriendDecl?
2844  // In Other cases when LexicalDC != DC we don't want it to be added,
2845  // e.g out-of-class definitions like void B::f() {} .
2846  if (LexicalDC != DC && IsFriend) {
2847  DC->makeDeclVisibleInContext(ToFunction);
2848  }
2849 
2850  // Import the rest of the chain. I.e. import all subsequent declarations.
2851  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt)
2852  if (!Importer.Import(*RedeclIt))
2853  return nullptr;
2854 
2855  if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
2856  ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod);
2857 
2858  return ToFunction;
2859 }
2860 
2862  return VisitFunctionDecl(D);
2863 }
2864 
2866  return VisitCXXMethodDecl(D);
2867 }
2868 
2870  return VisitCXXMethodDecl(D);
2871 }
2872 
2874  return VisitCXXMethodDecl(D);
2875 }
2876 
2878  // Import the major distinguishing characteristics of a variable.
2879  DeclContext *DC, *LexicalDC;
2880  DeclarationName Name;
2881  SourceLocation Loc;
2882  NamedDecl *ToD;
2883  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2884  return nullptr;
2885  if (ToD)
2886  return ToD;
2887 
2888  // Determine whether we've already imported this field.
2889  SmallVector<NamedDecl *, 2> FoundDecls;
2890  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2891  for (auto *FoundDecl : FoundDecls) {
2892  if (auto *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
2893  // For anonymous fields, match up by index.
2894  if (!Name &&
2896  ASTImporter::getFieldIndex(FoundField))
2897  continue;
2898 
2899  if (Importer.IsStructurallyEquivalent(D->getType(),
2900  FoundField->getType())) {
2901  Importer.MapImported(D, FoundField);
2902  // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
2903  // initializer of a FieldDecl might not had been instantiated in the
2904  // "To" context. However, the "From" context might instantiated that,
2905  // thus we have to merge that.
2906  if (Expr *FromInitializer = D->getInClassInitializer()) {
2907  // We don't have yet the initializer set.
2908  if (FoundField->hasInClassInitializer() &&
2909  !FoundField->getInClassInitializer()) {
2910  Expr *ToInitializer = Importer.Import(FromInitializer);
2911  if (!ToInitializer)
2912  // We can't return a nullptr here,
2913  // since we already mapped D as imported.
2914  return FoundField;
2915  FoundField->setInClassInitializer(ToInitializer);
2916  }
2917  }
2918  return FoundField;
2919  }
2920 
2921  Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2922  << Name << D->getType() << FoundField->getType();
2923  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2924  << FoundField->getType();
2925  return nullptr;
2926  }
2927  }
2928 
2929  // Import the type.
2930  QualType T = Importer.Import(D->getType());
2931  if (T.isNull())
2932  return nullptr;
2933 
2934  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2935  Expr *BitWidth = Importer.Import(D->getBitWidth());
2936  if (!BitWidth && D->getBitWidth())
2937  return nullptr;
2938 
2939  FieldDecl *ToField;
2940  if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
2941  Importer.Import(D->getInnerLocStart()), Loc,
2942  Name.getAsIdentifierInfo(), T, TInfo, BitWidth,
2943  D->isMutable(), D->getInClassInitStyle()))
2944  return ToField;
2945 
2946  ToField->setAccess(D->getAccess());
2947  ToField->setLexicalDeclContext(LexicalDC);
2948  if (Expr *FromInitializer = D->getInClassInitializer()) {
2949  Expr *ToInitializer = Importer.Import(FromInitializer);
2950  if (ToInitializer)
2951  ToField->setInClassInitializer(ToInitializer);
2952  else
2953  return nullptr;
2954  }
2955  ToField->setImplicit(D->isImplicit());
2956  LexicalDC->addDeclInternal(ToField);
2957  return ToField;
2958 }
2959 
2961  // Import the major distinguishing characteristics of a variable.
2962  DeclContext *DC, *LexicalDC;
2963  DeclarationName Name;
2964  SourceLocation Loc;
2965  NamedDecl *ToD;
2966  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2967  return nullptr;
2968  if (ToD)
2969  return ToD;
2970 
2971  // Determine whether we've already imported this field.
2972  SmallVector<NamedDecl *, 2> FoundDecls;
2973  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2974  for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2975  if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2976  // For anonymous indirect fields, match up by index.
2977  if (!Name &&
2979  ASTImporter::getFieldIndex(FoundField))
2980  continue;
2981 
2982  if (Importer.IsStructurallyEquivalent(D->getType(),
2983  FoundField->getType(),
2984  !Name.isEmpty())) {
2985  Importer.MapImported(D, FoundField);
2986  return FoundField;
2987  }
2988 
2989  // If there are more anonymous fields to check, continue.
2990  if (!Name && I < N-1)
2991  continue;
2992 
2993  Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2994  << Name << D->getType() << FoundField->getType();
2995  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2996  << FoundField->getType();
2997  return nullptr;
2998  }
2999  }
3000 
3001  // Import the type.
3002  QualType T = Importer.Import(D->getType());
3003  if (T.isNull())
3004  return nullptr;
3005 
3006  auto **NamedChain =
3007  new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3008 
3009  unsigned i = 0;
3010  for (auto *PI : D->chain()) {
3011  Decl *D = Importer.Import(PI);
3012  if (!D)
3013  return nullptr;
3014  NamedChain[i++] = cast<NamedDecl>(D);
3015  }
3016 
3017  llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3018  IndirectFieldDecl *ToIndirectField;
3019  if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3020  Loc, Name.getAsIdentifierInfo(), T, CH))
3021  // FIXME here we leak `NamedChain` which is allocated before
3022  return ToIndirectField;
3023 
3024  for (const auto *A : D->attrs())
3025  ToIndirectField->addAttr(Importer.Import(A));
3026 
3027  ToIndirectField->setAccess(D->getAccess());
3028  ToIndirectField->setLexicalDeclContext(LexicalDC);
3029  LexicalDC->addDeclInternal(ToIndirectField);
3030  return ToIndirectField;
3031 }
3032 
3034  // Import the major distinguishing characteristics of a declaration.
3035  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3036  DeclContext *LexicalDC = D->getDeclContext() == D->getLexicalDeclContext()
3037  ? DC : Importer.ImportContext(D->getLexicalDeclContext());
3038  if (!DC || !LexicalDC)
3039  return nullptr;
3040 
3041  // Determine whether we've already imported this decl.
3042  // FriendDecl is not a NamedDecl so we cannot use localUncachedLookup.
3043  auto *RD = cast<CXXRecordDecl>(DC);
3044  FriendDecl *ImportedFriend = RD->getFirstFriend();
3045 
3046  while (ImportedFriend) {
3047  if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3048  if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3049  /*Complain=*/false))
3050  return Importer.MapImported(D, ImportedFriend);
3051 
3052  } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3053  if (Importer.IsStructurallyEquivalent(
3054  D->getFriendType()->getType(),
3055  ImportedFriend->getFriendType()->getType(), true))
3056  return Importer.MapImported(D, ImportedFriend);
3057  }
3058  ImportedFriend = ImportedFriend->getNextFriend();
3059  }
3060 
3061  // Not found. Create it.
3063  if (NamedDecl *FriendD = D->getFriendDecl()) {
3064  auto *ToFriendD = cast_or_null<NamedDecl>(Importer.Import(FriendD));
3065  if (ToFriendD && FriendD->getFriendObjectKind() != Decl::FOK_None &&
3066  !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3067  ToFriendD->setObjectOfFriendDecl(false);
3068 
3069  ToFU = ToFriendD;
3070  } else // The friend is a type, not a decl.
3071  ToFU = Importer.Import(D->getFriendType());
3072  if (!ToFU)
3073  return nullptr;
3074 
3075  SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3076  auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3077  for (unsigned I = 0; I < D->NumTPLists; I++) {
3078  TemplateParameterList *List = ImportTemplateParameterList(FromTPLists[I]);
3079  if (!List)
3080  return nullptr;
3081  ToTPLists[I] = List;
3082  }
3083 
3084  FriendDecl *FrD;
3085  if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3086  Importer.Import(D->getLocation()), ToFU,
3087  Importer.Import(D->getFriendLoc()), ToTPLists))
3088  return FrD;
3089 
3090  FrD->setAccess(D->getAccess());
3091  FrD->setLexicalDeclContext(LexicalDC);
3092  LexicalDC->addDeclInternal(FrD);
3093  return FrD;
3094 }
3095 
3097  // Import the major distinguishing characteristics of an ivar.
3098  DeclContext *DC, *LexicalDC;
3099  DeclarationName Name;
3100  SourceLocation Loc;
3101  NamedDecl *ToD;
3102  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3103  return nullptr;
3104  if (ToD)
3105  return ToD;
3106 
3107  // Determine whether we've already imported this ivar
3108  SmallVector<NamedDecl *, 2> FoundDecls;
3109  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3110  for (auto *FoundDecl : FoundDecls) {
3111  if (auto *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3112  if (Importer.IsStructurallyEquivalent(D->getType(),
3113  FoundIvar->getType())) {
3114  Importer.MapImported(D, FoundIvar);
3115  return FoundIvar;
3116  }
3117 
3118  Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3119  << Name << D->getType() << FoundIvar->getType();
3120  Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3121  << FoundIvar->getType();
3122  return nullptr;
3123  }
3124  }
3125 
3126  // Import the type.
3127  QualType T = Importer.Import(D->getType());
3128  if (T.isNull())
3129  return nullptr;
3130 
3131  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3132  Expr *BitWidth = Importer.Import(D->getBitWidth());
3133  if (!BitWidth && D->getBitWidth())
3134  return nullptr;
3135 
3136  ObjCIvarDecl *ToIvar;
3137  if (GetImportedOrCreateDecl(
3138  ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3139  Importer.Import(D->getInnerLocStart()), Loc,
3140  Name.getAsIdentifierInfo(), T, TInfo, D->getAccessControl(), BitWidth,
3141  D->getSynthesize()))
3142  return ToIvar;
3143 
3144  ToIvar->setLexicalDeclContext(LexicalDC);
3145  LexicalDC->addDeclInternal(ToIvar);
3146  return ToIvar;
3147 }
3148 
3150 
3152  auto RedeclIt = Redecls.begin();
3153  // Import the first part of the decl chain. I.e. import all previous
3154  // declarations starting from the canonical decl.
3155  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt)
3156  if (!Importer.Import(*RedeclIt))
3157  return nullptr;
3158  assert(*RedeclIt == D);
3159 
3160  // Import the major distinguishing characteristics of a variable.
3161  DeclContext *DC, *LexicalDC;
3162  DeclarationName Name;
3163  SourceLocation Loc;
3164  NamedDecl *ToD;
3165  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3166  return nullptr;
3167  if (ToD)
3168  return ToD;
3169 
3170  // Try to find a variable in our own ("to") context with the same name and
3171  // in the same context as the variable we're importing.
3172  VarDecl *FoundByLookup = nullptr;
3173  if (D->isFileVarDecl()) {
3174  SmallVector<NamedDecl *, 4> ConflictingDecls;
3175  unsigned IDNS = Decl::IDNS_Ordinary;
3176  SmallVector<NamedDecl *, 2> FoundDecls;
3177  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3178  for (auto *FoundDecl : FoundDecls) {
3179  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3180  continue;
3181 
3182  if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3183  // We have found a variable that we may need to merge with. Check it.
3184  if (FoundVar->hasExternalFormalLinkage() &&
3185  D->hasExternalFormalLinkage()) {
3186  if (Importer.IsStructurallyEquivalent(D->getType(),
3187  FoundVar->getType())) {
3188 
3189  // The VarDecl in the "From" context has a definition, but in the
3190  // "To" context we already have a definition.
3191  VarDecl *FoundDef = FoundVar->getDefinition();
3192  if (D->isThisDeclarationADefinition() && FoundDef)
3193  // FIXME Check for ODR error if the two definitions have
3194  // different initializers?
3195  return Importer.MapImported(D, FoundDef);
3196 
3197  // The VarDecl in the "From" context has an initializer, but in the
3198  // "To" context we already have an initializer.
3199  const VarDecl *FoundDInit = nullptr;
3200  if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3201  // FIXME Diagnose ODR error if the two initializers are different?
3202  return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3203 
3204  FoundByLookup = FoundVar;
3205  break;
3206  }
3207 
3208  const ArrayType *FoundArray
3209  = Importer.getToContext().getAsArrayType(FoundVar->getType());
3210  const ArrayType *TArray
3211  = Importer.getToContext().getAsArrayType(D->getType());
3212  if (FoundArray && TArray) {
3213  if (isa<IncompleteArrayType>(FoundArray) &&
3214  isa<ConstantArrayType>(TArray)) {
3215  // Import the type.
3216  QualType T = Importer.Import(D->getType());
3217  if (T.isNull())
3218  return nullptr;
3219 
3220  FoundVar->setType(T);
3221  FoundByLookup = FoundVar;
3222  break;
3223  } else if (isa<IncompleteArrayType>(TArray) &&
3224  isa<ConstantArrayType>(FoundArray)) {
3225  FoundByLookup = FoundVar;
3226  break;
3227  }
3228  }
3229 
3230  Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3231  << Name << D->getType() << FoundVar->getType();
3232  Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3233  << FoundVar->getType();
3234  }
3235  }
3236 
3237  ConflictingDecls.push_back(FoundDecl);
3238  }
3239 
3240  if (!ConflictingDecls.empty()) {
3241  Name = Importer.HandleNameConflict(Name, DC, IDNS,
3242  ConflictingDecls.data(),
3243  ConflictingDecls.size());
3244  if (!Name)
3245  return nullptr;
3246  }
3247  }
3248 
3249  // Import the type.
3250  QualType T = Importer.Import(D->getType());
3251  if (T.isNull())
3252  return nullptr;
3253 
3254  // Create the imported variable.
3255  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3256  VarDecl *ToVar;
3257  if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3258  Importer.Import(D->getInnerLocStart()), Loc,
3259  Name.getAsIdentifierInfo(), T, TInfo,
3260  D->getStorageClass()))
3261  return ToVar;
3262 
3263  ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3264  ToVar->setAccess(D->getAccess());
3265  ToVar->setLexicalDeclContext(LexicalDC);
3266 
3267  if (FoundByLookup) {
3268  auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
3269  ToVar->setPreviousDecl(Recent);
3270  }
3271 
3272  if (ImportInitializer(D, ToVar))
3273  return nullptr;
3274 
3275  if (D->isConstexpr())
3276  ToVar->setConstexpr(true);
3277 
3278  if (D->getDeclContext()->containsDeclAndLoad(D))
3279  DC->addDeclInternal(ToVar);
3280  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3281  LexicalDC->addDeclInternal(ToVar);
3282 
3283  // Import the rest of the chain. I.e. import all subsequent declarations.
3284  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt)
3285  if (!Importer.Import(*RedeclIt))
3286  return nullptr;
3287 
3288  return ToVar;
3289 }
3290 
3292  // Parameters are created in the translation unit's context, then moved
3293  // into the function declaration's context afterward.
3294  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3295 
3296  // Import the name of this declaration.
3297  DeclarationName Name = Importer.Import(D->getDeclName());
3298  if (D->getDeclName() && !Name)
3299  return nullptr;
3300 
3301  // Import the location of this declaration.
3302  SourceLocation Loc = Importer.Import(D->getLocation());
3303 
3304  // Import the parameter's type.
3305  QualType T = Importer.Import(D->getType());
3306  if (T.isNull())
3307  return nullptr;
3308 
3309  // Create the imported parameter.
3310  ImplicitParamDecl *ToParm = nullptr;
3311  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, Loc,
3312  Name.getAsIdentifierInfo(), T,
3313  D->getParameterKind()))
3314  return ToParm;
3315  return ToParm;
3316 }
3317 
3319  // Parameters are created in the translation unit's context, then moved
3320  // into the function declaration's context afterward.
3321  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3322 
3323  // Import the name of this declaration.
3324  DeclarationName Name = Importer.Import(D->getDeclName());
3325  if (D->getDeclName() && !Name)
3326  return nullptr;
3327 
3328  // Import the location of this declaration.
3329  SourceLocation Loc = Importer.Import(D->getLocation());
3330 
3331  // Import the parameter's type.
3332  QualType T = Importer.Import(D->getType());
3333  if (T.isNull())
3334  return nullptr;
3335 
3336  // Create the imported parameter.
3337  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3338  ParmVarDecl *ToParm;
3339  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3340  Importer.Import(D->getInnerLocStart()), Loc,
3341  Name.getAsIdentifierInfo(), T, TInfo,
3342  D->getStorageClass(),
3343  /*DefaultArg*/ nullptr))
3344  return ToParm;
3345 
3346  // Set the default argument.
3348  ToParm->setKNRPromoted(D->isKNRPromoted());
3349 
3350  Expr *ToDefArg = nullptr;
3351  Expr *FromDefArg = nullptr;
3352  if (D->hasUninstantiatedDefaultArg()) {
3353  FromDefArg = D->getUninstantiatedDefaultArg();
3354  ToDefArg = Importer.Import(FromDefArg);
3355  ToParm->setUninstantiatedDefaultArg(ToDefArg);
3356  } else if (D->hasUnparsedDefaultArg()) {
3357  ToParm->setUnparsedDefaultArg();
3358  } else if (D->hasDefaultArg()) {
3359  FromDefArg = D->getDefaultArg();
3360  ToDefArg = Importer.Import(FromDefArg);
3361  ToParm->setDefaultArg(ToDefArg);
3362  }
3363  if (FromDefArg && !ToDefArg)
3364  return nullptr;
3365 
3366  if (D->isObjCMethodParameter()) {
3369  } else {
3370  ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3371  D->getFunctionScopeIndex());
3372  }
3373 
3374  return ToParm;
3375 }
3376 
3378  // Import the major distinguishing characteristics of a method.
3379  DeclContext *DC, *LexicalDC;
3380  DeclarationName Name;
3381  SourceLocation Loc;
3382  NamedDecl *ToD;
3383  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3384  return nullptr;
3385  if (ToD)
3386  return ToD;
3387 
3388  SmallVector<NamedDecl *, 2> FoundDecls;
3389  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3390  for (auto *FoundDecl : FoundDecls) {
3391  if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3392  if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3393  continue;
3394 
3395  // Check return types.
3396  if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3397  FoundMethod->getReturnType())) {
3398  Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3399  << D->isInstanceMethod() << Name << D->getReturnType()
3400  << FoundMethod->getReturnType();
3401  Importer.ToDiag(FoundMethod->getLocation(),
3402  diag::note_odr_objc_method_here)
3403  << D->isInstanceMethod() << Name;
3404  return nullptr;
3405  }
3406 
3407  // Check the number of parameters.
3408  if (D->param_size() != FoundMethod->param_size()) {
3409  Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3410  << D->isInstanceMethod() << Name
3411  << D->param_size() << FoundMethod->param_size();
3412  Importer.ToDiag(FoundMethod->getLocation(),
3413  diag::note_odr_objc_method_here)
3414  << D->isInstanceMethod() << Name;
3415  return nullptr;
3416  }
3417 
3418  // Check parameter types.
3420  PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3421  P != PEnd; ++P, ++FoundP) {
3422  if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3423  (*FoundP)->getType())) {
3424  Importer.FromDiag((*P)->getLocation(),
3425  diag::err_odr_objc_method_param_type_inconsistent)
3426  << D->isInstanceMethod() << Name
3427  << (*P)->getType() << (*FoundP)->getType();
3428  Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3429  << (*FoundP)->getType();
3430  return nullptr;
3431  }
3432  }
3433 
3434  // Check variadic/non-variadic.
3435  // Check the number of parameters.
3436  if (D->isVariadic() != FoundMethod->isVariadic()) {
3437  Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3438  << D->isInstanceMethod() << Name;
3439  Importer.ToDiag(FoundMethod->getLocation(),
3440  diag::note_odr_objc_method_here)
3441  << D->isInstanceMethod() << Name;
3442  return nullptr;
3443  }
3444 
3445  // FIXME: Any other bits we need to merge?
3446  return Importer.MapImported(D, FoundMethod);
3447  }
3448  }
3449 
3450  // Import the result type.
3451  QualType ResultTy = Importer.Import(D->getReturnType());
3452  if (ResultTy.isNull())
3453  return nullptr;
3454 
3455  TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3456 
3457  ObjCMethodDecl *ToMethod;
3458  if (GetImportedOrCreateDecl(
3459  ToMethod, D, Importer.getToContext(), Loc,
3460  Importer.Import(D->getEndLoc()), Name.getObjCSelector(), ResultTy,
3461  ReturnTInfo, DC, D->isInstanceMethod(), D->isVariadic(),
3462  D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3464  return ToMethod;
3465 
3466  // FIXME: When we decide to merge method definitions, we'll need to
3467  // deal with implicit parameters.
3468 
3469  // Import the parameters
3471  for (auto *FromP : D->parameters()) {
3472  auto *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3473  if (!ToP)
3474  return nullptr;
3475 
3476  ToParams.push_back(ToP);
3477  }
3478 
3479  // Set the parameters.
3480  for (auto *ToParam : ToParams) {
3481  ToParam->setOwningFunction(ToMethod);
3482  ToMethod->addDeclInternal(ToParam);
3483  }
3484 
3486  D->getSelectorLocs(SelLocs);
3487  for (auto &Loc : SelLocs)
3488  Loc = Importer.Import(Loc);
3489 
3490  ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3491 
3492  ToMethod->setLexicalDeclContext(LexicalDC);
3493  LexicalDC->addDeclInternal(ToMethod);
3494  return ToMethod;
3495 }
3496 
3498  // Import the major distinguishing characteristics of a category.
3499  DeclContext *DC, *LexicalDC;
3500  DeclarationName Name;
3501  SourceLocation Loc;
3502  NamedDecl *ToD;
3503  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3504  return nullptr;
3505  if (ToD)
3506  return ToD;
3507 
3508  TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3509  if (!BoundInfo)
3510  return nullptr;
3511 
3513  if (GetImportedOrCreateDecl(
3514  Result, D, Importer.getToContext(), DC, D->getVariance(),
3515  Importer.Import(D->getVarianceLoc()), D->getIndex(),
3516  Importer.Import(D->getLocation()), Name.getAsIdentifierInfo(),
3517  Importer.Import(D->getColonLoc()), BoundInfo))
3518  return Result;
3519 
3520  Result->setLexicalDeclContext(LexicalDC);
3521  return Result;
3522 }
3523 
3525  // Import the major distinguishing characteristics of a category.
3526  DeclContext *DC, *LexicalDC;
3527  DeclarationName Name;
3528  SourceLocation Loc;
3529  NamedDecl *ToD;
3530  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3531  return nullptr;
3532  if (ToD)
3533  return ToD;
3534 
3535  auto *ToInterface =
3536  cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3537  if (!ToInterface)
3538  return nullptr;
3539 
3540  // Determine if we've already encountered this category.
3541  ObjCCategoryDecl *MergeWithCategory
3542  = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3543  ObjCCategoryDecl *ToCategory = MergeWithCategory;
3544  if (!ToCategory) {
3545 
3546  if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
3547  Importer.Import(D->getAtStartLoc()), Loc,
3548  Importer.Import(D->getCategoryNameLoc()),
3549  Name.getAsIdentifierInfo(), ToInterface,
3550  /*TypeParamList=*/nullptr,
3551  Importer.Import(D->getIvarLBraceLoc()),
3552  Importer.Import(D->getIvarRBraceLoc())))
3553  return ToCategory;
3554 
3555  ToCategory->setLexicalDeclContext(LexicalDC);
3556  LexicalDC->addDeclInternal(ToCategory);
3557  // Import the type parameter list after calling Imported, to avoid
3558  // loops when bringing in their DeclContext.
3559  ToCategory->setTypeParamList(ImportObjCTypeParamList(
3560  D->getTypeParamList()));
3561 
3562  // Import protocols
3564  SmallVector<SourceLocation, 4> ProtocolLocs;
3566  = D->protocol_loc_begin();
3568  FromProtoEnd = D->protocol_end();
3569  FromProto != FromProtoEnd;
3570  ++FromProto, ++FromProtoLoc) {
3571  auto *ToProto =
3572  cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3573  if (!ToProto)
3574  return nullptr;
3575  Protocols.push_back(ToProto);
3576  ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3577  }
3578 
3579  // FIXME: If we're merging, make sure that the protocol list is the same.
3580  ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3581  ProtocolLocs.data(), Importer.getToContext());
3582  } else {
3583  Importer.MapImported(D, ToCategory);
3584  }
3585 
3586  // Import all of the members of this category.
3587  ImportDeclContext(D);
3588 
3589  // If we have an implementation, import it as well.
3590  if (D->getImplementation()) {
3591  auto *Impl =
3592  cast_or_null<ObjCCategoryImplDecl>(
3593  Importer.Import(D->getImplementation()));
3594  if (!Impl)
3595  return nullptr;
3596 
3597  ToCategory->setImplementation(Impl);
3598  }
3599 
3600  return ToCategory;
3601 }
3602 
3604  ObjCProtocolDecl *To,
3606  if (To->getDefinition()) {
3607  if (shouldForceImportDeclContext(Kind))
3608  ImportDeclContext(From);
3609  return false;
3610  }
3611 
3612  // Start the protocol definition
3613  To->startDefinition();
3614 
3615  // Import protocols
3617  SmallVector<SourceLocation, 4> ProtocolLocs;
3619  FromProtoLoc = From->protocol_loc_begin();
3620  for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3621  FromProtoEnd = From->protocol_end();
3622  FromProto != FromProtoEnd;
3623  ++FromProto, ++FromProtoLoc) {
3624  auto *ToProto = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3625  if (!ToProto)
3626  return true;
3627  Protocols.push_back(ToProto);
3628  ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3629  }
3630 
3631  // FIXME: If we're merging, make sure that the protocol list is the same.
3632  To->setProtocolList(Protocols.data(), Protocols.size(),
3633  ProtocolLocs.data(), Importer.getToContext());
3634 
3635  if (shouldForceImportDeclContext(Kind)) {
3636  // Import all of the members of this protocol.
3637  ImportDeclContext(From, /*ForceImport=*/true);
3638  }
3639  return false;
3640 }
3641 
3643  // If this protocol has a definition in the translation unit we're coming
3644  // from, but this particular declaration is not that definition, import the
3645  // definition and map to that.
3646  ObjCProtocolDecl *Definition = D->getDefinition();
3647  if (Definition && Definition != D) {
3648  Decl *ImportedDef = Importer.Import(Definition);
3649  if (!ImportedDef)
3650  return nullptr;
3651 
3652  return Importer.MapImported(D, ImportedDef);
3653  }
3654 
3655  // Import the major distinguishing characteristics of a protocol.
3656  DeclContext *DC, *LexicalDC;
3657  DeclarationName Name;
3658  SourceLocation Loc;
3659  NamedDecl *ToD;
3660  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3661  return nullptr;
3662  if (ToD)
3663  return ToD;
3664 
3665  ObjCProtocolDecl *MergeWithProtocol = nullptr;
3666  SmallVector<NamedDecl *, 2> FoundDecls;
3667  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3668  for (auto *FoundDecl : FoundDecls) {
3670  continue;
3671 
3672  if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
3673  break;
3674  }
3675 
3676  ObjCProtocolDecl *ToProto = MergeWithProtocol;
3677  if (!ToProto) {
3678  if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
3679  Name.getAsIdentifierInfo(), Loc,
3680  Importer.Import(D->getAtStartLoc()),
3681  /*PrevDecl=*/nullptr))
3682  return ToProto;
3683  ToProto->setLexicalDeclContext(LexicalDC);
3684  LexicalDC->addDeclInternal(ToProto);
3685  }
3686 
3687  Importer.MapImported(D, ToProto);
3688 
3689  if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3690  return nullptr;
3691 
3692  return ToProto;
3693 }
3694 
3696  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3697  DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3698 
3699  SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3700  SourceLocation LangLoc = Importer.Import(D->getLocation());
3701 
3702  bool HasBraces = D->hasBraces();
3703 
3704  LinkageSpecDecl *ToLinkageSpec;
3705  if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
3706  ExternLoc, LangLoc, D->getLanguage(), HasBraces))
3707  return ToLinkageSpec;
3708 
3709  if (HasBraces) {
3710  SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3711  ToLinkageSpec->setRBraceLoc(RBraceLoc);
3712  }
3713 
3714  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3715  LexicalDC->addDeclInternal(ToLinkageSpec);
3716 
3717  return ToLinkageSpec;
3718 }
3719 
3721  DeclContext *DC, *LexicalDC;
3722  DeclarationName Name;
3723  SourceLocation Loc;
3724  NamedDecl *ToD = nullptr;
3725  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3726  return nullptr;
3727  if (ToD)
3728  return ToD;
3729 
3730  DeclarationNameInfo NameInfo(Name,
3731  Importer.Import(D->getNameInfo().getLoc()));
3732  ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3733 
3734  UsingDecl *ToUsing;
3735  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
3736  Importer.Import(D->getUsingLoc()),
3737  Importer.Import(D->getQualifierLoc()), NameInfo,
3738  D->hasTypename()))
3739  return ToUsing;
3740 
3741  ToUsing->setLexicalDeclContext(LexicalDC);
3742  LexicalDC->addDeclInternal(ToUsing);
3743 
3744  if (NamedDecl *FromPattern =
3745  Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
3746  if (auto *ToPattern =
3747  dyn_cast_or_null<NamedDecl>(Importer.Import(FromPattern)))
3748  Importer.getToContext().setInstantiatedFromUsingDecl(ToUsing, ToPattern);
3749  else
3750  return nullptr;
3751  }
3752 
3753  for (auto *FromShadow : D->shadows()) {
3754  if (auto *ToShadow =
3755  dyn_cast_or_null<UsingShadowDecl>(Importer.Import(FromShadow)))
3756  ToUsing->addShadowDecl(ToShadow);
3757  else
3758  // FIXME: We return a nullptr here but the definition is already created
3759  // and available with lookups. How to fix this?..
3760  return nullptr;
3761  }
3762  return ToUsing;
3763 }
3764 
3766  DeclContext *DC, *LexicalDC;
3767  DeclarationName Name;
3768  SourceLocation Loc;
3769  NamedDecl *ToD = nullptr;
3770  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3771  return nullptr;
3772  if (ToD)
3773  return ToD;
3774 
3775  auto *ToUsing = dyn_cast_or_null<UsingDecl>(
3776  Importer.Import(D->getUsingDecl()));
3777  if (!ToUsing)
3778  return nullptr;
3779 
3780  auto *ToTarget = dyn_cast_or_null<NamedDecl>(
3781  Importer.Import(D->getTargetDecl()));
3782  if (!ToTarget)
3783  return nullptr;
3784 
3785  UsingShadowDecl *ToShadow;
3786  if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
3787  ToUsing, ToTarget))
3788  return ToShadow;
3789 
3790  ToShadow->setLexicalDeclContext(LexicalDC);
3791  ToShadow->setAccess(D->getAccess());
3792 
3793  if (UsingShadowDecl *FromPattern =
3794  Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
3795  if (auto *ToPattern =
3796  dyn_cast_or_null<UsingShadowDecl>(Importer.Import(FromPattern)))
3797  Importer.getToContext().setInstantiatedFromUsingShadowDecl(ToShadow,
3798  ToPattern);
3799  else
3800  // FIXME: We return a nullptr here but the definition is already created
3801  // and available with lookups. How to fix this?..
3802  return nullptr;
3803  }
3804 
3805  LexicalDC->addDeclInternal(ToShadow);
3806 
3807  return ToShadow;
3808 }
3809 
3811  DeclContext *DC, *LexicalDC;
3812  DeclarationName Name;
3813  SourceLocation Loc;
3814  NamedDecl *ToD = nullptr;
3815  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3816  return nullptr;
3817  if (ToD)
3818  return ToD;
3819 
3820  DeclContext *ToComAncestor = Importer.ImportContext(D->getCommonAncestor());
3821  if (!ToComAncestor)
3822  return nullptr;
3823 
3824  auto *ToNominated = cast_or_null<NamespaceDecl>(
3825  Importer.Import(D->getNominatedNamespace()));
3826  if (!ToNominated)
3827  return nullptr;
3828 
3829  UsingDirectiveDecl *ToUsingDir;
3830  if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
3831  Importer.Import(D->getUsingLoc()),
3832  Importer.Import(D->getNamespaceKeyLocation()),
3833  Importer.Import(D->getQualifierLoc()),
3834  Importer.Import(D->getIdentLocation()),
3835  ToNominated, ToComAncestor))
3836  return ToUsingDir;
3837 
3838  ToUsingDir->setLexicalDeclContext(LexicalDC);
3839  LexicalDC->addDeclInternal(ToUsingDir);
3840 
3841  return ToUsingDir;
3842 }
3843 
3846  DeclContext *DC, *LexicalDC;
3847  DeclarationName Name;
3848  SourceLocation Loc;
3849  NamedDecl *ToD = nullptr;
3850  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3851  return nullptr;
3852  if (ToD)
3853  return ToD;
3854 
3855  DeclarationNameInfo NameInfo(Name, Importer.Import(D->getNameInfo().getLoc()));
3856  ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3857 
3858  UnresolvedUsingValueDecl *ToUsingValue;
3859  if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
3860  Importer.Import(D->getUsingLoc()),
3861  Importer.Import(D->getQualifierLoc()), NameInfo,
3862  Importer.Import(D->getEllipsisLoc())))
3863  return ToUsingValue;
3864 
3865  ToUsingValue->setAccess(D->getAccess());
3866  ToUsingValue->setLexicalDeclContext(LexicalDC);
3867  LexicalDC->addDeclInternal(ToUsingValue);
3868 
3869  return ToUsingValue;
3870 }
3871 
3874  DeclContext *DC, *LexicalDC;
3875  DeclarationName Name;
3876  SourceLocation Loc;
3877  NamedDecl *ToD = nullptr;
3878  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3879  return nullptr;
3880  if (ToD)
3881  return ToD;
3882 
3883  UnresolvedUsingTypenameDecl *ToUsing;
3884  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
3885  Importer.Import(D->getUsingLoc()),
3886  Importer.Import(D->getTypenameLoc()),
3887  Importer.Import(D->getQualifierLoc()), Loc, Name,
3888  Importer.Import(D->getEllipsisLoc())))
3889  return ToUsing;
3890 
3891  ToUsing->setAccess(D->getAccess());
3892  ToUsing->setLexicalDeclContext(LexicalDC);
3893  LexicalDC->addDeclInternal(ToUsing);
3894 
3895  return ToUsing;
3896 }
3897 
3899  ObjCInterfaceDecl *To,
3901  if (To->getDefinition()) {
3902  // Check consistency of superclass.
3903  ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3904  if (FromSuper) {
3905  FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3906  if (!FromSuper)
3907  return true;
3908  }
3909 
3910  ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3911  if ((bool)FromSuper != (bool)ToSuper ||
3912  (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3913  Importer.ToDiag(To->getLocation(),
3914  diag::err_odr_objc_superclass_inconsistent)
3915  << To->getDeclName();
3916  if (ToSuper)
3917  Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3918  << To->getSuperClass()->getDeclName();
3919  else
3920  Importer.ToDiag(To->getLocation(),
3921  diag::note_odr_objc_missing_superclass);
3922  if (From->getSuperClass())
3923  Importer.FromDiag(From->getSuperClassLoc(),
3924  diag::note_odr_objc_superclass)
3925  << From->getSuperClass()->getDeclName();
3926  else
3927  Importer.FromDiag(From->getLocation(),
3928  diag::note_odr_objc_missing_superclass);
3929  }
3930 
3931  if (shouldForceImportDeclContext(Kind))
3932  ImportDeclContext(From);
3933  return false;
3934  }
3935 
3936  // Start the definition.
3937  To->startDefinition();
3938 
3939  // If this class has a superclass, import it.
3940  if (From->getSuperClass()) {
3941  TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3942  if (!SuperTInfo)
3943  return true;
3944 
3945  To->setSuperClass(SuperTInfo);
3946  }
3947 
3948  // Import protocols
3950  SmallVector<SourceLocation, 4> ProtocolLocs;
3952  FromProtoLoc = From->protocol_loc_begin();
3953 
3954  for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3955  FromProtoEnd = From->protocol_end();
3956  FromProto != FromProtoEnd;
3957  ++FromProto, ++FromProtoLoc) {
3958  auto *ToProto = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3959  if (!ToProto)
3960  return true;
3961  Protocols.push_back(ToProto);
3962  ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3963  }
3964 
3965  // FIXME: If we're merging, make sure that the protocol list is the same.
3966  To->setProtocolList(Protocols.data(), Protocols.size(),
3967  ProtocolLocs.data(), Importer.getToContext());
3968 
3969  // Import categories. When the categories themselves are imported, they'll
3970  // hook themselves into this interface.
3971  for (auto *Cat : From->known_categories())
3972  Importer.Import(Cat);
3973 
3974  // If we have an @implementation, import it as well.
3975  if (From->getImplementation()) {
3976  auto *Impl = cast_or_null<ObjCImplementationDecl>(
3977  Importer.Import(From->getImplementation()));
3978  if (!Impl)
3979  return true;
3980 
3981  To->setImplementation(Impl);
3982  }
3983 
3984  if (shouldForceImportDeclContext(Kind)) {
3985  // Import all of the members of this class.
3986  ImportDeclContext(From, /*ForceImport=*/true);
3987  }
3988  return false;
3989 }
3990 
3993  if (!list)
3994  return nullptr;
3995 
3997  for (auto fromTypeParam : *list) {
3998  auto *toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3999  Importer.Import(fromTypeParam));
4000  if (!toTypeParam)
4001  return nullptr;
4002 
4003  toTypeParams.push_back(toTypeParam);
4004  }
4005 
4006  return ObjCTypeParamList::create(Importer.getToContext(),
4007  Importer.Import(list->getLAngleLoc()),
4008  toTypeParams,
4009  Importer.Import(list->getRAngleLoc()));
4010 }
4011 
4013  // If this class has a definition in the translation unit we're coming from,
4014  // but this particular declaration is not that definition, import the
4015  // definition and map to that.
4016  ObjCInterfaceDecl *Definition = D->getDefinition();
4017  if (Definition && Definition != D) {
4018  Decl *ImportedDef = Importer.Import(Definition);
4019  if (!ImportedDef)
4020  return nullptr;
4021 
4022  return Importer.MapImported(D, ImportedDef);
4023  }
4024 
4025  // Import the major distinguishing characteristics of an @interface.
4026  DeclContext *DC, *LexicalDC;
4027  DeclarationName Name;
4028  SourceLocation Loc;
4029  NamedDecl *ToD;
4030  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4031  return nullptr;
4032  if (ToD)
4033  return ToD;
4034 
4035  // Look for an existing interface with the same name.
4036  ObjCInterfaceDecl *MergeWithIface = nullptr;
4037  SmallVector<NamedDecl *, 2> FoundDecls;
4038  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4039  for (auto *FoundDecl : FoundDecls) {
4041  continue;
4042 
4043  if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4044  break;
4045  }
4046 
4047  // Create an interface declaration, if one does not already exist.
4048  ObjCInterfaceDecl *ToIface = MergeWithIface;
4049  if (!ToIface) {
4050  if (GetImportedOrCreateDecl(
4051  ToIface, D, Importer.getToContext(), DC,
4052  Importer.Import(D->getAtStartLoc()), Name.getAsIdentifierInfo(),
4053  /*TypeParamList=*/nullptr,
4054  /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4055  return ToIface;
4056  ToIface->setLexicalDeclContext(LexicalDC);
4057  LexicalDC->addDeclInternal(ToIface);
4058  }
4059  Importer.MapImported(D, ToIface);
4060  // Import the type parameter list after calling Imported, to avoid
4061  // loops when bringing in their DeclContext.
4062  ToIface->setTypeParamList(ImportObjCTypeParamList(
4064 
4065  if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
4066  return nullptr;
4067 
4068  return ToIface;
4069 }
4070 
4072  auto *Category = cast_or_null<ObjCCategoryDecl>(
4073  Importer.Import(D->getCategoryDecl()));
4074  if (!Category)
4075  return nullptr;
4076 
4077  ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4078  if (!ToImpl) {
4079  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4080  if (!DC)
4081  return nullptr;
4082 
4083  SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
4084  if (GetImportedOrCreateDecl(
4085  ToImpl, D, Importer.getToContext(), DC,
4086  Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4087  Importer.Import(D->getLocation()),
4088  Importer.Import(D->getAtStartLoc()), CategoryNameLoc))
4089  return ToImpl;
4090 
4091  DeclContext *LexicalDC = DC;
4092  if (D->getDeclContext() != D->getLexicalDeclContext()) {
4093  LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4094  if (!LexicalDC)
4095  return nullptr;
4096 
4097  ToImpl->setLexicalDeclContext(LexicalDC);
4098  }
4099 
4100  LexicalDC->addDeclInternal(ToImpl);
4101  Category->setImplementation(ToImpl);
4102  }
4103 
4104  Importer.MapImported(D, ToImpl);
4105  ImportDeclContext(D);
4106  return ToImpl;
4107 }
4108 
4110  // Find the corresponding interface.
4111  auto *Iface = cast_or_null<ObjCInterfaceDecl>(
4112  Importer.Import(D->getClassInterface()));
4113  if (!Iface)
4114  return nullptr;
4115 
4116  // Import the superclass, if any.
4117  ObjCInterfaceDecl *Super = nullptr;
4118  if (D->getSuperClass()) {
4119  Super = cast_or_null<ObjCInterfaceDecl>(
4120  Importer.Import(D->getSuperClass()));
4121  if (!Super)
4122  return nullptr;
4123  }
4124 
4125  ObjCImplementationDecl *Impl = Iface->getImplementation();
4126  if (!Impl) {
4127  // We haven't imported an implementation yet. Create a new @implementation
4128  // now.
4129  if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4130  Importer.ImportContext(D->getDeclContext()),
4131  Iface, Super, Importer.Import(D->getLocation()),
4132  Importer.Import(D->getAtStartLoc()),
4133  Importer.Import(D->getSuperClassLoc()),
4134  Importer.Import(D->getIvarLBraceLoc()),
4135  Importer.Import(D->getIvarRBraceLoc())))
4136  return Impl;
4137 
4138  if (D->getDeclContext() != D->getLexicalDeclContext()) {
4139  DeclContext *LexicalDC
4140  = Importer.ImportContext(D->getLexicalDeclContext());
4141  if (!LexicalDC)
4142  return nullptr;
4143  Impl->setLexicalDeclContext(LexicalDC);
4144  }
4145 
4146  // Associate the implementation with the class it implements.
4147  Iface->setImplementation(Impl);
4148  Importer.MapImported(D, Iface->getImplementation());
4149  } else {
4150  Importer.MapImported(D, Iface->getImplementation());
4151 
4152  // Verify that the existing @implementation has the same superclass.
4153  if ((Super && !Impl->getSuperClass()) ||
4154  (!Super && Impl->getSuperClass()) ||
4155  (Super && Impl->getSuperClass() &&
4157  Impl->getSuperClass()))) {
4158  Importer.ToDiag(Impl->getLocation(),
4159  diag::err_odr_objc_superclass_inconsistent)
4160  << Iface->getDeclName();
4161  // FIXME: It would be nice to have the location of the superclass
4162  // below.
4163  if (Impl->getSuperClass())
4164  Importer.ToDiag(Impl->getLocation(),
4165  diag::note_odr_objc_superclass)
4166  << Impl->getSuperClass()->getDeclName();
4167  else
4168  Importer.ToDiag(Impl->getLocation(),
4169  diag::note_odr_objc_missing_superclass);
4170  if (D->getSuperClass())
4171  Importer.FromDiag(D->getLocation(),
4172  diag::note_odr_objc_superclass)
4173  << D->getSuperClass()->getDeclName();
4174  else
4175  Importer.FromDiag(D->getLocation(),
4176  diag::note_odr_objc_missing_superclass);
4177  return nullptr;
4178  }
4179  }
4180 
4181  // Import all of the members of this @implementation.
4182  ImportDeclContext(D);
4183 
4184  return Impl;
4185 }
4186 
4188  // Import the major distinguishing characteristics of an @property.
4189  DeclContext *DC, *LexicalDC;
4190  DeclarationName Name;
4191  SourceLocation Loc;
4192  NamedDecl *ToD;
4193  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4194  return nullptr;
4195  if (ToD)
4196  return ToD;
4197 
4198  // Check whether we have already imported this property.
4199  SmallVector<NamedDecl *, 2> FoundDecls;
4200  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4201  for (auto *FoundDecl : FoundDecls) {
4202  if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4203  // Check property types.
4204  if (!Importer.IsStructurallyEquivalent(D->getType(),
4205  FoundProp->getType())) {
4206  Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
4207  << Name << D->getType() << FoundProp->getType();
4208  Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4209  << FoundProp->getType();
4210  return nullptr;
4211  }
4212 
4213  // FIXME: Check property attributes, getters, setters, etc.?
4214 
4215  // Consider these properties to be equivalent.
4216  Importer.MapImported(D, FoundProp);
4217  return FoundProp;
4218  }
4219  }
4220 
4221  // Import the type.
4222  TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4223  if (!TSI)
4224  return nullptr;
4225 
4226  // Create the new property.
4227  ObjCPropertyDecl *ToProperty;
4228  if (GetImportedOrCreateDecl(
4229  ToProperty, D, Importer.getToContext(), DC, Loc,
4230  Name.getAsIdentifierInfo(), Importer.Import(D->getAtLoc()),
4231  Importer.Import(D->getLParenLoc()), Importer.Import(D->getType()),
4232  TSI, D->getPropertyImplementation()))
4233  return ToProperty;
4234 
4235  ToProperty->setLexicalDeclContext(LexicalDC);
4236  LexicalDC->addDeclInternal(ToProperty);
4237 
4238  ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4239  ToProperty->setPropertyAttributesAsWritten(
4241  ToProperty->setGetterName(Importer.Import(D->getGetterName()),
4242  Importer.Import(D->getGetterNameLoc()));
4243  ToProperty->setSetterName(Importer.Import(D->getSetterName()),
4244  Importer.Import(D->getSetterNameLoc()));
4245  ToProperty->setGetterMethodDecl(
4246  cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4247  ToProperty->setSetterMethodDecl(
4248  cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4249  ToProperty->setPropertyIvarDecl(
4250  cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4251  return ToProperty;
4252 }
4253 
4255  auto *Property = cast_or_null<ObjCPropertyDecl>(
4256  Importer.Import(D->getPropertyDecl()));
4257  if (!Property)
4258  return nullptr;
4259 
4260  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4261  if (!DC)
4262  return nullptr;
4263 
4264  // Import the lexical declaration context.
4265  DeclContext *LexicalDC = DC;
4266  if (D->getDeclContext() != D->getLexicalDeclContext()) {
4267  LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4268  if (!LexicalDC)
4269  return nullptr;
4270  }
4271 
4272  auto *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4273  if (!InImpl)
4274  return nullptr;
4275 
4276  // Import the ivar (for an @synthesize).
4277  ObjCIvarDecl *Ivar = nullptr;
4278  if (D->getPropertyIvarDecl()) {
4279  Ivar = cast_or_null<ObjCIvarDecl>(
4280  Importer.Import(D->getPropertyIvarDecl()));
4281  if (!Ivar)
4282  return nullptr;
4283  }
4284 
4285  ObjCPropertyImplDecl *ToImpl
4286  = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4287  Property->getQueryKind());
4288  if (!ToImpl) {
4289  if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4290  Importer.Import(D->getBeginLoc()),
4291  Importer.Import(D->getLocation()), Property,
4292  D->getPropertyImplementation(), Ivar,
4293  Importer.Import(D->getPropertyIvarDeclLoc())))
4294  return ToImpl;
4295 
4296  ToImpl->setLexicalDeclContext(LexicalDC);
4297  LexicalDC->addDeclInternal(ToImpl);
4298  } else {
4299  // Check that we have the same kind of property implementation (@synthesize
4300  // vs. @dynamic).
4301  if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4302  Importer.ToDiag(ToImpl->getLocation(),
4303  diag::err_odr_objc_property_impl_kind_inconsistent)
4304  << Property->getDeclName()
4305  << (ToImpl->getPropertyImplementation()
4307  Importer.FromDiag(D->getLocation(),
4308  diag::note_odr_objc_property_impl_kind)
4309  << D->getPropertyDecl()->getDeclName()
4311  return nullptr;
4312  }
4313 
4314  // For @synthesize, check that we have the same
4316  Ivar != ToImpl->getPropertyIvarDecl()) {
4317  Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4318  diag::err_odr_objc_synthesize_ivar_inconsistent)
4319  << Property->getDeclName()
4320  << ToImpl->getPropertyIvarDecl()->getDeclName()
4321  << Ivar->getDeclName();
4322  Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4323  diag::note_odr_objc_synthesize_ivar_here)
4324  << D->getPropertyIvarDecl()->getDeclName();
4325  return nullptr;
4326  }
4327 
4328  // Merge the existing implementation with the new implementation.
4329  Importer.MapImported(D, ToImpl);
4330  }
4331 
4332  return ToImpl;
4333 }
4334 
4336  // For template arguments, we adopt the translation unit as our declaration
4337  // context. This context will be fixed when the actual template declaration
4338  // is created.
4339 
4340  // FIXME: Import default argument.
4341  TemplateTypeParmDecl *ToD = nullptr;
4342  (void)GetImportedOrCreateDecl(
4343  ToD, D, Importer.getToContext(),
4344  Importer.getToContext().getTranslationUnitDecl(),
4345  Importer.Import(D->getBeginLoc()), Importer.Import(D->getLocation()),
4346  D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
4348  return ToD;
4349 }
4350 
4351 Decl *
4353  // Import the name of this declaration.
4354  DeclarationName Name = Importer.Import(D->getDeclName());
4355  if (D->getDeclName() && !Name)
4356  return nullptr;
4357 
4358  // Import the location of this declaration.
4359  SourceLocation Loc = Importer.Import(D->getLocation());
4360 
4361  // Import the type of this declaration.
4362  QualType T = Importer.Import(D->getType());
4363  if (T.isNull())
4364  return nullptr;
4365 
4366  // Import type-source information.
4367  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4368  if (D->getTypeSourceInfo() && !TInfo)
4369  return nullptr;
4370 
4371  // FIXME: Import default argument.
4372 
4373  NonTypeTemplateParmDecl *ToD = nullptr;
4374  (void)GetImportedOrCreateDecl(
4375  ToD, D, Importer.getToContext(),
4376  Importer.getToContext().getTranslationUnitDecl(),
4377  Importer.Import(D->getInnerLocStart()), Loc, D->getDepth(),
4378  D->getPosition(), Name.getAsIdentifierInfo(), T, D->isParameterPack(),
4379  TInfo);
4380  return ToD;
4381 }
4382 
4383 Decl *
4385  // Import the name of this declaration.
4386  DeclarationName Name = Importer.Import(D->getDeclName());
4387  if (D->getDeclName() && !Name)
4388  return nullptr;
4389 
4390  // Import the location of this declaration.
4391  SourceLocation Loc = Importer.Import(D->getLocation());
4392 
4393  // Import template parameters.
4394  TemplateParameterList *TemplateParams
4395  = ImportTemplateParameterList(D->getTemplateParameters());
4396  if (!TemplateParams)
4397  return nullptr;
4398 
4399  // FIXME: Import default argument.
4400 
4401  TemplateTemplateParmDecl *ToD = nullptr;
4402  (void)GetImportedOrCreateDecl(
4403  ToD, D, Importer.getToContext(),
4404  Importer.getToContext().getTranslationUnitDecl(), Loc, D->getDepth(),
4405  D->getPosition(), D->isParameterPack(), Name.getAsIdentifierInfo(),
4406  TemplateParams);
4407  return ToD;
4408 }
4409 
4410 // Returns the definition for a (forward) declaration of a ClassTemplateDecl, if
4411 // it has any definition in the redecl chain.
4413  CXXRecordDecl *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
4414  if (!ToTemplatedDef)
4415  return nullptr;
4416  ClassTemplateDecl *TemplateWithDef =
4417  ToTemplatedDef->getDescribedClassTemplate();
4418  return TemplateWithDef;
4419 }
4420 
4422  bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None;
4423 
4424  // If this record has a definition in the translation unit we're coming from,
4425  // but this particular declaration is not that definition, import the
4426  // definition and map to that.
4427  auto *Definition =
4428  cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4429  if (Definition && Definition != D->getTemplatedDecl() && !IsFriend) {
4430  Decl *ImportedDef
4431  = Importer.Import(Definition->getDescribedClassTemplate());
4432  if (!ImportedDef)
4433  return nullptr;
4434 
4435  return Importer.MapImported(D, ImportedDef);
4436  }
4437 
4438  // Import the major distinguishing characteristics of this class template.
4439  DeclContext *DC, *LexicalDC;
4440  DeclarationName Name;
4441  SourceLocation Loc;
4442  NamedDecl *ToD;
4443  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4444  return nullptr;
4445  if (ToD)
4446  return ToD;
4447 
4448  // We may already have a template of the same name; try to find and match it.
4449  if (!DC->isFunctionOrMethod()) {
4450  SmallVector<NamedDecl *, 4> ConflictingDecls;
4451  SmallVector<NamedDecl *, 2> FoundDecls;
4452  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4453  for (auto *FoundDecl : FoundDecls) {
4455  continue;
4456 
4457  Decl *Found = FoundDecl;
4458  if (auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found)) {
4459 
4460  // The class to be imported is a definition.
4461  if (D->isThisDeclarationADefinition()) {
4462  // Lookup will find the fwd decl only if that is more recent than the
4463  // definition. So, try to get the definition if that is available in
4464  // the redecl chain.
4465  ClassTemplateDecl *TemplateWithDef = getDefinition(FoundTemplate);
4466  if (TemplateWithDef)
4467  FoundTemplate = TemplateWithDef;
4468  else
4469  continue;
4470  }
4471 
4472  if (IsStructuralMatch(D, FoundTemplate)) {
4473  if (!IsFriend) {
4474  Importer.MapImported(D->getTemplatedDecl(),
4475  FoundTemplate->getTemplatedDecl());
4476  return Importer.MapImported(D, FoundTemplate);
4477  }
4478 
4479  continue;
4480  }
4481  }
4482 
4483  ConflictingDecls.push_back(FoundDecl);
4484  }
4485 
4486  if (!ConflictingDecls.empty()) {
4487  Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4488  ConflictingDecls.data(),
4489  ConflictingDecls.size());
4490  }
4491 
4492  if (!Name)
4493  return nullptr;
4494  }
4495 
4496  CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
4497 
4498  // Create the declaration that is being templated.
4499  auto *ToTemplated = cast_or_null<CXXRecordDecl>(
4500  Importer.Import(FromTemplated));
4501  if (!ToTemplated)
4502  return nullptr;
4503 
4504  // Create the class template declaration itself.
4505  TemplateParameterList *TemplateParams =
4506  ImportTemplateParameterList(D->getTemplateParameters());
4507  if (!TemplateParams)
4508  return nullptr;
4509 
4510  ClassTemplateDecl *D2;
4511  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
4512  TemplateParams, ToTemplated))
4513  return D2;
4514 
4515  ToTemplated->setDescribedClassTemplate(D2);
4516 
4517  if (ToTemplated->getPreviousDecl()) {
4518  assert(
4519  ToTemplated->getPreviousDecl()->getDescribedClassTemplate() &&
4520  "Missing described template");
4521  D2->setPreviousDecl(
4522  ToTemplated->getPreviousDecl()->getDescribedClassTemplate());
4523  }
4524  D2->setAccess(D->getAccess());
4525  D2->setLexicalDeclContext(LexicalDC);
4526  if (!IsFriend)
4527  LexicalDC->addDeclInternal(D2);
4528 
4529  if (FromTemplated->isCompleteDefinition() &&
4530  !ToTemplated->isCompleteDefinition()) {
4531  // FIXME: Import definition!
4532  }
4533 
4534  return D2;
4535 }
4536 
4539  // If this record has a definition in the translation unit we're coming from,
4540  // but this particular declaration is not that definition, import the
4541  // definition and map to that.
4542  TagDecl *Definition = D->getDefinition();
4543  if (Definition && Definition != D) {
4544  Decl *ImportedDef = Importer.Import(Definition);
4545  if (!ImportedDef)
4546  return nullptr;
4547 
4548  return Importer.MapImported(D, ImportedDef);
4549  }
4550 
4551  auto *ClassTemplate =
4552  cast_or_null<ClassTemplateDecl>(Importer.Import(
4553  D->getSpecializedTemplate()));
4554  if (!ClassTemplate)
4555  return nullptr;
4556 
4557  // Import the context of this declaration.
4558  DeclContext *DC = ClassTemplate->getDeclContext();
4559  if (!DC)
4560  return nullptr;
4561 
4562  DeclContext *LexicalDC = DC;
4563  if (D->getDeclContext() != D->getLexicalDeclContext()) {
4564  LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4565  if (!LexicalDC)
4566  return nullptr;
4567  }
4568 
4569  // Import the location of this declaration.
4570  SourceLocation StartLoc = Importer.Import(D->getBeginLoc());
4571  SourceLocation IdLoc = Importer.Import(D->getLocation());
4572 
4573  // Import template arguments.
4574  SmallVector<TemplateArgument, 2> TemplateArgs;
4575  if (ImportTemplateArguments(D->getTemplateArgs().data(),
4576  D->getTemplateArgs().size(),
4577  TemplateArgs))
4578  return nullptr;
4579 
4580  // Try to find an existing specialization with these template arguments.
4581  void *InsertPos = nullptr;
4582  ClassTemplateSpecializationDecl *D2 = nullptr;
4585  if (PartialSpec)
4586  D2 = ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
4587  else
4588  D2 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4589  ClassTemplateSpecializationDecl * const PrevDecl = D2;
4590  RecordDecl *FoundDef = D2 ? D2->getDefinition() : nullptr;
4591  if (FoundDef) {
4592  if (!D->isCompleteDefinition()) {
4593  // The "From" translation unit only had a forward declaration; call it
4594  // the same declaration.
4595  // TODO Handle the redecl chain properly!
4596  return Importer.MapImported(D, FoundDef);
4597  }
4598 
4599  if (IsStructuralMatch(D, FoundDef)) {
4600 
4601  Importer.MapImported(D, FoundDef);
4602 
4603  // Import those those default field initializers which have been
4604  // instantiated in the "From" context, but not in the "To" context.
4605  for (auto *FromField : D->fields())
4606  Importer.Import(FromField);
4607 
4608  // Import those methods which have been instantiated in the
4609  // "From" context, but not in the "To" context.
4610  for (CXXMethodDecl *FromM : D->methods())
4611  Importer.Import(FromM);
4612 
4613  // TODO Import instantiated default arguments.
4614  // TODO Import instantiated exception specifications.
4615  //
4616  // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint what
4617  // else could be fused during an AST merge.
4618 
4619  return FoundDef;
4620  }
4621  } else { // We either couldn't find any previous specialization in the "To"
4622  // context, or we found one but without definition. Let's create a
4623  // new specialization and register that at the class template.
4624  if (PartialSpec) {
4625  // Import TemplateArgumentListInfo.
4626  TemplateArgumentListInfo ToTAInfo;
4627  const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
4628  if (ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
4629  return nullptr;
4630 
4631  QualType CanonInjType = Importer.Import(
4632  PartialSpec->getInjectedSpecializationType());
4633  if (CanonInjType.isNull())
4634  return nullptr;
4635  CanonInjType = CanonInjType.getCanonicalType();
4636 
4637  TemplateParameterList *ToTPList = ImportTemplateParameterList(
4638  PartialSpec->getTemplateParameters());
4639  if (!ToTPList && PartialSpec->getTemplateParameters())
4640  return nullptr;
4641 
4642  if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
4643  D2, D, Importer.getToContext(), D->getTagKind(), DC, StartLoc,
4644  IdLoc, ToTPList, ClassTemplate,
4645  llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
4646  ToTAInfo, CanonInjType,
4647  cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
4648  return D2;
4649 
4650  // Update InsertPos, because preceding import calls may have invalidated
4651  // it by adding new specializations.
4652  if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos))
4653  // Add this partial specialization to the class template.
4654  ClassTemplate->AddPartialSpecialization(
4655  cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos);
4656 
4657  } else { // Not a partial specialization.
4658  if (GetImportedOrCreateDecl(
4659  D2, D, Importer.getToContext(), D->getTagKind(), DC, StartLoc,
4660  IdLoc, ClassTemplate, TemplateArgs, PrevDecl))
4661  return D2;
4662 
4663  // Update InsertPos, because preceding import calls may have invalidated
4664  // it by adding new specializations.
4665  if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
4666  // Add this specialization to the class template.
4667  ClassTemplate->AddSpecialization(D2, InsertPos);
4668  }
4669 
4671 
4672  // Import the qualifier, if any.
4673  D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4674 
4675  if (auto *TSI = D->getTypeAsWritten()) {
4676  TypeSourceInfo *TInfo = Importer.Import(TSI);
4677  if (!TInfo)
4678  return nullptr;
4679  D2->setTypeAsWritten(TInfo);
4680  D2->setTemplateKeywordLoc(Importer.Import(D->getTemplateKeywordLoc()));
4681  D2->setExternLoc(Importer.Import(D->getExternLoc()));
4682  }
4683 
4684  SourceLocation POI = Importer.Import(D->getPointOfInstantiation());
4685  if (POI.isValid())
4686  D2->setPointOfInstantiation(POI);
4687  else if (D->getPointOfInstantiation().isValid())
4688  return nullptr;
4689 
4691 
4692  // Set the context of this specialization/instantiation.
4693  D2->setLexicalDeclContext(LexicalDC);
4694 
4695  // Add to the DC only if it was an explicit specialization/instantiation.
4697  LexicalDC->addDeclInternal(D2);
4698  }
4699  }
4700  if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4701  return nullptr;
4702 
4703  return D2;
4704 }
4705 
4707  // If this variable has a definition in the translation unit we're coming
4708  // from,
4709  // but this particular declaration is not that definition, import the
4710  // definition and map to that.
4711  auto *Definition =
4712  cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4713  if (Definition && Definition != D->getTemplatedDecl()) {
4714  Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4715  if (!ImportedDef)
4716  return nullptr;
4717 
4718  return Importer.MapImported(D, ImportedDef);
4719  }
4720 
4721  // Import the major distinguishing characteristics of this variable template.
4722  DeclContext *DC, *LexicalDC;
4723  DeclarationName Name;
4724  SourceLocation Loc;
4725  NamedDecl *ToD;
4726  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4727  return nullptr;
4728  if (ToD)
4729  return ToD;
4730 
4731  // We may already have a template of the same name; try to find and match it.
4732  assert(!DC->isFunctionOrMethod() &&
4733  "Variable templates cannot be declared at function scope");
4734  SmallVector<NamedDecl *, 4> ConflictingDecls;
4735  SmallVector<NamedDecl *, 2> FoundDecls;
4736  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4737  for (auto *FoundDecl : FoundDecls) {
4739  continue;
4740 
4741  Decl *Found = FoundDecl;
4742  if (auto *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4743  if (IsStructuralMatch(D, FoundTemplate)) {
4744  // The variable templates structurally match; call it the same template.
4745  Importer.MapImported(D->getTemplatedDecl(),
4746  FoundTemplate->getTemplatedDecl());
4747  return Importer.MapImported(D, FoundTemplate);
4748  }
4749  }
4750 
4751  ConflictingDecls.push_back(FoundDecl);
4752  }
4753 
4754  if (!ConflictingDecls.empty()) {
4755  Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4756  ConflictingDecls.data(),
4757  ConflictingDecls.size());
4758  }
4759 
4760  if (!Name)
4761  return nullptr;
4762 
4763  VarDecl *DTemplated = D->getTemplatedDecl();
4764 
4765  // Import the type.
4766  QualType T = Importer.Import(DTemplated->getType());
4767  if (T.isNull())
4768  return nullptr;
4769 
4770  // Create the declaration that is being templated.
4771  auto *ToTemplated = dyn_cast_or_null<VarDecl>(Importer.Import(DTemplated));
4772  if (!ToTemplated)
4773  return nullptr;
4774 
4775  // Create the variable template declaration itself.
4776  TemplateParameterList *TemplateParams =
4777  ImportTemplateParameterList(D->getTemplateParameters());
4778  if (!TemplateParams)
4779  return nullptr;
4780 
4781  VarTemplateDecl *ToVarTD;
4782  if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
4783  Name, TemplateParams, ToTemplated))
4784  return ToVarTD;
4785 
4786  ToTemplated->setDescribedVarTemplate(ToVarTD);
4787 
4788  ToVarTD->setAccess(D->getAccess());
4789  ToVarTD->setLexicalDeclContext(LexicalDC);
4790  LexicalDC->addDeclInternal(ToVarTD);
4791 
4792  if (DTemplated->isThisDeclarationADefinition() &&
4793  !ToTemplated->isThisDeclarationADefinition()) {
4794  // FIXME: Import definition!
4795  }
4796 
4797  return ToVarTD;
4798 }
4799 
4802  // If this record has a definition in the translation unit we're coming from,
4803  // but this particular declaration is not that definition, import the
4804  // definition and map to that.
4805  VarDecl *Definition = D->getDefinition();
4806  if (Definition && Definition != D) {
4807  Decl *ImportedDef = Importer.Import(Definition);
4808  if (!ImportedDef)
4809  return nullptr;
4810 
4811  return Importer.MapImported(D, ImportedDef);
4812  }
4813 
4814  auto *VarTemplate = cast_or_null<VarTemplateDecl>(
4815  Importer.Import(D->getSpecializedTemplate()));
4816  if (!VarTemplate)
4817  return nullptr;
4818 
4819  // Import the context of this declaration.
4820  DeclContext *DC = VarTemplate->getDeclContext();
4821  if (!DC)
4822  return nullptr;
4823 
4824  DeclContext *LexicalDC = DC;
4825  if (D->getDeclContext() != D->getLexicalDeclContext()) {
4826  LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4827  if (!LexicalDC)
4828  return nullptr;
4829  }
4830 
4831  // Import the location of this declaration.
4832  SourceLocation StartLoc = Importer.Import(D->getBeginLoc());
4833  SourceLocation IdLoc = Importer.Import(D->getLocation());
4834 
4835  // Import template arguments.
4836  SmallVector<TemplateArgument, 2> TemplateArgs;
4837  if (ImportTemplateArguments(D->getTemplateArgs().data(),
4838  D->getTemplateArgs().size(), TemplateArgs))
4839  return nullptr;
4840 
4841  // Try to find an existing specialization with these template arguments.
4842  void *InsertPos = nullptr;
4843  VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4844  TemplateArgs, InsertPos);
4845  if (D2) {
4846  // We already have a variable template specialization with these template
4847  // arguments.
4848 
4849  // FIXME: Check for specialization vs. instantiation errors.
4850 
4851  if (VarDecl *FoundDef = D2->getDefinition()) {
4852  if (!D->isThisDeclarationADefinition() ||
4853  IsStructuralMatch(D, FoundDef)) {
4854  // The record types structurally match, or the "from" translation
4855  // unit only had a forward declaration anyway; call it the same
4856  // variable.
4857  return Importer.MapImported(D, FoundDef);
4858  }
4859  }
4860  } else {
4861  // Import the type.
4862  QualType T = Importer.Import(D->getType());
4863  if (T.isNull())
4864  return nullptr;
4865 
4866  TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4867  if (D->getTypeSourceInfo() && !TInfo)
4868  return nullptr;
4869 
4870  TemplateArgumentListInfo ToTAInfo;
4871  if (ImportTemplateArgumentListInfo(D->getTemplateArgsInfo(), ToTAInfo))
4872  return nullptr;
4873 
4874  using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
4875  // Create a new specialization.
4876  if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
4877  // Import TemplateArgumentListInfo
4878  TemplateArgumentListInfo ArgInfos;
4879  const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
4880  // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
4881  if (ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ArgInfos))
4882  return nullptr;
4883 
4884  TemplateParameterList *ToTPList = ImportTemplateParameterList(
4885  FromPartial->getTemplateParameters());
4886  if (!ToTPList)
4887  return nullptr;
4888 
4889  PartVarSpecDecl *ToPartial;
4890  if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
4891  StartLoc, IdLoc, ToTPList, VarTemplate, T,
4892  TInfo, D->getStorageClass(), TemplateArgs,
4893  ArgInfos))
4894  return ToPartial;
4895 
4896  auto *FromInst = FromPartial->getInstantiatedFromMember();
4897  auto *ToInst = cast_or_null<PartVarSpecDecl>(Importer.Import(FromInst));
4898  if (FromInst && !ToInst)
4899  return nullptr;
4900 
4901  ToPartial->setInstantiatedFromMember(ToInst);
4902  if (FromPartial->isMemberSpecialization())
4903  ToPartial->setMemberSpecialization();
4904 
4905  D2 = ToPartial;
4906  } else { // Full specialization
4907  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, StartLoc,
4908  IdLoc, VarTemplate, T, TInfo,
4909  D->getStorageClass(), TemplateArgs))
4910  return D2;
4911  }
4912 
4914  if (POI.isValid())
4915  D2->setPointOfInstantiation(Importer.Import(POI));
4916 
4918  D2->setTemplateArgsInfo(ToTAInfo);
4919 
4920  // Add this specialization to the class template.
4921  VarTemplate->AddSpecialization(D2, InsertPos);
4922 
4923  // Import the qualifier, if any.
4924  D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4925 
4926  if (D->isConstexpr())
4927  D2->setConstexpr(true);
4928 
4929  // Add the specialization to this context.
4930  D2->setLexicalDeclContext(LexicalDC);
4931  LexicalDC->addDeclInternal(D2);
4932 
4933  D2->setAccess(D->getAccess());
4934  }
4935 
4936  if (ImportInitializer(D, D2))
4937  return nullptr;
4938 
4939  return D2;
4940 }
4941 
4943  DeclContext *DC, *LexicalDC;
4944  DeclarationName Name;
4945  SourceLocation Loc;
4946  NamedDecl *ToD;
4947 
4948  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4949  return nullptr;
4950 
4951  if (ToD)
4952  return ToD;
4953 
4954  // Try to find a function in our own ("to") context with the same name, same
4955  // type, and in the same context as the function we're importing.
4956  if (!LexicalDC->isFunctionOrMethod()) {
4957  unsigned IDNS = Decl::IDNS_Ordinary;
4958  SmallVector<NamedDecl *, 2> FoundDecls;
4959  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4960  for (auto *FoundDecl : FoundDecls) {
4961  if (!FoundDecl->isInIdentifierNamespace(IDNS))
4962  continue;
4963 
4964  if (auto *FoundFunction = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
4965  if (FoundFunction->hasExternalFormalLinkage() &&
4966  D->hasExternalFormalLinkage()) {
4967  if (IsStructuralMatch(D, FoundFunction)) {
4968  Importer.MapImported(D, FoundFunction);
4969  // FIXME: Actually try to merge the body and other attributes.
4970  return FoundFunction;
4971  }
4972  }
4973  }
4974  }
4975  }
4976 
4977  TemplateParameterList *Params =
4978  ImportTemplateParameterList(D->getTemplateParameters());
4979  if (!Params)
4980  return nullptr;
4981 
4982  auto *TemplatedFD =
4983  cast_or_null<FunctionDecl>(Importer.Import(D->getTemplatedDecl()));
4984  if (!TemplatedFD)
4985  return nullptr;
4986 
4987  FunctionTemplateDecl *ToFunc;
4988  if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
4989  Params, TemplatedFD))
4990  return ToFunc;
4991 
4992  TemplatedFD->setDescribedFunctionTemplate(ToFunc);
4993  ToFunc->setAccess(D->getAccess());
4994  ToFunc->setLexicalDeclContext(LexicalDC);
4995 
4996  LexicalDC->addDeclInternal(ToFunc);
4997  return ToFunc;
4998 }
4999 
5000 //----------------------------------------------------------------------------
5001 // Import Statements
5002 //----------------------------------------------------------------------------
5003 
5005  if (DG.isNull())
5006  return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
5007  size_t NumDecls = DG.end() - DG.begin();
5008  SmallVector<Decl *, 1> ToDecls(NumDecls);
5009  auto &_Importer = this->Importer;
5010  std::transform(DG.begin(), DG.end(), ToDecls.begin(),
5011  [&_Importer](Decl *D) -> Decl * {
5012  return _Importer.Import(D);
5013  });
5014  return DeclGroupRef::Create(Importer.getToContext(),
5015  ToDecls.begin(),
5016  NumDecls);
5017 }
5018 
5020  Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5021  << S->getStmtClassName();
5022  return nullptr;
5023 }
5024 
5027  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5028  IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5029  // ToII is nullptr when no symbolic name is given for output operand
5030  // see ParseStmtAsm::ParseAsmOperandsOpt
5031  if (!ToII && S->getOutputIdentifier(I))
5032  return nullptr;
5033  Names.push_back(ToII);
5034  }
5035  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5036  IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5037  // ToII is nullptr when no symbolic name is given for input operand
5038  // see ParseStmtAsm::ParseAsmOperandsOpt
5039  if (!ToII && S->getInputIdentifier(I))
5040  return nullptr;
5041  Names.push_back(ToII);
5042  }
5043 
5045  for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5046  auto *Clobber = cast_or_null<StringLiteral>(
5047  Importer.Import(S->getClobberStringLiteral(I)));
5048  if (!Clobber)
5049  return nullptr;
5050  Clobbers.push_back(Clobber);
5051  }
5052 
5053  SmallVector<StringLiteral *, 4> Constraints;
5054  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5055  auto *Output = cast_or_null<StringLiteral>(
5056  Importer.Import(S->getOutputConstraintLiteral(I)));
5057  if (!Output)
5058  return nullptr;
5059  Constraints.push_back(Output);
5060  }
5061 
5062  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5063  auto *Input = cast_or_null<StringLiteral>(
5064  Importer.Import(S->getInputConstraintLiteral(I)));
5065  if (!Input)
5066  return nullptr;
5067  Constraints.push_back(Input);
5068  }
5069 
5071  if (ImportContainerChecked(S->outputs(), Exprs))
5072  return nullptr;
5073 
5074  if (ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
5075  return nullptr;
5076 
5077  auto *AsmStr = cast_or_null<StringLiteral>(
5078  Importer.Import(S->getAsmString()));
5079  if (!AsmStr)
5080  return nullptr;
5081 
5082  return new (Importer.getToContext()) GCCAsmStmt(
5083  Importer.getToContext(),
5084  Importer.Import(S->getAsmLoc()),
5085  S->isSimple(),
5086  S->isVolatile(),
5087  S->getNumOutputs(),
5088  S->getNumInputs(),
5089  Names.data(),
5090  Constraints.data(),
5091  Exprs.data(),
5092  AsmStr,
5093  S->getNumClobbers(),
5094  Clobbers.data(),
5095  Importer.Import(S->getRParenLoc()));
5096 }
5097 
5099  DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
5100  for (auto *ToD : ToDG) {
5101  if (!ToD)
5102  return nullptr;
5103  }
5104  SourceLocation ToStartLoc = Importer.Import(S->getBeginLoc());
5105  SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
5106  return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
5107 }
5108 
5110  SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
5111  return new (Importer.getToContext()) NullStmt(ToSemiLoc,
5112  S->hasLeadingEmptyMacro());
5113 }
5114 
5116  SmallVector<Stmt *, 8> ToStmts(S->size());
5117 
5118  if (ImportContainerChecked(S->body(), ToStmts))
5119  return nullptr;
5120 
5121  SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
5122  SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
5123  return CompoundStmt::Create(Importer.getToContext(), ToStmts, ToLBraceLoc,
5124  ToRBraceLoc);
5125 }
5126 
5128  Expr *ToLHS = Importer.Import(S->getLHS());
5129  if (!ToLHS)
5130  return nullptr;
5131  Expr *ToRHS = Importer.Import(S->getRHS());
5132  if (!ToRHS && S->getRHS())
5133  return nullptr;
5134  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5135  if (!ToSubStmt && S->getSubStmt())
5136  return nullptr;
5137  SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
5138  SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
5139  SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5140  auto *ToStmt = new (Importer.getToContext())
5141  CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
5142  ToStmt->setSubStmt(ToSubStmt);
5143  return ToStmt;
5144 }
5145 
5147  SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
5148  SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5149  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5150  if (!ToSubStmt && S->getSubStmt())
5151  return nullptr;
5152  return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
5153  ToSubStmt);
5154 }
5155 
5157  SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
5158  auto *ToLabelDecl = cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
5159  if (!ToLabelDecl && S->getDecl())
5160  return nullptr;
5161  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5162  if (!ToSubStmt && S->getSubStmt())
5163  return nullptr;
5164  return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
5165  ToSubStmt);
5166 }
5167 
5169  SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
5170  ArrayRef<const Attr*> FromAttrs(S->getAttrs());
5171  SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
5172  if (ImportContainerChecked(FromAttrs, ToAttrs))
5173  return nullptr;
5174  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5175  if (!ToSubStmt && S->getSubStmt())
5176  return nullptr;
5177  return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
5178  ToAttrs, ToSubStmt);
5179 }
5180 
5182  SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
5183  Stmt *ToInit = Importer.Import(S->getInit());
5184  if (!ToInit && S->getInit())
5185  return nullptr;
5186  VarDecl *ToConditionVariable = nullptr;
5187  if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5188  ToConditionVariable =
5189  dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5190  if (!ToConditionVariable)
5191  return nullptr;
5192  }
5193  Expr *ToCondition = Importer.Import(S->getCond());
5194  if (!ToCondition && S->getCond())
5195  return nullptr;
5196  Stmt *ToThenStmt = Importer.Import(S->getThen());
5197  if (!ToThenStmt && S->getThen())
5198  return nullptr;
5199  SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
5200  Stmt *ToElseStmt = Importer.Import(S->getElse());
5201  if (!ToElseStmt && S->getElse())
5202  return nullptr;
5203  return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
5204  ToIfLoc, S->isConstexpr(),
5205  ToInit,
5206  ToConditionVariable,
5207  ToCondition, ToThenStmt,
5208  ToElseLoc, ToElseStmt);
5209 }
5210 
5212  Stmt *ToInit = Importer.Import(S->getInit());
5213  if (!ToInit && S->getInit())
5214  return nullptr;
5215  VarDecl *ToConditionVariable = nullptr;
5216  if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5217  ToConditionVariable =
5218  dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5219  if (!ToConditionVariable)
5220  return nullptr;
5221  }
5222  Expr *ToCondition = Importer.Import(S->getCond());
5223  if (!ToCondition && S->getCond())
5224  return nullptr;
5225  auto *ToStmt = new (Importer.getToContext()) SwitchStmt(
5226  Importer.getToContext(), ToInit,
5227  ToConditionVariable, ToCondition);
5228  Stmt *ToBody = Importer.Import(S->getBody());
5229  if (!ToBody && S->getBody())
5230  return nullptr;
5231  ToStmt->setBody(ToBody);
5232  ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
5233  // Now we have to re-chain the cases.
5234  SwitchCase *LastChainedSwitchCase = nullptr;
5235  for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5236  SC = SC->getNextSwitchCase()) {
5237  auto *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
5238  if (!ToSC)
5239  return nullptr;
5240  if (LastChainedSwitchCase)
5241  LastChainedSwitchCase->setNextSwitchCase(ToSC);
5242  else
5243  ToStmt->setSwitchCaseList(ToSC);
5244  LastChainedSwitchCase = ToSC;
5245  }
5246  return ToStmt;
5247 }
5248 
5250  VarDecl *ToConditionVariable = nullptr;
5251  if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5252  ToConditionVariable =
5253  dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5254  if (!ToConditionVariable)
5255  return nullptr;
5256  }
5257  Expr *ToCondition = Importer.Import(S->getCond());
5258  if (!ToCondition && S->getCond())
5259  return nullptr;
5260  Stmt *ToBody = Importer.Import(S->getBody());
5261  if (!ToBody && S->getBody())
5262  return nullptr;
5263  SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5264  return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
5265  ToConditionVariable,
5266  ToCondition, ToBody,
5267  ToWhileLoc);
5268 }
5269 
5271  Stmt *ToBody = Importer.Import(S->getBody());
5272  if (!ToBody && S->getBody())
5273  return nullptr;
5274  Expr *ToCondition = Importer.Import(S->getCond());
5275  if (!ToCondition && S->getCond())
5276  return nullptr;
5277  SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
5278  SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5279  SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5280  return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
5281  ToDoLoc, ToWhileLoc,
5282  ToRParenLoc);
5283 }
5284 
5286  Stmt *ToInit = Importer.Import(S->getInit());
5287  if (!ToInit && S->getInit())
5288  return nullptr;
5289  Expr *ToCondition = Importer.Import(S->getCond());
5290  if (!ToCondition && S->getCond())
5291  return nullptr;
5292  VarDecl *ToConditionVariable = nullptr;
5293  if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5294  ToConditionVariable =
5295  dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5296  if (!ToConditionVariable)
5297  return nullptr;
5298  }
5299  Expr *ToInc = Importer.Import(S->getInc());
5300  if (!ToInc && S->getInc())
5301  return nullptr;
5302  Stmt *ToBody = Importer.Import(S->getBody());
5303  if (!ToBody && S->getBody())
5304  return nullptr;
5305  SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5306  SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
5307  SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5308  return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
5309  ToInit, ToCondition,
5310  ToConditionVariable,
5311  ToInc, ToBody,
5312  ToForLoc, ToLParenLoc,
5313  ToRParenLoc);
5314 }
5315 
5317  LabelDecl *ToLabel = nullptr;
5318  if (LabelDecl *FromLabel = S->getLabel()) {
5319  ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
5320  if (!ToLabel)
5321  return nullptr;
5322  }
5323  SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5324  SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
5325  return new (Importer.getToContext()) GotoStmt(ToLabel,
5326  ToGotoLoc, ToLabelLoc);
5327 }
5328 
5330  SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5331  SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
5332  Expr *ToTarget = Importer.Import(S->getTarget());
5333  if (!ToTarget && S->getTarget())
5334  return nullptr;
5335  return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
5336  ToTarget);
5337 }
5338 
5340  SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
5341  return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
5342 }
5343 
5345  SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
5346  return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
5347 }
5348 
5350  SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
5351  Expr *ToRetExpr = Importer.Import(S->getRetValue());
5352  if (!ToRetExpr && S->getRetValue())
5353  return nullptr;
5354  auto *NRVOCandidate = const_cast<VarDecl *>(S->getNRVOCandidate());
5355  auto *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
5356  if (!ToNRVOCandidate && NRVOCandidate)
5357  return nullptr;
5358  return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
5359  ToNRVOCandidate);
5360 }
5361 
5363  SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
5364  VarDecl *ToExceptionDecl = nullptr;
5365  if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
5366  ToExceptionDecl =
5367  dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5368  if (!ToExceptionDecl)
5369  return nullptr;
5370  }
5371  Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
5372  if (!ToHandlerBlock && S->getHandlerBlock())
5373  return nullptr;
5374  return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
5375  ToExceptionDecl,
5376  ToHandlerBlock);
5377 }
5378 
5380  SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
5381  Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
5382  if (!ToTryBlock && S->getTryBlock())
5383  return nullptr;
5384  SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5385  for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5386  CXXCatchStmt *FromHandler = S->getHandler(HI);
5387  if (Stmt *ToHandler = Importer.Import(FromHandler))
5388  ToHandlers[HI] = ToHandler;
5389  else
5390  return nullptr;
5391  }
5392  return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
5393  ToHandlers);
5394 }
5395 
5397  auto *ToInit = dyn_cast_or_null<Stmt>(Importer.Import(S->getInit()));
5398  if (!ToInit && S->getInit())
5399  return nullptr;
5400  auto *ToRange =
5401  dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
5402  if (!ToRange && S->getRangeStmt())
5403  return nullptr;
5404  auto *ToBegin =
5405  dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
5406  if (!ToBegin && S->getBeginStmt())
5407  return nullptr;
5408  auto *ToEnd =
5409  dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
5410  if (!ToEnd && S->getEndStmt())
5411  return nullptr;
5412  Expr *ToCond = Importer.Import(S->getCond());
5413  if (!ToCond && S->getCond())
5414  return nullptr;
5415  Expr *ToInc = Importer.Import(S->getInc());
5416  if (!ToInc && S->getInc())
5417  return nullptr;
5418  auto *ToLoopVar =
5419  dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
5420  if (!ToLoopVar && S->getLoopVarStmt())
5421  return nullptr;
5422  Stmt *ToBody = Importer.Import(S->getBody());
5423  if (!ToBody && S->getBody())
5424  return nullptr;
5425  SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5426  SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
5427  SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5428  SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5429  return new (Importer.getToContext())
5430  CXXForRangeStmt(ToInit, ToRange, ToBegin, ToEnd, ToCond, ToInc, ToLoopVar,
5431  ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
5432 }
5433 
5435  Stmt *ToElem = Importer.Import(S->getElement());
5436  if (!ToElem && S->getElement())
5437  return nullptr;
5438  Expr *ToCollect = Importer.Import(S->getCollection());
5439  if (!ToCollect && S->getCollection())
5440  return nullptr;
5441  Stmt *ToBody = Importer.Import(S->getBody());
5442  if (!ToBody && S->getBody())
5443  return nullptr;
5444  SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5445  SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5446  return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
5447  ToCollect,
5448  ToBody, ToForLoc,
5449  ToRParenLoc);
5450 }
5451 
5453  SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
5454  SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5455  VarDecl *ToExceptionDecl = nullptr;
5456  if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
5457  ToExceptionDecl =
5458  dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5459  if (!ToExceptionDecl)
5460  return nullptr;
5461  }
5462  Stmt *ToBody = Importer.Import(S->getCatchBody());
5463  if (!ToBody && S->getCatchBody())
5464  return nullptr;
5465  return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
5466  ToRParenLoc,
5467  ToExceptionDecl,
5468  ToBody);
5469 }
5470 
5472  SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
5473  Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
5474  if (!ToAtFinallyStmt && S->getFinallyBody())
5475  return nullptr;
5476  return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
5477  ToAtFinallyStmt);
5478 }
5479 
5481  SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
5482  Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
5483  if (!ToAtTryStmt && S->getTryBody())
5484  return nullptr;
5485  SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
5486  for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
5487  ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
5488  if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
5489  ToCatchStmts[CI] = ToCatchStmt;
5490  else
5491  return nullptr;
5492  }
5493  Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
5494  if (!ToAtFinallyStmt && S->getFinallyStmt())
5495  return nullptr;
5496  return ObjCAtTryStmt::Create(Importer.getToContext(),
5497  ToAtTryLoc, ToAtTryStmt,
5498  ToCatchStmts.begin(), ToCatchStmts.size(),
5499  ToAtFinallyStmt);
5500 }
5501 
5504  SourceLocation ToAtSynchronizedLoc =
5505  Importer.Import(S->getAtSynchronizedLoc());
5506  Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5507  if (!ToSynchExpr && S->getSynchExpr())
5508  return nullptr;
5509  Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5510  if (!ToSynchBody && S->getSynchBody())
5511  return nullptr;
5512  return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5513  ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5514 }
5515 
5517  SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5518  Expr *ToThrow = Importer.Import(S->getThrowExpr());
5519  if (!ToThrow && S->getThrowExpr())
5520  return nullptr;
5521  return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5522 }
5523 
5526  SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5527  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5528  if (!ToSubStmt && S->getSubStmt())
5529  return nullptr;
5530  return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5531  ToSubStmt);
5532 }
5533 
5534 //----------------------------------------------------------------------------
5535 // Import Expressions
5536 //----------------------------------------------------------------------------
5538  Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
5539  << E->getStmtClassName();
5540  return nullptr;
5541 }
5542 
5544  QualType T = Importer.Import(E->getType());
5545  if (T.isNull())
5546  return nullptr;
5547 
5548  Expr *SubExpr = Importer.Import(E->getSubExpr());
5549  if (!SubExpr && E->getSubExpr())
5550  return nullptr;
5551 
5552  TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
5553  if (!TInfo)
5554  return nullptr;
5555 
5556  return new (Importer.getToContext()) VAArgExpr(
5557  Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
5558  Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
5559 }
5560 
5562  QualType T = Importer.Import(E->getType());
5563  if (T.isNull())
5564  return nullptr;
5565 
5566  return new (Importer.getToContext())
5567  GNUNullExpr(T, Importer.Import(E->getBeginLoc()));
5568 }
5569 
5571  QualType T = Importer.Import(E->getType());
5572  if (T.isNull())
5573  return nullptr;
5574 
5575  auto *SL = cast_or_null<StringLiteral>(Importer.Import(E->getFunctionName()));
5576  if (!SL && E->getFunctionName())
5577  return nullptr;
5578 
5579  return new (Importer.getToContext()) PredefinedExpr(
5580  Importer.Import(E->getBeginLoc()), T, E->getIdentType(), SL);
5581 }
5582 
5584  auto *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5585  if (!ToD)
5586  return nullptr;
5587 
5588  NamedDecl *FoundD = nullptr;
5589  if (E->getDecl() != E->getFoundDecl()) {
5590  FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5591  if (!FoundD)
5592  return nullptr;
5593  }
5594 
5595  QualType T = Importer.Import(E->getType());
5596  if (T.isNull())
5597  return nullptr;
5598 
5599  TemplateArgumentListInfo ToTAInfo;
5600  TemplateArgumentListInfo *ResInfo = nullptr;
5601  if (E->hasExplicitTemplateArgs()) {
5602  if (ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
5603  return nullptr;
5604  ResInfo = &ToTAInfo;
5605  }
5606 
5607  DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5608  Importer.Import(E->getQualifierLoc()),
5609  Importer.Import(E->getTemplateKeywordLoc()),
5610  ToD,
5612  Importer.Import(E->getLocation()),
5613  T, E->getValueKind(),
5614  FoundD, ResInfo);
5615  if (E->hadMultipleCandidates())
5616  DRE->setHadMultipleCandidates(true);
5617  return DRE;
5618 }
5619 
5621  QualType T = Importer.Import(E->getType());
5622  if (T.isNull())
5623  return nullptr;
5624 
5625  return new (Importer.getToContext()) ImplicitValueInitExpr(T);
5626 }
5627 
5630  if (D.isFieldDesignator()) {
5631  IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
5632  // Caller checks for import error
5633  return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
5634  Importer.Import(D.getFieldLoc()));
5635  }
5636  if (D.isArrayDesignator())
5637  return Designator(D.getFirstExprIndex(),
5638  Importer.Import(D.getLBracketLoc()),
5639  Importer.Import(D.getRBracketLoc()));
5640 
5641  assert(D.isArrayRangeDesignator());
5642  return Designator(D.getFirstExprIndex(),
5643  Importer.Import(D.getLBracketLoc()),
5644  Importer.Import(D.getEllipsisLoc()),
5645  Importer.Import(D.getRBracketLoc()));
5646 }
5647 
5648