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