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