clang  15.0.0git
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"
47 #include "clang/Basic/Builtins.h"
51 #include "clang/Basic/LLVM.h"
55 #include "clang/Basic/Specifiers.h"
56 #include "llvm/ADT/APSInt.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/None.h"
60 #include "llvm/ADT/Optional.h"
61 #include "llvm/ADT/ScopeExit.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstddef>
70 #include <memory>
71 #include <type_traits>
72 #include <utility>
73 
74 namespace clang {
75 
76  using llvm::make_error;
77  using llvm::Error;
78  using llvm::Expected;
86 
88  // FIXME: Improve error texts.
89  switch (Error) {
90  case NameConflict:
91  return "NameConflict";
93  return "UnsupportedConstruct";
94  case Unknown:
95  return "Unknown error";
96  }
97  llvm_unreachable("Invalid error code.");
98  return "Invalid error code.";
99  }
100 
101  void ASTImportError::log(raw_ostream &OS) const { OS << toString(); }
102 
103  std::error_code ASTImportError::convertToErrorCode() const {
104  llvm_unreachable("Function not implemented.");
105  }
106 
107  char ASTImportError::ID;
108 
109  template <class T>
112  SmallVector<Decl *, 2> Redecls;
113  for (auto *R : D->getFirstDecl()->redecls()) {
114  if (R != D->getFirstDecl())
115  Redecls.push_back(R);
116  }
117  Redecls.push_back(D->getFirstDecl());
118  std::reverse(Redecls.begin(), Redecls.end());
119  return Redecls;
120  }
121 
123  if (auto *FD = dyn_cast<FunctionDecl>(D))
124  return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
125  if (auto *VD = dyn_cast<VarDecl>(D))
126  return getCanonicalForwardRedeclChain<VarDecl>(VD);
127  if (auto *TD = dyn_cast<TagDecl>(D))
128  return getCanonicalForwardRedeclChain<TagDecl>(TD);
129  llvm_unreachable("Bad declaration kind");
130  }
131 
132  void updateFlags(const Decl *From, Decl *To) {
133  // Check if some flags or attrs are new in 'From' and copy into 'To'.
134  // FIXME: Other flags or attrs?
135  if (From->isUsed(false) && !To->isUsed(false))
136  To->setIsUsed();
137  }
138 
139  /// How to handle import errors that occur when import of a child declaration
140  /// of a DeclContext fails.
142  /// This context is imported (in the 'from' domain).
143  /// It is nullptr if a non-DeclContext is imported.
144  const DeclContext *const FromDC;
145  /// Ignore import errors of the children.
146  /// If true, the context can be imported successfully if a child
147  /// of it failed to import. Otherwise the import errors of the child nodes
148  /// are accumulated (joined) into the import error object of the parent.
149  /// (Import of a parent can fail in other ways.)
150  bool const IgnoreChildErrors;
151 
152  public:
154  : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(FromDC)) {}
156  : FromDC(dyn_cast<DeclContext>(FromD)),
157  IgnoreChildErrors(!isa<TagDecl>(FromD)) {}
158 
159  /// Process the import result of a child (of the current declaration).
160  /// \param ResultErr The import error that can be used as result of
161  /// importing the parent. This may be changed by the function.
162  /// \param ChildErr Result of importing a child. Can be success or error.
163  void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
164  if (ChildErr && !IgnoreChildErrors)
165  ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr));
166  else
167  consumeError(std::move(ChildErr));
168  }
169 
170  /// Determine if import failure of a child does not cause import failure of
171  /// its parent.
172  bool ignoreChildErrorOnParent(Decl *FromChildD) const {
173  if (!IgnoreChildErrors || !FromDC)
174  return false;
175  return FromDC->containsDecl(FromChildD);
176  }
177  };
178 
179  class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
180  public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
181  public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
182  ASTImporter &Importer;
183 
184  // Use this instead of Importer.importInto .
185  template <typename ImportT>
186  LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) {
187  return Importer.importInto(To, From);
188  }
189 
190  // Use this to import pointers of specific type.
191  template <typename ImportT>
192  LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) {
193  auto ToOrErr = Importer.Import(From);
194  if (ToOrErr)
195  To = cast_or_null<ImportT>(*ToOrErr);
196  return ToOrErr.takeError();
197  }
198 
199  // Call the import function of ASTImporter for a baseclass of type `T` and
200  // cast the return value to `T`.
201  template <typename T>
202  auto import(T *From)
203  -> std::conditional_t<std::is_base_of<Type, T>::value,
205  auto ToOrErr = Importer.Import(From);
206  if (!ToOrErr)
207  return ToOrErr.takeError();
208  return cast_or_null<T>(*ToOrErr);
209  }
210 
211  template <typename T>
212  auto import(const T *From) {
213  return import(const_cast<T *>(From));
214  }
215 
216  // Call the import function of ASTImporter for type `T`.
217  template <typename T>
218  Expected<T> import(const T &From) {
219  return Importer.Import(From);
220  }
221 
222  // Import an Optional<T> by importing the contained T, if any.
223  template<typename T>
224  Expected<Optional<T>> import(Optional<T> From) {
225  if (!From)
226  return Optional<T>();
227  return import(*From);
228  }
229 
230  ExplicitSpecifier importExplicitSpecifier(Error &Err,
231  ExplicitSpecifier ESpec);
232 
233  // Wrapper for an overload set.
234  template <typename ToDeclT> struct CallOverloadedCreateFun {
235  template <typename... Args> decltype(auto) operator()(Args &&... args) {
236  return ToDeclT::Create(std::forward<Args>(args)...);
237  }
238  };
239 
240  // Always use these functions to create a Decl during import. There are
241  // certain tasks which must be done after the Decl was created, e.g. we
242  // must immediately register that as an imported Decl. The parameter `ToD`
243  // will be set to the newly created Decl or if had been imported before
244  // then to the already imported Decl. Returns a bool value set to true if
245  // the `FromD` had been imported before.
246  template <typename ToDeclT, typename FromDeclT, typename... Args>
247  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
248  Args &&... args) {
249  // There may be several overloads of ToDeclT::Create. We must make sure
250  // to call the one which would be chosen by the arguments, thus we use a
251  // wrapper for the overload set.
252  CallOverloadedCreateFun<ToDeclT> OC;
253  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
254  std::forward<Args>(args)...);
255  }
256  // Use this overload if a special Type is needed to be created. E.g if we
257  // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
258  // then:
259  // TypedefNameDecl *ToTypedef;
260  // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
261  template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
262  typename... Args>
263  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
264  Args &&... args) {
265  CallOverloadedCreateFun<NewDeclT> OC;
266  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
267  std::forward<Args>(args)...);
268  }
269  // Use this version if a special create function must be
270  // used, e.g. CXXRecordDecl::CreateLambda .
271  template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
272  typename... Args>
273  LLVM_NODISCARD bool
274  GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
275  FromDeclT *FromD, Args &&... args) {
276  if (Importer.getImportDeclErrorIfAny(FromD)) {
277  ToD = nullptr;
278  return true; // Already imported but with error.
279  }
280  ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
281  if (ToD)
282  return true; // Already imported.
283  ToD = CreateFun(std::forward<Args>(args)...);
284  // Keep track of imported Decls.
285  Importer.RegisterImportedDecl(FromD, ToD);
286  Importer.SharedState->markAsNewDecl(ToD);
287  InitializeImportedDecl(FromD, ToD);
288  return false; // A new Decl is created.
289  }
290 
291  void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
293  if (FromD->isUsed())
294  ToD->setIsUsed();
295  if (FromD->isImplicit())
296  ToD->setImplicit();
297  }
298 
299  // Check if we have found an existing definition. Returns with that
300  // definition if yes, otherwise returns null.
301  Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
302  const FunctionDecl *Definition = nullptr;
303  if (D->doesThisDeclarationHaveABody() &&
304  FoundFunction->hasBody(Definition))
305  return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
306  return nullptr;
307  }
308 
309  void addDeclToContexts(Decl *FromD, Decl *ToD) {
310  if (Importer.isMinimalImport()) {
311  // In minimal import case the decl must be added even if it is not
312  // contained in original context, for LLDB compatibility.
313  // FIXME: Check if a better solution is possible.
314  if (!FromD->getDescribedTemplate() &&
317  return;
318  }
319 
320  DeclContext *FromDC = FromD->getDeclContext();
321  DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
322  DeclContext *ToDC = ToD->getDeclContext();
323  DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
324 
325  bool Visible = false;
326  if (FromDC->containsDeclAndLoad(FromD)) {
327  ToDC->addDeclInternal(ToD);
328  Visible = true;
329  }
330  if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
331  ToLexicalDC->addDeclInternal(ToD);
332  Visible = true;
333  }
334 
335  // If the Decl was added to any context, it was made already visible.
336  // Otherwise it is still possible that it should be visible.
337  if (!Visible) {
338  if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
339  auto *ToNamed = cast<NamedDecl>(ToD);
340  DeclContextLookupResult FromLookup =
341  FromDC->lookup(FromNamed->getDeclName());
342  if (llvm::is_contained(FromLookup, FromNamed))
343  ToDC->makeDeclVisibleInContext(ToNamed);
344  }
345  }
346  }
347 
348  void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
349  DeclContext *OldDC) {
350  ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
351  if (!LT)
352  return;
353 
354  for (NamedDecl *TP : Params)
355  LT->update(TP, OldDC);
356  }
357 
358  void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
359  updateLookupTableForTemplateParameters(
360  Params, Importer.getToContext().getTranslationUnitDecl());
361  }
362 
363  public:
364  explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
365 
369 
370  // Importing types
371  ExpectedType VisitType(const Type *T);
385  // FIXME: DependentSizedExtVectorType
394  // FIXME: DependentTypeOfExprType
403  // FIXME: DependentDecltypeType
409  const SubstTemplateTypeParmType *T);
413  const TemplateSpecializationType *T);
422 
423  // Importing declarations
425  SourceLocation &Loc);
427  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
428  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
429  Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
431  const DeclarationNameInfo &From, DeclarationNameInfo &To);
432  Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
434  Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
436 
438  Expected<APValue> ImportAPValue(const APValue &FromValue);
439 
441 
442  /// What we should import from the definition.
444  /// Import the default subset of the definition, which might be
445  /// nothing (if minimal import is set) or might be everything (if minimal
446  /// import is not set).
448  /// Import everything.
450  /// Import only the bare bones needed to establish a valid
451  /// DeclContext.
453  };
454 
456  return IDK == IDK_Everything ||
457  (IDK == IDK_Default && !Importer.isMinimalImport());
458  }
459 
462  RecordDecl *From, RecordDecl *To,
465  EnumDecl *From, EnumDecl *To,
474  const TemplateArgument *FromArgs, unsigned NumFromArgs,
478 
479  template <typename InContainerTy>
481  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
482 
483  template<typename InContainerTy>
485  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
486  const InContainerTy &Container, TemplateArgumentListInfo &Result);
487 
490  std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
493  FunctionDecl *FromFD);
495  DeclaratorDecl *ToD);
496 
498 
500 
502  ParmVarDecl *ToParam);
503 
506 
507  template <typename T>
508  bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
509 
510  bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true);
557 
560 
575 
576  // Importing statements
596  // FIXME: MSAsmStmt
597  // FIXME: SEHExceptStmt
598  // FIXME: SEHFinallyStmt
599  // FIXME: SEHTryStmt
600  // FIXME: SEHLeaveStmt
601  // FIXME: CapturedStmt
605  // FIXME: MSDependentExistsStmt
613 
614  // Importing expressions
689 
690  // Helper for chaining together multiple imports. If an error is detected,
691  // subsequent imports will return default constructed nodes, so that failure
692  // can be detected with a single conditional branch after a sequence of
693  // imports.
694  template <typename T> T importChecked(Error &Err, const T &From) {
695  // Don't attempt to import nodes if we hit an error earlier.
696  if (Err)
697  return T{};
698  Expected<T> MaybeVal = import(From);
699  if (!MaybeVal) {
700  Err = MaybeVal.takeError();
701  return T{};
702  }
703  return *MaybeVal;
704  }
705 
706  template<typename IIter, typename OIter>
707  Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
708  using ItemT = std::remove_reference_t<decltype(*Obegin)>;
709  for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
710  Expected<ItemT> ToOrErr = import(*Ibegin);
711  if (!ToOrErr)
712  return ToOrErr.takeError();
713  *Obegin = *ToOrErr;
714  }
715  return Error::success();
716  }
717 
718  // Import every item from a container structure into an output container.
719  // If error occurs, stops at first error and returns the error.
720  // The output container should have space for all needed elements (it is not
721  // expanded, new items are put into from the beginning).
722  template<typename InContainerTy, typename OutContainerTy>
724  const InContainerTy &InContainer, OutContainerTy &OutContainer) {
725  return ImportArrayChecked(
726  InContainer.begin(), InContainer.end(), OutContainer.begin());
727  }
728 
729  template<typename InContainerTy, typename OIter>
730  Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
731  return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
732  }
733 
735  CXXMethodDecl *FromMethod);
736 
738  FunctionDecl *FromFD);
739 
740  // Returns true if the given function has a placeholder return type and
741  // that type is declared inside the body of the function.
742  // E.g. auto f() { struct X{}; return X(); }
744  };
745 
746 template <typename InContainerTy>
748  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
749  const InContainerTy &Container, TemplateArgumentListInfo &Result) {
750  auto ToLAngleLocOrErr = import(FromLAngleLoc);
751  if (!ToLAngleLocOrErr)
752  return ToLAngleLocOrErr.takeError();
753  auto ToRAngleLocOrErr = import(FromRAngleLoc);
754  if (!ToRAngleLocOrErr)
755  return ToRAngleLocOrErr.takeError();
756 
757  TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
758  if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
759  return Err;
760  Result = ToTAInfo;
761  return Error::success();
762 }
763 
764 template <>
765 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
766  const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
768  From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
769 }
770 
771 template <>
774  const ASTTemplateArgumentListInfo &From,
775  TemplateArgumentListInfo &Result) {
776  return ImportTemplateArgumentListInfo(
777  From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
778 }
779 
782  FunctionDecl *FromFD) {
783  assert(FromFD->getTemplatedKind() ==
785 
787 
788  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
789  if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
790  return std::move(Err);
791 
792  // Import template arguments.
793  auto TemplArgs = FTSInfo->TemplateArguments->asArray();
794  if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
795  std::get<1>(Result)))
796  return std::move(Err);
797 
798  return Result;
799 }
800 
801 template <>
803 ASTNodeImporter::import(TemplateParameterList *From) {
804  SmallVector<NamedDecl *, 4> To(From->size());
805  if (Error Err = ImportContainerChecked(*From, To))
806  return std::move(Err);
807 
808  ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
809  if (!ToRequiresClause)
810  return ToRequiresClause.takeError();
811 
812  auto ToTemplateLocOrErr = import(From->getTemplateLoc());
813  if (!ToTemplateLocOrErr)
814  return ToTemplateLocOrErr.takeError();
815  auto ToLAngleLocOrErr = import(From->getLAngleLoc());
816  if (!ToLAngleLocOrErr)
817  return ToLAngleLocOrErr.takeError();
818  auto ToRAngleLocOrErr = import(From->getRAngleLoc());
819  if (!ToRAngleLocOrErr)
820  return ToRAngleLocOrErr.takeError();
821 
823  Importer.getToContext(),
824  *ToTemplateLocOrErr,
825  *ToLAngleLocOrErr,
826  To,
827  *ToRAngleLocOrErr,
828  *ToRequiresClause);
829 }
830 
831 template <>
833 ASTNodeImporter::import(const TemplateArgument &From) {
834  switch (From.getKind()) {
836  return TemplateArgument();
837 
838  case TemplateArgument::Type: {
839  ExpectedType ToTypeOrErr = import(From.getAsType());
840  if (!ToTypeOrErr)
841  return ToTypeOrErr.takeError();
842  return TemplateArgument(*ToTypeOrErr);
843  }
844 
846  ExpectedType ToTypeOrErr = import(From.getIntegralType());
847  if (!ToTypeOrErr)
848  return ToTypeOrErr.takeError();
849  return TemplateArgument(From, *ToTypeOrErr);
850  }
851 
853  Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
854  if (!ToOrErr)
855  return ToOrErr.takeError();
856  ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
857  if (!ToTypeOrErr)
858  return ToTypeOrErr.takeError();
859  return TemplateArgument(*ToOrErr, *ToTypeOrErr);
860  }
861 
863  ExpectedType ToTypeOrErr = import(From.getNullPtrType());
864  if (!ToTypeOrErr)
865  return ToTypeOrErr.takeError();
866  return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
867  }
868 
870  Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
871  if (!ToTemplateOrErr)
872  return ToTemplateOrErr.takeError();
873 
874  return TemplateArgument(*ToTemplateOrErr);
875  }
876 
878  Expected<TemplateName> ToTemplateOrErr =
879  import(From.getAsTemplateOrTemplatePattern());
880  if (!ToTemplateOrErr)
881  return ToTemplateOrErr.takeError();
882 
883  return TemplateArgument(
884  *ToTemplateOrErr, From.getNumTemplateExpansions());
885  }
886 
888  if (ExpectedExpr ToExpr = import(From.getAsExpr()))
889  return TemplateArgument(*ToExpr);
890  else
891  return ToExpr.takeError();
892 
893  case TemplateArgument::Pack: {
895  ToPack.reserve(From.pack_size());
896  if (Error Err = ImportTemplateArguments(
897  From.pack_begin(), From.pack_size(), ToPack))
898  return std::move(Err);
899 
900  return TemplateArgument(
901  llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
902  }
903  }
904 
905  llvm_unreachable("Invalid template argument kind");
906 }
907 
908 template <>
910 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
911  Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
912  if (!ArgOrErr)
913  return ArgOrErr.takeError();
914  TemplateArgument Arg = *ArgOrErr;
915 
916  TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
917 
919  if (Arg.getKind() == TemplateArgument::Expression) {
920  ExpectedExpr E = import(FromInfo.getAsExpr());
921  if (!E)
922  return E.takeError();
923  ToInfo = TemplateArgumentLocInfo(*E);
924  } else if (Arg.getKind() == TemplateArgument::Type) {
925  if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
926  ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
927  else
928  return TSIOrErr.takeError();
929  } else {
930  auto ToTemplateQualifierLocOrErr =
931  import(FromInfo.getTemplateQualifierLoc());
932  if (!ToTemplateQualifierLocOrErr)
933  return ToTemplateQualifierLocOrErr.takeError();
934  auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
935  if (!ToTemplateNameLocOrErr)
936  return ToTemplateNameLocOrErr.takeError();
937  auto ToTemplateEllipsisLocOrErr =
938  import(FromInfo.getTemplateEllipsisLoc());
939  if (!ToTemplateEllipsisLocOrErr)
940  return ToTemplateEllipsisLocOrErr.takeError();
941  ToInfo = TemplateArgumentLocInfo(
942  Importer.getToContext(), *ToTemplateQualifierLocOrErr,
943  *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
944  }
945 
946  return TemplateArgumentLoc(Arg, ToInfo);
947 }
948 
949 template <>
950 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
951  if (DG.isNull())
952  return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
953  size_t NumDecls = DG.end() - DG.begin();
954  SmallVector<Decl *, 1> ToDecls;
955  ToDecls.reserve(NumDecls);
956  for (Decl *FromD : DG) {
957  if (auto ToDOrErr = import(FromD))
958  ToDecls.push_back(*ToDOrErr);
959  else
960  return ToDOrErr.takeError();
961  }
962  return DeclGroupRef::Create(Importer.getToContext(),
963  ToDecls.begin(),
964  NumDecls);
965 }
966 
967 template <>
969 ASTNodeImporter::import(const Designator &D) {
970  if (D.isFieldDesignator()) {
971  IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
972 
973  ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
974  if (!ToDotLocOrErr)
975  return ToDotLocOrErr.takeError();
976 
977  ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
978  if (!ToFieldLocOrErr)
979  return ToFieldLocOrErr.takeError();
980 
981  return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
982  }
983 
984  ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
985  if (!ToLBracketLocOrErr)
986  return ToLBracketLocOrErr.takeError();
987 
988  ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
989  if (!ToRBracketLocOrErr)
990  return ToRBracketLocOrErr.takeError();
991 
992  if (D.isArrayDesignator())
993  return Designator(D.getFirstExprIndex(),
994  *ToLBracketLocOrErr, *ToRBracketLocOrErr);
995 
996  ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
997  if (!ToEllipsisLocOrErr)
998  return ToEllipsisLocOrErr.takeError();
999 
1000  assert(D.isArrayRangeDesignator());
1001  return Designator(
1002  D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
1003  *ToRBracketLocOrErr);
1004 }
1005 
1006 template <>
1007 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
1008  VarDecl *Var = nullptr;
1009  if (From.capturesVariable()) {
1010  if (auto VarOrErr = import(From.getCapturedVar()))
1011  Var = *VarOrErr;
1012  else
1013  return VarOrErr.takeError();
1014  }
1015 
1016  auto LocationOrErr = import(From.getLocation());
1017  if (!LocationOrErr)
1018  return LocationOrErr.takeError();
1019 
1020  SourceLocation EllipsisLoc;
1021  if (From.isPackExpansion())
1022  if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
1023  return std::move(Err);
1024 
1025  return LambdaCapture(
1026  *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
1027  EllipsisLoc);
1028 }
1029 
1030 template <typename T>
1032  if (Found->getLinkageInternal() != From->getLinkageInternal())
1033  return false;
1034 
1035  if (From->hasExternalFormalLinkage())
1036  return Found->hasExternalFormalLinkage();
1037  if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
1038  return false;
1039  if (From->isInAnonymousNamespace())
1040  return Found->isInAnonymousNamespace();
1041  else
1042  return !Found->isInAnonymousNamespace() &&
1043  !Found->hasExternalFormalLinkage();
1044 }
1045 
1046 template <>
1048  TypedefNameDecl *From) {
1049  if (Found->getLinkageInternal() != From->getLinkageInternal())
1050  return false;
1051 
1052  if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1053  return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1054  return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1055 }
1056 
1057 } // namespace clang
1058 
1059 //----------------------------------------------------------------------------
1060 // Import Types
1061 //----------------------------------------------------------------------------
1062 
1063 using namespace clang;
1064 
1066  Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1067  << T->getTypeClassName();
1068  return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1069 }
1070 
1072  ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1073  if (!UnderlyingTypeOrErr)
1074  return UnderlyingTypeOrErr.takeError();
1075 
1076  return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1077 }
1078 
1080  switch (T->getKind()) {
1081 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1082  case BuiltinType::Id: \
1083  return Importer.getToContext().SingletonId;
1084 #include "clang/Basic/OpenCLImageTypes.def"
1085 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1086  case BuiltinType::Id: \
1087  return Importer.getToContext().Id##Ty;
1088 #include "clang/Basic/OpenCLExtensionTypes.def"
1089 #define SVE_TYPE(Name, Id, SingletonId) \
1090  case BuiltinType::Id: \
1091  return Importer.getToContext().SingletonId;
1092 #include "clang/Basic/AArch64SVEACLETypes.def"
1093 #define PPC_VECTOR_TYPE(Name, Id, Size) \
1094  case BuiltinType::Id: \
1095  return Importer.getToContext().Id##Ty;
1096 #include "clang/Basic/PPCTypes.def"
1097 #define RVV_TYPE(Name, Id, SingletonId) \
1098  case BuiltinType::Id: \
1099  return Importer.getToContext().SingletonId;
1100 #include "clang/Basic/RISCVVTypes.def"
1101 #define SHARED_SINGLETON_TYPE(Expansion)
1102 #define BUILTIN_TYPE(Id, SingletonId) \
1103  case BuiltinType::Id: return Importer.getToContext().SingletonId;
1104 #include "clang/AST/BuiltinTypes.def"
1105 
1106  // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1107  // context supports C++.
1108 
1109  // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1110  // context supports ObjC.
1111 
1112  case BuiltinType::Char_U:
1113  // The context we're importing from has an unsigned 'char'. If we're
1114  // importing into a context with a signed 'char', translate to
1115  // 'unsigned char' instead.
1116  if (Importer.getToContext().getLangOpts().CharIsSigned)
1117  return Importer.getToContext().UnsignedCharTy;
1118 
1119  return Importer.getToContext().CharTy;
1120 
1121  case BuiltinType::Char_S:
1122  // The context we're importing from has an unsigned 'char'. If we're
1123  // importing into a context with a signed 'char', translate to
1124  // 'unsigned char' instead.
1125  if (!Importer.getToContext().getLangOpts().CharIsSigned)
1126  return Importer.getToContext().SignedCharTy;
1127 
1128  return Importer.getToContext().CharTy;
1129 
1130  case BuiltinType::WChar_S:
1131  case BuiltinType::WChar_U:
1132  // FIXME: If not in C++, shall we translate to the C equivalent of
1133  // wchar_t?
1134  return Importer.getToContext().WCharTy;
1135  }
1136 
1137  llvm_unreachable("Invalid BuiltinType Kind!");
1138 }
1139 
1141  ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1142  if (!ToOriginalTypeOrErr)
1143  return ToOriginalTypeOrErr.takeError();
1144 
1145  return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1146 }
1147 
1149  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1150  if (!ToElementTypeOrErr)
1151  return ToElementTypeOrErr.takeError();
1152 
1153  return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1154 }
1155 
1157  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1158  if (!ToPointeeTypeOrErr)
1159  return ToPointeeTypeOrErr.takeError();
1160 
1161  return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1162 }
1163 
1165  // FIXME: Check for blocks support in "to" context.
1166  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1167  if (!ToPointeeTypeOrErr)
1168  return ToPointeeTypeOrErr.takeError();
1169 
1170  return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1171 }
1172 
1175  // FIXME: Check for C++ support in "to" context.
1176  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1177  if (!ToPointeeTypeOrErr)
1178  return ToPointeeTypeOrErr.takeError();
1179 
1180  return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1181 }
1182 
1185  // FIXME: Check for C++0x support in "to" context.
1186  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1187  if (!ToPointeeTypeOrErr)
1188  return ToPointeeTypeOrErr.takeError();
1189 
1190  return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1191 }
1192 
1195  // FIXME: Check for C++ support in "to" context.
1196  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1197  if (!ToPointeeTypeOrErr)
1198  return ToPointeeTypeOrErr.takeError();
1199 
1200  ExpectedTypePtr ClassTypeOrErr = import(T->getClass());
1201  if (!ClassTypeOrErr)
1202  return ClassTypeOrErr.takeError();
1203 
1204  return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr,
1205  *ClassTypeOrErr);
1206 }
1207 
1210  Error Err = Error::success();
1211  auto ToElementType = importChecked(Err, T->getElementType());
1212  auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1213  if (Err)
1214  return std::move(Err);
1215 
1216  return Importer.getToContext().getConstantArrayType(
1217  ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1219 }
1220 
1223  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1224  if (!ToElementTypeOrErr)
1225  return ToElementTypeOrErr.takeError();
1226 
1227  return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1228  T->getSizeModifier(),
1230 }
1231 
1234  Error Err = Error::success();
1235  QualType ToElementType = importChecked(Err, T->getElementType());
1236  Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1237  SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1238  if (Err)
1239  return std::move(Err);
1240  return Importer.getToContext().getVariableArrayType(
1241  ToElementType, ToSizeExpr, T->getSizeModifier(),
1242  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1243 }
1244 
1246  const DependentSizedArrayType *T) {
1247  Error Err = Error::success();
1248  QualType ToElementType = importChecked(Err, T->getElementType());
1249  Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1250  SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1251  if (Err)
1252  return std::move(Err);
1253  // SizeExpr may be null if size is not specified directly.
1254  // For example, 'int a[]'.
1255 
1256  return Importer.getToContext().getDependentSizedArrayType(
1257  ToElementType, ToSizeExpr, T->getSizeModifier(),
1258  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1259 }
1260 
1262  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1263  if (!ToElementTypeOrErr)
1264  return ToElementTypeOrErr.takeError();
1265 
1266  return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1267  T->getNumElements(),
1268  T->getVectorKind());
1269 }
1270 
1272  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1273  if (!ToElementTypeOrErr)
1274  return ToElementTypeOrErr.takeError();
1275 
1276  return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1277  T->getNumElements());
1278 }
1279 
1282  // FIXME: What happens if we're importing a function without a prototype
1283  // into C++? Should we make it variadic?
1284  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1285  if (!ToReturnTypeOrErr)
1286  return ToReturnTypeOrErr.takeError();
1287 
1288  return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1289  T->getExtInfo());
1290 }
1291 
1294  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1295  if (!ToReturnTypeOrErr)
1296  return ToReturnTypeOrErr.takeError();
1297 
1298  // Import argument types
1299  SmallVector<QualType, 4> ArgTypes;
1300  for (const auto &A : T->param_types()) {
1301  ExpectedType TyOrErr = import(A);
1302  if (!TyOrErr)
1303  return TyOrErr.takeError();
1304  ArgTypes.push_back(*TyOrErr);
1305  }
1306 
1307  // Import exception types
1308  SmallVector<QualType, 4> ExceptionTypes;
1309  for (const auto &E : T->exceptions()) {
1310  ExpectedType TyOrErr = import(E);
1311  if (!TyOrErr)
1312  return TyOrErr.takeError();
1313  ExceptionTypes.push_back(*TyOrErr);
1314  }
1315 
1317  Error Err = Error::success();
1319  ToEPI.ExtInfo = FromEPI.ExtInfo;
1320  ToEPI.Variadic = FromEPI.Variadic;
1321  ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1322  ToEPI.TypeQuals = FromEPI.TypeQuals;
1323  ToEPI.RefQualifier = FromEPI.RefQualifier;
1324  ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1325  ToEPI.ExceptionSpec.NoexceptExpr =
1327  ToEPI.ExceptionSpec.SourceDecl =
1328  importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1331  ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1332 
1333  if (Err)
1334  return std::move(Err);
1335 
1336  return Importer.getToContext().getFunctionType(
1337  *ToReturnTypeOrErr, ArgTypes, ToEPI);
1338 }
1339 
1341  const UnresolvedUsingType *T) {
1342  Error Err = Error::success();
1343  auto ToD = importChecked(Err, T->getDecl());
1344  auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1345  if (Err)
1346  return std::move(Err);
1347 
1348  return Importer.getToContext().getTypeDeclType(
1349  ToD, cast_or_null<TypeDecl>(ToPrevD));
1350 }
1351 
1353  ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1354  if (!ToInnerTypeOrErr)
1355  return ToInnerTypeOrErr.takeError();
1356 
1357  return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1358 }
1359 
1361  Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1362  if (!ToDeclOrErr)
1363  return ToDeclOrErr.takeError();
1364 
1365  return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1366 }
1367 
1369  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1370  if (!ToExprOrErr)
1371  return ToExprOrErr.takeError();
1372 
1373  return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1374 }
1375 
1377  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1378  if (!ToUnderlyingTypeOrErr)
1379  return ToUnderlyingTypeOrErr.takeError();
1380 
1381  return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1382 }
1383 
1385  Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl());
1386  if (!FoundOrErr)
1387  return FoundOrErr.takeError();
1388  Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType());
1389  if (!UnderlyingOrErr)
1390  return UnderlyingOrErr.takeError();
1391 
1392  return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr);
1393 }
1394 
1396  // FIXME: Make sure that the "to" context supports C++0x!
1397  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1398  if (!ToExprOrErr)
1399  return ToExprOrErr.takeError();
1400 
1401  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1402  if (!ToUnderlyingTypeOrErr)
1403  return ToUnderlyingTypeOrErr.takeError();
1404 
1405  return Importer.getToContext().getDecltypeType(
1406  *ToExprOrErr, *ToUnderlyingTypeOrErr);
1407 }
1408 
1411  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1412  if (!ToBaseTypeOrErr)
1413  return ToBaseTypeOrErr.takeError();
1414 
1415  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1416  if (!ToUnderlyingTypeOrErr)
1417  return ToUnderlyingTypeOrErr.takeError();
1418 
1419  return Importer.getToContext().getUnaryTransformType(
1420  *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1421 }
1422 
1424  // FIXME: Make sure that the "to" context supports C++11!
1425  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1426  if (!ToDeducedTypeOrErr)
1427  return ToDeducedTypeOrErr.takeError();
1428 
1429  ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1430  if (!ToTypeConstraintConcept)
1431  return ToTypeConstraintConcept.takeError();
1432 
1433  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1435  if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(),
1436  FromTemplateArgs.size(),
1437  ToTemplateArgs))
1438  return std::move(Err);
1439 
1440  return Importer.getToContext().getAutoType(
1441  *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1442  /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1443  ToTemplateArgs);
1444 }
1445 
1448  // FIXME: Make sure that the "to" context supports C++17!
1449  Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1450  if (!ToTemplateNameOrErr)
1451  return ToTemplateNameOrErr.takeError();
1452  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1453  if (!ToDeducedTypeOrErr)
1454  return ToDeducedTypeOrErr.takeError();
1455 
1457  *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1458 }
1459 
1461  const InjectedClassNameType *T) {
1462  Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1463  if (!ToDeclOrErr)
1464  return ToDeclOrErr.takeError();
1465 
1466  ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1467  if (!ToInjTypeOrErr)
1468  return ToInjTypeOrErr.takeError();
1469 
1470  // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1471  // See comments in InjectedClassNameType definition for details
1472  // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1473  enum {
1474  TypeAlignmentInBits = 4,
1476  };
1477 
1478  return QualType(new (Importer.getToContext(), TypeAlignment)
1479  InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1480 }
1481 
1483  Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1484  if (!ToDeclOrErr)
1485  return ToDeclOrErr.takeError();
1486 
1487  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1488 }
1489 
1491  Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1492  if (!ToDeclOrErr)
1493  return ToDeclOrErr.takeError();
1494 
1495  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1496 }
1497 
1499  ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1500  if (!ToModifiedTypeOrErr)
1501  return ToModifiedTypeOrErr.takeError();
1502  ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1503  if (!ToEquivalentTypeOrErr)
1504  return ToEquivalentTypeOrErr.takeError();
1505 
1506  return Importer.getToContext().getAttributedType(T->getAttrKind(),
1507  *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1508 }
1509 
1511  const TemplateTypeParmType *T) {
1512  Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1513  if (!ToDeclOrErr)
1514  return ToDeclOrErr.takeError();
1515 
1516  return Importer.getToContext().getTemplateTypeParmType(
1517  T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1518 }
1519 
1521  const SubstTemplateTypeParmType *T) {
1523  import(T->getReplacedParameter());
1524  if (!ReplacedOrErr)
1525  return ReplacedOrErr.takeError();
1526 
1527  ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1528  if (!ToReplacementTypeOrErr)
1529  return ToReplacementTypeOrErr.takeError();
1530 
1531  return Importer.getToContext().getSubstTemplateTypeParmType(
1532  *ReplacedOrErr, ToReplacementTypeOrErr->getCanonicalType());
1533 }
1534 
1536  const SubstTemplateTypeParmPackType *T) {
1538  import(T->getReplacedParameter());
1539  if (!ReplacedOrErr)
1540  return ReplacedOrErr.takeError();
1541 
1542  Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack());
1543  if (!ToArgumentPack)
1544  return ToArgumentPack.takeError();
1545 
1547  *ReplacedOrErr, *ToArgumentPack);
1548 }
1549 
1551  const TemplateSpecializationType *T) {
1552  auto ToTemplateOrErr = import(T->getTemplateName());
1553  if (!ToTemplateOrErr)
1554  return ToTemplateOrErr.takeError();
1555 
1556  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1557  if (Error Err = ImportTemplateArguments(
1558  T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1559  return std::move(Err);
1560 
1561  QualType ToCanonType;
1562  if (!T->isCanonicalUnqualified()) {
1563  QualType FromCanonType
1564  = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1565  if (ExpectedType TyOrErr = import(FromCanonType))
1566  ToCanonType = *TyOrErr;
1567  else
1568  return TyOrErr.takeError();
1569  }
1570  return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1571  ToTemplateArgs,
1572  ToCanonType);
1573 }
1574 
1576  // Note: the qualifier in an ElaboratedType is optional.
1577  auto ToQualifierOrErr = import(T->getQualifier());
1578  if (!ToQualifierOrErr)
1579  return ToQualifierOrErr.takeError();
1580 
1581  ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1582  if (!ToNamedTypeOrErr)
1583  return ToNamedTypeOrErr.takeError();
1584 
1585  Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1586  if (!ToOwnedTagDeclOrErr)
1587  return ToOwnedTagDeclOrErr.takeError();
1588 
1589  return Importer.getToContext().getElaboratedType(T->getKeyword(),
1590  *ToQualifierOrErr,
1591  *ToNamedTypeOrErr,
1592  *ToOwnedTagDeclOrErr);
1593 }
1594 
1597  ExpectedType ToPatternOrErr = import(T->getPattern());
1598  if (!ToPatternOrErr)
1599  return ToPatternOrErr.takeError();
1600 
1601  return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1602  T->getNumExpansions(),
1603  /*ExpactPack=*/false);
1604 }
1605 
1608  auto ToQualifierOrErr = import(T->getQualifier());
1609  if (!ToQualifierOrErr)
1610  return ToQualifierOrErr.takeError();
1611 
1612  IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1613 
1615  ToPack.reserve(T->getNumArgs());
1616  if (Error Err = ImportTemplateArguments(
1617  T->getArgs(), T->getNumArgs(), ToPack))
1618  return std::move(Err);
1619 
1621  T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1622 }
1623 
1626  auto ToQualifierOrErr = import(T->getQualifier());
1627  if (!ToQualifierOrErr)
1628  return ToQualifierOrErr.takeError();
1629 
1630  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1631 
1632  QualType Canon;
1633  if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1634  if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1635  Canon = (*TyOrErr).getCanonicalType();
1636  else
1637  return TyOrErr.takeError();
1638  }
1639 
1640  return Importer.getToContext().getDependentNameType(T->getKeyword(),
1641  *ToQualifierOrErr,
1642  Name, Canon);
1643 }
1644 
1647  Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1648  if (!ToDeclOrErr)
1649  return ToDeclOrErr.takeError();
1650 
1651  return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1652 }
1653 
1655  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1656  if (!ToBaseTypeOrErr)
1657  return ToBaseTypeOrErr.takeError();
1658 
1659  SmallVector<QualType, 4> TypeArgs;
1660  for (auto TypeArg : T->getTypeArgsAsWritten()) {
1661  if (ExpectedType TyOrErr = import(TypeArg))
1662  TypeArgs.push_back(*TyOrErr);
1663  else
1664  return TyOrErr.takeError();
1665  }
1666 
1668  for (auto *P : T->quals()) {
1669  if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1670  Protocols.push_back(*ProtocolOrErr);
1671  else
1672  return ProtocolOrErr.takeError();
1673 
1674  }
1675 
1676  return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1677  Protocols,
1678  T->isKindOfTypeAsWritten());
1679 }
1680 
1683  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1684  if (!ToPointeeTypeOrErr)
1685  return ToPointeeTypeOrErr.takeError();
1686 
1687  return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1688 }
1689 
1690 //----------------------------------------------------------------------------
1691 // Import Declarations
1692 //----------------------------------------------------------------------------
1694  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1695  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1696  // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1697  // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1698  // FIXME: We could support these constructs by importing a different type of
1699  // this parameter and by importing the original type of the parameter only
1700  // after the FunctionDecl is created. See
1701  // VisitFunctionDecl::UsedDifferentProtoType.
1702  DeclContext *OrigDC = D->getDeclContext();
1703  FunctionDecl *FunDecl;
1704  if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1705  FunDecl->hasBody()) {
1706  auto getLeafPointeeType = [](const Type *T) {
1707  while (T->isPointerType() || T->isArrayType()) {
1708  T = T->getPointeeOrArrayElementType();
1709  }
1710  return T;
1711  };
1712  for (const ParmVarDecl *P : FunDecl->parameters()) {
1713  const Type *LeafT =
1714  getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1715  auto *RT = dyn_cast<RecordType>(LeafT);
1716  if (RT && RT->getDecl() == D) {
1717  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1718  << D->getDeclKindName();
1719  return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1720  }
1721  }
1722  }
1723 
1724  // Import the context of this declaration.
1725  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1726  return Err;
1727 
1728  // Import the name of this declaration.
1729  if (Error Err = importInto(Name, D->getDeclName()))
1730  return Err;
1731 
1732  // Import the location of this declaration.
1733  if (Error Err = importInto(Loc, D->getLocation()))
1734  return Err;
1735 
1736  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1737  if (ToD)
1738  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1739  return Err;
1740 
1741  return Error::success();
1742 }
1743 
1745  NamedDecl *&ToD, SourceLocation &Loc) {
1746 
1747  // Import the name of this declaration.
1748  if (Error Err = importInto(Name, D->getDeclName()))
1749  return Err;
1750 
1751  // Import the location of this declaration.
1752  if (Error Err = importInto(Loc, D->getLocation()))
1753  return Err;
1754 
1755  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1756  if (ToD)
1757  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1758  return Err;
1759 
1760  return Error::success();
1761 }
1762 
1764  if (!FromD)
1765  return Error::success();
1766 
1767  if (!ToD)
1768  if (Error Err = importInto(ToD, FromD))
1769  return Err;
1770 
1771  if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1772  if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1773  if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1774  !ToRecord->getDefinition()) {
1775  if (Error Err = ImportDefinition(FromRecord, ToRecord))
1776  return Err;
1777  }
1778  }
1779  return Error::success();
1780  }
1781 
1782  if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1783  if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1784  if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1785  if (Error Err = ImportDefinition(FromEnum, ToEnum))
1786  return Err;
1787  }
1788  }
1789  return Error::success();
1790  }
1791 
1792  return Error::success();
1793 }
1794 
1795 Error
1797  const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1798  // NOTE: To.Name and To.Loc are already imported.
1799  // We only have to import To.LocInfo.
1800  switch (To.getName().getNameKind()) {
1807  return Error::success();
1808 
1810  if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1811  To.setCXXOperatorNameRange(*ToRangeOrErr);
1812  else
1813  return ToRangeOrErr.takeError();
1814  return Error::success();
1815  }
1817  if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1818  To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1819  else
1820  return LocOrErr.takeError();
1821  return Error::success();
1822  }
1826  if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1827  To.setNamedTypeInfo(*ToTInfoOrErr);
1828  else
1829  return ToTInfoOrErr.takeError();
1830  return Error::success();
1831  }
1832  }
1833  llvm_unreachable("Unknown name kind.");
1834 }
1835 
1836 Error
1838  if (Importer.isMinimalImport() && !ForceImport) {
1839  auto ToDCOrErr = Importer.ImportContext(FromDC);
1840  return ToDCOrErr.takeError();
1841  }
1842 
1843  // We use strict error handling in case of records and enums, but not
1844  // with e.g. namespaces.
1845  //
1846  // FIXME Clients of the ASTImporter should be able to choose an
1847  // appropriate error handling strategy for their needs. For instance,
1848  // they may not want to mark an entire namespace as erroneous merely
1849  // because there is an ODR error with two typedefs. As another example,
1850  // the client may allow EnumConstantDecls with same names but with
1851  // different values in two distinct translation units.
1852  ChildErrorHandlingStrategy HandleChildErrors(FromDC);
1853 
1854  Error ChildErrors = Error::success();
1855  for (auto *From : FromDC->decls()) {
1856  ExpectedDecl ImportedOrErr = import(From);
1857 
1858  // If we are in the process of ImportDefinition(...) for a RecordDecl we
1859  // want to make sure that we are also completing each FieldDecl. There
1860  // are currently cases where this does not happen and this is correctness
1861  // fix since operations such as code generation will expect this to be so.
1862  if (ImportedOrErr) {
1863  FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
1864  Decl *ImportedDecl = *ImportedOrErr;
1865  FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
1866  if (FieldFrom && FieldTo) {
1867  RecordDecl *FromRecordDecl = nullptr;
1868  RecordDecl *ToRecordDecl = nullptr;
1869  // If we have a field that is an ArrayType we need to check if the array
1870  // element is a RecordDecl and if so we need to import the definition.
1871  if (FieldFrom->getType()->isArrayType()) {
1872  // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
1873  FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1874  ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1875  }
1876 
1877  if (!FromRecordDecl || !ToRecordDecl) {
1878  const RecordType *RecordFrom =
1879  FieldFrom->getType()->getAs<RecordType>();
1880  const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
1881 
1882  if (RecordFrom && RecordTo) {
1883  FromRecordDecl = RecordFrom->getDecl();
1884  ToRecordDecl = RecordTo->getDecl();
1885  }
1886  }
1887 
1888  if (FromRecordDecl && ToRecordDecl) {
1889  if (FromRecordDecl->isCompleteDefinition() &&
1890  !ToRecordDecl->isCompleteDefinition()) {
1891  Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
1892  HandleChildErrors.handleChildImportResult(ChildErrors,
1893  std::move(Err));
1894  }
1895  }
1896  }
1897  } else {
1898  HandleChildErrors.handleChildImportResult(ChildErrors,
1899  ImportedOrErr.takeError());
1900  }
1901  }
1902 
1903  // We reorder declarations in RecordDecls because they may have another order
1904  // in the "to" context than they have in the "from" context. This may happen
1905  // e.g when we import a class like this:
1906  // struct declToImport {
1907  // int a = c + b;
1908  // int b = 1;
1909  // int c = 2;
1910  // };
1911  // During the import of `a` we import first the dependencies in sequence,
1912  // thus the order would be `c`, `b`, `a`. We will get the normal order by
1913  // first removing the already imported members and then adding them in the
1914  // order as they apper in the "from" context.
1915  //
1916  // Keeping field order is vital because it determines structure layout.
1917  //
1918  // Here and below, we cannot call field_begin() method and its callers on
1919  // ToDC if it has an external storage. Calling field_begin() will
1920  // automatically load all the fields by calling
1921  // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1922  // call ASTImporter::Import(). This is because the ExternalASTSource
1923  // interface in LLDB is implemented by the means of the ASTImporter. However,
1924  // calling an import at this point would result in an uncontrolled import, we
1925  // must avoid that.
1926  const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1927  if (!FromRD)
1928  return ChildErrors;
1929 
1930  auto ToDCOrErr = Importer.ImportContext(FromDC);
1931  if (!ToDCOrErr) {
1932  consumeError(std::move(ChildErrors));
1933  return ToDCOrErr.takeError();
1934  }
1935 
1936  DeclContext *ToDC = *ToDCOrErr;
1937  // Remove all declarations, which may be in wrong order in the
1938  // lexical DeclContext and then add them in the proper order.
1939  for (auto *D : FromRD->decls()) {
1940  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1941  assert(D && "DC contains a null decl");
1942  Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1943  // Remove only the decls which we successfully imported.
1944  if (ToD) {
1945  assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
1946  // Remove the decl from its wrong place in the linked list.
1947  ToDC->removeDecl(ToD);
1948  // Add the decl to the end of the linked list.
1949  // This time it will be at the proper place because the enclosing for
1950  // loop iterates in the original (good) order of the decls.
1951  ToDC->addDeclInternal(ToD);
1952  }
1953  }
1954  }
1955 
1956  return ChildErrors;
1957 }
1958 
1960  Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1961  auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1962  if (!ToDCOrErr)
1963  return ToDCOrErr.takeError();
1964  ToDC = *ToDCOrErr;
1965 
1966  if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1967  auto ToLexicalDCOrErr = Importer.ImportContext(
1968  FromD->getLexicalDeclContext());
1969  if (!ToLexicalDCOrErr)
1970  return ToLexicalDCOrErr.takeError();
1971  ToLexicalDC = *ToLexicalDCOrErr;
1972  } else
1973  ToLexicalDC = ToDC;
1974 
1975  return Error::success();
1976 }
1977 
1979  const CXXRecordDecl *From, CXXRecordDecl *To) {
1980  assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1981  "Import implicit methods to or from non-definition");
1982 
1983  for (CXXMethodDecl *FromM : From->methods())
1984  if (FromM->isImplicit()) {
1985  Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1986  if (!ToMOrErr)
1987  return ToMOrErr.takeError();
1988  }
1989 
1990  return Error::success();
1991 }
1992 
1994  ASTImporter &Importer) {
1995  if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1996  if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1997  To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1998  else
1999  return ToTypedefOrErr.takeError();
2000  }
2001  return Error::success();
2002 }
2003 
2006  auto DefinitionCompleter = [To]() {
2007  // There are cases in LLDB when we first import a class without its
2008  // members. The class will have DefinitionData, but no members. Then,
2009  // importDefinition is called from LLDB, which tries to get the members, so
2010  // when we get here, the class already has the DefinitionData set, so we
2011  // must unset the CompleteDefinition here to be able to complete again the
2012  // definition.
2013  To->setCompleteDefinition(false);
2014  To->completeDefinition();
2015  };
2016 
2017  if (To->getDefinition() || To->isBeingDefined()) {
2018  if (Kind == IDK_Everything ||
2019  // In case of lambdas, the class already has a definition ptr set, but
2020  // the contained decls are not imported yet. Also, isBeingDefined was
2021  // set in CXXRecordDecl::CreateLambda. We must import the contained
2022  // decls here and finish the definition.
2024  if (To->isLambda()) {
2025  auto *FromCXXRD = cast<CXXRecordDecl>(From);
2026  SmallVector<LambdaCapture, 8> ToCaptures;
2027  ToCaptures.reserve(FromCXXRD->capture_size());
2028  for (const auto &FromCapture : FromCXXRD->captures()) {
2029  if (auto ToCaptureOrErr = import(FromCapture))
2030  ToCaptures.push_back(*ToCaptureOrErr);
2031  else
2032  return ToCaptureOrErr.takeError();
2033  }
2034  cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
2035  ToCaptures);
2036  }
2037 
2038  Error Result = ImportDeclContext(From, /*ForceImport=*/true);
2039  // Finish the definition of the lambda, set isBeingDefined to false.
2040  if (To->isLambda())
2041  DefinitionCompleter();
2042  return Result;
2043  }
2044 
2045  return Error::success();
2046  }
2047 
2048  To->startDefinition();
2049  // Set the definition to complete even if it is really not complete during
2050  // import. Some AST constructs (expressions) require the record layout
2051  // to be calculated (see 'clang::computeDependence') at the time they are
2052  // constructed. Import of such AST node is possible during import of the
2053  // same record, there is no way to have a completely defined record (all
2054  // fields imported) at that time without multiple AST import passes.
2055  if (!Importer.isMinimalImport())
2056  To->setCompleteDefinition(true);
2057  // Complete the definition even if error is returned.
2058  // The RecordDecl may be already part of the AST so it is better to
2059  // have it in complete state even if something is wrong with it.
2060  auto DefinitionCompleterScopeExit =
2061  llvm::make_scope_exit(DefinitionCompleter);
2062 
2063  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2064  return Err;
2065 
2066  // Add base classes.
2067  auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
2068  auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
2069  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2070 
2071  struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2072  struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2073 
2074  #define FIELD(Name, Width, Merge) \
2075  ToData.Name = FromData.Name;
2076  #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2077 
2078  // Copy over the data stored in RecordDeclBits
2079  ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2080 
2082  for (const auto &Base1 : FromCXX->bases()) {
2083  ExpectedType TyOrErr = import(Base1.getType());
2084  if (!TyOrErr)
2085  return TyOrErr.takeError();
2086 
2087  SourceLocation EllipsisLoc;
2088  if (Base1.isPackExpansion()) {
2089  if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2090  EllipsisLoc = *LocOrErr;
2091  else
2092  return LocOrErr.takeError();
2093  }
2094 
2095  // Ensure that we have a definition for the base.
2096  if (Error Err =
2097  ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2098  return Err;
2099 
2100  auto RangeOrErr = import(Base1.getSourceRange());
2101  if (!RangeOrErr)
2102  return RangeOrErr.takeError();
2103 
2104  auto TSIOrErr = import(Base1.getTypeSourceInfo());
2105  if (!TSIOrErr)
2106  return TSIOrErr.takeError();
2107 
2108  Bases.push_back(
2109  new (Importer.getToContext()) CXXBaseSpecifier(
2110  *RangeOrErr,
2111  Base1.isVirtual(),
2112  Base1.isBaseOfClass(),
2113  Base1.getAccessSpecifierAsWritten(),
2114  *TSIOrErr,
2115  EllipsisLoc));
2116  }
2117  if (!Bases.empty())
2118  ToCXX->setBases(Bases.data(), Bases.size());
2119  }
2120 
2122  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2123  return Err;
2124  }
2125 
2126  return Error::success();
2127 }
2128 
2130  if (To->getAnyInitializer())
2131  return Error::success();
2132 
2133  Expr *FromInit = From->getInit();
2134  if (!FromInit)
2135  return Error::success();
2136 
2137  ExpectedExpr ToInitOrErr = import(FromInit);
2138  if (!ToInitOrErr)
2139  return ToInitOrErr.takeError();
2140 
2141  To->setInit(*ToInitOrErr);
2142  if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2143  EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2144  ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2145  ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2146  // FIXME: Also import the initializer value.
2147  }
2148 
2149  // FIXME: Other bits to merge?
2150  return Error::success();
2151 }
2152 
2155  if (To->getDefinition() || To->isBeingDefined()) {
2156  if (Kind == IDK_Everything)
2157  return ImportDeclContext(From, /*ForceImport=*/true);
2158  return Error::success();
2159  }
2160 
2161  To->startDefinition();
2162 
2163  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2164  return Err;
2165 
2166  ExpectedType ToTypeOrErr =
2167  import(Importer.getFromContext().getTypeDeclType(From));
2168  if (!ToTypeOrErr)
2169  return ToTypeOrErr.takeError();
2170 
2171  ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2172  if (!ToPromotionTypeOrErr)
2173  return ToPromotionTypeOrErr.takeError();
2174 
2176  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2177  return Err;
2178 
2179  // FIXME: we might need to merge the number of positive or negative bits
2180  // if the enumerator lists don't match.
2181  To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2182  From->getNumPositiveBits(),
2183  From->getNumNegativeBits());
2184  return Error::success();
2185 }
2186 
2188  const TemplateArgument *FromArgs, unsigned NumFromArgs,
2190  for (unsigned I = 0; I != NumFromArgs; ++I) {
2191  if (auto ToOrErr = import(FromArgs[I]))
2192  ToArgs.push_back(*ToOrErr);
2193  else
2194  return ToOrErr.takeError();
2195  }
2196 
2197  return Error::success();
2198 }
2199 
2200 // FIXME: Do not forget to remove this and use only 'import'.
2203  return import(From);
2204 }
2205 
2206 template <typename InContainerTy>
2208  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2209  for (const auto &FromLoc : Container) {
2210  if (auto ToLocOrErr = import(FromLoc))
2211  ToTAInfo.addArgument(*ToLocOrErr);
2212  else
2213  return ToLocOrErr.takeError();
2214  }
2215  return Error::success();
2216 }
2217 
2222 }
2223 
2224 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
2225  // Eliminate a potential failure point where we attempt to re-import
2226  // something we're trying to import while completing ToRecord.
2227  Decl *ToOrigin = Importer.GetOriginalDecl(To);
2228  if (ToOrigin) {
2229  To = ToOrigin;
2230  }
2231 
2233  Importer.getFromContext(), Importer.getToContext(),
2235  false, Complain);
2236  return Ctx.IsEquivalent(From, To);
2237 }
2238 
2240  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2241  << D->getDeclKindName();
2242  return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2243 }
2244 
2246  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2247  << D->getDeclKindName();
2248  return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2249 }
2250 
2252  // Import the context of this declaration.
2253  DeclContext *DC, *LexicalDC;
2254  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2255  return std::move(Err);
2256 
2257  // Import the location of this declaration.
2258  ExpectedSLoc LocOrErr = import(D->getLocation());
2259  if (!LocOrErr)
2260  return LocOrErr.takeError();
2261 
2262  EmptyDecl *ToD;
2263  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2264  return ToD;
2265 
2266  ToD->setLexicalDeclContext(LexicalDC);
2267  LexicalDC->addDeclInternal(ToD);
2268  return ToD;
2269 }
2270 
2272  TranslationUnitDecl *ToD =
2273  Importer.getToContext().getTranslationUnitDecl();
2274 
2275  Importer.MapImported(D, ToD);
2276 
2277  return ToD;
2278 }
2279 
2281  DeclContext *DC, *LexicalDC;
2282  DeclarationName Name;
2283  SourceLocation Loc;
2284  NamedDecl *ToND;
2285  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2286  return std::move(Err);
2287  if (ToND)
2288  return ToND;
2289 
2290  BindingDecl *ToD;
2291  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
2292  Name.getAsIdentifierInfo()))
2293  return ToD;
2294 
2295  Error Err = Error::success();
2296  QualType ToType = importChecked(Err, D->getType());
2297  Expr *ToBinding = importChecked(Err, D->getBinding());
2298  ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
2299  if (Err)
2300  return std::move(Err);
2301 
2302  ToD->setBinding(ToType, ToBinding);
2303  ToD->setDecomposedDecl(ToDecomposedDecl);
2304  addDeclToContexts(D, ToD);
2305 
2306  return ToD;
2307 }
2308 
2310  ExpectedSLoc LocOrErr = import(D->getLocation());
2311  if (!LocOrErr)
2312  return LocOrErr.takeError();
2313  auto ColonLocOrErr = import(D->getColonLoc());
2314  if (!ColonLocOrErr)
2315  return ColonLocOrErr.takeError();
2316 
2317  // Import the context of this declaration.
2318  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2319  if (!DCOrErr)
2320  return DCOrErr.takeError();
2321  DeclContext *DC = *DCOrErr;
2322 
2323  AccessSpecDecl *ToD;
2324  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2325  DC, *LocOrErr, *ColonLocOrErr))
2326  return ToD;
2327 
2328  // Lexical DeclContext and Semantic DeclContext
2329  // is always the same for the accessSpec.
2330  ToD->setLexicalDeclContext(DC);
2331  DC->addDeclInternal(ToD);
2332 
2333  return ToD;
2334 }
2335 
2337  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2338  if (!DCOrErr)
2339  return DCOrErr.takeError();
2340  DeclContext *DC = *DCOrErr;
2341  DeclContext *LexicalDC = DC;
2342 
2343  Error Err = Error::success();
2344  auto ToLocation = importChecked(Err, D->getLocation());
2345  auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2346  auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2347  auto ToMessage = importChecked(Err, D->getMessage());
2348  if (Err)
2349  return std::move(Err);
2350 
2351  StaticAssertDecl *ToD;
2352  if (GetImportedOrCreateDecl(
2353  ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2354  ToRParenLoc, D->isFailed()))
2355  return ToD;
2356 
2357  ToD->setLexicalDeclContext(LexicalDC);
2358  LexicalDC->addDeclInternal(ToD);
2359  return ToD;
2360 }
2361 
2363  // Import the major distinguishing characteristics of this namespace.
2364  DeclContext *DC, *LexicalDC;
2365  DeclarationName Name;
2366  SourceLocation Loc;
2367  NamedDecl *ToD;
2368  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2369  return std::move(Err);
2370  if (ToD)
2371  return ToD;
2372 
2373  NamespaceDecl *MergeWithNamespace = nullptr;
2374  if (!Name) {
2375  // This is an anonymous namespace. Adopt an existing anonymous
2376  // namespace if we can.
2377  // FIXME: Not testable.
2378  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2379  MergeWithNamespace = TU->getAnonymousNamespace();
2380  else
2381  MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2382  } else {
2383  SmallVector<NamedDecl *, 4> ConflictingDecls;
2384  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2385  for (auto *FoundDecl : FoundDecls) {
2387  continue;
2388 
2389  if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2390  MergeWithNamespace = FoundNS;
2391  ConflictingDecls.clear();
2392  break;
2393  }
2394 
2395  ConflictingDecls.push_back(FoundDecl);
2396  }
2397 
2398  if (!ConflictingDecls.empty()) {
2399  ExpectedName NameOrErr = Importer.HandleNameConflict(
2400  Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2401  ConflictingDecls.size());
2402  if (NameOrErr)
2403  Name = NameOrErr.get();
2404  else
2405  return NameOrErr.takeError();
2406  }
2407  }
2408 
2409  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2410  if (!BeginLocOrErr)
2411  return BeginLocOrErr.takeError();
2412  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2413  if (!RBraceLocOrErr)
2414  return RBraceLocOrErr.takeError();
2415 
2416  // Create the "to" namespace, if needed.
2417  NamespaceDecl *ToNamespace = MergeWithNamespace;
2418  if (!ToNamespace) {
2419  if (GetImportedOrCreateDecl(
2420  ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2421  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2422  /*PrevDecl=*/nullptr))
2423  return ToNamespace;
2424  ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2425  ToNamespace->setLexicalDeclContext(LexicalDC);
2426  LexicalDC->addDeclInternal(ToNamespace);
2427 
2428  // If this is an anonymous namespace, register it as the anonymous
2429  // namespace within its context.
2430  if (!Name) {
2431  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2432  TU->setAnonymousNamespace(ToNamespace);
2433  else
2434  cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2435  }
2436  }
2437  Importer.MapImported(D, ToNamespace);
2438 
2439  if (Error Err = ImportDeclContext(D))
2440  return std::move(Err);
2441 
2442  return ToNamespace;
2443 }
2444 
2446  // Import the major distinguishing characteristics of this namespace.
2447  DeclContext *DC, *LexicalDC;
2448  DeclarationName Name;
2449  SourceLocation Loc;
2450  NamedDecl *LookupD;
2451  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2452  return std::move(Err);
2453  if (LookupD)
2454  return LookupD;
2455 
2456  // NOTE: No conflict resolution is done for namespace aliases now.
2457 
2458  Error Err = Error::success();
2459  auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2460  auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2461  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2462  auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2463  auto ToNamespace = importChecked(Err, D->getNamespace());
2464  if (Err)
2465  return std::move(Err);
2466 
2467  IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2468 
2469  NamespaceAliasDecl *ToD;
2470  if (GetImportedOrCreateDecl(
2471  ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2472  ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2473  return ToD;
2474 
2475  ToD->setLexicalDeclContext(LexicalDC);
2476  LexicalDC->addDeclInternal(ToD);
2477 
2478  return ToD;
2479 }
2480 
2483  // Import the major distinguishing characteristics of this typedef.
2484  DeclarationName Name;
2485  SourceLocation Loc;
2486  NamedDecl *ToD;
2487  // Do not import the DeclContext, we will import it once the TypedefNameDecl
2488  // is created.
2489  if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2490  return std::move(Err);
2491  if (ToD)
2492  return ToD;
2493 
2494  DeclContext *DC = cast_or_null<DeclContext>(
2495  Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2496  DeclContext *LexicalDC =
2497  cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2498  cast<Decl>(D->getLexicalDeclContext())));
2499 
2500  // If this typedef is not in block scope, determine whether we've
2501  // seen a typedef with the same name (that we can merge with) or any
2502  // other entity by that name (which name lookup could conflict with).
2503  // Note: Repeated typedefs are not valid in C99:
2504  // 'typedef int T; typedef int T;' is invalid
2505  // We do not care about this now.
2506  if (DC && !DC->isFunctionOrMethod()) {
2507  SmallVector<NamedDecl *, 4> ConflictingDecls;
2508  unsigned IDNS = Decl::IDNS_Ordinary;
2509  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2510  for (auto *FoundDecl : FoundDecls) {
2511  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2512  continue;
2513  if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2514  if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2515  continue;
2516 
2517  QualType FromUT = D->getUnderlyingType();
2518  QualType FoundUT = FoundTypedef->getUnderlyingType();
2519  if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2520  // If the "From" context has a complete underlying type but we
2521  // already have a complete underlying type then return with that.
2522  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2523  return Importer.MapImported(D, FoundTypedef);
2524  // FIXME Handle redecl chain. When you do that make consistent changes
2525  // in ASTImporterLookupTable too.
2526  } else {
2527  ConflictingDecls.push_back(FoundDecl);
2528  }
2529  }
2530  }
2531 
2532  if (!ConflictingDecls.empty()) {
2533  ExpectedName NameOrErr = Importer.HandleNameConflict(
2534  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2535  if (NameOrErr)
2536  Name = NameOrErr.get();
2537  else
2538  return NameOrErr.takeError();
2539  }
2540  }
2541 
2542  Error Err = Error::success();
2544  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2545  auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2546  if (Err)
2547  return std::move(Err);
2548 
2549  // Create the new typedef node.
2550  // FIXME: ToUnderlyingType is not used.
2551  (void)ToUnderlyingType;
2552  TypedefNameDecl *ToTypedef;
2553  if (IsAlias) {
2554  if (GetImportedOrCreateDecl<TypeAliasDecl>(
2555  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2556  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2557  return ToTypedef;
2558  } else if (GetImportedOrCreateDecl<TypedefDecl>(
2559  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2560  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2561  return ToTypedef;
2562 
2563  // Import the DeclContext and set it to the Typedef.
2564  if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2565  return std::move(Err);
2566  ToTypedef->setDeclContext(DC);
2567  ToTypedef->setLexicalDeclContext(LexicalDC);
2568  // Add to the lookupTable because we could not do that in MapImported.
2569  Importer.AddToLookupTable(ToTypedef);
2570 
2571  ToTypedef->setAccess(D->getAccess());
2572 
2573  // Templated declarations should not appear in DeclContext.
2574  TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2575  if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2576  LexicalDC->addDeclInternal(ToTypedef);
2577 
2578  return ToTypedef;
2579 }
2580 
2582  return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2583 }
2584 
2586  return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2587 }
2588 
2591  // Import the major distinguishing characteristics of this typedef.
2592  DeclContext *DC, *LexicalDC;
2593  DeclarationName Name;
2594  SourceLocation Loc;
2595  NamedDecl *FoundD;
2596  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2597  return std::move(Err);
2598  if (FoundD)
2599  return FoundD;
2600 
2601  // If this typedef is not in block scope, determine whether we've
2602  // seen a typedef with the same name (that we can merge with) or any
2603  // other entity by that name (which name lookup could conflict with).
2604  if (!DC->isFunctionOrMethod()) {
2605  SmallVector<NamedDecl *, 4> ConflictingDecls;
2606  unsigned IDNS = Decl::IDNS_Ordinary;
2607  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2608  for (auto *FoundDecl : FoundDecls) {
2609  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2610  continue;
2611  if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2612  return Importer.MapImported(D, FoundAlias);
2613  ConflictingDecls.push_back(FoundDecl);
2614  }
2615 
2616  if (!ConflictingDecls.empty()) {
2617  ExpectedName NameOrErr = Importer.HandleNameConflict(
2618  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2619  if (NameOrErr)
2620  Name = NameOrErr.get();
2621  else
2622  return NameOrErr.takeError();
2623  }
2624  }
2625 
2626  Error Err = Error::success();
2627  auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2628  auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2629  if (Err)
2630  return std::move(Err);
2631 
2632  TypeAliasTemplateDecl *ToAlias;
2633  if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2634  Name, ToTemplateParameters, ToTemplatedDecl))
2635  return ToAlias;
2636 
2637  ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2638 
2639  ToAlias->setAccess(D->getAccess());
2640  ToAlias->setLexicalDeclContext(LexicalDC);
2641  LexicalDC->addDeclInternal(ToAlias);
2642  if (DC != Importer.getToContext().getTranslationUnitDecl())
2643  updateLookupTableForTemplateParameters(*ToTemplateParameters);
2644  return ToAlias;
2645 }
2646 
2648  // Import the major distinguishing characteristics of this label.
2649  DeclContext *DC, *LexicalDC;
2650  DeclarationName Name;
2651  SourceLocation Loc;
2652  NamedDecl *ToD;
2653  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2654  return std::move(Err);
2655  if (ToD)
2656  return ToD;
2657 
2658  assert(LexicalDC->isFunctionOrMethod());
2659 
2660  LabelDecl *ToLabel;
2661  if (D->isGnuLocal()) {
2662  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2663  if (!BeginLocOrErr)
2664  return BeginLocOrErr.takeError();
2665  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2666  Name.getAsIdentifierInfo(), *BeginLocOrErr))
2667  return ToLabel;
2668 
2669  } else {
2670  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2671  Name.getAsIdentifierInfo()))
2672  return ToLabel;
2673 
2674  }
2675 
2676  Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2677  if (!ToStmtOrErr)
2678  return ToStmtOrErr.takeError();
2679 
2680  ToLabel->setStmt(*ToStmtOrErr);
2681  ToLabel->setLexicalDeclContext(LexicalDC);
2682  LexicalDC->addDeclInternal(ToLabel);
2683  return ToLabel;
2684 }
2685 
2687  // Import the major distinguishing characteristics of this enum.
2688  DeclContext *DC, *LexicalDC;
2689  DeclarationName Name;
2690  SourceLocation Loc;
2691  NamedDecl *ToD;
2692  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2693  return std::move(Err);
2694  if (ToD)
2695  return ToD;
2696 
2697  // Figure out what enum name we're looking for.
2698  unsigned IDNS = Decl::IDNS_Tag;
2699  DeclarationName SearchName = Name;
2700  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2701  if (Error Err = importInto(
2702  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2703  return std::move(Err);
2704  IDNS = Decl::IDNS_Ordinary;
2705  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2706  IDNS |= Decl::IDNS_Ordinary;
2707 
2708  // We may already have an enum of the same name; try to find and match it.
2709  EnumDecl *PrevDecl = nullptr;
2710  if (!DC->isFunctionOrMethod() && SearchName) {
2711  SmallVector<NamedDecl *, 4> ConflictingDecls;
2712  auto FoundDecls =
2713  Importer.findDeclsInToCtx(DC, SearchName);
2714  for (auto *FoundDecl : FoundDecls) {
2715  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2716  continue;
2717 
2718  if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2719  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2720  FoundDecl = Tag->getDecl();
2721  }
2722 
2723  if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2724  if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2725  continue;
2726  if (IsStructuralMatch(D, FoundEnum)) {
2727  EnumDecl *FoundDef = FoundEnum->getDefinition();
2728  if (D->isThisDeclarationADefinition() && FoundDef)
2729  return Importer.MapImported(D, FoundDef);
2730  PrevDecl = FoundEnum->getMostRecentDecl();
2731  break;
2732  }
2733  ConflictingDecls.push_back(FoundDecl);
2734  }
2735  }
2736 
2737  if (!ConflictingDecls.empty()) {
2738  ExpectedName NameOrErr = Importer.HandleNameConflict(
2739  SearchName, DC, IDNS, ConflictingDecls.data(),
2740  ConflictingDecls.size());
2741  if (NameOrErr)
2742  Name = NameOrErr.get();
2743  else
2744  return NameOrErr.takeError();
2745  }
2746  }
2747 
2748  Error Err = Error::success();
2749  auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2750  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2751  auto ToIntegerType = importChecked(Err, D->getIntegerType());
2752  auto ToBraceRange = importChecked(Err, D->getBraceRange());
2753  if (Err)
2754  return std::move(Err);
2755 
2756  // Create the enum declaration.
2757  EnumDecl *D2;
2758  if (GetImportedOrCreateDecl(
2759  D2, D, Importer.getToContext(), DC, ToBeginLoc,
2760  Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2761  D->isScopedUsingClassTag(), D->isFixed()))
2762  return D2;
2763 
2764  D2->setQualifierInfo(ToQualifierLoc);
2765  D2->setIntegerType(ToIntegerType);
2766  D2->setBraceRange(ToBraceRange);
2767  D2->setAccess(D->getAccess());
2768  D2->setLexicalDeclContext(LexicalDC);
2769  addDeclToContexts(D, D2);
2770 
2771  if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
2772  TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2773  EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2774  if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
2775  D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
2776  else
2777  return ToInstOrErr.takeError();
2778  if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
2780  else
2781  return POIOrErr.takeError();
2782  }
2783 
2784  // Import the definition
2785  if (D->isCompleteDefinition())
2786  if (Error Err = ImportDefinition(D, D2))
2787  return std::move(Err);
2788 
2789  return D2;
2790 }
2791 
2793  bool IsFriendTemplate = false;
2794  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2795  IsFriendTemplate =
2796  DCXX->getDescribedClassTemplate() &&
2797  DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2799  }
2800 
2801  // Import the major distinguishing characteristics of this record.
2802  DeclContext *DC = nullptr, *LexicalDC = nullptr;
2803  DeclarationName Name;
2804  SourceLocation Loc;
2805  NamedDecl *ToD = nullptr;
2806  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2807  return std::move(Err);
2808  if (ToD)
2809  return ToD;
2810 
2811  // Figure out what structure name we're looking for.
2812  unsigned IDNS = Decl::IDNS_Tag;
2813  DeclarationName SearchName = Name;
2814  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2815  if (Error Err = importInto(
2816  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2817  return std::move(Err);
2818  IDNS = Decl::IDNS_Ordinary;
2819  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2821 
2822  // We may already have a record of the same name; try to find and match it.
2823  RecordDecl *PrevDecl = nullptr;
2824  if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2825  SmallVector<NamedDecl *, 4> ConflictingDecls;
2826  auto FoundDecls =
2827  Importer.findDeclsInToCtx(DC, SearchName);
2828  if (!FoundDecls.empty()) {
2829  // We're going to have to compare D against potentially conflicting Decls,
2830  // so complete it.
2833  }
2834 
2835  for (auto *FoundDecl : FoundDecls) {
2836  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2837  continue;
2838 
2839  Decl *Found = FoundDecl;
2840  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2841  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2842  Found = Tag->getDecl();
2843  }
2844 
2845  if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2846  // Do not emit false positive diagnostic in case of unnamed
2847  // struct/union and in case of anonymous structs. Would be false
2848  // because there may be several anonymous/unnamed structs in a class.
2849  // E.g. these are both valid:
2850  // struct A { // unnamed structs
2851  // struct { struct A *next; } entry0;
2852  // struct { struct A *next; } entry1;
2853  // };
2854  // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2855  if (!SearchName)
2856  if (!IsStructuralMatch(D, FoundRecord, false))
2857  continue;
2858 
2859  if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
2860  continue;
2861 
2862  if (IsStructuralMatch(D, FoundRecord)) {
2863  RecordDecl *FoundDef = FoundRecord->getDefinition();
2864  if (D->isThisDeclarationADefinition() && FoundDef) {
2865  // FIXME: Structural equivalence check should check for same
2866  // user-defined methods.
2867  Importer.MapImported(D, FoundDef);
2868  if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2869  auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2870  assert(FoundCXX && "Record type mismatch");
2871 
2872  if (!Importer.isMinimalImport())
2873  // FoundDef may not have every implicit method that D has
2874  // because implicit methods are created only if they are used.
2875  if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2876  return std::move(Err);
2877  }
2878  }
2879  PrevDecl = FoundRecord->getMostRecentDecl();
2880  break;
2881  }
2882  ConflictingDecls.push_back(FoundDecl);
2883  } // kind is RecordDecl
2884  } // for
2885 
2886  if (!ConflictingDecls.empty() && SearchName) {
2887  ExpectedName NameOrErr = Importer.HandleNameConflict(
2888  SearchName, DC, IDNS, ConflictingDecls.data(),
2889  ConflictingDecls.size());
2890  if (NameOrErr)
2891  Name = NameOrErr.get();
2892  else
2893  return NameOrErr.takeError();
2894  }
2895  }
2896 
2897  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2898  if (!BeginLocOrErr)
2899  return BeginLocOrErr.takeError();
2900 
2901  // Create the record declaration.
2902  RecordDecl *D2 = nullptr;
2903  CXXRecordDecl *D2CXX = nullptr;
2904  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2905  if (DCXX->isLambda()) {
2906  auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2907  if (!TInfoOrErr)
2908  return TInfoOrErr.takeError();
2909  if (GetImportedOrCreateSpecialDecl(
2910  D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2911  DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(),
2912  DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2913  return D2CXX;
2914  ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2915  if (!CDeclOrErr)
2916  return CDeclOrErr.takeError();
2917  D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
2918  DCXX->hasKnownLambdaInternalLinkage());
2920  DCXX->getDeviceLambdaManglingNumber());
2921  } else if (DCXX->isInjectedClassName()) {
2922  // We have to be careful to do a similar dance to the one in
2923  // Sema::ActOnStartCXXMemberDeclarations
2924  const bool DelayTypeCreation = true;
2925  if (GetImportedOrCreateDecl(
2926  D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2927  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2928  cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2929  return D2CXX;
2930  Importer.getToContext().getTypeDeclType(
2931  D2CXX, dyn_cast<CXXRecordDecl>(DC));
2932  } else {
2933  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2934  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2935  Name.getAsIdentifierInfo(),
2936  cast_or_null<CXXRecordDecl>(PrevDecl)))
2937  return D2CXX;
2938  }
2939 
2940  D2 = D2CXX;
2941  D2->setAccess(D->getAccess());
2942  D2->setLexicalDeclContext(LexicalDC);
2943  addDeclToContexts(D, D2);
2944 
2945  if (ClassTemplateDecl *FromDescribed =
2946  DCXX->getDescribedClassTemplate()) {
2947  ClassTemplateDecl *ToDescribed;
2948  if (Error Err = importInto(ToDescribed, FromDescribed))
2949  return std::move(Err);
2950  D2CXX->setDescribedClassTemplate(ToDescribed);
2951  if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2952  // In a record describing a template the type should be an
2953  // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2954  // previously set type to the correct value here (ToDescribed is not
2955  // available at record create).
2956  // FIXME: The previous type is cleared but not removed from
2957  // ASTContext's internal storage.
2958  CXXRecordDecl *Injected = nullptr;
2959  for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2960  auto *Record = dyn_cast<CXXRecordDecl>(Found);
2961  if (Record && Record->isInjectedClassName()) {
2962  Injected = Record;
2963  break;
2964  }
2965  }
2966  // Create an injected type for the whole redecl chain.
2967  SmallVector<Decl *, 2> Redecls =
2969  for (auto *R : Redecls) {
2970  auto *RI = cast<CXXRecordDecl>(R);
2971  RI->setTypeForDecl(nullptr);
2972  // Below we create a new injected type and assign that to the
2973  // canonical decl, subsequent declarations in the chain will reuse
2974  // that type.
2976  RI, ToDescribed->getInjectedClassNameSpecialization());
2977  }
2978  // Set the new type for the previous injected decl too.
2979  if (Injected) {
2980  Injected->setTypeForDecl(nullptr);
2981  Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2982  }
2983  }
2984  } else if (MemberSpecializationInfo *MemberInfo =
2985  DCXX->getMemberSpecializationInfo()) {
2987  MemberInfo->getTemplateSpecializationKind();
2988  CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2989 
2990  if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2991  D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2992  else
2993  return ToInstOrErr.takeError();
2994 
2995  if (ExpectedSLoc POIOrErr =
2996  import(MemberInfo->getPointOfInstantiation()))
2998  *POIOrErr);
2999  else
3000  return POIOrErr.takeError();
3001  }
3002 
3003  } else {
3004  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3005  D->getTagKind(), DC, *BeginLocOrErr, Loc,
3006  Name.getAsIdentifierInfo(), PrevDecl))
3007  return D2;
3008  D2->setLexicalDeclContext(LexicalDC);
3009  addDeclToContexts(D, D2);
3010  }
3011 
3012  if (auto BraceRangeOrErr = import(D->getBraceRange()))
3013  D2->setBraceRange(*BraceRangeOrErr);
3014  else
3015  return BraceRangeOrErr.takeError();
3016  if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3017  D2->setQualifierInfo(*QualifierLocOrErr);
3018  else
3019  return QualifierLocOrErr.takeError();
3020 
3021  if (D->isAnonymousStructOrUnion())
3022  D2->setAnonymousStructOrUnion(true);
3023 
3024  if (D->isCompleteDefinition())
3025  if (Error Err = ImportDefinition(D, D2, IDK_Default))
3026  return std::move(Err);
3027 
3028  return D2;
3029 }
3030 
3032  // Import the major distinguishing characteristics of this enumerator.
3033  DeclContext *DC, *LexicalDC;
3034  DeclarationName Name;
3035  SourceLocation Loc;
3036  NamedDecl *ToD;
3037  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3038  return std::move(Err);
3039  if (ToD)
3040  return ToD;
3041 
3042  // Determine whether there are any other declarations with the same name and
3043  // in the same context.
3044  if (!LexicalDC->isFunctionOrMethod()) {
3045  SmallVector<NamedDecl *, 4> ConflictingDecls;
3046  unsigned IDNS = Decl::IDNS_Ordinary;
3047  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3048  for (auto *FoundDecl : FoundDecls) {
3049  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3050  continue;
3051 
3052  if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3053  if (IsStructuralMatch(D, FoundEnumConstant))
3054  return Importer.MapImported(D, FoundEnumConstant);
3055  ConflictingDecls.push_back(FoundDecl);
3056  }
3057  }
3058 
3059  if (!ConflictingDecls.empty()) {
3060  ExpectedName NameOrErr = Importer.HandleNameConflict(
3061  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3062  if (NameOrErr)
3063  Name = NameOrErr.get();
3064  else
3065  return NameOrErr.takeError();
3066  }
3067  }
3068 
3069  ExpectedType TypeOrErr = import(D->getType());
3070  if (!TypeOrErr)
3071  return TypeOrErr.takeError();
3072 
3073  ExpectedExpr InitOrErr = import(D->getInitExpr());
3074  if (!InitOrErr)
3075  return InitOrErr.takeError();
3076 
3077  EnumConstantDecl *ToEnumerator;
3078  if (GetImportedOrCreateDecl(
3079  ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3080  Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3081  return ToEnumerator;
3082 
3083  ToEnumerator->setAccess(D->getAccess());
3084  ToEnumerator->setLexicalDeclContext(LexicalDC);
3085  LexicalDC->addDeclInternal(ToEnumerator);
3086  return ToEnumerator;
3087 }
3088 
3090  DeclaratorDecl *ToD) {
3091  unsigned int Num = FromD->getNumTemplateParameterLists();
3092  if (Num == 0)
3093  return Error::success();
3095  for (unsigned int I = 0; I < Num; ++I)
3096  if (Expected<TemplateParameterList *> ToTPListOrErr =
3097  import(FromD->getTemplateParameterList(I)))
3098  ToTPLists[I] = *ToTPListOrErr;
3099  else
3100  return ToTPListOrErr.takeError();
3101  ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3102  return Error::success();
3103 }
3104 
3106  FunctionDecl *FromFD, FunctionDecl *ToFD) {
3107  switch (FromFD->getTemplatedKind()) {
3110  return Error::success();
3111 
3114 
3115  if (Expected<FunctionDecl *> InstFDOrErr =
3116  import(FromFD->getInstantiatedFromMemberFunction()))
3117  ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3118  else
3119  return InstFDOrErr.takeError();
3120 
3121  if (ExpectedSLoc POIOrErr = import(
3124  else
3125  return POIOrErr.takeError();
3126 
3127  return Error::success();
3128  }
3129 
3131  auto FunctionAndArgsOrErr =
3133  if (!FunctionAndArgsOrErr)
3134  return FunctionAndArgsOrErr.takeError();
3135 
3137  Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3138 
3139  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3140  TemplateArgumentListInfo ToTAInfo;
3141  const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3142  if (FromTAArgsAsWritten)
3144  *FromTAArgsAsWritten, ToTAInfo))
3145  return Err;
3146 
3147  ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3148  if (!POIOrErr)
3149  return POIOrErr.takeError();
3150 
3151  if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3152  return Err;
3153 
3154  TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3155  ToFD->setFunctionTemplateSpecialization(
3156  std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3157  TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3158  return Error::success();
3159  }
3160 
3162  auto *FromInfo = FromFD->getDependentSpecializationInfo();
3163  UnresolvedSet<8> TemplDecls;
3164  unsigned NumTemplates = FromInfo->getNumTemplates();
3165  for (unsigned I = 0; I < NumTemplates; I++) {
3166  if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
3167  import(FromInfo->getTemplate(I)))
3168  TemplDecls.addDecl(*ToFTDOrErr);
3169  else
3170  return ToFTDOrErr.takeError();
3171  }
3172 
3173  // Import TemplateArgumentListInfo.
3174  TemplateArgumentListInfo ToTAInfo;
3176  FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
3177  llvm::makeArrayRef(
3178  FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
3179  ToTAInfo))
3180  return Err;
3181 
3183  TemplDecls, ToTAInfo);
3184  return Error::success();
3185  }
3186  }
3187  llvm_unreachable("All cases should be covered!");
3188 }
3189 
3192  auto FunctionAndArgsOrErr =
3194  if (!FunctionAndArgsOrErr)
3195  return FunctionAndArgsOrErr.takeError();
3196 
3197  FunctionTemplateDecl *Template;
3198  TemplateArgsTy ToTemplArgs;
3199  std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3200  void *InsertPos = nullptr;
3201  auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3202  return FoundSpec;
3203 }
3204 
3206  FunctionDecl *ToFD) {
3207  if (Stmt *FromBody = FromFD->getBody()) {
3208  if (ExpectedStmt ToBodyOrErr = import(FromBody))
3209  ToFD->setBody(*ToBodyOrErr);
3210  else
3211  return ToBodyOrErr.takeError();
3212  }
3213  return Error::success();
3214 }
3215 
3216 // Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3217 // which is equal to the given DC.
3218 static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3219  const DeclContext *DCi = D->getDeclContext();
3220  while (DCi != D->getTranslationUnitDecl()) {
3221  if (DCi == DC)
3222  return true;
3223  DCi = DCi->getParent();
3224  }
3225  return false;
3226 }
3227 
3229  if (T.isNull())
3230  return false;
3231  if (const auto *RecordT = T->getAs<RecordType>()) {
3232  const RecordDecl *RD = RecordT->getDecl();
3233  assert(RD);
3234  if (isAncestorDeclContextOf(FD, RD)) {
3235  assert(RD->getLexicalDeclContext() == RD->getDeclContext());
3236  return true;
3237  }
3238  if (const auto *RDTempl = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3239  return llvm::count_if(RDTempl->getTemplateArgs().asArray(),
3240  [FD](const TemplateArgument &Arg) {
3241  return hasTypeDeclaredInsideFunction(
3242  Arg.getAsType(), FD);
3243  });
3244  }
3245  return false;
3246 }
3247 
3249  QualType FromTy = D->getType();
3250  const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
3251  assert(FromFPT && "Must be called on FunctionProtoType");
3252  if (const AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType())
3253  return hasTypeDeclaredInsideFunction(AutoT->getDeducedType(), D);
3254  if (const auto *TypedefT = FromFPT->getReturnType()->getAs<TypedefType>()) {
3255  const TypedefNameDecl *TD = TypedefT->getDecl();
3256  assert(TD);
3257  if (isAncestorDeclContextOf(D, TD)) {
3258  assert(TD->getLexicalDeclContext() == TD->getDeclContext());
3259  return true;
3260  }
3261  }
3262  return false;
3263 }
3264 
3266 ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3267  Expr *ExplicitExpr = ESpec.getExpr();
3268  if (ExplicitExpr)
3269  ExplicitExpr = importChecked(Err, ESpec.getExpr());
3270  return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3271 }
3272 
3274 
3276  auto RedeclIt = Redecls.begin();
3277  // Import the first part of the decl chain. I.e. import all previous
3278  // declarations starting from the canonical decl.
3279  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3280  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3281  if (!ToRedeclOrErr)
3282  return ToRedeclOrErr.takeError();
3283  }
3284  assert(*RedeclIt == D);
3285 
3286  // Import the major distinguishing characteristics of this function.
3287  DeclContext *DC, *LexicalDC;
3288  DeclarationName Name;
3289  SourceLocation Loc;
3290  NamedDecl *ToD;
3291  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3292  return std::move(Err);
3293  if (ToD)
3294  return ToD;
3295 
3296  FunctionDecl *FoundByLookup = nullptr;
3298 
3299  // If this is a function template specialization, then try to find the same
3300  // existing specialization in the "to" context. The lookup below will not
3301  // find any specialization, but would find the primary template; thus, we
3302  // have to skip normal lookup in case of specializations.
3303  // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3304  if (D->getTemplatedKind() ==
3306  auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3307  if (!FoundFunctionOrErr)
3308  return FoundFunctionOrErr.takeError();
3309  if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3310  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3311  return Def;
3312  FoundByLookup = FoundFunction;
3313  }
3314  }
3315  // Try to find a function in our own ("to") context with the same name, same
3316  // type, and in the same context as the function we're importing.
3317  else if (!LexicalDC->isFunctionOrMethod()) {
3318  SmallVector<NamedDecl *, 4> ConflictingDecls;
3320  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3321  for (auto *FoundDecl : FoundDecls) {
3322  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3323  continue;
3324 
3325  if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3326  if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3327  continue;
3328 
3329  if (IsStructuralMatch(D, FoundFunction)) {
3330  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3331  return Def;
3332  FoundByLookup = FoundFunction;
3333  break;
3334  }
3335  // FIXME: Check for overloading more carefully, e.g., by boosting
3336  // Sema::IsOverload out to the AST library.
3337 
3338  // Function overloading is okay in C++.
3339  if (Importer.getToContext().getLangOpts().CPlusPlus)
3340  continue;
3341 
3342  // Complain about inconsistent function types.
3343  Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3344  << Name << D->getType() << FoundFunction->getType();
3345  Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3346  << FoundFunction->getType();
3347  ConflictingDecls.push_back(FoundDecl);
3348  }
3349  }
3350 
3351  if (!ConflictingDecls.empty()) {
3352  ExpectedName NameOrErr = Importer.HandleNameConflict(
3353  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3354  if (NameOrErr)
3355  Name = NameOrErr.get();
3356  else
3357  return NameOrErr.takeError();
3358  }
3359  }
3360 
3361  // We do not allow more than one in-class declaration of a function. This is
3362  // because AST clients like VTableBuilder asserts on this. VTableBuilder
3363  // assumes there is only one in-class declaration. Building a redecl
3364  // chain would result in more than one in-class declaration for
3365  // overrides (even if they are part of the same redecl chain inside the
3366  // derived class.)
3367  if (FoundByLookup) {
3368  if (isa<CXXMethodDecl>(FoundByLookup)) {
3369  if (D->getLexicalDeclContext() == D->getDeclContext()) {
3370  if (!D->doesThisDeclarationHaveABody()) {
3371  if (FunctionTemplateDecl *DescribedD =
3373  // Handle a "templated" function together with its described
3374  // template. This avoids need for a similar check at import of the
3375  // described template.
3376  assert(FoundByLookup->getDescribedFunctionTemplate() &&
3377  "Templated function mapped to non-templated?");
3378  Importer.MapImported(DescribedD,
3379  FoundByLookup->getDescribedFunctionTemplate());
3380  }
3381  return Importer.MapImported(D, FoundByLookup);
3382  } else {
3383  // Let's continue and build up the redecl chain in this case.
3384  // FIXME Merge the functions into one decl.
3385  }
3386  }
3387  }
3388  }
3389 
3390  DeclarationNameInfo NameInfo(Name, Loc);
3391  // Import additional name location/type info.
3392  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3393  return std::move(Err);
3394 
3395  QualType FromTy = D->getType();
3396  TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
3397  // Set to true if we do not import the type of the function as is. There are
3398  // cases when the original type would result in an infinite recursion during
3399  // the import. To avoid an infinite recursion when importing, we create the
3400  // FunctionDecl with a simplified function type and update it only after the
3401  // relevant AST nodes are already imported.
3402  // The type is related to TypeSourceInfo (it references the type), so we must
3403  // do the same with TypeSourceInfo.
3404  bool UsedDifferentProtoType = false;
3405  if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3406  QualType FromReturnTy = FromFPT->getReturnType();
3407  // Functions with auto return type may define a struct inside their body
3408  // and the return type could refer to that struct.
3409  // E.g.: auto foo() { struct X{}; return X(); }
3410  // To avoid an infinite recursion when importing, create the FunctionDecl
3411  // with a simplified return type.
3413  FromReturnTy = Importer.getFromContext().VoidTy;
3414  UsedDifferentProtoType = true;
3415  }
3416  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3417  // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3418  // FunctionDecl that we are importing the FunctionProtoType for.
3419  // To avoid an infinite recursion when importing, create the FunctionDecl
3420  // with a simplified function type.
3421  if (FromEPI.ExceptionSpec.SourceDecl ||
3422  FromEPI.ExceptionSpec.SourceTemplate ||
3423  FromEPI.ExceptionSpec.NoexceptExpr) {
3425  FromEPI = DefaultEPI;
3426  UsedDifferentProtoType = true;
3427  }
3428  FromTy = Importer.getFromContext().getFunctionType(
3429  FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3430  FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
3431  FromTy, D->getBeginLoc());
3432  }
3433 
3434  Error Err = Error::success();
3435  auto T = importChecked(Err, FromTy);
3436  auto TInfo = importChecked(Err, FromTSI);
3437  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3438  auto ToEndLoc = importChecked(Err, D->getEndLoc());
3439  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3440  auto TrailingRequiresClause =
3442  if (Err)
3443  return std::move(Err);
3444 
3445  // Import the function parameters.
3446  SmallVector<ParmVarDecl *, 8> Parameters;
3447  for (auto P : D->parameters()) {
3448  if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3449  Parameters.push_back(*ToPOrErr);
3450  else
3451  return ToPOrErr.takeError();
3452  }
3453 
3454  // Create the imported function.
3455  FunctionDecl *ToFunction = nullptr;
3456  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3457  ExplicitSpecifier ESpec =
3458  importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3459  if (Err)
3460  return std::move(Err);
3461  auto ToInheritedConstructor = InheritedConstructor();
3462  if (FromConstructor->isInheritingConstructor()) {
3463  Expected<InheritedConstructor> ImportedInheritedCtor =
3464  import(FromConstructor->getInheritedConstructor());
3465  if (!ImportedInheritedCtor)
3466  return ImportedInheritedCtor.takeError();
3467  ToInheritedConstructor = *ImportedInheritedCtor;
3468  }
3469  if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3470  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3471  ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3473  ToInheritedConstructor, TrailingRequiresClause))
3474  return ToFunction;
3475  } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3476 
3477  Error Err = Error::success();
3478  auto ToOperatorDelete = importChecked(
3479  Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3480  auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3481  if (Err)
3482  return std::move(Err);
3483 
3484  if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3485  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3486  ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3488  TrailingRequiresClause))
3489  return ToFunction;
3490 
3491  CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3492 
3493  ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3494  } else if (CXXConversionDecl *FromConversion =
3495  dyn_cast<CXXConversionDecl>(D)) {
3496  ExplicitSpecifier ESpec =
3497  importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3498  if (Err)
3499  return std::move(Err);
3500  if (GetImportedOrCreateDecl<CXXConversionDecl>(
3501  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3502  ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3503  D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3504  SourceLocation(), TrailingRequiresClause))
3505  return ToFunction;
3506  } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3507  if (GetImportedOrCreateDecl<CXXMethodDecl>(
3508  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3509  ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3510  Method->UsesFPIntrin(), Method->isInlineSpecified(),
3511  D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3512  return ToFunction;
3513  } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3514  ExplicitSpecifier ESpec =
3515  importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3516  CXXConstructorDecl *Ctor =
3517  importChecked(Err, Guide->getCorrespondingConstructor());
3518  if (Err)
3519  return std::move(Err);
3520  if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3521  ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3522  NameInfo, T, TInfo, ToEndLoc, Ctor))
3523  return ToFunction;
3524  cast<CXXDeductionGuideDecl>(ToFunction)
3525  ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
3526  } else {
3527  if (GetImportedOrCreateDecl(
3528  ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3529  NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3531  D->getConstexprKind(), TrailingRequiresClause))
3532  return ToFunction;
3533  }
3534 
3535  // Connect the redecl chain.
3536  if (FoundByLookup) {
3537  auto *Recent = const_cast<FunctionDecl *>(
3538  FoundByLookup->getMostRecentDecl());
3539  ToFunction->setPreviousDecl(Recent);
3540  // FIXME Probably we should merge exception specifications. E.g. In the
3541  // "To" context the existing function may have exception specification with
3542  // noexcept-unevaluated, while the newly imported function may have an
3543  // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3544  // decl and its redeclarations may be required.
3545  }
3546 
3547  ToFunction->setQualifierInfo(ToQualifierLoc);
3548  ToFunction->setAccess(D->getAccess());
3549  ToFunction->setLexicalDeclContext(LexicalDC);
3550  ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3551  ToFunction->setTrivial(D->isTrivial());
3552  ToFunction->setPure(D->isPure());
3553  ToFunction->setDefaulted(D->isDefaulted());
3555  ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3556  ToFunction->setRangeEnd(ToEndLoc);
3557 
3558  // Set the parameters.
3559  for (auto *Param : Parameters) {
3560  Param->setOwningFunction(ToFunction);
3561  ToFunction->addDeclInternal(Param);
3562  if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3563  LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3564  }
3565  ToFunction->setParams(Parameters);
3566 
3567  // We need to complete creation of FunctionProtoTypeLoc manually with setting
3568  // params it refers to.
3569  if (TInfo) {
3570  if (auto ProtoLoc =
3571  TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3572  for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3573  ProtoLoc.setParam(I, Parameters[I]);
3574  }
3575  }
3576 
3577  // Import the describing template function, if any.
3578  if (FromFT) {
3579  auto ToFTOrErr = import(FromFT);
3580  if (!ToFTOrErr)
3581  return ToFTOrErr.takeError();
3582  }
3583 
3584  // Import Ctor initializers.
3585  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3586  if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3587  SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3588  // Import first, then allocate memory and copy if there was no error.
3589  if (Error Err = ImportContainerChecked(
3590  FromConstructor->inits(), CtorInitializers))
3591  return std::move(Err);
3592  auto **Memory =
3593  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3594  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3595  auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3596  ToCtor->setCtorInitializers(Memory);
3597  ToCtor->setNumCtorInitializers(NumInitializers);
3598  }
3599  }
3600 
3601  if (D->doesThisDeclarationHaveABody()) {
3602  Error Err = ImportFunctionDeclBody(D, ToFunction);
3603 
3604  if (Err)
3605  return std::move(Err);
3606  }
3607 
3608  // Import and set the original type in case we used another type.
3609  if (UsedDifferentProtoType) {
3610  if (ExpectedType TyOrErr = import(D->getType()))
3611  ToFunction->setType(*TyOrErr);
3612  else
3613  return TyOrErr.takeError();
3614  if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo()))
3615  ToFunction->setTypeSourceInfo(*TSIOrErr);
3616  else
3617  return TSIOrErr.takeError();
3618  }
3619 
3620  // FIXME: Other bits to merge?
3621 
3622  // If it is a template, import all related things.
3623  if (Error Err = ImportTemplateInformation(D, ToFunction))
3624  return std::move(Err);
3625 
3626  addDeclToContexts(D, ToFunction);
3627 
3628  if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3629  if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3630  FromCXXMethod))
3631  return std::move(Err);
3632 
3633  // Import the rest of the chain. I.e. import all subsequent declarations.
3634  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3635  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3636  if (!ToRedeclOrErr)
3637  return ToRedeclOrErr.takeError();
3638  }
3639 
3640  return ToFunction;
3641 }
3642 
3644  return VisitFunctionDecl(D);
3645 }
3646 
3648  return VisitCXXMethodDecl(D);
3649 }
3650 
3652  return VisitCXXMethodDecl(D);
3653 }
3654 
3656  return VisitCXXMethodDecl(D);
3657 }
3658 
3661  return VisitFunctionDecl(D);
3662 }
3663 
3665  // Import the major distinguishing characteristics of a variable.
3666  DeclContext *DC, *LexicalDC;
3667  DeclarationName Name;
3668  SourceLocation Loc;
3669  NamedDecl *ToD;
3670  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3671  return std::move(Err);
3672  if (ToD)
3673  return ToD;
3674 
3675  // Determine whether we've already imported this field.
3676  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3677  for (auto *FoundDecl : FoundDecls) {
3678  if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3679  // For anonymous fields, match up by index.
3680  if (!Name &&
3682  ASTImporter::getFieldIndex(FoundField))
3683  continue;
3684 
3685  if (Importer.IsStructurallyEquivalent(D->getType(),
3686  FoundField->getType())) {
3687  Importer.MapImported(D, FoundField);
3688  // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3689  // initializer of a FieldDecl might not had been instantiated in the
3690  // "To" context. However, the "From" context might instantiated that,
3691  // thus we have to merge that.
3692  // Note: `hasInClassInitializer()` is not the same as non-null
3693  // `getInClassInitializer()` value.
3694  if (Expr *FromInitializer = D->getInClassInitializer()) {
3695  if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) {
3696  // Import of the FromInitializer may result in the setting of
3697  // InClassInitializer. If not, set it here.
3698  assert(FoundField->hasInClassInitializer() &&
3699  "Field should have an in-class initializer if it has an "
3700  "expression for it.");
3701  if (!FoundField->getInClassInitializer())
3702  FoundField->setInClassInitializer(*ToInitializerOrErr);
3703  } else {
3704  return ToInitializerOrErr.takeError();
3705  }
3706  }
3707  return FoundField;
3708  }
3709 
3710  // FIXME: Why is this case not handled with calling HandleNameConflict?
3711  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3712  << Name << D->getType() << FoundField->getType();
3713  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3714  << FoundField->getType();
3715 
3716  return make_error<ASTImportError>(ASTImportError::NameConflict);
3717  }
3718  }
3719 
3720  Error Err = Error::success();
3721  auto ToType = importChecked(Err, D->getType());
3722  auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
3723  auto ToBitWidth = importChecked(Err, D->getBitWidth());
3724  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3725  auto ToInitializer = importChecked(Err, D->getInClassInitializer());
3726  if (Err)
3727  return std::move(Err);
3728  const Type *ToCapturedVLAType = nullptr;
3729  if (Error Err = Importer.importInto(
3730  ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
3731  return std::move(Err);
3732 
3733  FieldDecl *ToField;
3734  if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3735  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3736  ToType, ToTInfo, ToBitWidth, D->isMutable(),
3737  D->getInClassInitStyle()))
3738  return ToField;
3739 
3740  ToField->setAccess(D->getAccess());
3741  ToField->setLexicalDeclContext(LexicalDC);
3742  if (ToInitializer)
3743  ToField->setInClassInitializer(ToInitializer);
3744  ToField->setImplicit(D->isImplicit());
3745  if (ToCapturedVLAType)
3746  ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
3747  LexicalDC->addDeclInternal(ToField);
3748  return ToField;
3749 }
3750 
3752  // Import the major distinguishing characteristics of a variable.
3753  DeclContext *DC, *LexicalDC;
3754  DeclarationName Name;
3755  SourceLocation Loc;
3756  NamedDecl *ToD;
3757  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3758  return std::move(Err);
3759  if (ToD)
3760  return ToD;
3761 
3762  // Determine whether we've already imported this field.
3763  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3764  for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3765  if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3766  // For anonymous indirect fields, match up by index.
3767  if (!Name &&
3769  ASTImporter::getFieldIndex(FoundField))
3770  continue;
3771 
3772  if (Importer.IsStructurallyEquivalent(D->getType(),
3773  FoundField->getType(),
3774  !Name.isEmpty())) {
3775  Importer.MapImported(D, FoundField);
3776  return FoundField;
3777  }
3778 
3779  // If there are more anonymous fields to check, continue.
3780  if (!Name && I < N-1)
3781  continue;
3782 
3783  // FIXME: Why is this case not handled with calling HandleNameConflict?
3784  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3785  << Name << D->getType() << FoundField->getType();
3786  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3787  << FoundField->getType();
3788 
3789  return make_error<ASTImportError>(ASTImportError::NameConflict);
3790  }
3791  }
3792 
3793  // Import the type.
3794  auto TypeOrErr = import(D->getType());
3795  if (!TypeOrErr)
3796  return TypeOrErr.takeError();
3797 
3798  auto **NamedChain =
3799  new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3800 
3801  unsigned i = 0;
3802  for (auto *PI : D->chain())
3803  if (Expected<NamedDecl *> ToD = import(PI))
3804  NamedChain[i++] = *ToD;
3805  else
3806  return ToD.takeError();
3807 
3808  llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3809  IndirectFieldDecl *ToIndirectField;
3810  if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3811  Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3812  // FIXME here we leak `NamedChain` which is allocated before
3813  return ToIndirectField;
3814 
3815  ToIndirectField->setAccess(D->getAccess());
3816  ToIndirectField->setLexicalDeclContext(LexicalDC);
3817  LexicalDC->addDeclInternal(ToIndirectField);
3818  return ToIndirectField;
3819 }
3820 
3821 /// Used as return type of getFriendCountAndPosition.
3823  /// Number of similar looking friends.
3824  unsigned int TotalCount;
3825  /// Index of the specific FriendDecl.
3826  unsigned int IndexOfDecl;
3827 };
3828 
3829 template <class T>
3831  const FriendDecl *FD,
3832  llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
3833  unsigned int FriendCount = 0;
3834  llvm::Optional<unsigned int> FriendPosition;
3835  const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
3836 
3837  T TypeOrDecl = GetCanTypeOrDecl(FD);
3838 
3839  for (const FriendDecl *FoundFriend : RD->friends()) {
3840  if (FoundFriend == FD) {
3841  FriendPosition = FriendCount;
3842  ++FriendCount;
3843  } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
3844  GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
3845  ++FriendCount;
3846  }
3847  }
3848 
3849  assert(FriendPosition && "Friend decl not found in own parent.");
3850 
3851  return {FriendCount, *FriendPosition};
3852 }
3853 
3855  if (FD->getFriendType())
3856  return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
3857  if (TypeSourceInfo *TSI = F->getFriendType())
3858  return TSI->getType().getCanonicalType();
3859  llvm_unreachable("Wrong friend object type.");
3860  });
3861  else
3862  return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
3863  if (Decl *D = F->getFriendDecl())
3864  return D->getCanonicalDecl();
3865  llvm_unreachable("Wrong friend object type.");
3866  });
3867 }
3868 
3870  // Import the major distinguishing characteristics of a declaration.
3871  DeclContext *DC, *LexicalDC;
3872  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3873  return std::move(Err);
3874 
3875  // Determine whether we've already imported this decl.
3876  // FriendDecl is not a NamedDecl so we cannot use lookup.
3877  // We try to maintain order and count of redundant friend declarations.
3878  const auto *RD = cast<CXXRecordDecl>(DC);
3879  FriendDecl *ImportedFriend = RD->getFirstFriend();
3880  SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
3881 
3882  while (ImportedFriend) {
3883  bool Match = false;
3884  if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3885  Match =
3886  IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3887  /*Complain=*/false);
3888  } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3889  Match = Importer.IsStructurallyEquivalent(
3890  D->getFriendType()->getType(),
3891  ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
3892  }
3893  if (Match)
3894  ImportedEquivalentFriends.push_back(ImportedFriend);
3895 
3896  ImportedFriend = ImportedFriend->getNextFriend();
3897  }
3898  FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
3899 
3900  assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
3901  "Class with non-matching friends is imported, ODR check wrong?");
3902  if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
3903  return Importer.MapImported(
3904  D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
3905 
3906  // Not found. Create it.
3907  // The declarations will be put into order later by ImportDeclContext.
3909  if (NamedDecl *FriendD = D->getFriendDecl()) {
3910  NamedDecl *ToFriendD;
3911  if (Error Err = importInto(ToFriendD, FriendD))
3912  return std::move(Err);
3913 
3914  if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3915  !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3916  ToFriendD->setObjectOfFriendDecl(false);
3917 
3918  ToFU = ToFriendD;
3919  } else { // The friend is a type, not a decl.
3920  if (auto TSIOrErr = import(D->getFriendType()))
3921  ToFU = *TSIOrErr;
3922  else
3923  return TSIOrErr.takeError();
3924  }
3925 
3926  SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3927  auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3928  for (unsigned I = 0; I < D->NumTPLists; I++) {
3929  if (auto ListOrErr = import(FromTPLists[I]))
3930  ToTPLists[I] = *ListOrErr;
3931  else
3932  return ListOrErr.takeError();
3933  }
3934 
3935  auto LocationOrErr = import(D->getLocation());
3936  if (!LocationOrErr)
3937  return LocationOrErr.takeError();
3938  auto FriendLocOrErr = import(D->getFriendLoc());
3939  if (!FriendLocOrErr)
3940  return FriendLocOrErr.takeError();
3941 
3942  FriendDecl *FrD;
3943  if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3944  *LocationOrErr, ToFU,
3945  *FriendLocOrErr, ToTPLists))
3946  return FrD;
3947 
3948  FrD->setAccess(D->getAccess());
3949  FrD->setLexicalDeclContext(LexicalDC);
3950  LexicalDC->addDeclInternal(FrD);
3951  return FrD;
3952 }
3953 
3955  // Import the major distinguishing characteristics of an ivar.
3956  DeclContext *DC, *LexicalDC;
3957  DeclarationName Name;
3958  SourceLocation Loc;
3959  NamedDecl *ToD;
3960  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3961  return std::move(Err);
3962  if (ToD)
3963  return ToD;
3964 
3965  // Determine whether we've already imported this ivar
3966  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3967  for (auto *FoundDecl : FoundDecls) {
3968  if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3969  if (Importer.IsStructurallyEquivalent(D->getType(),
3970  FoundIvar->getType())) {
3971  Importer.MapImported(D, FoundIvar);
3972  return FoundIvar;
3973  }
3974 
3975  Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3976  << Name << D->getType() << FoundIvar->getType();
3977  Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3978  << FoundIvar->getType();
3979 
3980  return make_error<ASTImportError>(ASTImportError::NameConflict);
3981  }
3982  }
3983 
3984  Error Err = Error::success();
3985  auto ToType = importChecked(Err, D->getType());
3986  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
3987  auto ToBitWidth = importChecked(Err, D->getBitWidth());
3988  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3989  if (Err)
3990  return std::move(Err);
3991 
3992  ObjCIvarDecl *ToIvar;
3993  if (GetImportedOrCreateDecl(
3994  ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3995  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3996  ToType, ToTypeSourceInfo,
3997  D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3998  return ToIvar;
3999 
4000  ToIvar->setLexicalDeclContext(LexicalDC);
4001  LexicalDC->addDeclInternal(ToIvar);
4002  return ToIvar;
4003 }
4004 
4006 
4008  auto RedeclIt = Redecls.begin();
4009  // Import the first part of the decl chain. I.e. import all previous
4010  // declarations starting from the canonical decl.
4011  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4012  ExpectedDecl RedeclOrErr = import(*RedeclIt);
4013  if (!RedeclOrErr)
4014  return RedeclOrErr.takeError();
4015  }
4016  assert(*RedeclIt == D);
4017 
4018  // Import the major distinguishing characteristics of a variable.
4019  DeclContext *DC, *LexicalDC;
4020  DeclarationName Name;
4021  SourceLocation Loc;
4022  NamedDecl *ToD;
4023  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4024  return std::move(Err);
4025  if (ToD)
4026  return ToD;
4027 
4028  // Try to find a variable in our own ("to") context with the same name and
4029  // in the same context as the variable we're importing.
4030  VarDecl *FoundByLookup = nullptr;
4031  if (D->isFileVarDecl()) {
4032  SmallVector<NamedDecl *, 4> ConflictingDecls;
4033  unsigned IDNS = Decl::IDNS_Ordinary;
4034  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4035  for (auto *FoundDecl : FoundDecls) {
4036  if (!FoundDecl->isInIdentifierNamespace(IDNS))
4037  continue;
4038 
4039  if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
4040  if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
4041  continue;
4042  if (Importer.IsStructurallyEquivalent(D->getType(),
4043  FoundVar->getType())) {
4044 
4045  // The VarDecl in the "From" context has a definition, but in the
4046  // "To" context we already have a definition.
4047  VarDecl *FoundDef = FoundVar->getDefinition();
4048  if (D->isThisDeclarationADefinition() && FoundDef)
4049  // FIXME Check for ODR error if the two definitions have
4050  // different initializers?
4051  return Importer.MapImported(D, FoundDef);
4052 
4053  // The VarDecl in the "From" context has an initializer, but in the
4054  // "To" context we already have an initializer.
4055  const VarDecl *FoundDInit = nullptr;
4056  if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
4057  // FIXME Diagnose ODR error if the two initializers are different?
4058  return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4059 
4060  FoundByLookup = FoundVar;
4061  break;
4062  }
4063 
4064  const ArrayType *FoundArray
4065  = Importer.getToContext().getAsArrayType(FoundVar->getType());
4066  const ArrayType *TArray
4067  = Importer.getToContext().getAsArrayType(D->getType());
4068  if (FoundArray && TArray) {
4069  if (isa<IncompleteArrayType>(FoundArray) &&
4070  isa<ConstantArrayType>(TArray)) {
4071  // Import the type.
4072  if (auto TyOrErr = import(D->getType()))
4073  FoundVar->setType(*TyOrErr);
4074  else
4075  return TyOrErr.takeError();
4076 
4077  FoundByLookup = FoundVar;
4078  break;
4079  } else if (isa<IncompleteArrayType>(TArray) &&
4080  isa<ConstantArrayType>(FoundArray)) {
4081  FoundByLookup = FoundVar;
4082  break;
4083  }
4084  }
4085 
4086  Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4087  << Name << D->getType() << FoundVar->getType();
4088  Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4089  << FoundVar->getType();
4090  ConflictingDecls.push_back(FoundDecl);
4091  }
4092  }
4093 
4094  if (!ConflictingDecls.empty()) {
4095  ExpectedName NameOrErr = Importer.HandleNameConflict(
4096  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4097  if (NameOrErr)
4098  Name = NameOrErr.get();
4099  else
4100  return NameOrErr.takeError();
4101  }
4102  }
4103 
4104  Error Err = Error::success();
4105  auto ToType = importChecked(Err, D->getType());
4106  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4107  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4108  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4109  if (Err)
4110  return std::move(Err);
4111 
4112  VarDecl *ToVar;
4113  if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
4114  SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4115  if (Error Err =
4116  ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
4117  return std::move(Err);
4118  DecompositionDecl *ToDecomp;
4119  if (GetImportedOrCreateDecl(
4120  ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4121  Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4122  return ToDecomp;
4123  ToVar = ToDecomp;
4124  } else {
4125  // Create the imported variable.
4126  if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4127  ToInnerLocStart, Loc,
4128  Name.getAsIdentifierInfo(), ToType,
4129  ToTypeSourceInfo, D->getStorageClass()))
4130  return ToVar;
4131  }
4132 
4133  ToVar->setTSCSpec(D->getTSCSpec());
4134  ToVar->setQualifierInfo(ToQualifierLoc);
4135  ToVar->setAccess(D->getAccess());
4136  ToVar->setLexicalDeclContext(LexicalDC);
4137 
4138  if (FoundByLookup) {
4139  auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4140  ToVar->setPreviousDecl(Recent);
4141  }
4142 
4143  // Import the described template, if any.
4144  if (D->getDescribedVarTemplate()) {
4145  auto ToVTOrErr = import(D->getDescribedVarTemplate());
4146  if (!ToVTOrErr)
4147  return ToVTOrErr.takeError();
4148  }
4149 
4150  if (Error Err = ImportInitializer(D, ToVar))
4151  return std::move(Err);
4152 
4153  if (D->isConstexpr())
4154  ToVar->setConstexpr(true);
4155 
4156  addDeclToContexts(D, ToVar);
4157 
4158  // Import the rest of the chain. I.e. import all subsequent declarations.
4159  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4160  ExpectedDecl RedeclOrErr = import(*RedeclIt);
4161  if (!RedeclOrErr)
4162  return RedeclOrErr.takeError();
4163  }
4164 
4165  return ToVar;
4166 }
4167 
4169  // Parameters are created in the translation unit's context, then moved
4170  // into the function declaration's context afterward.
4171  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4172 
4173  Error Err = Error::success();
4174  auto ToDeclName = importChecked(Err, D->getDeclName());
4175  auto ToLocation = importChecked(Err, D->getLocation());
4176  auto ToType = importChecked(Err, D->getType());
4177  if (Err)
4178  return std::move(Err);
4179 
4180  // Create the imported parameter.
4181  ImplicitParamDecl *ToParm = nullptr;
4182  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4183  ToLocation, ToDeclName.getAsIdentifierInfo(),
4184  ToType, D->getParameterKind()))
4185  return ToParm;
4186  return ToParm;
4187 }
4188 
4190  const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4191  ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4192  ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4193 
4194  if (FromParam->hasUninstantiatedDefaultArg()) {
4195  if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4196  ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4197  else
4198  return ToDefArgOrErr.takeError();
4199  } else if (FromParam->hasUnparsedDefaultArg()) {
4200  ToParam->setUnparsedDefaultArg();
4201  } else if (FromParam->hasDefaultArg()) {
4202  if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4203  ToParam->setDefaultArg(*ToDefArgOrErr);
4204  else
4205  return ToDefArgOrErr.takeError();
4206  }
4207 
4208  return Error::success();
4209 }
4210 
4213  Error Err = Error::success();
4214  CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor());
4215  ConstructorUsingShadowDecl *ToShadow =
4216  importChecked(Err, From.getShadowDecl());
4217  if (Err)
4218  return std::move(Err);
4219  return InheritedConstructor(ToShadow, ToBaseCtor);
4220 }
4221 
4223  // Parameters are created in the translation unit's context, then moved
4224  // into the function declaration's context afterward.
4225  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4226 
4227  Error Err = Error::success();
4228  auto ToDeclName = importChecked(Err, D->getDeclName());
4229  auto ToLocation = importChecked(Err, D->getLocation());
4230  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4231  auto ToType = importChecked(Err, D->getType());
4232  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4233  if (Err)
4234  return std::move(Err);
4235 
4236  ParmVarDecl *ToParm;
4237  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4238  ToInnerLocStart, ToLocation,
4239  ToDeclName.getAsIdentifierInfo(), ToType,
4240  ToTypeSourceInfo, D->getStorageClass(),
4241  /*DefaultArg*/ nullptr))
4242  return ToParm;
4243 
4244  // Set the default argument. It should be no problem if it was already done.
4245  // Do not import the default expression before GetImportedOrCreateDecl call
4246  // to avoid possible infinite import loop because circular dependency.
4247  if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4248  return std::move(Err);
4249 
4250  if (D->isObjCMethodParameter()) {
4253  } else {
4254  ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4255  D->getFunctionScopeIndex());
4256  }
4257 
4258  return ToParm;
4259 }
4260 
4262  // Import the major distinguishing characteristics of a method.
4263  DeclContext *DC, *LexicalDC;
4264  DeclarationName Name;
4265  SourceLocation Loc;
4266  NamedDecl *ToD;
4267  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4268  return std::move(Err);
4269  if (ToD)
4270  return ToD;
4271 
4272  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4273  for (auto *FoundDecl : FoundDecls) {
4274  if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4275  if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4276  continue;
4277 
4278  // Check return types.
4279  if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4280  FoundMethod->getReturnType())) {
4281  Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4282  << D->isInstanceMethod() << Name << D->getReturnType()
4283  << FoundMethod->getReturnType();
4284  Importer.ToDiag(FoundMethod->getLocation(),
4285  diag::note_odr_objc_method_here)
4286  << D->isInstanceMethod() << Name;
4287 
4288  return make_error<ASTImportError>(ASTImportError::NameConflict);
4289  }
4290 
4291  // Check the number of parameters.
4292  if (D->param_size() != FoundMethod->param_size()) {
4293  Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4294  << D->isInstanceMethod() << Name
4295  << D->param_size() << FoundMethod->param_size();
4296  Importer.ToDiag(FoundMethod->getLocation(),
4297  diag::note_odr_objc_method_here)
4298  << D->isInstanceMethod() << Name;
4299 
4300  return make_error<ASTImportError>(ASTImportError::NameConflict);
4301  }
4302 
4303  // Check parameter types.
4305  PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4306  P != PEnd; ++P, ++FoundP) {
4307  if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4308  (*FoundP)->getType())) {
4309  Importer.FromDiag((*P)->getLocation(),
4310  diag::warn_odr_objc_method_param_type_inconsistent)
4311  << D->isInstanceMethod() << Name
4312  << (*P)->getType() << (*FoundP)->getType();
4313  Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4314  << (*FoundP)->getType();
4315 
4316  return make_error<ASTImportError>(ASTImportError::NameConflict);
4317  }
4318  }
4319 
4320  // Check variadic/non-variadic.
4321  // Check the number of parameters.
4322  if (D->isVariadic() != FoundMethod->isVariadic()) {
4323  Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4324  << D->isInstanceMethod() << Name;
4325  Importer.ToDiag(FoundMethod->getLocation(),
4326  diag::note_odr_objc_method_here)
4327  << D->isInstanceMethod() << Name;
4328 
4329  return make_error<ASTImportError>(ASTImportError::NameConflict);
4330  }
4331 
4332  // FIXME: Any other bits we need to merge?
4333  return Importer.MapImported(D, FoundMethod);
4334  }
4335  }
4336 
4337  Error Err = Error::success();
4338  auto ToEndLoc = importChecked(Err, D->getEndLoc());
4339  auto ToReturnType = importChecked(Err, D->getReturnType());
4340  auto ToReturnTypeSourceInfo =
4342  if (Err)
4343  return std::move(Err);
4344 
4345  ObjCMethodDecl *ToMethod;
4346  if (GetImportedOrCreateDecl(
4347  ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4348  Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4352  return ToMethod;
4353 
4354  // FIXME: When we decide to merge method definitions, we'll need to
4355  // deal with implicit parameters.
4356 
4357  // Import the parameters
4359  for (auto *FromP : D->parameters()) {
4360  if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4361  ToParams.push_back(*ToPOrErr);
4362  else
4363  return ToPOrErr.takeError();
4364  }
4365 
4366  // Set the parameters.
4367  for (auto *ToParam : ToParams) {
4368  ToParam->setOwningFunction(ToMethod);
4369  ToMethod->addDeclInternal(ToParam);
4370  }
4371 
4372  SmallVector<SourceLocation, 12> FromSelLocs;
4373  D->getSelectorLocs(FromSelLocs);
4374  SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4375  if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4376  return std::move(Err);
4377 
4378  ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4379 
4380  ToMethod->setLexicalDeclContext(LexicalDC);
4381  LexicalDC->addDeclInternal(ToMethod);
4382 
4383  // Implicit params are declared when Sema encounters the definition but this
4384  // never happens when the method is imported. Manually declare the implicit
4385  // params now that the MethodDecl knows its class interface.
4386  if (D->getSelfDecl())
4387  ToMethod->createImplicitParams(Importer.getToContext(),
4388  ToMethod->getClassInterface());
4389 
4390  return ToMethod;
4391 }
4392 
4394  // Import the major distinguishing characteristics of a category.
4395  DeclContext *DC, *LexicalDC;
4396  DeclarationName Name;
4397  SourceLocation Loc;
4398  NamedDecl *ToD;
4399  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4400  return std::move(Err);
4401  if (ToD)
4402  return ToD;
4403 
4404  Error Err = Error::success();
4405  auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4406  auto ToLocation = importChecked(Err, D->getLocation());
4407  auto ToColonLoc = importChecked(Err, D->getColonLoc());
4408  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4409  if (Err)
4410  return std::move(Err);
4411 
4412  ObjCTypeParamDecl *Result;
4413  if (GetImportedOrCreateDecl(
4414  Result, D, Importer.getToContext(), DC, D->getVariance(),
4415  ToVarianceLoc, D->getIndex(),
4416  ToLocation, Name.getAsIdentifierInfo(),
4417  ToColonLoc, ToTypeSourceInfo))
4418  return Result;
4419 
4420  Result->setLexicalDeclContext(LexicalDC);
4421  return Result;
4422 }
4423 
4425  // Import the major distinguishing characteristics of a category.
4426  DeclContext *DC, *LexicalDC;
4427  DeclarationName Name;
4428  SourceLocation Loc;
4429  NamedDecl *ToD;
4430  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4431  return std::move(Err);
4432  if (ToD)
4433  return ToD;
4434 
4435  ObjCInterfaceDecl *ToInterface;
4436  if (Error Err = importInto(ToInterface, D->getClassInterface()))
4437  return std::move(Err);
4438 
4439  // Determine if we've already encountered this category.
4440  ObjCCategoryDecl *MergeWithCategory
4441  = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4442  ObjCCategoryDecl *ToCategory = MergeWithCategory;
4443  if (!ToCategory) {
4444 
4445  Error Err = Error::success();
4446  auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4447  auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4448  auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4449  auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4450  if (Err)
4451  return std::move(Err);
4452 
4453  if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4454  ToAtStartLoc, Loc,
4455  ToCategoryNameLoc,
4456  Name.getAsIdentifierInfo(), ToInterface,
4457  /*TypeParamList=*/nullptr,
4458  ToIvarLBraceLoc,
4459  ToIvarRBraceLoc))
4460  return ToCategory;
4461 
4462  ToCategory->setLexicalDeclContext(LexicalDC);
4463  LexicalDC->addDeclInternal(ToCategory);
4464  // Import the type parameter list after MapImported, to avoid
4465  // loops when bringing in their DeclContext.
4466  if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4467  ToCategory->setTypeParamList(*PListOrErr);
4468  else
4469  return PListOrErr.takeError();
4470 
4471  // Import protocols
4473  SmallVector<SourceLocation, 4> ProtocolLocs;
4475  = D->protocol_loc_begin();
4477  FromProtoEnd = D->protocol_end();
4478  FromProto != FromProtoEnd;
4479  ++FromProto, ++FromProtoLoc) {
4480  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4481  Protocols.push_back(*ToProtoOrErr);
4482  else
4483  return ToProtoOrErr.takeError();
4484 
4485  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4486  ProtocolLocs.push_back(*ToProtoLocOrErr);
4487  else
4488  return ToProtoLocOrErr.takeError();
4489  }
4490 
4491  // FIXME: If we're merging, make sure that the protocol list is the same.
4492  ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4493  ProtocolLocs.data(), Importer.getToContext());
4494 
4495  } else {
4496  Importer.MapImported(D, ToCategory);
4497  }
4498 
4499  // Import all of the members of this category.
4500  if (Error Err = ImportDeclContext(D))
4501  return std::move(Err);
4502 
4503  // If we have an implementation, import it as well.
4504  if (D->getImplementation()) {
4505  if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4506  import(D->getImplementation()))
4507  ToCategory->setImplementation(*ToImplOrErr);
4508  else
4509  return ToImplOrErr.takeError();
4510  }
4511 
4512  return ToCategory;
4513 }
4514 
4517  if (To->getDefinition()) {
4519  if (Error Err = ImportDeclContext(From))
4520  return Err;
4521  return Error::success();
4522  }
4523 
4524  // Start the protocol definition
4525  To->startDefinition();
4526 
4527  // Import protocols
4529  SmallVector<SourceLocation, 4> ProtocolLocs;
4531  From->protocol_loc_begin();
4532  for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4533  FromProtoEnd = From->protocol_end();
4534  FromProto != FromProtoEnd;
4535  ++FromProto, ++FromProtoLoc) {
4536  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4537  Protocols.push_back(*ToProtoOrErr);
4538  else
4539  return ToProtoOrErr.takeError();
4540 
4541  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4542  ProtocolLocs.push_back(*ToProtoLocOrErr);
4543  else
4544  return ToProtoLocOrErr.takeError();
4545 
4546  }
4547 
4548  // FIXME: If we're merging, make sure that the protocol list is the same.
4549  To->setProtocolList(Protocols.data(), Protocols.size(),
4550  ProtocolLocs.data(), Importer.getToContext());
4551 
4553  // Import all of the members of this protocol.
4554  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4555  return Err;
4556  }
4557  return Error::success();
4558 }
4559 
4561  // If this protocol has a definition in the translation unit we're coming
4562  // from, but this particular declaration is not that definition, import the
4563  // definition and map to that.
4564  ObjCProtocolDecl *Definition = D->getDefinition();
4565  if (Definition && Definition != D) {
4566  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4567  return Importer.MapImported(D, *ImportedDefOrErr);
4568  else
4569  return ImportedDefOrErr.takeError();
4570  }
4571 
4572  // Import the major distinguishing characteristics of a protocol.
4573  DeclContext *DC, *LexicalDC;
4574  DeclarationName Name;
4575  SourceLocation Loc;
4576  NamedDecl *ToD;
4577  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4578  return std::move(Err);
4579  if (ToD)
4580  return ToD;
4581 
4582  ObjCProtocolDecl *MergeWithProtocol = nullptr;
4583  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4584  for (auto *FoundDecl : FoundDecls) {
4586  continue;
4587 
4588  if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4589  break;
4590  }
4591 
4592  ObjCProtocolDecl *ToProto = MergeWithProtocol;
4593  if (!ToProto) {
4594  auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4595  if (!ToAtBeginLocOrErr)
4596  return ToAtBeginLocOrErr.takeError();
4597 
4598  if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4599  Name.getAsIdentifierInfo(), Loc,
4600  *ToAtBeginLocOrErr,
4601  /*PrevDecl=*/nullptr))
4602  return ToProto;
4603  ToProto->setLexicalDeclContext(LexicalDC);
4604  LexicalDC->addDeclInternal(ToProto);
4605  }
4606 
4607  Importer.MapImported(D, ToProto);
4608 
4610  if (Error Err = ImportDefinition(D, ToProto))
4611  return std::move(Err);
4612 
4613  return ToProto;
4614 }
4615 
4617  DeclContext *DC, *LexicalDC;
4618  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4619  return std::move(Err);
4620 
4621  ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4622  if (!ExternLocOrErr)
4623  return ExternLocOrErr.takeError();
4624 
4625  ExpectedSLoc LangLocOrErr = import(D->getLocation());
4626  if (!LangLocOrErr)
4627  return LangLocOrErr.takeError();
4628 
4629  bool HasBraces = D->hasBraces();
4630 
4631  LinkageSpecDecl *ToLinkageSpec;
4632  if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4633  *ExternLocOrErr, *LangLocOrErr,
4634  D->getLanguage(), HasBraces))
4635  return ToLinkageSpec;
4636 
4637  if (HasBraces) {
4638  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4639  if (!RBraceLocOrErr)
4640  return RBraceLocOrErr.takeError();
4641  ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4642  }
4643 
4644  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4645  LexicalDC->addDeclInternal(ToLinkageSpec);
4646 
4647  return ToLinkageSpec;
4648 }
4649 
4651  BaseUsingDecl *ToSI) {
4652  for (UsingShadowDecl *FromShadow : D->shadows()) {
4653  if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4654  ToSI->addShadowDecl(*ToShadowOrErr);
4655  else
4656  // FIXME: We return error here but the definition is already created
4657  // and available with lookups. How to fix this?..
4658  return ToShadowOrErr.takeError();
4659  }
4660  return ToSI;
4661 }
4662 
4664  DeclContext *DC, *LexicalDC;
4665  DeclarationName Name;
4666  SourceLocation Loc;
4667  NamedDecl *ToD = nullptr;
4668  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4669  return std::move(Err);
4670  if (ToD)
4671  return ToD;
4672 
4673  Error Err = Error::success();
4674  auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4675  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4676  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4677  if (Err)
4678  return std::move(Err);
4679 
4680  DeclarationNameInfo NameInfo(Name, ToLoc);
4681  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4682  return std::move(Err);
4683 
4684  UsingDecl *ToUsing;
4685  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4686  ToUsingLoc, ToQualifierLoc, NameInfo,
4687  D->hasTypename()))
4688  return ToUsing;
4689 
4690  ToUsing->setLexicalDeclContext(LexicalDC);
4691  LexicalDC->addDeclInternal(ToUsing);
4692 
4693  if (NamedDecl *FromPattern =
4695  if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4697  ToUsing, *ToPatternOrErr);
4698  else
4699  return ToPatternOrErr.takeError();
4700  }
4701 
4702  return ImportUsingShadowDecls(D, ToUsing);
4703 }
4704 
4706  DeclContext *DC, *LexicalDC;
4707  DeclarationName Name;
4708  SourceLocation Loc;
4709  NamedDecl *ToD = nullptr;
4710  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4711  return std::move(Err);
4712  if (ToD)
4713  return ToD;
4714 
4715  Error Err = Error::success();
4716  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4717  auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
4718  auto ToEnumDecl = importChecked(Err, D->getEnumDecl());
4719  if (Err)
4720  return std::move(Err);
4721 
4722  UsingEnumDecl *ToUsingEnum;
4723  if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
4724  ToUsingLoc, ToEnumLoc, Loc, ToEnumDecl))
4725  return ToUsingEnum;
4726 
4727  ToUsingEnum->setLexicalDeclContext(LexicalDC);
4728  LexicalDC->addDeclInternal(ToUsingEnum);
4729 
4730  if (UsingEnumDecl *FromPattern =
4732  if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
4733  Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
4734  *ToPatternOrErr);
4735  else
4736  return ToPatternOrErr.takeError();
4737  }
4738 
4739  return ImportUsingShadowDecls(D, ToUsingEnum);
4740 }
4741 
4743  DeclContext *DC, *LexicalDC;
4744  DeclarationName Name;
4745  SourceLocation Loc;
4746  NamedDecl *ToD = nullptr;
4747  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4748  return std::move(Err);
4749  if (ToD)
4750  return ToD;
4751 
4752  Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
4753  if (!ToIntroducerOrErr)
4754  return ToIntroducerOrErr.takeError();
4755 
4756  Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4757  if (!ToTargetOrErr)
4758  return ToTargetOrErr.takeError();
4759 
4760  UsingShadowDecl *ToShadow;
4761  if (auto *FromConstructorUsingShadow =
4762  dyn_cast<ConstructorUsingShadowDecl>(D)) {
4763  Error Err = Error::success();
4765  Err, FromConstructorUsingShadow->getNominatedBaseClassShadowDecl());
4766  if (Err)
4767  return std::move(Err);
4768  // The 'Target' parameter of ConstructorUsingShadowDecl constructor
4769  // is really the "NominatedBaseClassShadowDecl" value if it exists
4770  // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl).
4771  // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to
4772  // get the correct values.
4773  if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>(
4774  ToShadow, D, Importer.getToContext(), DC, Loc,
4775  cast<UsingDecl>(*ToIntroducerOrErr),
4776  Nominated ? Nominated : *ToTargetOrErr,
4777  FromConstructorUsingShadow->constructsVirtualBase()))
4778  return ToShadow;
4779  } else {
4780  if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4781  Name, *ToIntroducerOrErr, *ToTargetOrErr))
4782  return ToShadow;
4783  }
4784 
4785  ToShadow->setLexicalDeclContext(LexicalDC);
4786  ToShadow->setAccess(D->getAccess());
4787 
4788  if (UsingShadowDecl *FromPattern =
4790  if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4792  ToShadow, *ToPatternOrErr);
4793  else
4794  // FIXME: We return error here but the definition is already created
4795  // and available with lookups. How to fix this?..
4796  return ToPatternOrErr.takeError();
4797  }
4798 
4799  LexicalDC->addDeclInternal(ToShadow);
4800 
4801  return ToShadow;
4802 }
4803 
4805  DeclContext *DC, *LexicalDC;
4806  DeclarationName Name;
4807  SourceLocation Loc;
4808  NamedDecl *ToD = nullptr;
4809  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4810  return std::move(Err);
4811  if (ToD)
4812  return ToD;
4813 
4814  auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4815  if (!ToComAncestorOrErr)
4816  return ToComAncestorOrErr.takeError();
4817 
4818  Error Err = Error::success();
4819  auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
4820  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4821  auto ToNamespaceKeyLocation =
4823  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4824  auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
4825  if (Err)
4826  return std::move(Err);
4827 
4828  UsingDirectiveDecl *ToUsingDir;
4829  if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4830  ToUsingLoc,
4831  ToNamespaceKeyLocation,
4832  ToQualifierLoc,
4833  ToIdentLocation,
4834  ToNominatedNamespace, *ToComAncestorOrErr))
4835  return ToUsingDir;
4836 
4837  ToUsingDir->setLexicalDeclContext(LexicalDC);
4838  LexicalDC->addDeclInternal(ToUsingDir);
4839 
4840  return ToUsingDir;
4841 }
4842 
4844  DeclContext *DC, *LexicalDC;
4845  DeclarationName Name;
4846  SourceLocation Loc;
4847  NamedDecl *ToD = nullptr;
4848  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4849  return std::move(Err);
4850  if (ToD)
4851  return ToD;
4852 
4853  auto ToInstantiatedFromUsingOrErr =
4854  Importer.Import(D->getInstantiatedFromUsingDecl());
4855  if (!ToInstantiatedFromUsingOrErr)
4856  return ToInstantiatedFromUsingOrErr.takeError();
4857  SmallVector<NamedDecl *, 4> Expansions(D->expansions().size());
4858  if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin()))
4859  return std::move(Err);
4860 
4861  UsingPackDecl *ToUsingPack;
4862  if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
4863  cast<NamedDecl>(*ToInstantiatedFromUsingOrErr),
4864  Expansions))
4865  return ToUsingPack;
4866 
4867  addDeclToContexts(D, ToUsingPack);
4868 
4869  return ToUsingPack;
4870 }
4871 
4874  DeclContext *DC, *LexicalDC;
4875  DeclarationName Name;
4876  SourceLocation Loc;
4877  NamedDecl *ToD = nullptr;
4878  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4879  return std::move(Err);
4880  if (ToD)
4881  return ToD;
4882 
4883  Error Err = Error::success();
4884  auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4885  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4886  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4887  auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4888  if (Err)
4889  return std::move(Err);
4890 
4891  DeclarationNameInfo NameInfo(Name, ToLoc);
4892  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4893  return std::move(Err);
4894 
4895  UnresolvedUsingValueDecl *ToUsingValue;
4896  if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4897  ToUsingLoc, ToQualifierLoc, NameInfo,
4898  ToEllipsisLoc))
4899  return ToUsingValue;
4900 
4901  ToUsingValue->setAccess(D->getAccess());
4902  ToUsingValue->setLexicalDeclContext(LexicalDC);
4903  LexicalDC->addDeclInternal(ToUsingValue);
4904 
4905  return ToUsingValue;
4906 }
4907 
4910  DeclContext *DC, *LexicalDC;
4911  DeclarationName Name;
4912  SourceLocation Loc;
4913  NamedDecl *ToD = nullptr;
4914  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4915  return std::move(Err);
4916  if (ToD)
4917  return ToD;
4918 
4919  Error Err = Error::success();
4920  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4921  auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
4922  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4923  auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4924  if (Err)
4925  return std::move(Err);
4926 
4927  UnresolvedUsingTypenameDecl *ToUsing;
4928  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4929  ToUsingLoc, ToTypenameLoc,
4930  ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4931  return ToUsing;
4932 
4933  ToUsing->setAccess(D->getAccess());
4934  ToUsing->setLexicalDeclContext(LexicalDC);
4935  LexicalDC->addDeclInternal(ToUsing);
4936 
4937  return ToUsing;
4938 }
4939 
4941  Decl* ToD = nullptr;
4942  switch (D->getBuiltinTemplateKind()) {
4944  ToD = Importer.getToContext().getMakeIntegerSeqDecl();
4945  break;
4947  ToD = Importer.getToContext().getTypePackElementDecl();
4948  break;
4949  }
4950  assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
4951  Importer.MapImported(D, ToD);
4952  return ToD;
4953 }
4954 
4957  if (To->getDefinition()) {
4958  // Check consistency of superclass.
4959  ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4960  if (FromSuper) {
4961  if (auto FromSuperOrErr = import(FromSuper))
4962  FromSuper = *FromSuperOrErr;
4963  else
4964  return FromSuperOrErr.takeError();
4965  }
4966 
4967  ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4968  if ((bool)FromSuper != (bool)ToSuper ||
4969  (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4970  Importer.ToDiag(To->getLocation(),
4971  diag::warn_odr_objc_superclass_inconsistent)
4972  << To->getDeclName();
4973  if (ToSuper)
4974  Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4975  << To->getSuperClass()->getDeclName();
4976  else
4977  Importer.ToDiag(To->getLocation(),
4978  diag::note_odr_objc_missing_superclass);
4979  if (From->getSuperClass())
4980  Importer.FromDiag(From->getSuperClassLoc(),
4981  diag::note_odr_objc_superclass)
4982  << From->getSuperClass()->getDeclName();
4983  else
4984  Importer.FromDiag(From->getLocation(),
4985  diag::note_odr_objc_missing_superclass);
4986  }
4987 
4989  if (Error Err = ImportDeclContext(From))
4990  return Err;
4991  return Error::success();
4992  }
4993 
4994  // Start the definition.
4995  To->startDefinition();
4996 
4997  // If this class has a superclass, import it.
4998  if (From->getSuperClass()) {
4999  if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
5000  To->setSuperClass(*SuperTInfoOrErr);
5001  else
5002  return SuperTInfoOrErr.takeError();
5003  }
5004 
5005  // Import protocols
5007  SmallVector<SourceLocation, 4> ProtocolLocs;
5009  From->protocol_loc_begin();
5010 
5011  for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
5012  FromProtoEnd = From->protocol_end();
5013  FromProto != FromProtoEnd;
5014  ++FromProto, ++FromProtoLoc) {
5015  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
5016  Protocols.push_back(*ToProtoOrErr);
5017  else
5018  return ToProtoOrErr.takeError();
5019 
5020  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
5021  ProtocolLocs.push_back(*ToProtoLocOrErr);
5022  else
5023  return ToProtoLocOrErr.takeError();
5024 
5025  }
5026 
5027  // FIXME: If we're merging, make sure that the protocol list is the same.
5028  To->setProtocolList(Protocols.data(), Protocols.size(),
5029  ProtocolLocs.data(), Importer.getToContext());
5030 
5031  // Import categories. When the categories themselves are imported, they'll
5032  // hook themselves into this interface.
5033  for (auto *Cat : From->known_categories()) {
5034  auto ToCatOrErr = import(Cat);
5035  if (!ToCatOrErr)
5036  return ToCatOrErr.takeError();
5037  }
5038 
5039  // If we have an @implementation, import it as well.
5040  if (From->getImplementation()) {
5041  if (Expected<ObjCImplementationDecl *> ToImplOrErr =
5042  import(From->getImplementation()))
5043  To->setImplementation(*ToImplOrErr);
5044  else
5045  return ToImplOrErr.takeError();
5046  }
5047 
5048  // Import all of the members of this class.
5049  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
5050  return Err;
5051 
5052  return Error::success();
5053 }
5054 
5057  if (!list)
5058  return nullptr;
5059 
5061  for (auto *fromTypeParam : *list) {
5062  if (auto toTypeParamOrErr = import(fromTypeParam))
5063  toTypeParams.push_back(*toTypeParamOrErr);
5064  else
5065  return toTypeParamOrErr.takeError();
5066  }
5067 
5068  auto LAngleLocOrErr = import(list->getLAngleLoc());
5069  if (!LAngleLocOrErr)
5070  return LAngleLocOrErr.takeError();
5071 
5072  auto RAngleLocOrErr = import(list->getRAngleLoc());
5073  if (!RAngleLocOrErr)
5074  return RAngleLocOrErr.takeError();
5075 
5076  return ObjCTypeParamList::create(Importer.getToContext(),
5077  *LAngleLocOrErr,
5078  toTypeParams,
5079  *RAngleLocOrErr);
5080 }
5081 
5083  // If this class has a definition in the translation unit we're coming from,
5084  // but this particular declaration is not that definition, import the
5085  // definition and map to that.
5086  ObjCInterfaceDecl *Definition = D->getDefinition();
5087  if (Definition && Definition != D) {
5088  if (ExpectedDecl ImportedDefOrErr = import(Definition))
5089  return Importer.MapImported(D, *ImportedDefOrErr);
5090  else
5091  return ImportedDefOrErr.takeError();
5092  }
5093 
5094  // Import the major distinguishing characteristics of an @interface.
5095  DeclContext *DC, *LexicalDC;
5096  DeclarationName Name;
5097  SourceLocation Loc;
5098  NamedDecl *ToD;
5099  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5100  return std::move(Err);
5101  if (ToD)
5102  return ToD;
5103 
5104  // Look for an existing interface with the same name.
5105  ObjCInterfaceDecl *MergeWithIface = nullptr;
5106  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5107  for (auto *FoundDecl : FoundDecls) {
5109  continue;
5110 
5111  if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
5112  break;
5113  }
5114 
5115  // Create an interface declaration, if one does not already exist.
5116  ObjCInterfaceDecl *ToIface = MergeWithIface;
5117  if (!ToIface) {
5118  ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
5119  if (!AtBeginLocOrErr)
5120  return AtBeginLocOrErr.takeError();
5121 
5122  if (GetImportedOrCreateDecl(
5123  ToIface, D, Importer.getToContext(), DC,
5124  *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
5125  /*TypeParamList=*/nullptr,
5126  /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
5127  return ToIface;
5128  ToIface->setLexicalDeclContext(LexicalDC);
5129  LexicalDC->addDeclInternal(ToIface);
5130  }
5131  Importer.MapImported(D, ToIface);
5132  // Import the type parameter list after MapImported, to avoid
5133  // loops when bringing in their DeclContext.
5134  if (auto ToPListOrErr =
5136  ToIface->setTypeParamList(*ToPListOrErr);
5137  else
5138  return ToPListOrErr.takeError();
5139 
5141  if (Error Err = ImportDefinition(D, ToIface))
5142  return std::move(Err);
5143 
5144  return ToIface;
5145 }
5146 
5150  if (Error Err = importInto(Category, D->getCategoryDecl()))
5151  return std::move(Err);
5152 
5153  ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5154  if (!ToImpl) {
5155  DeclContext *DC, *LexicalDC;
5156  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5157  return std::move(Err);
5158 
5159  Error Err = Error::success();
5160  auto ToLocation = importChecked(Err, D->getLocation());
5161  auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5162  auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
5163  if (Err)
5164  return std::move(Err);
5165 
5166  if (GetImportedOrCreateDecl(
5167  ToImpl, D, Importer.getToContext(), DC,
5168  Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5169  ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5170  return ToImpl;
5171 
5172  ToImpl->setLexicalDeclContext(LexicalDC);
5173  LexicalDC->addDeclInternal(ToImpl);
5174  Category->setImplementation(ToImpl);
5175  }
5176 
5177  Importer.MapImported(D, ToImpl);
5178  if (Error Err = ImportDeclContext(D))
5179  return std::move(Err);
5180 
5181  return ToImpl;
5182 }
5183 
5186  // Find the corresponding interface.
5187  ObjCInterfaceDecl *Iface;
5188  if (Error Err = importInto(Iface, D->getClassInterface()))
5189  return std::move(Err);
5190 
5191  // Import the superclass, if any.
5192  ObjCInterfaceDecl *Super;
5193  if (Error Err = importInto(Super, D->getSuperClass()))
5194  return std::move(Err);
5195 
5196  ObjCImplementationDecl *Impl = Iface->getImplementation();
5197  if (!Impl) {
5198  // We haven't imported an implementation yet. Create a new @implementation
5199  // now.
5200  DeclContext *DC, *LexicalDC;
5201  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5202  return std::move(Err);
5203 
5204  Error Err = Error::success();
5205  auto ToLocation = importChecked(Err, D->getLocation());
5206  auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5207  auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
5208  auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
5209  auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
5210  if (Err)
5211  return std::move(Err);
5212 
5213  if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5214  DC, Iface, Super,
5215  ToLocation,
5216  ToAtStartLoc,
5217  ToSuperClassLoc,
5218  ToIvarLBraceLoc,
5219  ToIvarRBraceLoc))
5220  return Impl;
5221 
5222  Impl->setLexicalDeclContext(LexicalDC);
5223 
5224  // Associate the implementation with the class it implements.
5225  Iface->setImplementation(Impl);
5226  Importer.MapImported(D, Iface->getImplementation());
5227  } else {
5228  Importer.MapImported(D, Iface->getImplementation());
5229 
5230  // Verify that the existing @implementation has the same superclass.
5231  if ((Super && !Impl->getSuperClass()) ||
5232  (!Super && Impl->getSuperClass()) ||
5233  (Super && Impl->getSuperClass() &&
5235  Impl->getSuperClass()))) {
5236  Importer.ToDiag(Impl->getLocation(),
5237  diag::warn_odr_objc_superclass_inconsistent)
5238  << Iface->getDeclName();
5239  // FIXME: It would be nice to have the location of the superclass
5240  // below.
5241  if (Impl->getSuperClass())
5242  Importer.ToDiag(Impl->getLocation(),
5243  diag::note_odr_objc_superclass)
5244  << Impl->getSuperClass()->getDeclName();
5245  else
5246  Importer.ToDiag(Impl->getLocation(),
5247  diag::note_odr_objc_missing_superclass);
5248  if (D->getSuperClass())
5249  Importer.FromDiag(D->getLocation(),
5250  diag::note_odr_objc_superclass)
5251  << D->getSuperClass()->getDeclName();
5252  else
5253  Importer.FromDiag(D->getLocation(),
5254  diag::note_odr_objc_missing_superclass);
5255 
5256  return make_error<ASTImportError>(ASTImportError::NameConflict);
5257  }
5258  }
5259 
5260  // Import all of the members of this @implementation.
5261  if (Error Err = ImportDeclContext(D))
5262  return std::move(Err);
5263 
5264  return Impl;
5265 }
5266 
5268  // Import the major distinguishing characteristics of an @property.
5269  DeclContext *DC, *LexicalDC;
5270  DeclarationName Name;
5271  SourceLocation Loc;
5272  NamedDecl *ToD;
5273  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5274  return std::move(Err);
5275  if (ToD)
5276  return ToD;
5277 
5278  // Check whether we have already imported this property.
5279  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5280  for (auto *FoundDecl : FoundDecls) {