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