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