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