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