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