1//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTImporter class which imports AST nodes from one
10// context into another context.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTImporter.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTDiagnostic.h"
17#include "clang/AST/ASTImporterSharedState.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclAccessPair.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"
29#include "clang/AST/DeclarationName.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
32#include "clang/AST/ExprObjC.h"
33#include "clang/AST/ExternalASTSource.h"
34#include "clang/AST/LambdaCapture.h"
35#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/OperationKinds.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"
46#include "clang/AST/UnresolvedSet.h"
47#include "clang/Basic/Builtins.h"
48#include "clang/Basic/ExceptionSpecificationType.h"
49#include "clang/Basic/FileManager.h"
50#include "clang/Basic/IdentifierTable.h"
51#include "clang/Basic/LLVM.h"
52#include "clang/Basic/LangOptions.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "llvm/ADT/APSInt.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/ScopeExit.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MemoryBuffer.h"
65#include <algorithm>
66#include <cassert>
67#include <cstddef>
68#include <memory>
69#include <optional>
70#include <type_traits>
71#include <utility>
72
73namespace clang {
74
75 using llvm::make_error;
76 using llvm::Error;
77 using llvm::Expected;
78 using ExpectedTypePtr = llvm::Expected<const Type *>;
79 using ExpectedType = llvm::Expected<QualType>;
80 using ExpectedStmt = llvm::Expected<Stmt *>;
81 using ExpectedExpr = llvm::Expected<Expr *>;
82 using ExpectedDecl = llvm::Expected<Decl *>;
83 using ExpectedSLoc = llvm::Expected<SourceLocation>;
84 using ExpectedName = llvm::Expected<DeclarationName>;
85
86 std::string ASTImportError::toString() const {
87 // FIXME: Improve error texts.
88 switch (Error) {
89 case NameConflict:
90 return "NameConflict";
91 case UnsupportedConstruct:
92 return "UnsupportedConstruct";
93 case Unknown:
94 return "Unknown error";
95 }
96 llvm_unreachable("Invalid error code.");
97 return "Invalid error code.";
98 }
99
100 void ASTImportError::log(raw_ostream &OS) const { OS << toString(); }
101
102 std::error_code ASTImportError::convertToErrorCode() const {
103 llvm_unreachable("Function not implemented.");
104 }
105
106 char ASTImportError::ID;
107
108 template <class T>
109 SmallVector<Decl *, 2>
110 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
111 SmallVector<Decl *, 2> Redecls;
112 for (auto *R : D->getFirstDecl()->redecls()) {
113 if (R != D->getFirstDecl())
114 Redecls.push_back(Elt: R);
115 }
116 Redecls.push_back(Elt: D->getFirstDecl());
117 std::reverse(first: Redecls.begin(), last: Redecls.end());
118 return Redecls;
119 }
120
121 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
122 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
123 return getCanonicalForwardRedeclChain<FunctionDecl>(D: FD);
124 if (auto *VD = dyn_cast<VarDecl>(Val: D))
125 return getCanonicalForwardRedeclChain<VarDecl>(D: VD);
126 if (auto *TD = dyn_cast<TagDecl>(Val: D))
127 return getCanonicalForwardRedeclChain<TagDecl>(D: TD);
128 llvm_unreachable("Bad declaration kind");
129 }
130
131 void updateFlags(const Decl *From, Decl *To) {
132 // Check if some flags or attrs are new in 'From' and copy into 'To'.
133 // FIXME: Other flags or attrs?
134 if (From->isUsed(CheckUsedAttr: false) && !To->isUsed(CheckUsedAttr: false))
135 To->setIsUsed();
136 }
137
138 /// How to handle import errors that occur when import of a child declaration
139 /// of a DeclContext fails.
140 class ChildErrorHandlingStrategy {
141 /// This context is imported (in the 'from' domain).
142 /// It is nullptr if a non-DeclContext is imported.
143 const DeclContext *const FromDC;
144 /// Ignore import errors of the children.
145 /// If true, the context can be imported successfully if a child
146 /// of it failed to import. Otherwise the import errors of the child nodes
147 /// are accumulated (joined) into the import error object of the parent.
148 /// (Import of a parent can fail in other ways.)
149 bool const IgnoreChildErrors;
150
151 public:
152 ChildErrorHandlingStrategy(const DeclContext *FromDC)
153 : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(Val: FromDC)) {}
154 ChildErrorHandlingStrategy(const Decl *FromD)
155 : FromDC(dyn_cast<DeclContext>(Val: FromD)),
156 IgnoreChildErrors(!isa<TagDecl>(Val: FromD)) {}
157
158 /// Process the import result of a child (of the current declaration).
159 /// \param ResultErr The import error that can be used as result of
160 /// importing the parent. This may be changed by the function.
161 /// \param ChildErr Result of importing a child. Can be success or error.
162 void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
163 if (ChildErr && !IgnoreChildErrors)
164 ResultErr = joinErrors(E1: std::move(ResultErr), E2: std::move(ChildErr));
165 else
166 consumeError(Err: std::move(ChildErr));
167 }
168
169 /// Determine if import failure of a child does not cause import failure of
170 /// its parent.
171 bool ignoreChildErrorOnParent(Decl *FromChildD) const {
172 if (!IgnoreChildErrors || !FromDC)
173 return false;
174 return FromDC->containsDecl(D: FromChildD);
175 }
176 };
177
178 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
179 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
180 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
181 ASTImporter &Importer;
182
183 // Use this instead of Importer.importInto .
184 template <typename ImportT>
185 [[nodiscard]] Error importInto(ImportT &To, const ImportT &From) {
186 return Importer.importInto(To, From);
187 }
188
189 // Use this to import pointers of specific type.
190 template <typename ImportT>
191 [[nodiscard]] Error importInto(ImportT *&To, ImportT *From) {
192 auto ToOrErr = Importer.Import(From);
193 if (ToOrErr)
194 To = cast_or_null<ImportT>(*ToOrErr);
195 return ToOrErr.takeError();
196 }
197
198 // Call the import function of ASTImporter for a baseclass of type `T` and
199 // cast the return value to `T`.
200 template <typename T>
201 auto import(T *From)
202 -> std::conditional_t<std::is_base_of_v<Type, T>, Expected<const T *>,
203 Expected<T *>> {
204 auto ToOrErr = Importer.Import(From);
205 if (!ToOrErr)
206 return ToOrErr.takeError();
207 return cast_or_null<T>(*ToOrErr);
208 }
209
210 template <typename T>
211 auto import(const T *From) {
212 return import(const_cast<T *>(From));
213 }
214
215 // Call the import function of ASTImporter for type `T`.
216 template <typename T>
217 Expected<T> import(const T &From) {
218 return Importer.Import(From);
219 }
220
221 // Import an std::optional<T> by importing the contained T, if any.
222 template <typename T>
223 Expected<std::optional<T>> import(std::optional<T> From) {
224 if (!From)
225 return std::nullopt;
226 return import(*From);
227 }
228
229 ExplicitSpecifier importExplicitSpecifier(Error &Err,
230 ExplicitSpecifier ESpec);
231
232 // Wrapper for an overload set.
233 template <typename ToDeclT> struct CallOverloadedCreateFun {
234 template <typename... Args> decltype(auto) operator()(Args &&... args) {
235 return ToDeclT::Create(std::forward<Args>(args)...);
236 }
237 };
238
239 // Always use these functions to create a Decl during import. There are
240 // certain tasks which must be done after the Decl was created, e.g. we
241 // must immediately register that as an imported Decl. The parameter `ToD`
242 // will be set to the newly created Decl or if had been imported before
243 // then to the already imported Decl. Returns a bool value set to true if
244 // the `FromD` had been imported before.
245 template <typename ToDeclT, typename FromDeclT, typename... Args>
246 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
247 Args &&...args) {
248 // There may be several overloads of ToDeclT::Create. We must make sure
249 // to call the one which would be chosen by the arguments, thus we use a
250 // wrapper for the overload set.
251 CallOverloadedCreateFun<ToDeclT> OC;
252 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
253 std::forward<Args>(args)...);
254 }
255 // Use this overload if a special Type is needed to be created. E.g if we
256 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
257 // then:
258 // TypedefNameDecl *ToTypedef;
259 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
260 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
261 typename... Args>
262 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
263 Args &&...args) {
264 CallOverloadedCreateFun<NewDeclT> OC;
265 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
266 std::forward<Args>(args)...);
267 }
268 // Use this version if a special create function must be
269 // used, e.g. CXXRecordDecl::CreateLambda .
270 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
271 typename... Args>
272 [[nodiscard]] bool
273 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
274 FromDeclT *FromD, Args &&...args) {
275 if (Importer.getImportDeclErrorIfAny(FromD)) {
276 ToD = nullptr;
277 return true; // Already imported but with error.
278 }
279 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
280 if (ToD)
281 return true; // Already imported.
282 ToD = CreateFun(std::forward<Args>(args)...);
283 // Keep track of imported Decls.
284 Importer.RegisterImportedDecl(FromD, ToD);
285 Importer.SharedState->markAsNewDecl(ToD);
286 InitializeImportedDecl(FromD, ToD);
287 return false; // A new Decl is created.
288 }
289
290 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
291 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
292 if (FromD->isUsed())
293 ToD->setIsUsed();
294 if (FromD->isImplicit())
295 ToD->setImplicit();
296 }
297
298 // Check if we have found an existing definition. Returns with that
299 // definition if yes, otherwise returns null.
300 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
301 const FunctionDecl *Definition = nullptr;
302 if (D->doesThisDeclarationHaveABody() &&
303 FoundFunction->hasBody(Definition))
304 return Importer.MapImported(From: D, To: const_cast<FunctionDecl *>(Definition));
305 return nullptr;
306 }
307
308 void addDeclToContexts(Decl *FromD, Decl *ToD) {
309 if (Importer.isMinimalImport()) {
310 // In minimal import case the decl must be added even if it is not
311 // contained in original context, for LLDB compatibility.
312 // FIXME: Check if a better solution is possible.
313 if (!FromD->getDescribedTemplate() &&
314 FromD->getFriendObjectKind() == Decl::FOK_None)
315 ToD->getLexicalDeclContext()->addDeclInternal(D: ToD);
316 return;
317 }
318
319 DeclContext *FromDC = FromD->getDeclContext();
320 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
321 DeclContext *ToDC = ToD->getDeclContext();
322 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
323
324 bool Visible = false;
325 if (FromDC->containsDeclAndLoad(D: FromD)) {
326 ToDC->addDeclInternal(D: ToD);
327 Visible = true;
328 }
329 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(D: FromD)) {
330 ToLexicalDC->addDeclInternal(D: ToD);
331 Visible = true;
332 }
333
334 // If the Decl was added to any context, it was made already visible.
335 // Otherwise it is still possible that it should be visible.
336 if (!Visible) {
337 if (auto *FromNamed = dyn_cast<NamedDecl>(Val: FromD)) {
338 auto *ToNamed = cast<NamedDecl>(Val: ToD);
339 DeclContextLookupResult FromLookup =
340 FromDC->lookup(Name: FromNamed->getDeclName());
341 if (llvm::is_contained(Range&: FromLookup, Element: FromNamed))
342 ToDC->makeDeclVisibleInContext(D: ToNamed);
343 }
344 }
345 }
346
347 void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
348 DeclContext *OldDC) {
349 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
350 if (!LT)
351 return;
352
353 for (NamedDecl *TP : Params)
354 LT->update(ND: TP, OldDC);
355 }
356
357 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
358 updateLookupTableForTemplateParameters(
359 Params, OldDC: Importer.getToContext().getTranslationUnitDecl());
360 }
361
362 public:
363 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
364
365 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
366 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
367 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
368
369 // Importing types
370 ExpectedType VisitType(const Type *T);
371#define TYPE(Class, Base) \
372 ExpectedType Visit##Class##Type(const Class##Type *T);
373#include "clang/AST/TypeNodes.inc"
374
375 // Importing declarations
376 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
377 SourceLocation &Loc);
378 Error ImportDeclParts(
379 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
380 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
381 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
382 Error ImportDeclarationNameLoc(
383 const DeclarationNameInfo &From, DeclarationNameInfo &To);
384 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
385 Error ImportDeclContext(
386 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
387 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
388
389 Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To);
390 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
391 Expected<APValue> ImportAPValue(const APValue &FromValue);
392
393 using Designator = DesignatedInitExpr::Designator;
394
395 /// What we should import from the definition.
396 enum ImportDefinitionKind {
397 /// Import the default subset of the definition, which might be
398 /// nothing (if minimal import is set) or might be everything (if minimal
399 /// import is not set).
400 IDK_Default,
401 /// Import everything.
402 IDK_Everything,
403 /// Import only the bare bones needed to establish a valid
404 /// DeclContext.
405 IDK_Basic
406 };
407
408 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
409 return IDK == IDK_Everything ||
410 (IDK == IDK_Default && !Importer.isMinimalImport());
411 }
412
413 Error ImportInitializer(VarDecl *From, VarDecl *To);
414 Error ImportDefinition(
415 RecordDecl *From, RecordDecl *To,
416 ImportDefinitionKind Kind = IDK_Default);
417 Error ImportDefinition(
418 EnumDecl *From, EnumDecl *To,
419 ImportDefinitionKind Kind = IDK_Default);
420 Error ImportDefinition(
421 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
422 ImportDefinitionKind Kind = IDK_Default);
423 Error ImportDefinition(
424 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
425 ImportDefinitionKind Kind = IDK_Default);
426 Error ImportTemplateArguments(ArrayRef<TemplateArgument> FromArgs,
427 SmallVectorImpl<TemplateArgument> &ToArgs);
428 Expected<TemplateArgument>
429 ImportTemplateArgument(const TemplateArgument &From);
430
431 template <typename InContainerTy>
432 Error ImportTemplateArgumentListInfo(
433 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
434
435 template<typename InContainerTy>
436 Error ImportTemplateArgumentListInfo(
437 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
438 const InContainerTy &Container, TemplateArgumentListInfo &Result);
439
440 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
441 using FunctionTemplateAndArgsTy =
442 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
443 Expected<FunctionTemplateAndArgsTy>
444 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
445 FunctionDecl *FromFD);
446
447 template <typename DeclTy>
448 Error ImportTemplateParameterLists(const DeclTy *FromD, DeclTy *ToD);
449
450 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
451
452 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
453
454 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
455 ParmVarDecl *ToParam);
456
457 Expected<InheritedConstructor>
458 ImportInheritedConstructor(const InheritedConstructor &From);
459
460 template <typename T>
461 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
462
463 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true,
464 bool IgnoreTemplateParmDepth = false);
465 ExpectedDecl VisitDecl(Decl *D);
466 ExpectedDecl VisitImportDecl(ImportDecl *D);
467 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
468 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
469 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
470 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
471 ExpectedDecl VisitBindingDecl(BindingDecl *D);
472 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
473 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
474 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
475 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
476 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
477 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
478 ExpectedDecl VisitLabelDecl(LabelDecl *D);
479 ExpectedDecl VisitEnumDecl(EnumDecl *D);
480 ExpectedDecl VisitRecordDecl(RecordDecl *D);
481 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
482 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
483 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
484 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
485 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
486 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
487 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
488 ExpectedDecl VisitFieldDecl(FieldDecl *D);
489 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
490 ExpectedDecl VisitFriendDecl(FriendDecl *D);
491 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
492 ExpectedDecl VisitVarDecl(VarDecl *D);
493 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
494 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
495 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
496 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
497 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
498 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
499 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
500 ExpectedDecl VisitUsingDecl(UsingDecl *D);
501 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
502 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
503 ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D);
504 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
505 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
506 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
507 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
508 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
509 ExpectedDecl
510 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
511
512 Expected<ObjCTypeParamList *>
513 ImportObjCTypeParamList(ObjCTypeParamList *list);
514
515 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
516 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
517 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
518 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
519 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
520 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
521 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
522 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
523 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
524 ExpectedDecl VisitClassTemplateSpecializationDecl(
525 ClassTemplateSpecializationDecl *D);
526 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
527 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
528 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
529
530 // Importing statements
531 ExpectedStmt VisitStmt(Stmt *S);
532 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
533 ExpectedStmt VisitDeclStmt(DeclStmt *S);
534 ExpectedStmt VisitNullStmt(NullStmt *S);
535 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
536 ExpectedStmt VisitCaseStmt(CaseStmt *S);
537 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
538 ExpectedStmt VisitLabelStmt(LabelStmt *S);
539 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
540 ExpectedStmt VisitIfStmt(IfStmt *S);
541 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
542 ExpectedStmt VisitWhileStmt(WhileStmt *S);
543 ExpectedStmt VisitDoStmt(DoStmt *S);
544 ExpectedStmt VisitForStmt(ForStmt *S);
545 ExpectedStmt VisitGotoStmt(GotoStmt *S);
546 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
547 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
548 ExpectedStmt VisitBreakStmt(BreakStmt *S);
549 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
550 // FIXME: MSAsmStmt
551 // FIXME: SEHExceptStmt
552 // FIXME: SEHFinallyStmt
553 // FIXME: SEHTryStmt
554 // FIXME: SEHLeaveStmt
555 // FIXME: CapturedStmt
556 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
557 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
558 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
559 // FIXME: MSDependentExistsStmt
560 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
561 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
562 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
563 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
564 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
565 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
566 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
567
568 // Importing expressions
569 ExpectedStmt VisitExpr(Expr *E);
570 ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E);
571 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
572 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
573 ExpectedStmt VisitConvertVectorExpr(ConvertVectorExpr *E);
574 ExpectedStmt VisitShuffleVectorExpr(ShuffleVectorExpr *E);
575 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
576 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
577 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
578 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
579 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
580 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
581 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
582 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
583 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
584 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
585 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
586 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
587 ExpectedStmt VisitStringLiteral(StringLiteral *E);
588 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
589 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
590 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
591 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
592 ExpectedStmt VisitParenExpr(ParenExpr *E);
593 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
594 ExpectedStmt VisitStmtExpr(StmtExpr *E);
595 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
596 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
597 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
598 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
599 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
600 ExpectedStmt VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E);
601 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
602 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
603 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
604 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
605 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
606 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
607 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
608 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
609 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
610 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
611 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
612 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
613 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
614 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
615 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
616 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
617 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
618 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
619 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
620 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
621 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
622 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
623 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
624 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
625 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
626 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
627 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
628 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
629 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
630 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
631 ExpectedStmt VisitMemberExpr(MemberExpr *E);
632 ExpectedStmt VisitCallExpr(CallExpr *E);
633 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
634 ExpectedStmt VisitInitListExpr(InitListExpr *E);
635 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
636 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
637 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
638 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
639 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
640 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
641 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
642 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
643 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
644 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
645
646 // Helper for chaining together multiple imports. If an error is detected,
647 // subsequent imports will return default constructed nodes, so that failure
648 // can be detected with a single conditional branch after a sequence of
649 // imports.
650 template <typename T> T importChecked(Error &Err, const T &From) {
651 // Don't attempt to import nodes if we hit an error earlier.
652 if (Err)
653 return T{};
654 Expected<T> MaybeVal = import(From);
655 if (!MaybeVal) {
656 Err = MaybeVal.takeError();
657 return T{};
658 }
659 return *MaybeVal;
660 }
661
662 template<typename IIter, typename OIter>
663 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
664 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
665 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
666 Expected<ItemT> ToOrErr = import(*Ibegin);
667 if (!ToOrErr)
668 return ToOrErr.takeError();
669 *Obegin = *ToOrErr;
670 }
671 return Error::success();
672 }
673
674 // Import every item from a container structure into an output container.
675 // If error occurs, stops at first error and returns the error.
676 // The output container should have space for all needed elements (it is not
677 // expanded, new items are put into from the beginning).
678 template<typename InContainerTy, typename OutContainerTy>
679 Error ImportContainerChecked(
680 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
681 return ImportArrayChecked(
682 InContainer.begin(), InContainer.end(), OutContainer.begin());
683 }
684
685 template<typename InContainerTy, typename OIter>
686 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
687 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
688 }
689
690 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
691 CXXMethodDecl *FromMethod);
692
693 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
694 FunctionDecl *FromFD);
695
696 // Returns true if the given function has a placeholder return type and
697 // that type is declared inside the body of the function.
698 // E.g. auto f() { struct X{}; return X(); }
699 bool hasReturnTypeDeclaredInside(FunctionDecl *D);
700 };
701
702template <typename InContainerTy>
703Error ASTNodeImporter::ImportTemplateArgumentListInfo(
704 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
705 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
706 auto ToLAngleLocOrErr = import(From: FromLAngleLoc);
707 if (!ToLAngleLocOrErr)
708 return ToLAngleLocOrErr.takeError();
709 auto ToRAngleLocOrErr = import(From: FromRAngleLoc);
710 if (!ToRAngleLocOrErr)
711 return ToRAngleLocOrErr.takeError();
712
713 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
714 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
715 return Err;
716 Result = ToTAInfo;
717 return Error::success();
718}
719
720template <>
721Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
722 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
723 return ImportTemplateArgumentListInfo(
724 FromLAngleLoc: From.getLAngleLoc(), FromRAngleLoc: From.getRAngleLoc(), Container: From.arguments(), Result);
725}
726
727template <>
728Error ASTNodeImporter::ImportTemplateArgumentListInfo<
729 ASTTemplateArgumentListInfo>(
730 const ASTTemplateArgumentListInfo &From,
731 TemplateArgumentListInfo &Result) {
732 return ImportTemplateArgumentListInfo(
733 FromLAngleLoc: From.LAngleLoc, FromRAngleLoc: From.RAngleLoc, Container: From.arguments(), Result);
734}
735
736Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
737ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
738 FunctionDecl *FromFD) {
739 assert(FromFD->getTemplatedKind() ==
740 FunctionDecl::TK_FunctionTemplateSpecialization);
741
742 FunctionTemplateAndArgsTy Result;
743
744 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
745 if (Error Err = importInto(To&: std::get<0>(t&: Result), From: FTSInfo->getTemplate()))
746 return std::move(Err);
747
748 // Import template arguments.
749 if (Error Err = ImportTemplateArguments(FromArgs: FTSInfo->TemplateArguments->asArray(),
750 ToArgs&: std::get<1>(t&: Result)))
751 return std::move(Err);
752
753 return Result;
754}
755
756template <>
757Expected<TemplateParameterList *>
758ASTNodeImporter::import(TemplateParameterList *From) {
759 SmallVector<NamedDecl *, 4> To(From->size());
760 if (Error Err = ImportContainerChecked(InContainer: *From, OutContainer&: To))
761 return std::move(Err);
762
763 ExpectedExpr ToRequiresClause = import(From: From->getRequiresClause());
764 if (!ToRequiresClause)
765 return ToRequiresClause.takeError();
766
767 auto ToTemplateLocOrErr = import(From: From->getTemplateLoc());
768 if (!ToTemplateLocOrErr)
769 return ToTemplateLocOrErr.takeError();
770 auto ToLAngleLocOrErr = import(From: From->getLAngleLoc());
771 if (!ToLAngleLocOrErr)
772 return ToLAngleLocOrErr.takeError();
773 auto ToRAngleLocOrErr = import(From: From->getRAngleLoc());
774 if (!ToRAngleLocOrErr)
775 return ToRAngleLocOrErr.takeError();
776
777 return TemplateParameterList::Create(
778 C: Importer.getToContext(),
779 TemplateLoc: *ToTemplateLocOrErr,
780 LAngleLoc: *ToLAngleLocOrErr,
781 Params: To,
782 RAngleLoc: *ToRAngleLocOrErr,
783 RequiresClause: *ToRequiresClause);
784}
785
786template <>
787Expected<TemplateArgument>
788ASTNodeImporter::import(const TemplateArgument &From) {
789 switch (From.getKind()) {
790 case TemplateArgument::Null:
791 return TemplateArgument();
792
793 case TemplateArgument::Type: {
794 ExpectedType ToTypeOrErr = import(From: From.getAsType());
795 if (!ToTypeOrErr)
796 return ToTypeOrErr.takeError();
797 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ false,
798 From.getIsDefaulted());
799 }
800
801 case TemplateArgument::Integral: {
802 ExpectedType ToTypeOrErr = import(From: From.getIntegralType());
803 if (!ToTypeOrErr)
804 return ToTypeOrErr.takeError();
805 return TemplateArgument(From, *ToTypeOrErr);
806 }
807
808 case TemplateArgument::Declaration: {
809 Expected<ValueDecl *> ToOrErr = import(From: From.getAsDecl());
810 if (!ToOrErr)
811 return ToOrErr.takeError();
812 ExpectedType ToTypeOrErr = import(From: From.getParamTypeForDecl());
813 if (!ToTypeOrErr)
814 return ToTypeOrErr.takeError();
815 return TemplateArgument(dyn_cast<ValueDecl>(Val: (*ToOrErr)->getCanonicalDecl()),
816 *ToTypeOrErr, From.getIsDefaulted());
817 }
818
819 case TemplateArgument::NullPtr: {
820 ExpectedType ToTypeOrErr = import(From: From.getNullPtrType());
821 if (!ToTypeOrErr)
822 return ToTypeOrErr.takeError();
823 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ true,
824 From.getIsDefaulted());
825 }
826
827 case TemplateArgument::StructuralValue: {
828 ExpectedType ToTypeOrErr = import(From: From.getStructuralValueType());
829 if (!ToTypeOrErr)
830 return ToTypeOrErr.takeError();
831 Expected<APValue> ToValueOrErr = import(From: From.getAsStructuralValue());
832 if (!ToValueOrErr)
833 return ToValueOrErr.takeError();
834 return TemplateArgument(Importer.getToContext(), *ToTypeOrErr,
835 *ToValueOrErr);
836 }
837
838 case TemplateArgument::Template: {
839 Expected<TemplateName> ToTemplateOrErr = import(From: From.getAsTemplate());
840 if (!ToTemplateOrErr)
841 return ToTemplateOrErr.takeError();
842
843 return TemplateArgument(*ToTemplateOrErr, From.getIsDefaulted());
844 }
845
846 case TemplateArgument::TemplateExpansion: {
847 Expected<TemplateName> ToTemplateOrErr =
848 import(From: From.getAsTemplateOrTemplatePattern());
849 if (!ToTemplateOrErr)
850 return ToTemplateOrErr.takeError();
851
852 return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions(),
853 From.getIsDefaulted());
854 }
855
856 case TemplateArgument::Expression:
857 if (ExpectedExpr ToExpr = import(From: From.getAsExpr()))
858 return TemplateArgument(*ToExpr, From.getIsDefaulted());
859 else
860 return ToExpr.takeError();
861
862 case TemplateArgument::Pack: {
863 SmallVector<TemplateArgument, 2> ToPack;
864 ToPack.reserve(N: From.pack_size());
865 if (Error Err = ImportTemplateArguments(FromArgs: From.pack_elements(), ToArgs&: ToPack))
866 return std::move(Err);
867
868 return TemplateArgument(
869 llvm::ArrayRef(ToPack).copy(A&: Importer.getToContext()));
870 }
871 }
872
873 llvm_unreachable("Invalid template argument kind");
874}
875
876template <>
877Expected<TemplateArgumentLoc>
878ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
879 Expected<TemplateArgument> ArgOrErr = import(From: TALoc.getArgument());
880 if (!ArgOrErr)
881 return ArgOrErr.takeError();
882 TemplateArgument Arg = *ArgOrErr;
883
884 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
885
886 TemplateArgumentLocInfo ToInfo;
887 if (Arg.getKind() == TemplateArgument::Expression) {
888 ExpectedExpr E = import(From: FromInfo.getAsExpr());
889 if (!E)
890 return E.takeError();
891 ToInfo = TemplateArgumentLocInfo(*E);
892 } else if (Arg.getKind() == TemplateArgument::Type) {
893 if (auto TSIOrErr = import(From: FromInfo.getAsTypeSourceInfo()))
894 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
895 else
896 return TSIOrErr.takeError();
897 } else {
898 auto ToTemplateQualifierLocOrErr =
899 import(From: FromInfo.getTemplateQualifierLoc());
900 if (!ToTemplateQualifierLocOrErr)
901 return ToTemplateQualifierLocOrErr.takeError();
902 auto ToTemplateNameLocOrErr = import(From: FromInfo.getTemplateNameLoc());
903 if (!ToTemplateNameLocOrErr)
904 return ToTemplateNameLocOrErr.takeError();
905 auto ToTemplateEllipsisLocOrErr =
906 import(From: FromInfo.getTemplateEllipsisLoc());
907 if (!ToTemplateEllipsisLocOrErr)
908 return ToTemplateEllipsisLocOrErr.takeError();
909 ToInfo = TemplateArgumentLocInfo(
910 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
911 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
912 }
913
914 return TemplateArgumentLoc(Arg, ToInfo);
915}
916
917template <>
918Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
919 if (DG.isNull())
920 return DeclGroupRef::Create(C&: Importer.getToContext(), Decls: nullptr, NumDecls: 0);
921 size_t NumDecls = DG.end() - DG.begin();
922 SmallVector<Decl *, 1> ToDecls;
923 ToDecls.reserve(N: NumDecls);
924 for (Decl *FromD : DG) {
925 if (auto ToDOrErr = import(From: FromD))
926 ToDecls.push_back(Elt: *ToDOrErr);
927 else
928 return ToDOrErr.takeError();
929 }
930 return DeclGroupRef::Create(C&: Importer.getToContext(),
931 Decls: ToDecls.begin(),
932 NumDecls);
933}
934
935template <>
936Expected<ASTNodeImporter::Designator>
937ASTNodeImporter::import(const Designator &D) {
938 if (D.isFieldDesignator()) {
939 IdentifierInfo *ToFieldName = Importer.Import(FromId: D.getFieldName());
940
941 ExpectedSLoc ToDotLocOrErr = import(From: D.getDotLoc());
942 if (!ToDotLocOrErr)
943 return ToDotLocOrErr.takeError();
944
945 ExpectedSLoc ToFieldLocOrErr = import(From: D.getFieldLoc());
946 if (!ToFieldLocOrErr)
947 return ToFieldLocOrErr.takeError();
948
949 return DesignatedInitExpr::Designator::CreateFieldDesignator(
950 FieldName: ToFieldName, DotLoc: *ToDotLocOrErr, FieldLoc: *ToFieldLocOrErr);
951 }
952
953 ExpectedSLoc ToLBracketLocOrErr = import(From: D.getLBracketLoc());
954 if (!ToLBracketLocOrErr)
955 return ToLBracketLocOrErr.takeError();
956
957 ExpectedSLoc ToRBracketLocOrErr = import(From: D.getRBracketLoc());
958 if (!ToRBracketLocOrErr)
959 return ToRBracketLocOrErr.takeError();
960
961 if (D.isArrayDesignator())
962 return Designator::CreateArrayDesignator(Index: D.getArrayIndex(),
963 LBracketLoc: *ToLBracketLocOrErr,
964 RBracketLoc: *ToRBracketLocOrErr);
965
966 ExpectedSLoc ToEllipsisLocOrErr = import(From: D.getEllipsisLoc());
967 if (!ToEllipsisLocOrErr)
968 return ToEllipsisLocOrErr.takeError();
969
970 assert(D.isArrayRangeDesignator());
971 return Designator::CreateArrayRangeDesignator(
972 Index: D.getArrayIndex(), LBracketLoc: *ToLBracketLocOrErr, EllipsisLoc: *ToEllipsisLocOrErr,
973 RBracketLoc: *ToRBracketLocOrErr);
974}
975
976template <>
977Expected<ConceptReference *> ASTNodeImporter::import(ConceptReference *From) {
978 Error Err = Error::success();
979 auto ToNNS = importChecked(Err, From: From->getNestedNameSpecifierLoc());
980 auto ToTemplateKWLoc = importChecked(Err, From: From->getTemplateKWLoc());
981 auto ToConceptNameLoc =
982 importChecked(Err, From: From->getConceptNameInfo().getLoc());
983 auto ToConceptName = importChecked(Err, From: From->getConceptNameInfo().getName());
984 auto ToFoundDecl = importChecked(Err, From: From->getFoundDecl());
985 auto ToNamedConcept = importChecked(Err, From: From->getNamedConcept());
986 if (Err)
987 return std::move(Err);
988 TemplateArgumentListInfo ToTAInfo;
989 const auto *ASTTemplateArgs = From->getTemplateArgsAsWritten();
990 if (ASTTemplateArgs)
991 if (Error Err = ImportTemplateArgumentListInfo(From: *ASTTemplateArgs, Result&: ToTAInfo))
992 return std::move(Err);
993 auto *ConceptRef = ConceptReference::Create(
994 C: Importer.getToContext(), NNS: ToNNS, TemplateKWLoc: ToTemplateKWLoc,
995 ConceptNameInfo: DeclarationNameInfo(ToConceptName, ToConceptNameLoc), FoundDecl: ToFoundDecl,
996 NamedConcept: ToNamedConcept,
997 ArgsAsWritten: ASTTemplateArgs ? ASTTemplateArgumentListInfo::Create(
998 C: Importer.getToContext(), List: ToTAInfo)
999 : nullptr);
1000 return ConceptRef;
1001}
1002
1003template <>
1004Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
1005 ValueDecl *Var = nullptr;
1006 if (From.capturesVariable()) {
1007 if (auto VarOrErr = import(From: From.getCapturedVar()))
1008 Var = *VarOrErr;
1009 else
1010 return VarOrErr.takeError();
1011 }
1012
1013 auto LocationOrErr = import(From: From.getLocation());
1014 if (!LocationOrErr)
1015 return LocationOrErr.takeError();
1016
1017 SourceLocation EllipsisLoc;
1018 if (From.isPackExpansion())
1019 if (Error Err = importInto(To&: EllipsisLoc, From: From.getEllipsisLoc()))
1020 return std::move(Err);
1021
1022 return LambdaCapture(
1023 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
1024 EllipsisLoc);
1025}
1026
1027template <typename T>
1028bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
1029 if (Found->getLinkageInternal() != From->getLinkageInternal())
1030 return false;
1031
1032 if (From->hasExternalFormalLinkage())
1033 return Found->hasExternalFormalLinkage();
1034 if (Importer.GetFromTU(ToD: Found) != From->getTranslationUnitDecl())
1035 return false;
1036 if (From->isInAnonymousNamespace())
1037 return Found->isInAnonymousNamespace();
1038 else
1039 return !Found->isInAnonymousNamespace() &&
1040 !Found->hasExternalFormalLinkage();
1041}
1042
1043template <>
1044bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
1045 TypedefNameDecl *From) {
1046 if (Found->getLinkageInternal() != From->getLinkageInternal())
1047 return false;
1048
1049 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1050 return Importer.GetFromTU(ToD: Found) == From->getTranslationUnitDecl();
1051 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1052}
1053
1054} // namespace clang
1055
1056//----------------------------------------------------------------------------
1057// Import Types
1058//----------------------------------------------------------------------------
1059
1060using namespace clang;
1061
1062ExpectedType ASTNodeImporter::VisitType(const Type *T) {
1063 Importer.FromDiag(Loc: SourceLocation(), DiagID: diag::err_unsupported_ast_node)
1064 << T->getTypeClassName();
1065 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
1066}
1067
1068ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1069 ExpectedType UnderlyingTypeOrErr = import(From: T->getValueType());
1070 if (!UnderlyingTypeOrErr)
1071 return UnderlyingTypeOrErr.takeError();
1072
1073 return Importer.getToContext().getAtomicType(T: *UnderlyingTypeOrErr);
1074}
1075
1076ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1077 switch (T->getKind()) {
1078#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1079 case BuiltinType::Id: \
1080 return Importer.getToContext().SingletonId;
1081#include "clang/Basic/OpenCLImageTypes.def"
1082#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1083 case BuiltinType::Id: \
1084 return Importer.getToContext().Id##Ty;
1085#include "clang/Basic/OpenCLExtensionTypes.def"
1086#define SVE_TYPE(Name, Id, SingletonId) \
1087 case BuiltinType::Id: \
1088 return Importer.getToContext().SingletonId;
1089#include "clang/Basic/AArch64SVEACLETypes.def"
1090#define PPC_VECTOR_TYPE(Name, Id, Size) \
1091 case BuiltinType::Id: \
1092 return Importer.getToContext().Id##Ty;
1093#include "clang/Basic/PPCTypes.def"
1094#define RVV_TYPE(Name, Id, SingletonId) \
1095 case BuiltinType::Id: \
1096 return Importer.getToContext().SingletonId;
1097#include "clang/Basic/RISCVVTypes.def"
1098#define WASM_TYPE(Name, Id, SingletonId) \
1099 case BuiltinType::Id: \
1100 return Importer.getToContext().SingletonId;
1101#include "clang/Basic/WebAssemblyReferenceTypes.def"
1102#define AMDGPU_TYPE(Name, Id, SingletonId) \
1103 case BuiltinType::Id: \
1104 return Importer.getToContext().SingletonId;
1105#include "clang/Basic/AMDGPUTypes.def"
1106#define SHARED_SINGLETON_TYPE(Expansion)
1107#define BUILTIN_TYPE(Id, SingletonId) \
1108 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1109#include "clang/AST/BuiltinTypes.def"
1110
1111 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1112 // context supports C++.
1113
1114 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1115 // context supports ObjC.
1116
1117 case BuiltinType::Char_U:
1118 // The context we're importing from has an unsigned 'char'. If we're
1119 // importing into a context with a signed 'char', translate to
1120 // 'unsigned char' instead.
1121 if (Importer.getToContext().getLangOpts().CharIsSigned)
1122 return Importer.getToContext().UnsignedCharTy;
1123
1124 return Importer.getToContext().CharTy;
1125
1126 case BuiltinType::Char_S:
1127 // The context we're importing from has an unsigned 'char'. If we're
1128 // importing into a context with a signed 'char', translate to
1129 // 'unsigned char' instead.
1130 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1131 return Importer.getToContext().SignedCharTy;
1132
1133 return Importer.getToContext().CharTy;
1134
1135 case BuiltinType::WChar_S:
1136 case BuiltinType::WChar_U:
1137 // FIXME: If not in C++, shall we translate to the C equivalent of
1138 // wchar_t?
1139 return Importer.getToContext().WCharTy;
1140 }
1141
1142 llvm_unreachable("Invalid BuiltinType Kind!");
1143}
1144
1145ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1146 ExpectedType ToOriginalTypeOrErr = import(From: T->getOriginalType());
1147 if (!ToOriginalTypeOrErr)
1148 return ToOriginalTypeOrErr.takeError();
1149
1150 return Importer.getToContext().getDecayedType(T: *ToOriginalTypeOrErr);
1151}
1152
1153ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1154 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1155 if (!ToElementTypeOrErr)
1156 return ToElementTypeOrErr.takeError();
1157
1158 return Importer.getToContext().getComplexType(T: *ToElementTypeOrErr);
1159}
1160
1161ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1162 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1163 if (!ToPointeeTypeOrErr)
1164 return ToPointeeTypeOrErr.takeError();
1165
1166 return Importer.getToContext().getPointerType(T: *ToPointeeTypeOrErr);
1167}
1168
1169ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1170 // FIXME: Check for blocks support in "to" context.
1171 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1172 if (!ToPointeeTypeOrErr)
1173 return ToPointeeTypeOrErr.takeError();
1174
1175 return Importer.getToContext().getBlockPointerType(T: *ToPointeeTypeOrErr);
1176}
1177
1178ExpectedType
1179ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1180 // FIXME: Check for C++ support in "to" context.
1181 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeTypeAsWritten());
1182 if (!ToPointeeTypeOrErr)
1183 return ToPointeeTypeOrErr.takeError();
1184
1185 return Importer.getToContext().getLValueReferenceType(T: *ToPointeeTypeOrErr);
1186}
1187
1188ExpectedType
1189ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1190 // FIXME: Check for C++0x support in "to" context.
1191 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeTypeAsWritten());
1192 if (!ToPointeeTypeOrErr)
1193 return ToPointeeTypeOrErr.takeError();
1194
1195 return Importer.getToContext().getRValueReferenceType(T: *ToPointeeTypeOrErr);
1196}
1197
1198ExpectedType
1199ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1200 // FIXME: Check for C++ support in "to" context.
1201 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1202 if (!ToPointeeTypeOrErr)
1203 return ToPointeeTypeOrErr.takeError();
1204
1205 ExpectedTypePtr ClassTypeOrErr = import(From: T->getClass());
1206 if (!ClassTypeOrErr)
1207 return ClassTypeOrErr.takeError();
1208
1209 return Importer.getToContext().getMemberPointerType(T: *ToPointeeTypeOrErr,
1210 Cls: *ClassTypeOrErr);
1211}
1212
1213ExpectedType
1214ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1215 Error Err = Error::success();
1216 auto ToElementType = importChecked(Err, From: T->getElementType());
1217 auto ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1218 if (Err)
1219 return std::move(Err);
1220
1221 return Importer.getToContext().getConstantArrayType(
1222 EltTy: ToElementType, ArySize: T->getSize(), SizeExpr: ToSizeExpr, ASM: T->getSizeModifier(),
1223 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1224}
1225
1226ExpectedType
1227ASTNodeImporter::VisitArrayParameterType(const ArrayParameterType *T) {
1228 ExpectedType ToArrayTypeOrErr = VisitConstantArrayType(T);
1229 if (!ToArrayTypeOrErr)
1230 return ToArrayTypeOrErr.takeError();
1231
1232 return Importer.getToContext().getArrayParameterType(Ty: *ToArrayTypeOrErr);
1233}
1234
1235ExpectedType
1236ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1237 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1238 if (!ToElementTypeOrErr)
1239 return ToElementTypeOrErr.takeError();
1240
1241 return Importer.getToContext().getIncompleteArrayType(EltTy: *ToElementTypeOrErr,
1242 ASM: T->getSizeModifier(),
1243 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1244}
1245
1246ExpectedType
1247ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1248 Error Err = Error::success();
1249 QualType ToElementType = importChecked(Err, From: T->getElementType());
1250 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1251 SourceRange ToBracketsRange = importChecked(Err, From: T->getBracketsRange());
1252 if (Err)
1253 return std::move(Err);
1254 return Importer.getToContext().getVariableArrayType(
1255 EltTy: ToElementType, NumElts: ToSizeExpr, ASM: T->getSizeModifier(),
1256 IndexTypeQuals: T->getIndexTypeCVRQualifiers(), Brackets: ToBracketsRange);
1257}
1258
1259ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1260 const DependentSizedArrayType *T) {
1261 Error Err = Error::success();
1262 QualType ToElementType = importChecked(Err, From: T->getElementType());
1263 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1264 SourceRange ToBracketsRange = importChecked(Err, From: T->getBracketsRange());
1265 if (Err)
1266 return std::move(Err);
1267 // SizeExpr may be null if size is not specified directly.
1268 // For example, 'int a[]'.
1269
1270 return Importer.getToContext().getDependentSizedArrayType(
1271 EltTy: ToElementType, NumElts: ToSizeExpr, ASM: T->getSizeModifier(),
1272 IndexTypeQuals: T->getIndexTypeCVRQualifiers(), Brackets: ToBracketsRange);
1273}
1274
1275ExpectedType ASTNodeImporter::VisitDependentSizedExtVectorType(
1276 const DependentSizedExtVectorType *T) {
1277 Error Err = Error::success();
1278 QualType ToElementType = importChecked(Err, From: T->getElementType());
1279 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1280 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1281 if (Err)
1282 return std::move(Err);
1283 return Importer.getToContext().getDependentSizedExtVectorType(
1284 VectorType: ToElementType, SizeExpr: ToSizeExpr, AttrLoc: ToAttrLoc);
1285}
1286
1287ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1288 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1289 if (!ToElementTypeOrErr)
1290 return ToElementTypeOrErr.takeError();
1291
1292 return Importer.getToContext().getVectorType(VectorType: *ToElementTypeOrErr,
1293 NumElts: T->getNumElements(),
1294 VecKind: T->getVectorKind());
1295}
1296
1297ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1298 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1299 if (!ToElementTypeOrErr)
1300 return ToElementTypeOrErr.takeError();
1301
1302 return Importer.getToContext().getExtVectorType(VectorType: *ToElementTypeOrErr,
1303 NumElts: T->getNumElements());
1304}
1305
1306ExpectedType
1307ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1308 // FIXME: What happens if we're importing a function without a prototype
1309 // into C++? Should we make it variadic?
1310 ExpectedType ToReturnTypeOrErr = import(From: T->getReturnType());
1311 if (!ToReturnTypeOrErr)
1312 return ToReturnTypeOrErr.takeError();
1313
1314 return Importer.getToContext().getFunctionNoProtoType(ResultTy: *ToReturnTypeOrErr,
1315 Info: T->getExtInfo());
1316}
1317
1318ExpectedType
1319ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1320 ExpectedType ToReturnTypeOrErr = import(From: T->getReturnType());
1321 if (!ToReturnTypeOrErr)
1322 return ToReturnTypeOrErr.takeError();
1323
1324 // Import argument types
1325 SmallVector<QualType, 4> ArgTypes;
1326 for (const auto &A : T->param_types()) {
1327 ExpectedType TyOrErr = import(From: A);
1328 if (!TyOrErr)
1329 return TyOrErr.takeError();
1330 ArgTypes.push_back(Elt: *TyOrErr);
1331 }
1332
1333 // Import exception types
1334 SmallVector<QualType, 4> ExceptionTypes;
1335 for (const auto &E : T->exceptions()) {
1336 ExpectedType TyOrErr = import(From: E);
1337 if (!TyOrErr)
1338 return TyOrErr.takeError();
1339 ExceptionTypes.push_back(Elt: *TyOrErr);
1340 }
1341
1342 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1343 Error Err = Error::success();
1344 FunctionProtoType::ExtProtoInfo ToEPI;
1345 ToEPI.ExtInfo = FromEPI.ExtInfo;
1346 ToEPI.Variadic = FromEPI.Variadic;
1347 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1348 ToEPI.TypeQuals = FromEPI.TypeQuals;
1349 ToEPI.RefQualifier = FromEPI.RefQualifier;
1350 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1351 ToEPI.ExceptionSpec.NoexceptExpr =
1352 importChecked(Err, From: FromEPI.ExceptionSpec.NoexceptExpr);
1353 ToEPI.ExceptionSpec.SourceDecl =
1354 importChecked(Err, From: FromEPI.ExceptionSpec.SourceDecl);
1355 ToEPI.ExceptionSpec.SourceTemplate =
1356 importChecked(Err, From: FromEPI.ExceptionSpec.SourceTemplate);
1357 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1358
1359 if (Err)
1360 return std::move(Err);
1361
1362 return Importer.getToContext().getFunctionType(
1363 ResultTy: *ToReturnTypeOrErr, Args: ArgTypes, EPI: ToEPI);
1364}
1365
1366ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1367 const UnresolvedUsingType *T) {
1368 Error Err = Error::success();
1369 auto ToD = importChecked(Err, From: T->getDecl());
1370 auto ToPrevD = importChecked(Err, From: T->getDecl()->getPreviousDecl());
1371 if (Err)
1372 return std::move(Err);
1373
1374 return Importer.getToContext().getTypeDeclType(
1375 Decl: ToD, PrevDecl: cast_or_null<TypeDecl>(Val: ToPrevD));
1376}
1377
1378ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1379 ExpectedType ToInnerTypeOrErr = import(From: T->getInnerType());
1380 if (!ToInnerTypeOrErr)
1381 return ToInnerTypeOrErr.takeError();
1382
1383 return Importer.getToContext().getParenType(NamedType: *ToInnerTypeOrErr);
1384}
1385
1386ExpectedType
1387ASTNodeImporter::VisitPackIndexingType(clang::PackIndexingType const *T) {
1388
1389 ExpectedType Pattern = import(From: T->getPattern());
1390 if (!Pattern)
1391 return Pattern.takeError();
1392 ExpectedExpr Index = import(From: T->getIndexExpr());
1393 if (!Index)
1394 return Index.takeError();
1395 return Importer.getToContext().getPackIndexingType(Pattern: *Pattern, IndexExpr: *Index);
1396}
1397
1398ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1399 Expected<TypedefNameDecl *> ToDeclOrErr = import(From: T->getDecl());
1400 if (!ToDeclOrErr)
1401 return ToDeclOrErr.takeError();
1402
1403 TypedefNameDecl *ToDecl = *ToDeclOrErr;
1404 if (ToDecl->getTypeForDecl())
1405 return QualType(ToDecl->getTypeForDecl(), 0);
1406
1407 ExpectedType ToUnderlyingTypeOrErr = import(From: T->desugar());
1408 if (!ToUnderlyingTypeOrErr)
1409 return ToUnderlyingTypeOrErr.takeError();
1410
1411 return Importer.getToContext().getTypedefType(Decl: ToDecl, Underlying: *ToUnderlyingTypeOrErr);
1412}
1413
1414ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1415 ExpectedExpr ToExprOrErr = import(From: T->getUnderlyingExpr());
1416 if (!ToExprOrErr)
1417 return ToExprOrErr.takeError();
1418 return Importer.getToContext().getTypeOfExprType(E: *ToExprOrErr, Kind: T->getKind());
1419}
1420
1421ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1422 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnmodifiedType());
1423 if (!ToUnderlyingTypeOrErr)
1424 return ToUnderlyingTypeOrErr.takeError();
1425 return Importer.getToContext().getTypeOfType(QT: *ToUnderlyingTypeOrErr,
1426 Kind: T->getKind());
1427}
1428
1429ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) {
1430 Expected<UsingShadowDecl *> FoundOrErr = import(From: T->getFoundDecl());
1431 if (!FoundOrErr)
1432 return FoundOrErr.takeError();
1433 Expected<QualType> UnderlyingOrErr = import(From: T->getUnderlyingType());
1434 if (!UnderlyingOrErr)
1435 return UnderlyingOrErr.takeError();
1436
1437 return Importer.getToContext().getUsingType(Found: *FoundOrErr, Underlying: *UnderlyingOrErr);
1438}
1439
1440ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1441 // FIXME: Make sure that the "to" context supports C++0x!
1442 ExpectedExpr ToExprOrErr = import(From: T->getUnderlyingExpr());
1443 if (!ToExprOrErr)
1444 return ToExprOrErr.takeError();
1445
1446 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnderlyingType());
1447 if (!ToUnderlyingTypeOrErr)
1448 return ToUnderlyingTypeOrErr.takeError();
1449
1450 return Importer.getToContext().getDecltypeType(
1451 e: *ToExprOrErr, UnderlyingType: *ToUnderlyingTypeOrErr);
1452}
1453
1454ExpectedType
1455ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1456 ExpectedType ToBaseTypeOrErr = import(From: T->getBaseType());
1457 if (!ToBaseTypeOrErr)
1458 return ToBaseTypeOrErr.takeError();
1459
1460 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnderlyingType());
1461 if (!ToUnderlyingTypeOrErr)
1462 return ToUnderlyingTypeOrErr.takeError();
1463
1464 return Importer.getToContext().getUnaryTransformType(
1465 BaseType: *ToBaseTypeOrErr, UnderlyingType: *ToUnderlyingTypeOrErr, UKind: T->getUTTKind());
1466}
1467
1468ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1469 // FIXME: Make sure that the "to" context supports C++11!
1470 ExpectedType ToDeducedTypeOrErr = import(From: T->getDeducedType());
1471 if (!ToDeducedTypeOrErr)
1472 return ToDeducedTypeOrErr.takeError();
1473
1474 ExpectedDecl ToTypeConstraintConcept = import(From: T->getTypeConstraintConcept());
1475 if (!ToTypeConstraintConcept)
1476 return ToTypeConstraintConcept.takeError();
1477
1478 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1479 if (Error Err = ImportTemplateArguments(FromArgs: T->getTypeConstraintArguments(),
1480 ToArgs&: ToTemplateArgs))
1481 return std::move(Err);
1482
1483 return Importer.getToContext().getAutoType(
1484 DeducedType: *ToDeducedTypeOrErr, Keyword: T->getKeyword(), /*IsDependent*/false,
1485 /*IsPack=*/false, TypeConstraintConcept: cast_or_null<ConceptDecl>(Val: *ToTypeConstraintConcept),
1486 TypeConstraintArgs: ToTemplateArgs);
1487}
1488
1489ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1490 const DeducedTemplateSpecializationType *T) {
1491 // FIXME: Make sure that the "to" context supports C++17!
1492 Expected<TemplateName> ToTemplateNameOrErr = import(From: T->getTemplateName());
1493 if (!ToTemplateNameOrErr)
1494 return ToTemplateNameOrErr.takeError();
1495 ExpectedType ToDeducedTypeOrErr = import(From: T->getDeducedType());
1496 if (!ToDeducedTypeOrErr)
1497 return ToDeducedTypeOrErr.takeError();
1498
1499 return Importer.getToContext().getDeducedTemplateSpecializationType(
1500 Template: *ToTemplateNameOrErr, DeducedType: *ToDeducedTypeOrErr, IsDependent: T->isDependentType());
1501}
1502
1503ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1504 const InjectedClassNameType *T) {
1505 Expected<CXXRecordDecl *> ToDeclOrErr = import(From: T->getDecl());
1506 if (!ToDeclOrErr)
1507 return ToDeclOrErr.takeError();
1508
1509 // The InjectedClassNameType is created in VisitRecordDecl when the
1510 // T->getDecl() is imported. Here we can return the existing type.
1511 const Type *Ty = (*ToDeclOrErr)->getTypeForDecl();
1512 assert(isa_and_nonnull<InjectedClassNameType>(Ty));
1513 return QualType(Ty, 0);
1514}
1515
1516ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1517 Expected<RecordDecl *> ToDeclOrErr = import(From: T->getDecl());
1518 if (!ToDeclOrErr)
1519 return ToDeclOrErr.takeError();
1520
1521 return Importer.getToContext().getTagDeclType(Decl: *ToDeclOrErr);
1522}
1523
1524ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1525 Expected<EnumDecl *> ToDeclOrErr = import(From: T->getDecl());
1526 if (!ToDeclOrErr)
1527 return ToDeclOrErr.takeError();
1528
1529 return Importer.getToContext().getTagDeclType(Decl: *ToDeclOrErr);
1530}
1531
1532ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1533 ExpectedType ToModifiedTypeOrErr = import(From: T->getModifiedType());
1534 if (!ToModifiedTypeOrErr)
1535 return ToModifiedTypeOrErr.takeError();
1536 ExpectedType ToEquivalentTypeOrErr = import(From: T->getEquivalentType());
1537 if (!ToEquivalentTypeOrErr)
1538 return ToEquivalentTypeOrErr.takeError();
1539
1540 return Importer.getToContext().getAttributedType(attrKind: T->getAttrKind(),
1541 modifiedType: *ToModifiedTypeOrErr, equivalentType: *ToEquivalentTypeOrErr);
1542}
1543
1544ExpectedType
1545ASTNodeImporter::VisitCountAttributedType(const CountAttributedType *T) {
1546 ExpectedType ToWrappedTypeOrErr = import(From: T->desugar());
1547 if (!ToWrappedTypeOrErr)
1548 return ToWrappedTypeOrErr.takeError();
1549
1550 Error Err = Error::success();
1551 Expr *CountExpr = importChecked(Err, From: T->getCountExpr());
1552
1553 SmallVector<TypeCoupledDeclRefInfo, 1> CoupledDecls;
1554 for (const TypeCoupledDeclRefInfo &TI : T->dependent_decls()) {
1555 Expected<ValueDecl *> ToDeclOrErr = import(From: TI.getDecl());
1556 if (!ToDeclOrErr)
1557 return ToDeclOrErr.takeError();
1558 CoupledDecls.emplace_back(Args&: *ToDeclOrErr, Args: TI.isDeref());
1559 }
1560
1561 return Importer.getToContext().getCountAttributedType(
1562 T: *ToWrappedTypeOrErr, CountExpr, CountInBytes: T->isCountInBytes(), OrNull: T->isOrNull(),
1563 DependentDecls: ArrayRef(CoupledDecls.data(), CoupledDecls.size()));
1564}
1565
1566ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1567 const TemplateTypeParmType *T) {
1568 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(From: T->getDecl());
1569 if (!ToDeclOrErr)
1570 return ToDeclOrErr.takeError();
1571
1572 return Importer.getToContext().getTemplateTypeParmType(
1573 Depth: T->getDepth(), Index: T->getIndex(), ParameterPack: T->isParameterPack(), ParmDecl: *ToDeclOrErr);
1574}
1575
1576ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1577 const SubstTemplateTypeParmType *T) {
1578 Expected<Decl *> ReplacedOrErr = import(From: T->getAssociatedDecl());
1579 if (!ReplacedOrErr)
1580 return ReplacedOrErr.takeError();
1581
1582 ExpectedType ToReplacementTypeOrErr = import(From: T->getReplacementType());
1583 if (!ToReplacementTypeOrErr)
1584 return ToReplacementTypeOrErr.takeError();
1585
1586 return Importer.getToContext().getSubstTemplateTypeParmType(
1587 Replacement: *ToReplacementTypeOrErr, AssociatedDecl: *ReplacedOrErr, Index: T->getIndex(),
1588 PackIndex: T->getPackIndex());
1589}
1590
1591ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
1592 const SubstTemplateTypeParmPackType *T) {
1593 Expected<Decl *> ReplacedOrErr = import(From: T->getAssociatedDecl());
1594 if (!ReplacedOrErr)
1595 return ReplacedOrErr.takeError();
1596
1597 Expected<TemplateArgument> ToArgumentPack = import(From: T->getArgumentPack());
1598 if (!ToArgumentPack)
1599 return ToArgumentPack.takeError();
1600
1601 return Importer.getToContext().getSubstTemplateTypeParmPackType(
1602 AssociatedDecl: *ReplacedOrErr, Index: T->getIndex(), Final: T->getFinal(), ArgPack: *ToArgumentPack);
1603}
1604
1605ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1606 const TemplateSpecializationType *T) {
1607 auto ToTemplateOrErr = import(From: T->getTemplateName());
1608 if (!ToTemplateOrErr)
1609 return ToTemplateOrErr.takeError();
1610
1611 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1612 if (Error Err =
1613 ImportTemplateArguments(FromArgs: T->template_arguments(), ToArgs&: ToTemplateArgs))
1614 return std::move(Err);
1615
1616 QualType ToCanonType;
1617 if (!T->isCanonicalUnqualified()) {
1618 QualType FromCanonType
1619 = Importer.getFromContext().getCanonicalType(T: QualType(T, 0));
1620 if (ExpectedType TyOrErr = import(From: FromCanonType))
1621 ToCanonType = *TyOrErr;
1622 else
1623 return TyOrErr.takeError();
1624 }
1625 return Importer.getToContext().getTemplateSpecializationType(T: *ToTemplateOrErr,
1626 Args: ToTemplateArgs,
1627 Canon: ToCanonType);
1628}
1629
1630ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1631 // Note: the qualifier in an ElaboratedType is optional.
1632 auto ToQualifierOrErr = import(From: T->getQualifier());
1633 if (!ToQualifierOrErr)
1634 return ToQualifierOrErr.takeError();
1635
1636 ExpectedType ToNamedTypeOrErr = import(From: T->getNamedType());
1637 if (!ToNamedTypeOrErr)
1638 return ToNamedTypeOrErr.takeError();
1639
1640 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(From: T->getOwnedTagDecl());
1641 if (!ToOwnedTagDeclOrErr)
1642 return ToOwnedTagDeclOrErr.takeError();
1643
1644 return Importer.getToContext().getElaboratedType(Keyword: T->getKeyword(),
1645 NNS: *ToQualifierOrErr,
1646 NamedType: *ToNamedTypeOrErr,
1647 OwnedTagDecl: *ToOwnedTagDeclOrErr);
1648}
1649
1650ExpectedType
1651ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1652 ExpectedType ToPatternOrErr = import(From: T->getPattern());
1653 if (!ToPatternOrErr)
1654 return ToPatternOrErr.takeError();
1655
1656 return Importer.getToContext().getPackExpansionType(Pattern: *ToPatternOrErr,
1657 NumExpansions: T->getNumExpansions(),
1658 /*ExpactPack=*/ExpectPackInType: false);
1659}
1660
1661ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1662 const DependentTemplateSpecializationType *T) {
1663 auto ToQualifierOrErr = import(From: T->getQualifier());
1664 if (!ToQualifierOrErr)
1665 return ToQualifierOrErr.takeError();
1666
1667 IdentifierInfo *ToName = Importer.Import(FromId: T->getIdentifier());
1668
1669 SmallVector<TemplateArgument, 2> ToPack;
1670 ToPack.reserve(N: T->template_arguments().size());
1671 if (Error Err = ImportTemplateArguments(FromArgs: T->template_arguments(), ToArgs&: ToPack))
1672 return std::move(Err);
1673
1674 return Importer.getToContext().getDependentTemplateSpecializationType(
1675 Keyword: T->getKeyword(), NNS: *ToQualifierOrErr, Name: ToName, Args: ToPack);
1676}
1677
1678ExpectedType
1679ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1680 auto ToQualifierOrErr = import(From: T->getQualifier());
1681 if (!ToQualifierOrErr)
1682 return ToQualifierOrErr.takeError();
1683
1684 IdentifierInfo *Name = Importer.Import(FromId: T->getIdentifier());
1685
1686 QualType Canon;
1687 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1688 if (ExpectedType TyOrErr = import(From: T->getCanonicalTypeInternal()))
1689 Canon = (*TyOrErr).getCanonicalType();
1690 else
1691 return TyOrErr.takeError();
1692 }
1693
1694 return Importer.getToContext().getDependentNameType(Keyword: T->getKeyword(),
1695 NNS: *ToQualifierOrErr,
1696 Name, Canon);
1697}
1698
1699ExpectedType
1700ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1701 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(From: T->getDecl());
1702 if (!ToDeclOrErr)
1703 return ToDeclOrErr.takeError();
1704
1705 return Importer.getToContext().getObjCInterfaceType(Decl: *ToDeclOrErr);
1706}
1707
1708ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1709 ExpectedType ToBaseTypeOrErr = import(From: T->getBaseType());
1710 if (!ToBaseTypeOrErr)
1711 return ToBaseTypeOrErr.takeError();
1712
1713 SmallVector<QualType, 4> TypeArgs;
1714 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1715 if (ExpectedType TyOrErr = import(From: TypeArg))
1716 TypeArgs.push_back(Elt: *TyOrErr);
1717 else
1718 return TyOrErr.takeError();
1719 }
1720
1721 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1722 for (auto *P : T->quals()) {
1723 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(From: P))
1724 Protocols.push_back(Elt: *ProtocolOrErr);
1725 else
1726 return ProtocolOrErr.takeError();
1727
1728 }
1729
1730 return Importer.getToContext().getObjCObjectType(Base: *ToBaseTypeOrErr, typeArgs: TypeArgs,
1731 protocols: Protocols,
1732 isKindOf: T->isKindOfTypeAsWritten());
1733}
1734
1735ExpectedType
1736ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1737 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1738 if (!ToPointeeTypeOrErr)
1739 return ToPointeeTypeOrErr.takeError();
1740
1741 return Importer.getToContext().getObjCObjectPointerType(OIT: *ToPointeeTypeOrErr);
1742}
1743
1744ExpectedType
1745ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
1746 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnderlyingType());
1747 if (!ToUnderlyingTypeOrErr)
1748 return ToUnderlyingTypeOrErr.takeError();
1749
1750 IdentifierInfo *ToIdentifier = Importer.Import(FromId: T->getMacroIdentifier());
1751 return Importer.getToContext().getMacroQualifiedType(UnderlyingTy: *ToUnderlyingTypeOrErr,
1752 MacroII: ToIdentifier);
1753}
1754
1755ExpectedType clang::ASTNodeImporter::VisitAdjustedType(const AdjustedType *T) {
1756 Error Err = Error::success();
1757 QualType ToOriginalType = importChecked(Err, From: T->getOriginalType());
1758 QualType ToAdjustedType = importChecked(Err, From: T->getAdjustedType());
1759 if (Err)
1760 return std::move(Err);
1761
1762 return Importer.getToContext().getAdjustedType(Orig: ToOriginalType,
1763 New: ToAdjustedType);
1764}
1765
1766ExpectedType clang::ASTNodeImporter::VisitBitIntType(const BitIntType *T) {
1767 return Importer.getToContext().getBitIntType(Unsigned: T->isUnsigned(),
1768 NumBits: T->getNumBits());
1769}
1770
1771ExpectedType clang::ASTNodeImporter::VisitBTFTagAttributedType(
1772 const clang::BTFTagAttributedType *T) {
1773 Error Err = Error::success();
1774 const BTFTypeTagAttr *ToBTFAttr = importChecked(Err, From: T->getAttr());
1775 QualType ToWrappedType = importChecked(Err, From: T->getWrappedType());
1776 if (Err)
1777 return std::move(Err);
1778
1779 return Importer.getToContext().getBTFTagAttributedType(BTFAttr: ToBTFAttr,
1780 Wrapped: ToWrappedType);
1781}
1782
1783ExpectedType clang::ASTNodeImporter::VisitConstantMatrixType(
1784 const clang::ConstantMatrixType *T) {
1785 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1786 if (!ToElementTypeOrErr)
1787 return ToElementTypeOrErr.takeError();
1788
1789 return Importer.getToContext().getConstantMatrixType(
1790 ElementType: *ToElementTypeOrErr, NumRows: T->getNumRows(), NumColumns: T->getNumColumns());
1791}
1792
1793ExpectedType clang::ASTNodeImporter::VisitDependentAddressSpaceType(
1794 const clang::DependentAddressSpaceType *T) {
1795 Error Err = Error::success();
1796 QualType ToPointeeType = importChecked(Err, From: T->getPointeeType());
1797 Expr *ToAddrSpaceExpr = importChecked(Err, From: T->getAddrSpaceExpr());
1798 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1799 if (Err)
1800 return std::move(Err);
1801
1802 return Importer.getToContext().getDependentAddressSpaceType(
1803 PointeeType: ToPointeeType, AddrSpaceExpr: ToAddrSpaceExpr, AttrLoc: ToAttrLoc);
1804}
1805
1806ExpectedType clang::ASTNodeImporter::VisitDependentBitIntType(
1807 const clang::DependentBitIntType *T) {
1808 ExpectedExpr ToNumBitsExprOrErr = import(From: T->getNumBitsExpr());
1809 if (!ToNumBitsExprOrErr)
1810 return ToNumBitsExprOrErr.takeError();
1811 return Importer.getToContext().getDependentBitIntType(Unsigned: T->isUnsigned(),
1812 BitsExpr: *ToNumBitsExprOrErr);
1813}
1814
1815ExpectedType clang::ASTNodeImporter::VisitDependentSizedMatrixType(
1816 const clang::DependentSizedMatrixType *T) {
1817 Error Err = Error::success();
1818 QualType ToElementType = importChecked(Err, From: T->getElementType());
1819 Expr *ToRowExpr = importChecked(Err, From: T->getRowExpr());
1820 Expr *ToColumnExpr = importChecked(Err, From: T->getColumnExpr());
1821 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1822 if (Err)
1823 return std::move(Err);
1824
1825 return Importer.getToContext().getDependentSizedMatrixType(
1826 ElementType: ToElementType, RowExpr: ToRowExpr, ColumnExpr: ToColumnExpr, AttrLoc: ToAttrLoc);
1827}
1828
1829ExpectedType clang::ASTNodeImporter::VisitDependentVectorType(
1830 const clang::DependentVectorType *T) {
1831 Error Err = Error::success();
1832 QualType ToElementType = importChecked(Err, From: T->getElementType());
1833 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1834 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1835 if (Err)
1836 return std::move(Err);
1837
1838 return Importer.getToContext().getDependentVectorType(
1839 VectorType: ToElementType, SizeExpr: ToSizeExpr, AttrLoc: ToAttrLoc, VecKind: T->getVectorKind());
1840}
1841
1842ExpectedType clang::ASTNodeImporter::VisitObjCTypeParamType(
1843 const clang::ObjCTypeParamType *T) {
1844 Expected<ObjCTypeParamDecl *> ToDeclOrErr = import(From: T->getDecl());
1845 if (!ToDeclOrErr)
1846 return ToDeclOrErr.takeError();
1847
1848 SmallVector<ObjCProtocolDecl *, 4> ToProtocols;
1849 for (ObjCProtocolDecl *FromProtocol : T->getProtocols()) {
1850 Expected<ObjCProtocolDecl *> ToProtocolOrErr = import(From: FromProtocol);
1851 if (!ToProtocolOrErr)
1852 return ToProtocolOrErr.takeError();
1853 ToProtocols.push_back(Elt: *ToProtocolOrErr);
1854 }
1855
1856 return Importer.getToContext().getObjCTypeParamType(Decl: *ToDeclOrErr,
1857 protocols: ToProtocols);
1858}
1859
1860ExpectedType clang::ASTNodeImporter::VisitPipeType(const clang::PipeType *T) {
1861 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1862 if (!ToElementTypeOrErr)
1863 return ToElementTypeOrErr.takeError();
1864
1865 ASTContext &ToCtx = Importer.getToContext();
1866 if (T->isReadOnly())
1867 return ToCtx.getReadPipeType(T: *ToElementTypeOrErr);
1868 else
1869 return ToCtx.getWritePipeType(T: *ToElementTypeOrErr);
1870}
1871
1872//----------------------------------------------------------------------------
1873// Import Declarations
1874//----------------------------------------------------------------------------
1875Error ASTNodeImporter::ImportDeclParts(
1876 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1877 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1878 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1879 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1880 // FIXME: We could support these constructs by importing a different type of
1881 // this parameter and by importing the original type of the parameter only
1882 // after the FunctionDecl is created. See
1883 // VisitFunctionDecl::UsedDifferentProtoType.
1884 DeclContext *OrigDC = D->getDeclContext();
1885 FunctionDecl *FunDecl;
1886 if (isa<RecordDecl>(Val: D) && (FunDecl = dyn_cast<FunctionDecl>(Val: OrigDC)) &&
1887 FunDecl->hasBody()) {
1888 auto getLeafPointeeType = [](const Type *T) {
1889 while (T->isPointerType() || T->isArrayType()) {
1890 T = T->getPointeeOrArrayElementType();
1891 }
1892 return T;
1893 };
1894 for (const ParmVarDecl *P : FunDecl->parameters()) {
1895 const Type *LeafT =
1896 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1897 auto *RT = dyn_cast<RecordType>(Val: LeafT);
1898 if (RT && RT->getDecl() == D) {
1899 Importer.FromDiag(Loc: D->getLocation(), DiagID: diag::err_unsupported_ast_node)
1900 << D->getDeclKindName();
1901 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
1902 }
1903 }
1904 }
1905
1906 // Import the context of this declaration.
1907 if (Error Err = ImportDeclContext(From: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
1908 return Err;
1909
1910 // Import the name of this declaration.
1911 if (Error Err = importInto(To&: Name, From: D->getDeclName()))
1912 return Err;
1913
1914 // Import the location of this declaration.
1915 if (Error Err = importInto(To&: Loc, From: D->getLocation()))
1916 return Err;
1917
1918 ToD = cast_or_null<NamedDecl>(Val: Importer.GetAlreadyImportedOrNull(FromD: D));
1919 if (ToD)
1920 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD: D, ToD))
1921 return Err;
1922
1923 return Error::success();
1924}
1925
1926Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
1927 NamedDecl *&ToD, SourceLocation &Loc) {
1928
1929 // Import the name of this declaration.
1930 if (Error Err = importInto(To&: Name, From: D->getDeclName()))
1931 return Err;
1932
1933 // Import the location of this declaration.
1934 if (Error Err = importInto(To&: Loc, From: D->getLocation()))
1935 return Err;
1936
1937 ToD = cast_or_null<NamedDecl>(Val: Importer.GetAlreadyImportedOrNull(FromD: D));
1938 if (ToD)
1939 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD: D, ToD))
1940 return Err;
1941
1942 return Error::success();
1943}
1944
1945Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1946 if (!FromD)
1947 return Error::success();
1948
1949 if (!ToD)
1950 if (Error Err = importInto(To&: ToD, From: FromD))
1951 return Err;
1952
1953 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(Val: FromD)) {
1954 if (RecordDecl *ToRecord = cast<RecordDecl>(Val: ToD)) {
1955 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1956 !ToRecord->getDefinition()) {
1957 if (Error Err = ImportDefinition(From: FromRecord, To: ToRecord))
1958 return Err;
1959 }
1960 }
1961 return Error::success();
1962 }
1963
1964 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(Val: FromD)) {
1965 if (EnumDecl *ToEnum = cast<EnumDecl>(Val: ToD)) {
1966 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1967 if (Error Err = ImportDefinition(From: FromEnum, To: ToEnum))
1968 return Err;
1969 }
1970 }
1971 return Error::success();
1972 }
1973
1974 return Error::success();
1975}
1976
1977Error
1978ASTNodeImporter::ImportDeclarationNameLoc(
1979 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1980 // NOTE: To.Name and To.Loc are already imported.
1981 // We only have to import To.LocInfo.
1982 switch (To.getName().getNameKind()) {
1983 case DeclarationName::Identifier:
1984 case DeclarationName::ObjCZeroArgSelector:
1985 case DeclarationName::ObjCOneArgSelector:
1986 case DeclarationName::ObjCMultiArgSelector:
1987 case DeclarationName::CXXUsingDirective:
1988 case DeclarationName::CXXDeductionGuideName:
1989 return Error::success();
1990
1991 case DeclarationName::CXXOperatorName: {
1992 if (auto ToRangeOrErr = import(From: From.getCXXOperatorNameRange()))
1993 To.setCXXOperatorNameRange(*ToRangeOrErr);
1994 else
1995 return ToRangeOrErr.takeError();
1996 return Error::success();
1997 }
1998 case DeclarationName::CXXLiteralOperatorName: {
1999 if (ExpectedSLoc LocOrErr = import(From: From.getCXXLiteralOperatorNameLoc()))
2000 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
2001 else
2002 return LocOrErr.takeError();
2003 return Error::success();
2004 }
2005 case DeclarationName::CXXConstructorName:
2006 case DeclarationName::CXXDestructorName:
2007 case DeclarationName::CXXConversionFunctionName: {
2008 if (auto ToTInfoOrErr = import(From: From.getNamedTypeInfo()))
2009 To.setNamedTypeInfo(*ToTInfoOrErr);
2010 else
2011 return ToTInfoOrErr.takeError();
2012 return Error::success();
2013 }
2014 }
2015 llvm_unreachable("Unknown name kind.");
2016}
2017
2018Error
2019ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
2020 if (Importer.isMinimalImport() && !ForceImport) {
2021 auto ToDCOrErr = Importer.ImportContext(FromDC);
2022 return ToDCOrErr.takeError();
2023 }
2024
2025 // We use strict error handling in case of records and enums, but not
2026 // with e.g. namespaces.
2027 //
2028 // FIXME Clients of the ASTImporter should be able to choose an
2029 // appropriate error handling strategy for their needs. For instance,
2030 // they may not want to mark an entire namespace as erroneous merely
2031 // because there is an ODR error with two typedefs. As another example,
2032 // the client may allow EnumConstantDecls with same names but with
2033 // different values in two distinct translation units.
2034 ChildErrorHandlingStrategy HandleChildErrors(FromDC);
2035
2036 auto MightNeedReordering = [](const Decl *D) {
2037 return isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) || isa<FriendDecl>(Val: D);
2038 };
2039
2040 // Import everything that might need reordering first.
2041 Error ChildErrors = Error::success();
2042 for (auto *From : FromDC->decls()) {
2043 if (!MightNeedReordering(From))
2044 continue;
2045
2046 ExpectedDecl ImportedOrErr = import(From);
2047
2048 // If we are in the process of ImportDefinition(...) for a RecordDecl we
2049 // want to make sure that we are also completing each FieldDecl. There
2050 // are currently cases where this does not happen and this is correctness
2051 // fix since operations such as code generation will expect this to be so.
2052 if (!ImportedOrErr) {
2053 HandleChildErrors.handleChildImportResult(ResultErr&: ChildErrors,
2054 ChildErr: ImportedOrErr.takeError());
2055 continue;
2056 }
2057 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(Val: From);
2058 Decl *ImportedDecl = *ImportedOrErr;
2059 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(Val: ImportedDecl);
2060 if (FieldFrom && FieldTo) {
2061 Error Err = ImportFieldDeclDefinition(From: FieldFrom, To: FieldTo);
2062 HandleChildErrors.handleChildImportResult(ResultErr&: ChildErrors, ChildErr: std::move(Err));
2063 }
2064 }
2065
2066 // We reorder declarations in RecordDecls because they may have another order
2067 // in the "to" context than they have in the "from" context. This may happen
2068 // e.g when we import a class like this:
2069 // struct declToImport {
2070 // int a = c + b;
2071 // int b = 1;
2072 // int c = 2;
2073 // };
2074 // During the import of `a` we import first the dependencies in sequence,
2075 // thus the order would be `c`, `b`, `a`. We will get the normal order by
2076 // first removing the already imported members and then adding them in the
2077 // order as they appear in the "from" context.
2078 //
2079 // Keeping field order is vital because it determines structure layout.
2080 //
2081 // Here and below, we cannot call field_begin() method and its callers on
2082 // ToDC if it has an external storage. Calling field_begin() will
2083 // automatically load all the fields by calling
2084 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
2085 // call ASTImporter::Import(). This is because the ExternalASTSource
2086 // interface in LLDB is implemented by the means of the ASTImporter. However,
2087 // calling an import at this point would result in an uncontrolled import, we
2088 // must avoid that.
2089
2090 auto ToDCOrErr = Importer.ImportContext(FromDC);
2091 if (!ToDCOrErr) {
2092 consumeError(Err: std::move(ChildErrors));
2093 return ToDCOrErr.takeError();
2094 }
2095
2096 if (const auto *FromRD = dyn_cast<RecordDecl>(Val: FromDC)) {
2097 DeclContext *ToDC = *ToDCOrErr;
2098 // Remove all declarations, which may be in wrong order in the
2099 // lexical DeclContext and then add them in the proper order.
2100 for (auto *D : FromRD->decls()) {
2101 if (!MightNeedReordering(D))
2102 continue;
2103
2104 assert(D && "DC contains a null decl");
2105 if (Decl *ToD = Importer.GetAlreadyImportedOrNull(FromD: D)) {
2106 // Remove only the decls which we successfully imported.
2107 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
2108 // Remove the decl from its wrong place in the linked list.
2109 ToDC->removeDecl(D: ToD);
2110 // Add the decl to the end of the linked list.
2111 // This time it will be at the proper place because the enclosing for
2112 // loop iterates in the original (good) order of the decls.
2113 ToDC->addDeclInternal(D: ToD);
2114 }
2115 }
2116 }
2117
2118 // Import everything else.
2119 for (auto *From : FromDC->decls()) {
2120 if (MightNeedReordering(From))
2121 continue;
2122
2123 ExpectedDecl ImportedOrErr = import(From);
2124 if (!ImportedOrErr)
2125 HandleChildErrors.handleChildImportResult(ResultErr&: ChildErrors,
2126 ChildErr: ImportedOrErr.takeError());
2127 }
2128
2129 return ChildErrors;
2130}
2131
2132Error ASTNodeImporter::ImportFieldDeclDefinition(const FieldDecl *From,
2133 const FieldDecl *To) {
2134 RecordDecl *FromRecordDecl = nullptr;
2135 RecordDecl *ToRecordDecl = nullptr;
2136 // If we have a field that is an ArrayType we need to check if the array
2137 // element is a RecordDecl and if so we need to import the definition.
2138 QualType FromType = From->getType();
2139 QualType ToType = To->getType();
2140 if (FromType->isArrayType()) {
2141 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
2142 FromRecordDecl = FromType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2143 ToRecordDecl = ToType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2144 }
2145
2146 if (!FromRecordDecl || !ToRecordDecl) {
2147 const RecordType *RecordFrom = FromType->getAs<RecordType>();
2148 const RecordType *RecordTo = ToType->getAs<RecordType>();
2149
2150 if (RecordFrom && RecordTo) {
2151 FromRecordDecl = RecordFrom->getDecl();
2152 ToRecordDecl = RecordTo->getDecl();
2153 }
2154 }
2155
2156 if (FromRecordDecl && ToRecordDecl) {
2157 if (FromRecordDecl->isCompleteDefinition() &&
2158 !ToRecordDecl->isCompleteDefinition())
2159 return ImportDefinition(From: FromRecordDecl, To: ToRecordDecl);
2160 }
2161
2162 return Error::success();
2163}
2164
2165Error ASTNodeImporter::ImportDeclContext(
2166 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
2167 auto ToDCOrErr = Importer.ImportContext(FromDC: FromD->getDeclContext());
2168 if (!ToDCOrErr)
2169 return ToDCOrErr.takeError();
2170 ToDC = *ToDCOrErr;
2171
2172 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
2173 auto ToLexicalDCOrErr = Importer.ImportContext(
2174 FromDC: FromD->getLexicalDeclContext());
2175 if (!ToLexicalDCOrErr)
2176 return ToLexicalDCOrErr.takeError();
2177 ToLexicalDC = *ToLexicalDCOrErr;
2178 } else
2179 ToLexicalDC = ToDC;
2180
2181 return Error::success();
2182}
2183
2184Error ASTNodeImporter::ImportImplicitMethods(
2185 const CXXRecordDecl *From, CXXRecordDecl *To) {
2186 assert(From->isCompleteDefinition() && To->getDefinition() == To &&
2187 "Import implicit methods to or from non-definition");
2188
2189 for (CXXMethodDecl *FromM : From->methods())
2190 if (FromM->isImplicit()) {
2191 Expected<CXXMethodDecl *> ToMOrErr = import(From: FromM);
2192 if (!ToMOrErr)
2193 return ToMOrErr.takeError();
2194 }
2195
2196 return Error::success();
2197}
2198
2199static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
2200 ASTImporter &Importer) {
2201 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
2202 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromD: FromTypedef))
2203 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(Val: *ToTypedefOrErr));
2204 else
2205 return ToTypedefOrErr.takeError();
2206 }
2207 return Error::success();
2208}
2209
2210Error ASTNodeImporter::ImportDefinition(
2211 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
2212 auto DefinitionCompleter = [To]() {
2213 // There are cases in LLDB when we first import a class without its
2214 // members. The class will have DefinitionData, but no members. Then,
2215 // importDefinition is called from LLDB, which tries to get the members, so
2216 // when we get here, the class already has the DefinitionData set, so we
2217 // must unset the CompleteDefinition here to be able to complete again the
2218 // definition.
2219 To->setCompleteDefinition(false);
2220 To->completeDefinition();
2221 };
2222
2223 if (To->getDefinition() || To->isBeingDefined()) {
2224 if (Kind == IDK_Everything ||
2225 // In case of lambdas, the class already has a definition ptr set, but
2226 // the contained decls are not imported yet. Also, isBeingDefined was
2227 // set in CXXRecordDecl::CreateLambda. We must import the contained
2228 // decls here and finish the definition.
2229 (To->isLambda() && shouldForceImportDeclContext(IDK: Kind))) {
2230 if (To->isLambda()) {
2231 auto *FromCXXRD = cast<CXXRecordDecl>(Val: From);
2232 SmallVector<LambdaCapture, 8> ToCaptures;
2233 ToCaptures.reserve(N: FromCXXRD->capture_size());
2234 for (const auto &FromCapture : FromCXXRD->captures()) {
2235 if (auto ToCaptureOrErr = import(From: FromCapture))
2236 ToCaptures.push_back(Elt: *ToCaptureOrErr);
2237 else
2238 return ToCaptureOrErr.takeError();
2239 }
2240 cast<CXXRecordDecl>(Val: To)->setCaptures(Context&: Importer.getToContext(),
2241 Captures: ToCaptures);
2242 }
2243
2244 Error Result = ImportDeclContext(FromDC: From, /*ForceImport=*/true);
2245 // Finish the definition of the lambda, set isBeingDefined to false.
2246 if (To->isLambda())
2247 DefinitionCompleter();
2248 return Result;
2249 }
2250
2251 return Error::success();
2252 }
2253
2254 To->startDefinition();
2255 // Set the definition to complete even if it is really not complete during
2256 // import. Some AST constructs (expressions) require the record layout
2257 // to be calculated (see 'clang::computeDependence') at the time they are
2258 // constructed. Import of such AST node is possible during import of the
2259 // same record, there is no way to have a completely defined record (all
2260 // fields imported) at that time without multiple AST import passes.
2261 if (!Importer.isMinimalImport())
2262 To->setCompleteDefinition(true);
2263 // Complete the definition even if error is returned.
2264 // The RecordDecl may be already part of the AST so it is better to
2265 // have it in complete state even if something is wrong with it.
2266 auto DefinitionCompleterScopeExit =
2267 llvm::make_scope_exit(F&: DefinitionCompleter);
2268
2269 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2270 return Err;
2271
2272 // Add base classes.
2273 auto *ToCXX = dyn_cast<CXXRecordDecl>(Val: To);
2274 auto *FromCXX = dyn_cast<CXXRecordDecl>(Val: From);
2275 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2276
2277 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2278 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2279
2280 #define FIELD(Name, Width, Merge) \
2281 ToData.Name = FromData.Name;
2282 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2283
2284 // Copy over the data stored in RecordDeclBits
2285 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2286
2287 SmallVector<CXXBaseSpecifier *, 4> Bases;
2288 for (const auto &Base1 : FromCXX->bases()) {
2289 ExpectedType TyOrErr = import(From: Base1.getType());
2290 if (!TyOrErr)
2291 return TyOrErr.takeError();
2292
2293 SourceLocation EllipsisLoc;
2294 if (Base1.isPackExpansion()) {
2295 if (ExpectedSLoc LocOrErr = import(From: Base1.getEllipsisLoc()))
2296 EllipsisLoc = *LocOrErr;
2297 else
2298 return LocOrErr.takeError();
2299 }
2300
2301 // Ensure that we have a definition for the base.
2302 if (Error Err =
2303 ImportDefinitionIfNeeded(FromD: Base1.getType()->getAsCXXRecordDecl()))
2304 return Err;
2305
2306 auto RangeOrErr = import(From: Base1.getSourceRange());
2307 if (!RangeOrErr)
2308 return RangeOrErr.takeError();
2309
2310 auto TSIOrErr = import(From: Base1.getTypeSourceInfo());
2311 if (!TSIOrErr)
2312 return TSIOrErr.takeError();
2313
2314 Bases.push_back(
2315 Elt: new (Importer.getToContext()) CXXBaseSpecifier(
2316 *RangeOrErr,
2317 Base1.isVirtual(),
2318 Base1.isBaseOfClass(),
2319 Base1.getAccessSpecifierAsWritten(),
2320 *TSIOrErr,
2321 EllipsisLoc));
2322 }
2323 if (!Bases.empty())
2324 ToCXX->setBases(Bases: Bases.data(), NumBases: Bases.size());
2325 }
2326
2327 if (shouldForceImportDeclContext(IDK: Kind)) {
2328 if (Error Err = ImportDeclContext(FromDC: From, /*ForceImport=*/true))
2329 return Err;
2330 }
2331
2332 return Error::success();
2333}
2334
2335Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
2336 if (To->getAnyInitializer())
2337 return Error::success();
2338
2339 Expr *FromInit = From->getInit();
2340 if (!FromInit)
2341 return Error::success();
2342
2343 ExpectedExpr ToInitOrErr = import(From: FromInit);
2344 if (!ToInitOrErr)
2345 return ToInitOrErr.takeError();
2346
2347 To->setInit(*ToInitOrErr);
2348 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2349 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2350 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2351 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2352 // FIXME: Also import the initializer value.
2353 }
2354
2355 // FIXME: Other bits to merge?
2356 return Error::success();
2357}
2358
2359Error ASTNodeImporter::ImportDefinition(
2360 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2361 if (To->getDefinition() || To->isBeingDefined()) {
2362 if (Kind == IDK_Everything)
2363 return ImportDeclContext(FromDC: From, /*ForceImport=*/true);
2364 return Error::success();
2365 }
2366
2367 To->startDefinition();
2368
2369 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2370 return Err;
2371
2372 ExpectedType ToTypeOrErr =
2373 import(From: Importer.getFromContext().getTypeDeclType(Decl: From));
2374 if (!ToTypeOrErr)
2375 return ToTypeOrErr.takeError();
2376
2377 ExpectedType ToPromotionTypeOrErr = import(From: From->getPromotionType());
2378 if (!ToPromotionTypeOrErr)
2379 return ToPromotionTypeOrErr.takeError();
2380
2381 if (shouldForceImportDeclContext(IDK: Kind))
2382 if (Error Err = ImportDeclContext(FromDC: From, /*ForceImport=*/true))
2383 return Err;
2384
2385 // FIXME: we might need to merge the number of positive or negative bits
2386 // if the enumerator lists don't match.
2387 To->completeDefinition(NewType: *ToTypeOrErr, PromotionType: *ToPromotionTypeOrErr,
2388 NumPositiveBits: From->getNumPositiveBits(),
2389 NumNegativeBits: From->getNumNegativeBits());
2390 return Error::success();
2391}
2392
2393Error ASTNodeImporter::ImportTemplateArguments(
2394 ArrayRef<TemplateArgument> FromArgs,
2395 SmallVectorImpl<TemplateArgument> &ToArgs) {
2396 for (const auto &Arg : FromArgs) {
2397 if (auto ToOrErr = import(From: Arg))
2398 ToArgs.push_back(Elt: *ToOrErr);
2399 else
2400 return ToOrErr.takeError();
2401 }
2402
2403 return Error::success();
2404}
2405
2406// FIXME: Do not forget to remove this and use only 'import'.
2407Expected<TemplateArgument>
2408ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2409 return import(From);
2410}
2411
2412template <typename InContainerTy>
2413Error ASTNodeImporter::ImportTemplateArgumentListInfo(
2414 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2415 for (const auto &FromLoc : Container) {
2416 if (auto ToLocOrErr = import(FromLoc))
2417 ToTAInfo.addArgument(Loc: *ToLocOrErr);
2418 else
2419 return ToLocOrErr.takeError();
2420 }
2421 return Error::success();
2422}
2423
2424static StructuralEquivalenceKind
2425getStructuralEquivalenceKind(const ASTImporter &Importer) {
2426 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
2427 : StructuralEquivalenceKind::Default;
2428}
2429
2430bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain,
2431 bool IgnoreTemplateParmDepth) {
2432 // Eliminate a potential failure point where we attempt to re-import
2433 // something we're trying to import while completing ToRecord.
2434 Decl *ToOrigin = Importer.GetOriginalDecl(To);
2435 if (ToOrigin) {
2436 To = ToOrigin;
2437 }
2438
2439 StructuralEquivalenceContext Ctx(
2440 Importer.getFromContext(), Importer.getToContext(),
2441 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2442 /*StrictTypeSpelling=*/false, Complain, /*ErrorOnTagTypeMismatch=*/false,
2443 IgnoreTemplateParmDepth);
2444 return Ctx.IsEquivalent(D1: From, D2: To);
2445}
2446
2447ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2448 Importer.FromDiag(Loc: D->getLocation(), DiagID: diag::err_unsupported_ast_node)
2449 << D->getDeclKindName();
2450 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
2451}
2452
2453ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2454 Importer.FromDiag(Loc: D->getLocation(), DiagID: diag::err_unsupported_ast_node)
2455 << D->getDeclKindName();
2456 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
2457}
2458
2459ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2460 // Import the context of this declaration.
2461 DeclContext *DC, *LexicalDC;
2462 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
2463 return std::move(Err);
2464
2465 // Import the location of this declaration.
2466 ExpectedSLoc LocOrErr = import(From: D->getLocation());
2467 if (!LocOrErr)
2468 return LocOrErr.takeError();
2469
2470 EmptyDecl *ToD;
2471 if (GetImportedOrCreateDecl(ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: *LocOrErr))
2472 return ToD;
2473
2474 ToD->setLexicalDeclContext(LexicalDC);
2475 LexicalDC->addDeclInternal(D: ToD);
2476 return ToD;
2477}
2478
2479ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2480 TranslationUnitDecl *ToD =
2481 Importer.getToContext().getTranslationUnitDecl();
2482
2483 Importer.MapImported(From: D, To: ToD);
2484
2485 return ToD;
2486}
2487
2488ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) {
2489 DeclContext *DC, *LexicalDC;
2490 DeclarationName Name;
2491 SourceLocation Loc;
2492 NamedDecl *ToND;
2493 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD&: ToND, Loc))
2494 return std::move(Err);
2495 if (ToND)
2496 return ToND;
2497
2498 BindingDecl *ToD;
2499 if (GetImportedOrCreateDecl(ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2500 args: Name.getAsIdentifierInfo()))
2501 return ToD;
2502
2503 Error Err = Error::success();
2504 QualType ToType = importChecked(Err, From: D->getType());
2505 Expr *ToBinding = importChecked(Err, From: D->getBinding());
2506 ValueDecl *ToDecomposedDecl = importChecked(Err, From: D->getDecomposedDecl());
2507 if (Err)
2508 return std::move(Err);
2509
2510 ToD->setBinding(DeclaredType: ToType, Binding: ToBinding);
2511 ToD->setDecomposedDecl(ToDecomposedDecl);
2512 addDeclToContexts(FromD: D, ToD);
2513
2514 return ToD;
2515}
2516
2517ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2518 ExpectedSLoc LocOrErr = import(From: D->getLocation());
2519 if (!LocOrErr)
2520 return LocOrErr.takeError();
2521 auto ColonLocOrErr = import(From: D->getColonLoc());
2522 if (!ColonLocOrErr)
2523 return ColonLocOrErr.takeError();
2524
2525 // Import the context of this declaration.
2526 auto DCOrErr = Importer.ImportContext(FromDC: D->getDeclContext());
2527 if (!DCOrErr)
2528 return DCOrErr.takeError();
2529 DeclContext *DC = *DCOrErr;
2530
2531 AccessSpecDecl *ToD;
2532 if (GetImportedOrCreateDecl(ToD, FromD: D, args&: Importer.getToContext(), args: D->getAccess(),
2533 args&: DC, args&: *LocOrErr, args&: *ColonLocOrErr))
2534 return ToD;
2535
2536 // Lexical DeclContext and Semantic DeclContext
2537 // is always the same for the accessSpec.
2538 ToD->setLexicalDeclContext(DC);
2539 DC->addDeclInternal(D: ToD);
2540
2541 return ToD;
2542}
2543
2544ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2545 auto DCOrErr = Importer.ImportContext(FromDC: D->getDeclContext());
2546 if (!DCOrErr)
2547 return DCOrErr.takeError();
2548 DeclContext *DC = *DCOrErr;
2549 DeclContext *LexicalDC = DC;
2550
2551 Error Err = Error::success();
2552 auto ToLocation = importChecked(Err, From: D->getLocation());
2553 auto ToRParenLoc = importChecked(Err, From: D->getRParenLoc());
2554 auto ToAssertExpr = importChecked(Err, From: D->getAssertExpr());
2555 auto ToMessage = importChecked(Err, From: D->getMessage());
2556 if (Err)
2557 return std::move(Err);
2558
2559 StaticAssertDecl *ToD;
2560 if (GetImportedOrCreateDecl(
2561 ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToLocation, args&: ToAssertExpr, args&: ToMessage,
2562 args&: ToRParenLoc, args: D->isFailed()))
2563 return ToD;
2564
2565 ToD->setLexicalDeclContext(LexicalDC);
2566 LexicalDC->addDeclInternal(D: ToD);
2567 return ToD;
2568}
2569
2570ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2571 // Import the major distinguishing characteristics of this namespace.
2572 DeclContext *DC, *LexicalDC;
2573 DeclarationName Name;
2574 SourceLocation Loc;
2575 NamedDecl *ToD;
2576 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2577 return std::move(Err);
2578 if (ToD)
2579 return ToD;
2580
2581 NamespaceDecl *MergeWithNamespace = nullptr;
2582 if (!Name) {
2583 // This is an anonymous namespace. Adopt an existing anonymous
2584 // namespace if we can.
2585 // FIXME: Not testable.
2586 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: DC))
2587 MergeWithNamespace = TU->getAnonymousNamespace();
2588 else
2589 MergeWithNamespace = cast<NamespaceDecl>(Val: DC)->getAnonymousNamespace();
2590 } else {
2591 SmallVector<NamedDecl *, 4> ConflictingDecls;
2592 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2593 for (auto *FoundDecl : FoundDecls) {
2594 if (!FoundDecl->isInIdentifierNamespace(NS: Decl::IDNS_Namespace))
2595 continue;
2596
2597 if (auto *FoundNS = dyn_cast<NamespaceDecl>(Val: FoundDecl)) {
2598 MergeWithNamespace = FoundNS;
2599 ConflictingDecls.clear();
2600 break;
2601 }
2602
2603 ConflictingDecls.push_back(Elt: FoundDecl);
2604 }
2605
2606 if (!ConflictingDecls.empty()) {
2607 ExpectedName NameOrErr = Importer.HandleNameConflict(
2608 Name, DC, IDNS: Decl::IDNS_Namespace, Decls: ConflictingDecls.data(),
2609 NumDecls: ConflictingDecls.size());
2610 if (NameOrErr)
2611 Name = NameOrErr.get();
2612 else
2613 return NameOrErr.takeError();
2614 }
2615 }
2616
2617 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
2618 if (!BeginLocOrErr)
2619 return BeginLocOrErr.takeError();
2620 ExpectedSLoc RBraceLocOrErr = import(From: D->getRBraceLoc());
2621 if (!RBraceLocOrErr)
2622 return RBraceLocOrErr.takeError();
2623
2624 // Create the "to" namespace, if needed.
2625 NamespaceDecl *ToNamespace = MergeWithNamespace;
2626 if (!ToNamespace) {
2627 if (GetImportedOrCreateDecl(ToD&: ToNamespace, FromD: D, args&: Importer.getToContext(), args&: DC,
2628 args: D->isInline(), args&: *BeginLocOrErr, args&: Loc,
2629 args: Name.getAsIdentifierInfo(),
2630 /*PrevDecl=*/args: nullptr, args: D->isNested()))
2631 return ToNamespace;
2632 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2633 ToNamespace->setLexicalDeclContext(LexicalDC);
2634 LexicalDC->addDeclInternal(D: ToNamespace);
2635
2636 // If this is an anonymous namespace, register it as the anonymous
2637 // namespace within its context.
2638 if (!Name) {
2639 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: DC))
2640 TU->setAnonymousNamespace(ToNamespace);
2641 else
2642 cast<NamespaceDecl>(Val: DC)->setAnonymousNamespace(ToNamespace);
2643 }
2644 }
2645 Importer.MapImported(From: D, To: ToNamespace);
2646
2647 if (Error Err = ImportDeclContext(FromDC: D))
2648 return std::move(Err);
2649
2650 return ToNamespace;
2651}
2652
2653ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2654 // Import the major distinguishing characteristics of this namespace.
2655 DeclContext *DC, *LexicalDC;
2656 DeclarationName Name;
2657 SourceLocation Loc;
2658 NamedDecl *LookupD;
2659 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD&: LookupD, Loc))
2660 return std::move(Err);
2661 if (LookupD)
2662 return LookupD;
2663
2664 // NOTE: No conflict resolution is done for namespace aliases now.
2665
2666 Error Err = Error::success();
2667 auto ToNamespaceLoc = importChecked(Err, From: D->getNamespaceLoc());
2668 auto ToAliasLoc = importChecked(Err, From: D->getAliasLoc());
2669 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
2670 auto ToTargetNameLoc = importChecked(Err, From: D->getTargetNameLoc());
2671 auto ToNamespace = importChecked(Err, From: D->getNamespace());
2672 if (Err)
2673 return std::move(Err);
2674
2675 IdentifierInfo *ToIdentifier = Importer.Import(FromId: D->getIdentifier());
2676
2677 NamespaceAliasDecl *ToD;
2678 if (GetImportedOrCreateDecl(
2679 ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToNamespaceLoc, args&: ToAliasLoc,
2680 args&: ToIdentifier, args&: ToQualifierLoc, args&: ToTargetNameLoc, args&: ToNamespace))
2681 return ToD;
2682
2683 ToD->setLexicalDeclContext(LexicalDC);
2684 LexicalDC->addDeclInternal(D: ToD);
2685
2686 return ToD;
2687}
2688
2689ExpectedDecl
2690ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2691 // Import the major distinguishing characteristics of this typedef.
2692 DeclarationName Name;
2693 SourceLocation Loc;
2694 NamedDecl *ToD;
2695 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2696 // is created.
2697 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2698 return std::move(Err);
2699 if (ToD)
2700 return ToD;
2701
2702 DeclContext *DC = cast_or_null<DeclContext>(
2703 Val: Importer.GetAlreadyImportedOrNull(FromD: cast<Decl>(Val: D->getDeclContext())));
2704 DeclContext *LexicalDC =
2705 cast_or_null<DeclContext>(Val: Importer.GetAlreadyImportedOrNull(
2706 FromD: cast<Decl>(Val: D->getLexicalDeclContext())));
2707
2708 // If this typedef is not in block scope, determine whether we've
2709 // seen a typedef with the same name (that we can merge with) or any
2710 // other entity by that name (which name lookup could conflict with).
2711 // Note: Repeated typedefs are not valid in C99:
2712 // 'typedef int T; typedef int T;' is invalid
2713 // We do not care about this now.
2714 if (DC && !DC->isFunctionOrMethod()) {
2715 SmallVector<NamedDecl *, 4> ConflictingDecls;
2716 unsigned IDNS = Decl::IDNS_Ordinary;
2717 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2718 for (auto *FoundDecl : FoundDecls) {
2719 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
2720 continue;
2721 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(Val: FoundDecl)) {
2722 if (!hasSameVisibilityContextAndLinkage(Found: FoundTypedef, From: D))
2723 continue;
2724
2725 QualType FromUT = D->getUnderlyingType();
2726 QualType FoundUT = FoundTypedef->getUnderlyingType();
2727 if (Importer.IsStructurallyEquivalent(From: FromUT, To: FoundUT)) {
2728 // If the underlying declarations are unnamed records these can be
2729 // imported as different types. We should create a distinct typedef
2730 // node in this case.
2731 // If we found an existing underlying type with a record in a
2732 // different context (than the imported), this is already reason for
2733 // having distinct typedef nodes for these.
2734 // Again this can create situation like
2735 // 'typedef int T; typedef int T;' but this is hard to avoid without
2736 // a rename strategy at import.
2737 if (!FromUT.isNull() && !FoundUT.isNull()) {
2738 RecordDecl *FromR = FromUT->getAsRecordDecl();
2739 RecordDecl *FoundR = FoundUT->getAsRecordDecl();
2740 if (FromR && FoundR &&
2741 !hasSameVisibilityContextAndLinkage(Found: FoundR, From: FromR))
2742 continue;
2743 }
2744 // If the "From" context has a complete underlying type but we
2745 // already have a complete underlying type then return with that.
2746 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2747 return Importer.MapImported(From: D, To: FoundTypedef);
2748 // FIXME Handle redecl chain. When you do that make consistent changes
2749 // in ASTImporterLookupTable too.
2750 } else {
2751 ConflictingDecls.push_back(Elt: FoundDecl);
2752 }
2753 }
2754 }
2755
2756 if (!ConflictingDecls.empty()) {
2757 ExpectedName NameOrErr = Importer.HandleNameConflict(
2758 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
2759 if (NameOrErr)
2760 Name = NameOrErr.get();
2761 else
2762 return NameOrErr.takeError();
2763 }
2764 }
2765
2766 Error Err = Error::success();
2767 auto ToUnderlyingType = importChecked(Err, From: D->getUnderlyingType());
2768 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
2769 auto ToBeginLoc = importChecked(Err, From: D->getBeginLoc());
2770 if (Err)
2771 return std::move(Err);
2772
2773 // Create the new typedef node.
2774 // FIXME: ToUnderlyingType is not used.
2775 (void)ToUnderlyingType;
2776 TypedefNameDecl *ToTypedef;
2777 if (IsAlias) {
2778 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2779 ToD&: ToTypedef, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToBeginLoc, args&: Loc,
2780 args: Name.getAsIdentifierInfo(), args&: ToTypeSourceInfo))
2781 return ToTypedef;
2782 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2783 ToD&: ToTypedef, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToBeginLoc, args&: Loc,
2784 args: Name.getAsIdentifierInfo(), args&: ToTypeSourceInfo))
2785 return ToTypedef;
2786
2787 // Import the DeclContext and set it to the Typedef.
2788 if ((Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC)))
2789 return std::move(Err);
2790 ToTypedef->setDeclContext(DC);
2791 ToTypedef->setLexicalDeclContext(LexicalDC);
2792 // Add to the lookupTable because we could not do that in MapImported.
2793 Importer.AddToLookupTable(ToD: ToTypedef);
2794
2795 ToTypedef->setAccess(D->getAccess());
2796
2797 // Templated declarations should not appear in DeclContext.
2798 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(Val: D) : nullptr;
2799 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2800 LexicalDC->addDeclInternal(D: ToTypedef);
2801
2802 return ToTypedef;
2803}
2804
2805ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2806 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2807}
2808
2809ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2810 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2811}
2812
2813ExpectedDecl
2814ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2815 // Import the major distinguishing characteristics of this typedef.
2816 DeclContext *DC, *LexicalDC;
2817 DeclarationName Name;
2818 SourceLocation Loc;
2819 NamedDecl *FoundD;
2820 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD&: FoundD, Loc))
2821 return std::move(Err);
2822 if (FoundD)
2823 return FoundD;
2824
2825 // If this typedef is not in block scope, determine whether we've
2826 // seen a typedef with the same name (that we can merge with) or any
2827 // other entity by that name (which name lookup could conflict with).
2828 if (!DC->isFunctionOrMethod()) {
2829 SmallVector<NamedDecl *, 4> ConflictingDecls;
2830 unsigned IDNS = Decl::IDNS_Ordinary;
2831 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2832 for (auto *FoundDecl : FoundDecls) {
2833 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
2834 continue;
2835 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(Val: FoundDecl)) {
2836 if (IsStructuralMatch(From: D, To: FoundAlias))
2837 return Importer.MapImported(From: D, To: FoundAlias);
2838 ConflictingDecls.push_back(Elt: FoundDecl);
2839 }
2840 }
2841
2842 if (!ConflictingDecls.empty()) {
2843 ExpectedName NameOrErr = Importer.HandleNameConflict(
2844 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
2845 if (NameOrErr)
2846 Name = NameOrErr.get();
2847 else
2848 return NameOrErr.takeError();
2849 }
2850 }
2851
2852 Error Err = Error::success();
2853 auto ToTemplateParameters = importChecked(Err, From: D->getTemplateParameters());
2854 auto ToTemplatedDecl = importChecked(Err, From: D->getTemplatedDecl());
2855 if (Err)
2856 return std::move(Err);
2857
2858 TypeAliasTemplateDecl *ToAlias;
2859 if (GetImportedOrCreateDecl(ToD&: ToAlias, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2860 args&: Name, args&: ToTemplateParameters, args&: ToTemplatedDecl))
2861 return ToAlias;
2862
2863 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2864
2865 ToAlias->setAccess(D->getAccess());
2866 ToAlias->setLexicalDeclContext(LexicalDC);
2867 LexicalDC->addDeclInternal(D: ToAlias);
2868 if (DC != Importer.getToContext().getTranslationUnitDecl())
2869 updateLookupTableForTemplateParameters(Params&: *ToTemplateParameters);
2870 return ToAlias;
2871}
2872
2873ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2874 // Import the major distinguishing characteristics of this label.
2875 DeclContext *DC, *LexicalDC;
2876 DeclarationName Name;
2877 SourceLocation Loc;
2878 NamedDecl *ToD;
2879 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2880 return std::move(Err);
2881 if (ToD)
2882 return ToD;
2883
2884 assert(LexicalDC->isFunctionOrMethod());
2885
2886 LabelDecl *ToLabel;
2887 if (D->isGnuLocal()) {
2888 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
2889 if (!BeginLocOrErr)
2890 return BeginLocOrErr.takeError();
2891 if (GetImportedOrCreateDecl(ToD&: ToLabel, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2892 args: Name.getAsIdentifierInfo(), args&: *BeginLocOrErr))
2893 return ToLabel;
2894
2895 } else {
2896 if (GetImportedOrCreateDecl(ToD&: ToLabel, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2897 args: Name.getAsIdentifierInfo()))
2898 return ToLabel;
2899
2900 }
2901
2902 Expected<LabelStmt *> ToStmtOrErr = import(From: D->getStmt());
2903 if (!ToStmtOrErr)
2904 return ToStmtOrErr.takeError();
2905
2906 ToLabel->setStmt(*ToStmtOrErr);
2907 ToLabel->setLexicalDeclContext(LexicalDC);
2908 LexicalDC->addDeclInternal(D: ToLabel);
2909 return ToLabel;
2910}
2911
2912ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2913 // Import the major distinguishing characteristics of this enum.
2914 DeclContext *DC, *LexicalDC;
2915 DeclarationName Name;
2916 SourceLocation Loc;
2917 NamedDecl *ToD;
2918 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2919 return std::move(Err);
2920 if (ToD)
2921 return ToD;
2922
2923 // Figure out what enum name we're looking for.
2924 unsigned IDNS = Decl::IDNS_Tag;
2925 DeclarationName SearchName = Name;
2926 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2927 if (Error Err = importInto(
2928 To&: SearchName, From: D->getTypedefNameForAnonDecl()->getDeclName()))
2929 return std::move(Err);
2930 IDNS = Decl::IDNS_Ordinary;
2931 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2932 IDNS |= Decl::IDNS_Ordinary;
2933
2934 // We may already have an enum of the same name; try to find and match it.
2935 EnumDecl *PrevDecl = nullptr;
2936 if (!DC->isFunctionOrMethod()) {
2937 SmallVector<NamedDecl *, 4> ConflictingDecls;
2938 auto FoundDecls =
2939 Importer.findDeclsInToCtx(DC, Name: SearchName);
2940 for (auto *FoundDecl : FoundDecls) {
2941 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
2942 continue;
2943
2944 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: FoundDecl)) {
2945 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2946 FoundDecl = Tag->getDecl();
2947 }
2948
2949 if (auto *FoundEnum = dyn_cast<EnumDecl>(Val: FoundDecl)) {
2950 if (!hasSameVisibilityContextAndLinkage(Found: FoundEnum, From: D))
2951 continue;
2952 if (IsStructuralMatch(From: D, To: FoundEnum, Complain: !SearchName.isEmpty())) {
2953 EnumDecl *FoundDef = FoundEnum->getDefinition();
2954 if (D->isThisDeclarationADefinition() && FoundDef)
2955 return Importer.MapImported(From: D, To: FoundDef);
2956 PrevDecl = FoundEnum->getMostRecentDecl();
2957 break;
2958 }
2959 ConflictingDecls.push_back(Elt: FoundDecl);
2960 }
2961 }
2962
2963 // In case of unnamed enums, we try to find an existing similar one, if none
2964 // was found, perform the import always.
2965 // Structural in-equivalence is not detected in this way here, but it may
2966 // be found when the parent decl is imported (if the enum is part of a
2967 // class). To make this totally exact a more difficult solution is needed.
2968 if (SearchName && !ConflictingDecls.empty()) {
2969 ExpectedName NameOrErr = Importer.HandleNameConflict(
2970 Name: SearchName, DC, IDNS, Decls: ConflictingDecls.data(),
2971 NumDecls: ConflictingDecls.size());
2972 if (NameOrErr)
2973 Name = NameOrErr.get();
2974 else
2975 return NameOrErr.takeError();
2976 }
2977 }
2978
2979 Error Err = Error::success();
2980 auto ToBeginLoc = importChecked(Err, From: D->getBeginLoc());
2981 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
2982 auto ToIntegerType = importChecked(Err, From: D->getIntegerType());
2983 auto ToBraceRange = importChecked(Err, From: D->getBraceRange());
2984 if (Err)
2985 return std::move(Err);
2986
2987 // Create the enum declaration.
2988 EnumDecl *D2;
2989 if (GetImportedOrCreateDecl(
2990 ToD&: D2, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToBeginLoc,
2991 args&: Loc, args: Name.getAsIdentifierInfo(), args&: PrevDecl, args: D->isScoped(),
2992 args: D->isScopedUsingClassTag(), args: D->isFixed()))
2993 return D2;
2994
2995 D2->setQualifierInfo(ToQualifierLoc);
2996 D2->setIntegerType(ToIntegerType);
2997 D2->setBraceRange(ToBraceRange);
2998 D2->setAccess(D->getAccess());
2999 D2->setLexicalDeclContext(LexicalDC);
3000 addDeclToContexts(FromD: D, ToD: D2);
3001
3002 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
3003 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
3004 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
3005 if (Expected<EnumDecl *> ToInstOrErr = import(From: FromInst))
3006 D2->setInstantiationOfMemberEnum(ED: *ToInstOrErr, TSK: SK);
3007 else
3008 return ToInstOrErr.takeError();
3009 if (ExpectedSLoc POIOrErr = import(From: MemberInfo->getPointOfInstantiation()))
3010 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3011 else
3012 return POIOrErr.takeError();
3013 }
3014
3015 // Import the definition
3016 if (D->isCompleteDefinition())
3017 if (Error Err = ImportDefinition(From: D, To: D2))
3018 return std::move(Err);
3019
3020 return D2;
3021}
3022
3023ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
3024 bool IsFriendTemplate = false;
3025 if (auto *DCXX = dyn_cast<CXXRecordDecl>(Val: D)) {
3026 IsFriendTemplate =
3027 DCXX->getDescribedClassTemplate() &&
3028 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
3029 Decl::FOK_None;
3030 }
3031
3032 // Import the major distinguishing characteristics of this record.
3033 DeclContext *DC = nullptr, *LexicalDC = nullptr;
3034 DeclarationName Name;
3035 SourceLocation Loc;
3036 NamedDecl *ToD = nullptr;
3037 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3038 return std::move(Err);
3039 if (ToD)
3040 return ToD;
3041
3042 // Figure out what structure name we're looking for.
3043 unsigned IDNS = Decl::IDNS_Tag;
3044 DeclarationName SearchName = Name;
3045 if (!SearchName && D->getTypedefNameForAnonDecl()) {
3046 if (Error Err = importInto(
3047 To&: SearchName, From: D->getTypedefNameForAnonDecl()->getDeclName()))
3048 return std::move(Err);
3049 IDNS = Decl::IDNS_Ordinary;
3050 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
3051 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
3052
3053 bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
3054 : DC->isDependentContext();
3055 bool DependentFriend = IsFriendTemplate && IsDependentContext;
3056
3057 // We may already have a record of the same name; try to find and match it.
3058 RecordDecl *PrevDecl = nullptr;
3059 if (!DependentFriend && !DC->isFunctionOrMethod() && !D->isLambda()) {
3060 SmallVector<NamedDecl *, 4> ConflictingDecls;
3061 auto FoundDecls =
3062 Importer.findDeclsInToCtx(DC, Name: SearchName);
3063 if (!FoundDecls.empty()) {
3064 // We're going to have to compare D against potentially conflicting Decls,
3065 // so complete it.
3066 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
3067 D->getASTContext().getExternalSource()->CompleteType(Tag: D);
3068 }
3069
3070 for (auto *FoundDecl : FoundDecls) {
3071 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
3072 continue;
3073
3074 Decl *Found = FoundDecl;
3075 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Found)) {
3076 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
3077 Found = Tag->getDecl();
3078 }
3079
3080 if (auto *FoundRecord = dyn_cast<RecordDecl>(Val: Found)) {
3081 // Do not emit false positive diagnostic in case of unnamed
3082 // struct/union and in case of anonymous structs. Would be false
3083 // because there may be several anonymous/unnamed structs in a class.
3084 // E.g. these are both valid:
3085 // struct A { // unnamed structs
3086 // struct { struct A *next; } entry0;
3087 // struct { struct A *next; } entry1;
3088 // };
3089 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
3090 if (!SearchName)
3091 if (!IsStructuralMatch(From: D, To: FoundRecord, Complain: false))
3092 continue;
3093
3094 if (!hasSameVisibilityContextAndLinkage(Found: FoundRecord, From: D))
3095 continue;
3096
3097 if (IsStructuralMatch(From: D, To: FoundRecord)) {
3098 RecordDecl *FoundDef = FoundRecord->getDefinition();
3099 if (D->isThisDeclarationADefinition() && FoundDef) {
3100 // FIXME: Structural equivalence check should check for same
3101 // user-defined methods.
3102 Importer.MapImported(From: D, To: FoundDef);
3103 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(Val: D)) {
3104 auto *FoundCXX = dyn_cast<CXXRecordDecl>(Val: FoundDef);
3105 assert(FoundCXX && "Record type mismatch");
3106
3107 if (!Importer.isMinimalImport())
3108 // FoundDef may not have every implicit method that D has
3109 // because implicit methods are created only if they are used.
3110 if (Error Err = ImportImplicitMethods(From: DCXX, To: FoundCXX))
3111 return std::move(Err);
3112 }
3113 }
3114 PrevDecl = FoundRecord->getMostRecentDecl();
3115 break;
3116 }
3117 ConflictingDecls.push_back(Elt: FoundDecl);
3118 } // kind is RecordDecl
3119 } // for
3120
3121 if (!ConflictingDecls.empty() && SearchName) {
3122 ExpectedName NameOrErr = Importer.HandleNameConflict(
3123 Name: SearchName, DC, IDNS, Decls: ConflictingDecls.data(),
3124 NumDecls: ConflictingDecls.size());
3125 if (NameOrErr)
3126 Name = NameOrErr.get();
3127 else
3128 return NameOrErr.takeError();
3129 }
3130 }
3131
3132 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
3133 if (!BeginLocOrErr)
3134 return BeginLocOrErr.takeError();
3135
3136 // Create the record declaration.
3137 RecordDecl *D2 = nullptr;
3138 CXXRecordDecl *D2CXX = nullptr;
3139 if (auto *DCXX = dyn_cast<CXXRecordDecl>(Val: D)) {
3140 if (DCXX->isLambda()) {
3141 auto TInfoOrErr = import(From: DCXX->getLambdaTypeInfo());
3142 if (!TInfoOrErr)
3143 return TInfoOrErr.takeError();
3144 if (GetImportedOrCreateSpecialDecl(
3145 ToD&: D2CXX, CreateFun: CXXRecordDecl::CreateLambda, FromD: D, args&: Importer.getToContext(),
3146 args&: DC, args&: *TInfoOrErr, args&: Loc, args: DCXX->getLambdaDependencyKind(),
3147 args: DCXX->isGenericLambda(), args: DCXX->getLambdaCaptureDefault()))
3148 return D2CXX;
3149 CXXRecordDecl::LambdaNumbering Numbering = DCXX->getLambdaNumbering();
3150 ExpectedDecl CDeclOrErr = import(From: Numbering.ContextDecl);
3151 if (!CDeclOrErr)
3152 return CDeclOrErr.takeError();
3153 Numbering.ContextDecl = *CDeclOrErr;
3154 D2CXX->setLambdaNumbering(Numbering);
3155 } else if (DCXX->isInjectedClassName()) {
3156 // We have to be careful to do a similar dance to the one in
3157 // Sema::ActOnStartCXXMemberDeclarations
3158 const bool DelayTypeCreation = true;
3159 if (GetImportedOrCreateDecl(
3160 ToD&: D2CXX, FromD: D, args&: Importer.getToContext(), args: D->getTagKind(), args&: DC,
3161 args&: *BeginLocOrErr, args&: Loc, args: Name.getAsIdentifierInfo(),
3162 args: cast_or_null<CXXRecordDecl>(Val: PrevDecl), args: DelayTypeCreation))
3163 return D2CXX;
3164 Importer.getToContext().getTypeDeclType(
3165 Decl: D2CXX, PrevDecl: dyn_cast<CXXRecordDecl>(Val: DC));
3166 } else {
3167 if (GetImportedOrCreateDecl(ToD&: D2CXX, FromD: D, args&: Importer.getToContext(),
3168 args: D->getTagKind(), args&: DC, args&: *BeginLocOrErr, args&: Loc,
3169 args: Name.getAsIdentifierInfo(),
3170 args: cast_or_null<CXXRecordDecl>(Val: PrevDecl)))
3171 return D2CXX;
3172 }
3173
3174 D2 = D2CXX;
3175 D2->setAccess(D->getAccess());
3176 D2->setLexicalDeclContext(LexicalDC);
3177 addDeclToContexts(FromD: D, ToD: D2);
3178
3179 if (ClassTemplateDecl *FromDescribed =
3180 DCXX->getDescribedClassTemplate()) {
3181 ClassTemplateDecl *ToDescribed;
3182 if (Error Err = importInto(To&: ToDescribed, From: FromDescribed))
3183 return std::move(Err);
3184 D2CXX->setDescribedClassTemplate(ToDescribed);
3185 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
3186 // In a record describing a template the type should be an
3187 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
3188 // previously set type to the correct value here (ToDescribed is not
3189 // available at record create).
3190 CXXRecordDecl *Injected = nullptr;
3191 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
3192 auto *Record = dyn_cast<CXXRecordDecl>(Val: Found);
3193 if (Record && Record->isInjectedClassName()) {
3194 Injected = Record;
3195 break;
3196 }
3197 }
3198 // Create an injected type for the whole redecl chain.
3199 // The chain may contain an already existing injected type at the start,
3200 // if yes this should be reused. We must ensure that only one type
3201 // object exists for the injected type (including the injected record
3202 // declaration), ASTContext does not check it.
3203 SmallVector<Decl *, 2> Redecls =
3204 getCanonicalForwardRedeclChain(D: D2CXX);
3205 const Type *FrontTy =
3206 cast<CXXRecordDecl>(Val: Redecls.front())->getTypeForDecl();
3207 QualType InjSpec;
3208 if (auto *InjTy = FrontTy->getAs<InjectedClassNameType>())
3209 InjSpec = InjTy->getInjectedSpecializationType();
3210 else
3211 InjSpec = ToDescribed->getInjectedClassNameSpecialization();
3212 for (auto *R : Redecls) {
3213 auto *RI = cast<CXXRecordDecl>(Val: R);
3214 if (R != Redecls.front() ||
3215 !isa<InjectedClassNameType>(Val: RI->getTypeForDecl()))
3216 RI->setTypeForDecl(nullptr);
3217 // This function tries to get the injected type from getTypeForDecl,
3218 // then from the previous declaration if possible. If not, it creates
3219 // a new type.
3220 Importer.getToContext().getInjectedClassNameType(Decl: RI, TST: InjSpec);
3221 }
3222 // Set the new type for the injected decl too.
3223 if (Injected) {
3224 Injected->setTypeForDecl(nullptr);
3225 // This function will copy the injected type from D2CXX into Injected.
3226 // The injected decl does not have a previous decl to copy from.
3227 Importer.getToContext().getTypeDeclType(Decl: Injected, PrevDecl: D2CXX);
3228 }
3229 }
3230 } else if (MemberSpecializationInfo *MemberInfo =
3231 DCXX->getMemberSpecializationInfo()) {
3232 TemplateSpecializationKind SK =
3233 MemberInfo->getTemplateSpecializationKind();
3234 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
3235
3236 if (Expected<CXXRecordDecl *> ToInstOrErr = import(From: FromInst))
3237 D2CXX->setInstantiationOfMemberClass(RD: *ToInstOrErr, TSK: SK);
3238 else
3239 return ToInstOrErr.takeError();
3240
3241 if (ExpectedSLoc POIOrErr =
3242 import(From: MemberInfo->getPointOfInstantiation()))
3243 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
3244 *POIOrErr);
3245 else
3246 return POIOrErr.takeError();
3247 }
3248
3249 } else {
3250 if (GetImportedOrCreateDecl(ToD&: D2, FromD: D, args&: Importer.getToContext(),
3251 args: D->getTagKind(), args&: DC, args&: *BeginLocOrErr, args&: Loc,
3252 args: Name.getAsIdentifierInfo(), args&: PrevDecl))
3253 return D2;
3254 D2->setLexicalDeclContext(LexicalDC);
3255 addDeclToContexts(FromD: D, ToD: D2);
3256 }
3257
3258 if (auto BraceRangeOrErr = import(From: D->getBraceRange()))
3259 D2->setBraceRange(*BraceRangeOrErr);
3260 else
3261 return BraceRangeOrErr.takeError();
3262 if (auto QualifierLocOrErr = import(From: D->getQualifierLoc()))
3263 D2->setQualifierInfo(*QualifierLocOrErr);
3264 else
3265 return QualifierLocOrErr.takeError();
3266
3267 if (D->isAnonymousStructOrUnion())
3268 D2->setAnonymousStructOrUnion(true);
3269
3270 if (D->isCompleteDefinition())
3271 if (Error Err = ImportDefinition(From: D, To: D2, Kind: IDK_Default))
3272 return std::move(Err);
3273
3274 return D2;
3275}
3276
3277ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
3278 // Import the major distinguishing characteristics of this enumerator.
3279 DeclContext *DC, *LexicalDC;
3280 DeclarationName Name;
3281 SourceLocation Loc;
3282 NamedDecl *ToD;
3283 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3284 return std::move(Err);
3285 if (ToD)
3286 return ToD;
3287
3288 // Determine whether there are any other declarations with the same name and
3289 // in the same context.
3290 if (!LexicalDC->isFunctionOrMethod()) {
3291 SmallVector<NamedDecl *, 4> ConflictingDecls;
3292 unsigned IDNS = Decl::IDNS_Ordinary;
3293 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3294 for (auto *FoundDecl : FoundDecls) {
3295 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
3296 continue;
3297
3298 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(Val: FoundDecl)) {
3299 if (IsStructuralMatch(From: D, To: FoundEnumConstant))
3300 return Importer.MapImported(From: D, To: FoundEnumConstant);
3301 ConflictingDecls.push_back(Elt: FoundDecl);
3302 }
3303 }
3304
3305 if (!ConflictingDecls.empty()) {
3306 ExpectedName NameOrErr = Importer.HandleNameConflict(
3307 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
3308 if (NameOrErr)
3309 Name = NameOrErr.get();
3310 else
3311 return NameOrErr.takeError();
3312 }
3313 }
3314
3315 ExpectedType TypeOrErr = import(From: D->getType());
3316 if (!TypeOrErr)
3317 return TypeOrErr.takeError();
3318
3319 ExpectedExpr InitOrErr = import(From: D->getInitExpr());
3320 if (!InitOrErr)
3321 return InitOrErr.takeError();
3322
3323 EnumConstantDecl *ToEnumerator;
3324 if (GetImportedOrCreateDecl(
3325 ToD&: ToEnumerator, FromD: D, args&: Importer.getToContext(), args: cast<EnumDecl>(Val: DC), args&: Loc,
3326 args: Name.getAsIdentifierInfo(), args&: *TypeOrErr, args&: *InitOrErr, args: D->getInitVal()))
3327 return ToEnumerator;
3328
3329 ToEnumerator->setAccess(D->getAccess());
3330 ToEnumerator->setLexicalDeclContext(LexicalDC);
3331 LexicalDC->addDeclInternal(D: ToEnumerator);
3332 return ToEnumerator;
3333}
3334
3335template <typename DeclTy>
3336Error ASTNodeImporter::ImportTemplateParameterLists(const DeclTy *FromD,
3337 DeclTy *ToD) {
3338 unsigned int Num = FromD->getNumTemplateParameterLists();
3339 if (Num == 0)
3340 return Error::success();
3341 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
3342 for (unsigned int I = 0; I < Num; ++I)
3343 if (Expected<TemplateParameterList *> ToTPListOrErr =
3344 import(FromD->getTemplateParameterList(I)))
3345 ToTPLists[I] = *ToTPListOrErr;
3346 else
3347 return ToTPListOrErr.takeError();
3348 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3349 return Error::success();
3350}
3351
3352Error ASTNodeImporter::ImportTemplateInformation(
3353 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3354 switch (FromFD->getTemplatedKind()) {
3355 case FunctionDecl::TK_NonTemplate:
3356 case FunctionDecl::TK_FunctionTemplate:
3357 return Error::success();
3358
3359 case FunctionDecl::TK_DependentNonTemplate:
3360 if (Expected<FunctionDecl *> InstFDOrErr =
3361 import(From: FromFD->getInstantiatedFromDecl()))
3362 ToFD->setInstantiatedFromDecl(*InstFDOrErr);
3363 return Error::success();
3364 case FunctionDecl::TK_MemberSpecialization: {
3365 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
3366
3367 if (Expected<FunctionDecl *> InstFDOrErr =
3368 import(From: FromFD->getInstantiatedFromMemberFunction()))
3369 ToFD->setInstantiationOfMemberFunction(FD: *InstFDOrErr, TSK);
3370 else
3371 return InstFDOrErr.takeError();
3372
3373 if (ExpectedSLoc POIOrErr = import(
3374 From: FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
3375 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3376 else
3377 return POIOrErr.takeError();
3378
3379 return Error::success();
3380 }
3381
3382 case FunctionDecl::TK_FunctionTemplateSpecialization: {
3383 auto FunctionAndArgsOrErr =
3384 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3385 if (!FunctionAndArgsOrErr)
3386 return FunctionAndArgsOrErr.takeError();
3387
3388 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
3389 Context&: Importer.getToContext(), Args: std::get<1>(t&: *FunctionAndArgsOrErr));
3390
3391 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3392 TemplateArgumentListInfo ToTAInfo;
3393 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3394 if (FromTAArgsAsWritten)
3395 if (Error Err = ImportTemplateArgumentListInfo(
3396 From: *FromTAArgsAsWritten, Result&: ToTAInfo))
3397 return Err;
3398
3399 ExpectedSLoc POIOrErr = import(From: FTSInfo->getPointOfInstantiation());
3400 if (!POIOrErr)
3401 return POIOrErr.takeError();
3402
3403 if (Error Err = ImportTemplateParameterLists(FromD: FromFD, ToD: ToFD))
3404 return Err;
3405
3406 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3407 ToFD->setFunctionTemplateSpecialization(
3408 Template: std::get<0>(t&: *FunctionAndArgsOrErr), TemplateArgs: ToTAList, /* InsertPos= */ nullptr,
3409 TSK, TemplateArgsAsWritten: FromTAArgsAsWritten ? &ToTAInfo : nullptr, PointOfInstantiation: *POIOrErr);
3410 return Error::success();
3411 }
3412
3413 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
3414 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3415 UnresolvedSet<8> Candidates;
3416 for (FunctionTemplateDecl *FTD : FromInfo->getCandidates()) {
3417 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = import(From: FTD))
3418 Candidates.addDecl(D: *ToFTDOrErr);
3419 else
3420 return ToFTDOrErr.takeError();
3421 }
3422
3423 // Import TemplateArgumentListInfo.
3424 TemplateArgumentListInfo ToTAInfo;
3425 const auto *FromTAArgsAsWritten = FromInfo->TemplateArgumentsAsWritten;
3426 if (FromTAArgsAsWritten)
3427 if (Error Err =
3428 ImportTemplateArgumentListInfo(From: *FromTAArgsAsWritten, Result&: ToTAInfo))
3429 return Err;
3430
3431 ToFD->setDependentTemplateSpecialization(
3432 Context&: Importer.getToContext(), Templates: Candidates,
3433 TemplateArgs: FromTAArgsAsWritten ? &ToTAInfo : nullptr);
3434 return Error::success();
3435 }
3436 }
3437 llvm_unreachable("All cases should be covered!");
3438}
3439
3440Expected<FunctionDecl *>
3441ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
3442 auto FunctionAndArgsOrErr =
3443 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3444 if (!FunctionAndArgsOrErr)
3445 return FunctionAndArgsOrErr.takeError();
3446
3447 FunctionTemplateDecl *Template;
3448 TemplateArgsTy ToTemplArgs;
3449 std::tie(args&: Template, args&: ToTemplArgs) = *FunctionAndArgsOrErr;
3450 void *InsertPos = nullptr;
3451 auto *FoundSpec = Template->findSpecialization(Args: ToTemplArgs, InsertPos);
3452 return FoundSpec;
3453}
3454
3455Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
3456 FunctionDecl *ToFD) {
3457 if (Stmt *FromBody = FromFD->getBody()) {
3458 if (ExpectedStmt ToBodyOrErr = import(From: FromBody))
3459 ToFD->setBody(*ToBodyOrErr);
3460 else
3461 return ToBodyOrErr.takeError();
3462 }
3463 return Error::success();
3464}
3465
3466// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3467// which is equal to the given DC, or D is equal to DC.
3468static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3469 const DeclContext *DCi = dyn_cast<DeclContext>(Val: D);
3470 if (!DCi)
3471 DCi = D->getDeclContext();
3472 assert(DCi && "Declaration should have a context");
3473 while (DCi != D->getTranslationUnitDecl()) {
3474 if (DCi == DC)
3475 return true;
3476 DCi = DCi->getParent();
3477 }
3478 return false;
3479}
3480
3481// Check if there is a declaration that has 'DC' as parent context and is
3482// referenced from statement 'S' or one of its children. The search is done in
3483// BFS order through children of 'S'.
3484static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) {
3485 SmallVector<const Stmt *> ToProcess;
3486 ToProcess.push_back(Elt: S);
3487 while (!ToProcess.empty()) {
3488 const Stmt *CurrentS = ToProcess.pop_back_val();
3489 ToProcess.append(in_start: CurrentS->child_begin(), in_end: CurrentS->child_end());
3490 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: CurrentS)) {
3491 if (const Decl *D = DeclRef->getDecl())
3492 if (isAncestorDeclContextOf(DC, D))
3493 return true;
3494 } else if (const auto *E =
3495 dyn_cast_or_null<SubstNonTypeTemplateParmExpr>(Val: CurrentS)) {
3496 if (const Decl *D = E->getAssociatedDecl())
3497 if (isAncestorDeclContextOf(DC, D))
3498 return true;
3499 }
3500 }
3501 return false;
3502}
3503
3504namespace {
3505/// Check if a type has any reference to a declaration that is inside the body
3506/// of a function.
3507/// The \c CheckType(QualType) function should be used to determine
3508/// this property.
3509///
3510/// The type visitor visits one type object only (not recursive).
3511/// To find all referenced declarations we must discover all type objects until
3512/// the canonical type is reached (walk over typedef and similar objects). This
3513/// is done by loop over all "sugar" type objects. For every such type we must
3514/// check all declarations that are referenced from it. For this check the
3515/// visitor is used. In the visit functions all referenced declarations except
3516/// the one that follows in the sugar chain (if any) must be checked. For this
3517/// check the same visitor is re-used (it has no state-dependent data).
3518///
3519/// The visit functions have 3 possible return values:
3520/// - True, found a declaration inside \c ParentDC.
3521/// - False, found declarations only outside \c ParentDC and it is not possible
3522/// to find more declarations (the "sugar" chain does not continue).
3523/// - Empty optional value, found no declarations or only outside \c ParentDC,
3524/// but it is possible to find more declarations in the type "sugar" chain.
3525/// The loop over the "sugar" types can be implemented by using type visit
3526/// functions only (call \c CheckType with the desugared type). With the current
3527/// solution no visit function is needed if the type has only a desugared type
3528/// as data.
3529class IsTypeDeclaredInsideVisitor
3530 : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> {
3531public:
3532 IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC)
3533 : ParentDC(ParentDC) {}
3534
3535 bool CheckType(QualType T) {
3536 // Check the chain of "sugar" types.
3537 // The "sugar" types are typedef or similar types that have the same
3538 // canonical type.
3539 if (std::optional<bool> Res = Visit(T: T.getTypePtr()))
3540 return *Res;
3541 QualType DsT =
3542 T.getSingleStepDesugaredType(Context: ParentDC->getParentASTContext());
3543 while (DsT != T) {
3544 if (std::optional<bool> Res = Visit(T: DsT.getTypePtr()))
3545 return *Res;
3546 T = DsT;
3547 DsT = T.getSingleStepDesugaredType(Context: ParentDC->getParentASTContext());
3548 }
3549 return false;
3550 }
3551
3552 std::optional<bool> VisitTagType(const TagType *T) {
3553 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: T->getDecl()))
3554 for (const auto &Arg : Spec->getTemplateArgs().asArray())
3555 if (checkTemplateArgument(Arg))
3556 return true;
3557 return isAncestorDeclContextOf(DC: ParentDC, D: T->getDecl());
3558 }
3559
3560 std::optional<bool> VisitPointerType(const PointerType *T) {
3561 return CheckType(T: T->getPointeeType());
3562 }
3563
3564 std::optional<bool> VisitReferenceType(const ReferenceType *T) {
3565 return CheckType(T: T->getPointeeTypeAsWritten());
3566 }
3567
3568 std::optional<bool> VisitTypedefType(const TypedefType *T) {
3569 const TypedefNameDecl *TD = T->getDecl();
3570 assert(TD);
3571 return isAncestorDeclContextOf(DC: ParentDC, D: TD);
3572 }
3573
3574 std::optional<bool> VisitUsingType(const UsingType *T) {
3575 if (T->getFoundDecl() &&
3576 isAncestorDeclContextOf(DC: ParentDC, D: T->getFoundDecl()))
3577 return true;
3578
3579 return {};
3580 }
3581
3582 std::optional<bool>
3583 VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
3584 for (const auto &Arg : T->template_arguments())
3585 if (checkTemplateArgument(Arg))
3586 return true;
3587 // This type is a "sugar" to a record type, it can have a desugared type.
3588 return {};
3589 }
3590
3591 std::optional<bool>
3592 VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3593 // The "associated declaration" can be the same as ParentDC.
3594 if (isAncestorDeclContextOf(DC: ParentDC, D: T->getAssociatedDecl()))
3595 return true;
3596 return {};
3597 }
3598
3599 std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) {
3600 if (T->getSizeExpr() && isAncestorDeclContextOf(DC: ParentDC, S: T->getSizeExpr()))
3601 return true;
3602
3603 return CheckType(T: T->getElementType());
3604 }
3605
3606 std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) {
3607 llvm_unreachable(
3608 "Variable array should not occur in deduced return type of a function");
3609 }
3610
3611 std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) {
3612 llvm_unreachable("Incomplete array should not occur in deduced return type "
3613 "of a function");
3614 }
3615
3616 std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) {
3617 llvm_unreachable("Dependent array should not occur in deduced return type "
3618 "of a function");
3619 }
3620
3621private:
3622 const DeclContext *const ParentDC;
3623
3624 bool checkTemplateArgument(const TemplateArgument &Arg) {
3625 switch (Arg.getKind()) {
3626 case TemplateArgument::Null:
3627 return false;
3628 case TemplateArgument::Integral:
3629 return CheckType(T: Arg.getIntegralType());
3630 case TemplateArgument::Type:
3631 return CheckType(T: Arg.getAsType());
3632 case TemplateArgument::Expression:
3633 return isAncestorDeclContextOf(DC: ParentDC, S: Arg.getAsExpr());
3634 case TemplateArgument::Declaration:
3635 // FIXME: The declaration in this case is not allowed to be in a function?
3636 return isAncestorDeclContextOf(DC: ParentDC, D: Arg.getAsDecl());
3637 case TemplateArgument::NullPtr:
3638 // FIXME: The type is not allowed to be in the function?
3639 return CheckType(T: Arg.getNullPtrType());
3640 case TemplateArgument::StructuralValue:
3641 return CheckType(T: Arg.getStructuralValueType());
3642 case TemplateArgument::Pack:
3643 for (const auto &PackArg : Arg.getPackAsArray())
3644 if (checkTemplateArgument(Arg: PackArg))
3645 return true;
3646 return false;
3647 case TemplateArgument::Template:
3648 // Templates can not be defined locally in functions.
3649 // A template passed as argument can be not in ParentDC.
3650 return false;
3651 case TemplateArgument::TemplateExpansion:
3652 // Templates can not be defined locally in functions.
3653 // A template passed as argument can be not in ParentDC.
3654 return false;
3655 }
3656 llvm_unreachable("Unknown TemplateArgument::ArgKind enum");
3657 };
3658};
3659} // namespace
3660
3661/// This function checks if the given function has a return type that contains
3662/// a reference (in any way) to a declaration inside the same function.
3663bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
3664 QualType FromTy = D->getType();
3665 const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
3666 assert(FromFPT && "Must be called on FunctionProtoType");
3667
3668 auto IsCXX11LambdaWithouTrailingReturn = [&]() {
3669 if (Importer.FromContext.getLangOpts().CPlusPlus14) // C++14 or later
3670 return false;
3671
3672 if (FromFPT->hasTrailingReturn())
3673 return false;
3674
3675 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D))
3676 return cast<CXXRecordDecl>(Val: MD->getDeclContext())->isLambda();
3677
3678 return false;
3679 };
3680
3681 QualType RetT = FromFPT->getReturnType();
3682 if (isa<AutoType>(Val: RetT.getTypePtr()) || IsCXX11LambdaWithouTrailingReturn()) {
3683 FunctionDecl *Def = D->getDefinition();
3684 IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
3685 return Visitor.CheckType(T: RetT);
3686 }
3687
3688 return false;
3689}
3690
3691ExplicitSpecifier
3692ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3693 Expr *ExplicitExpr = ESpec.getExpr();
3694 if (ExplicitExpr)
3695 ExplicitExpr = importChecked(Err, From: ESpec.getExpr());
3696 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3697}
3698
3699ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3700
3701 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
3702 auto RedeclIt = Redecls.begin();
3703 // Import the first part of the decl chain. I.e. import all previous
3704 // declarations starting from the canonical decl.
3705 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3706 ExpectedDecl ToRedeclOrErr = import(From: *RedeclIt);
3707 if (!ToRedeclOrErr)
3708 return ToRedeclOrErr.takeError();
3709 }
3710 assert(*RedeclIt == D);
3711
3712 // Import the major distinguishing characteristics of this function.
3713 DeclContext *DC, *LexicalDC;
3714 DeclarationName Name;
3715 SourceLocation Loc;
3716 NamedDecl *ToD;
3717 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3718 return std::move(Err);
3719 if (ToD)
3720 return ToD;
3721
3722 FunctionDecl *FoundByLookup = nullptr;
3723 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3724
3725 // If this is a function template specialization, then try to find the same
3726 // existing specialization in the "to" context. The lookup below will not
3727 // find any specialization, but would find the primary template; thus, we
3728 // have to skip normal lookup in case of specializations.
3729 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3730 if (D->getTemplatedKind() ==
3731 FunctionDecl::TK_FunctionTemplateSpecialization) {
3732 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(FromFD: D);
3733 if (!FoundFunctionOrErr)
3734 return FoundFunctionOrErr.takeError();
3735 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3736 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3737 return Def;
3738 FoundByLookup = FoundFunction;
3739 }
3740 }
3741 // Try to find a function in our own ("to") context with the same name, same
3742 // type, and in the same context as the function we're importing.
3743 else if (!LexicalDC->isFunctionOrMethod()) {
3744 SmallVector<NamedDecl *, 4> ConflictingDecls;
3745 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3746 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3747 for (auto *FoundDecl : FoundDecls) {
3748 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
3749 continue;
3750
3751 if (auto *FoundFunction = dyn_cast<FunctionDecl>(Val: FoundDecl)) {
3752 if (!hasSameVisibilityContextAndLinkage(Found: FoundFunction, From: D))
3753 continue;
3754
3755 if (IsStructuralMatch(From: D, To: FoundFunction)) {
3756 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3757 return Def;
3758 FoundByLookup = FoundFunction;
3759 break;
3760 }
3761 // FIXME: Check for overloading more carefully, e.g., by boosting
3762 // Sema::IsOverload out to the AST library.
3763
3764 // Function overloading is okay in C++.
3765 if (Importer.getToContext().getLangOpts().CPlusPlus)
3766 continue;
3767
3768 // Complain about inconsistent function types.
3769 Importer.ToDiag(Loc, DiagID: diag::warn_odr_function_type_inconsistent)
3770 << Name << D->getType() << FoundFunction->getType();
3771 Importer.ToDiag(Loc: FoundFunction->getLocation(), DiagID: diag::note_odr_value_here)
3772 << FoundFunction->getType();
3773 ConflictingDecls.push_back(Elt: FoundDecl);
3774 }
3775 }
3776
3777 if (!ConflictingDecls.empty()) {
3778 ExpectedName NameOrErr = Importer.HandleNameConflict(
3779 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
3780 if (NameOrErr)
3781 Name = NameOrErr.get();
3782 else
3783 return NameOrErr.takeError();
3784 }
3785 }
3786
3787 // We do not allow more than one in-class declaration of a function. This is
3788 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3789 // assumes there is only one in-class declaration. Building a redecl
3790 // chain would result in more than one in-class declaration for
3791 // overrides (even if they are part of the same redecl chain inside the
3792 // derived class.)
3793 if (FoundByLookup) {
3794 if (isa<CXXMethodDecl>(Val: FoundByLookup)) {
3795 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3796 if (!D->doesThisDeclarationHaveABody()) {
3797 if (FunctionTemplateDecl *DescribedD =
3798 D->getDescribedFunctionTemplate()) {
3799 // Handle a "templated" function together with its described
3800 // template. This avoids need for a similar check at import of the
3801 // described template.
3802 assert(FoundByLookup->getDescribedFunctionTemplate() &&
3803 "Templated function mapped to non-templated?");
3804 Importer.MapImported(From: DescribedD,
3805 To: FoundByLookup->getDescribedFunctionTemplate());
3806 }
3807 return Importer.MapImported(From: D, To: FoundByLookup);
3808 } else {
3809 // Let's continue and build up the redecl chain in this case.
3810 // FIXME Merge the functions into one decl.
3811 }
3812 }
3813 }
3814 }
3815
3816 DeclarationNameInfo NameInfo(Name, Loc);
3817 // Import additional name location/type info.
3818 if (Error Err = ImportDeclarationNameLoc(From: D->getNameInfo(), To&: NameInfo))
3819 return std::move(Err);
3820
3821 QualType FromTy = D->getType();
3822 TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
3823 // Set to true if we do not import the type of the function as is. There are
3824 // cases when the original type would result in an infinite recursion during
3825 // the import. To avoid an infinite recursion when importing, we create the
3826 // FunctionDecl with a simplified function type and update it only after the
3827 // relevant AST nodes are already imported.
3828 // The type is related to TypeSourceInfo (it references the type), so we must
3829 // do the same with TypeSourceInfo.
3830 bool UsedDifferentProtoType = false;
3831 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3832 QualType FromReturnTy = FromFPT->getReturnType();
3833 // Functions with auto return type may define a struct inside their body
3834 // and the return type could refer to that struct.
3835 // E.g.: auto foo() { struct X{}; return X(); }
3836 // To avoid an infinite recursion when importing, create the FunctionDecl
3837 // with a simplified return type.
3838 if (hasReturnTypeDeclaredInside(D)) {
3839 FromReturnTy = Importer.getFromContext().VoidTy;
3840 UsedDifferentProtoType = true;
3841 }
3842 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3843 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3844 // FunctionDecl that we are importing the FunctionProtoType for.
3845 // To avoid an infinite recursion when importing, create the FunctionDecl
3846 // with a simplified function type.
3847 if (FromEPI.ExceptionSpec.SourceDecl ||
3848 FromEPI.ExceptionSpec.SourceTemplate ||
3849 FromEPI.ExceptionSpec.NoexceptExpr) {
3850 FunctionProtoType::ExtProtoInfo DefaultEPI;
3851 FromEPI = DefaultEPI;
3852 UsedDifferentProtoType = true;
3853 }
3854 FromTy = Importer.getFromContext().getFunctionType(
3855 ResultTy: FromReturnTy, Args: FromFPT->getParamTypes(), EPI: FromEPI);
3856 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
3857 T: FromTy, Loc: D->getBeginLoc());
3858 }
3859
3860 Error Err = Error::success();
3861 auto T = importChecked(Err, From: FromTy);
3862 auto TInfo = importChecked(Err, From: FromTSI);
3863 auto ToInnerLocStart = importChecked(Err, From: D->getInnerLocStart());
3864 auto ToEndLoc = importChecked(Err, From: D->getEndLoc());
3865 auto ToDefaultLoc = importChecked(Err, From: D->getDefaultLoc());
3866 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
3867 auto TrailingRequiresClause =
3868 importChecked(Err, From: D->getTrailingRequiresClause());
3869 if (Err)
3870 return std::move(Err);
3871
3872 // Import the function parameters.
3873 SmallVector<ParmVarDecl *, 8> Parameters;
3874 for (auto *P : D->parameters()) {
3875 if (Expected<ParmVarDecl *> ToPOrErr = import(From: P))
3876 Parameters.push_back(Elt: *ToPOrErr);
3877 else
3878 return ToPOrErr.takeError();
3879 }
3880
3881 // Create the imported function.
3882 FunctionDecl *ToFunction = nullptr;
3883 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
3884 ExplicitSpecifier ESpec =
3885 importExplicitSpecifier(Err, ESpec: FromConstructor->getExplicitSpecifier());
3886 if (Err)
3887 return std::move(Err);
3888 auto ToInheritedConstructor = InheritedConstructor();
3889 if (FromConstructor->isInheritingConstructor()) {
3890 Expected<InheritedConstructor> ImportedInheritedCtor =
3891 import(From: FromConstructor->getInheritedConstructor());
3892 if (!ImportedInheritedCtor)
3893 return ImportedInheritedCtor.takeError();
3894 ToInheritedConstructor = *ImportedInheritedCtor;
3895 }
3896 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3897 ToD&: ToFunction, FromD: D, args&: Importer.getToContext(), args: cast<CXXRecordDecl>(Val: DC),
3898 args&: ToInnerLocStart, args&: NameInfo, args&: T, args&: TInfo, args&: ESpec, args: D->UsesFPIntrin(),
3899 args: D->isInlineSpecified(), args: D->isImplicit(), args: D->getConstexprKind(),
3900 args&: ToInheritedConstructor, args&: TrailingRequiresClause))
3901 return ToFunction;
3902 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(Val: D)) {
3903
3904 Error Err = Error::success();
3905 auto ToOperatorDelete = importChecked(
3906 Err, From: const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3907 auto ToThisArg = importChecked(Err, From: FromDtor->getOperatorDeleteThisArg());
3908 if (Err)
3909 return std::move(Err);
3910
3911 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3912 ToD&: ToFunction, FromD: D, args&: Importer.getToContext(), args: cast<CXXRecordDecl>(Val: DC),
3913 args&: ToInnerLocStart, args&: NameInfo, args&: T, args&: TInfo, args: D->UsesFPIntrin(),
3914 args: D->isInlineSpecified(), args: D->isImplicit(), args: D->getConstexprKind(),
3915 args&: TrailingRequiresClause))
3916 return ToFunction;
3917
3918 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(Val: ToFunction);
3919
3920 ToDtor->setOperatorDelete(OD: ToOperatorDelete, ThisArg: ToThisArg);
3921 } else if (CXXConversionDecl *FromConversion =
3922 dyn_cast<CXXConversionDecl>(Val: D)) {
3923 ExplicitSpecifier ESpec =
3924 importExplicitSpecifier(Err, ESpec: FromConversion->getExplicitSpecifier());
3925 if (Err)
3926 return std::move(Err);
3927 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3928 ToD&: ToFunction, FromD: D, args&: Importer.getToContext(), args: cast<CXXRecordDecl>(Val: DC),
3929 args&: ToInnerLocStart, args&: NameInfo, args&: T, args&: TInfo, args: D->UsesFPIntrin(),
3930 args: D->isInlineSpecified(), args&: ESpec, args: D->getConstexprKind(),
3931 args: SourceLocation(), args&: TrailingRequiresClause))
3932 return ToFunction;
3933 } else if (auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
3934 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3935 ToD&: ToFunction, FromD: D, args&: Importer.getToContext(), args: cast<CXXRecordDecl>(Val: DC),
3936 args&: ToInnerLocStart, args&: NameInfo, args&: T, args&: TInfo, args: Method->getStorageClass(),
3937 args: Method->UsesFPIntrin(), args: Method->isInlineSpecified(),
3938 args: D->getConstexprKind(), args: SourceLocation(), args&: TrailingRequiresClause))
3939 return ToFunction;
3940 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) {
3941 ExplicitSpecifier ESpec =
3942 importExplicitSpecifier(Err, ESpec: Guide->getExplicitSpecifier());
3943 CXXConstructorDecl *Ctor =
3944 importChecked(Err, From: Guide->getCorrespondingConstructor());
3945 if (Err)
3946 return std::move(Err);
3947 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3948 ToD&: ToFunction, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToInnerLocStart, args&: ESpec,
3949 args&: NameInfo, args&: T, args&: TInfo, args&: ToEndLoc, args&: Ctor))
3950 return ToFunction;
3951 cast<CXXDeductionGuideDecl>(Val: ToFunction)
3952 ->setDeductionCandidateKind(Guide->getDeductionCandidateKind());
3953 } else {
3954 if (GetImportedOrCreateDecl(
3955 ToD&: ToFunction, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToInnerLocStart,
3956 args&: NameInfo, args&: T, args&: TInfo, args: D->getStorageClass(), args: D->UsesFPIntrin(),
3957 args: D->isInlineSpecified(), args: D->hasWrittenPrototype(),
3958 args: D->getConstexprKind(), args&: TrailingRequiresClause))
3959 return ToFunction;
3960 }
3961
3962 // Connect the redecl chain.
3963 if (FoundByLookup) {
3964 auto *Recent = const_cast<FunctionDecl *>(
3965 FoundByLookup->getMostRecentDecl());
3966 ToFunction->setPreviousDecl(Recent);
3967 // FIXME Probably we should merge exception specifications. E.g. In the
3968 // "To" context the existing function may have exception specification with
3969 // noexcept-unevaluated, while the newly imported function may have an
3970 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3971 // decl and its redeclarations may be required.
3972 }
3973
3974 StringLiteral *Msg = D->getDeletedMessage();
3975 if (Msg) {
3976 auto Imported = import(From: Msg);
3977 if (!Imported)
3978 return Imported.takeError();
3979 Msg = *Imported;
3980 }
3981
3982 ToFunction->setQualifierInfo(ToQualifierLoc);
3983 ToFunction->setAccess(D->getAccess());
3984 ToFunction->setLexicalDeclContext(LexicalDC);
3985 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3986 ToFunction->setTrivial(D->isTrivial());
3987 ToFunction->setIsPureVirtual(D->isPureVirtual());
3988 ToFunction->setDefaulted(D->isDefaulted());
3989 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3990 ToFunction->setDeletedAsWritten(D: D->isDeletedAsWritten());
3991 ToFunction->setFriendConstraintRefersToEnclosingTemplate(
3992 D->FriendConstraintRefersToEnclosingTemplate());
3993 ToFunction->setRangeEnd(ToEndLoc);
3994 ToFunction->setDefaultLoc(ToDefaultLoc);
3995
3996 if (Msg)
3997 ToFunction->setDefaultedOrDeletedInfo(
3998 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
3999 Context&: Importer.getToContext(), Lookups: {}, DeletedMessage: Msg));
4000
4001 // Set the parameters.
4002 for (auto *Param : Parameters) {
4003 Param->setOwningFunction(ToFunction);
4004 ToFunction->addDeclInternal(D: Param);
4005 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
4006 LT->update(ND: Param, OldDC: Importer.getToContext().getTranslationUnitDecl());
4007 }
4008 ToFunction->setParams(Parameters);
4009
4010 // We need to complete creation of FunctionProtoTypeLoc manually with setting
4011 // params it refers to.
4012 if (TInfo) {
4013 if (auto ProtoLoc =
4014 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
4015 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
4016 ProtoLoc.setParam(i: I, VD: Parameters[I]);
4017 }
4018 }
4019
4020 // Import the describing template function, if any.
4021 if (FromFT) {
4022 auto ToFTOrErr = import(From: FromFT);
4023 if (!ToFTOrErr)
4024 return ToFTOrErr.takeError();
4025 }
4026
4027 // Import Ctor initializers.
4028 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
4029 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
4030 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
4031 // Import first, then allocate memory and copy if there was no error.
4032 if (Error Err = ImportContainerChecked(
4033 InContainer: FromConstructor->inits(), OutContainer&: CtorInitializers))
4034 return std::move(Err);
4035 auto **Memory =
4036 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
4037 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
4038 auto *ToCtor = cast<CXXConstructorDecl>(Val: ToFunction);
4039 ToCtor->setCtorInitializers(Memory);
4040 ToCtor->setNumCtorInitializers(NumInitializers);
4041 }
4042 }
4043
4044 // If it is a template, import all related things.
4045 if (Error Err = ImportTemplateInformation(FromFD: D, ToFD: ToFunction))
4046 return std::move(Err);
4047
4048 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(Val: D))
4049 if (Error Err = ImportOverriddenMethods(ToMethod: cast<CXXMethodDecl>(Val: ToFunction),
4050 FromMethod: FromCXXMethod))
4051 return std::move(Err);
4052
4053 if (D->doesThisDeclarationHaveABody()) {
4054 Error Err = ImportFunctionDeclBody(FromFD: D, ToFD: ToFunction);
4055
4056 if (Err)
4057 return std::move(Err);
4058 }
4059
4060 // Import and set the original type in case we used another type.
4061 if (UsedDifferentProtoType) {
4062 if (ExpectedType TyOrErr = import(From: D->getType()))
4063 ToFunction->setType(*TyOrErr);
4064 else
4065 return TyOrErr.takeError();
4066 if (Expected<TypeSourceInfo *> TSIOrErr = import(From: D->getTypeSourceInfo()))
4067 ToFunction->setTypeSourceInfo(*TSIOrErr);
4068 else
4069 return TSIOrErr.takeError();
4070 }
4071
4072 // FIXME: Other bits to merge?
4073
4074 addDeclToContexts(FromD: D, ToD: ToFunction);
4075
4076 // Import the rest of the chain. I.e. import all subsequent declarations.
4077 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4078 ExpectedDecl ToRedeclOrErr = import(From: *RedeclIt);
4079 if (!ToRedeclOrErr)
4080 return ToRedeclOrErr.takeError();
4081 }
4082
4083 return ToFunction;
4084}
4085
4086ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
4087 return VisitFunctionDecl(D);
4088}
4089
4090ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
4091 return VisitCXXMethodDecl(D);
4092}
4093
4094ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
4095 return VisitCXXMethodDecl(D);
4096}
4097
4098ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
4099 return VisitCXXMethodDecl(D);
4100}
4101
4102ExpectedDecl
4103ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4104 return VisitFunctionDecl(D);
4105}
4106
4107ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
4108 // Import the major distinguishing characteristics of a variable.
4109 DeclContext *DC, *LexicalDC;
4110 DeclarationName Name;
4111 SourceLocation Loc;
4112 NamedDecl *ToD;
4113 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4114 return std::move(Err);
4115 if (ToD)
4116 return ToD;
4117
4118 // Determine whether we've already imported this field.
4119 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4120 for (auto *FoundDecl : FoundDecls) {
4121 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(Val: FoundDecl)) {
4122 // For anonymous fields, match up by index.
4123 if (!Name &&
4124 ASTImporter::getFieldIndex(F: D) !=
4125 ASTImporter::getFieldIndex(F: FoundField))
4126 continue;
4127
4128 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4129 To: FoundField->getType())) {
4130 Importer.MapImported(From: D, To: FoundField);
4131 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
4132 // initializer of a FieldDecl might not had been instantiated in the
4133 // "To" context. However, the "From" context might instantiated that,
4134 // thus we have to merge that.
4135 // Note: `hasInClassInitializer()` is not the same as non-null
4136 // `getInClassInitializer()` value.
4137 if (Expr *FromInitializer = D->getInClassInitializer()) {
4138 if (ExpectedExpr ToInitializerOrErr = import(From: FromInitializer)) {
4139 // Import of the FromInitializer may result in the setting of
4140 // InClassInitializer. If not, set it here.
4141 assert(FoundField->hasInClassInitializer() &&
4142 "Field should have an in-class initializer if it has an "
4143 "expression for it.");
4144 if (!FoundField->getInClassInitializer())
4145 FoundField->setInClassInitializer(*ToInitializerOrErr);
4146 } else {
4147 return ToInitializerOrErr.takeError();
4148 }
4149 }
4150 return FoundField;
4151 }
4152
4153 // FIXME: Why is this case not handled with calling HandleNameConflict?
4154 Importer.ToDiag(Loc, DiagID: diag::warn_odr_field_type_inconsistent)
4155 << Name << D->getType() << FoundField->getType();
4156 Importer.ToDiag(Loc: FoundField->getLocation(), DiagID: diag::note_odr_value_here)
4157 << FoundField->getType();
4158
4159 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4160 }
4161 }
4162
4163 Error Err = Error::success();
4164 auto ToType = importChecked(Err, From: D->getType());
4165 auto ToTInfo = importChecked(Err, From: D->getTypeSourceInfo());
4166 auto ToBitWidth = importChecked(Err, From: D->getBitWidth());
4167 auto ToInnerLocStart = importChecked(Err, From: D->getInnerLocStart());
4168 if (Err)
4169 return std::move(Err);
4170 const Type *ToCapturedVLAType = nullptr;
4171 if (Error Err = Importer.importInto(
4172 To&: ToCapturedVLAType, From: cast_or_null<Type>(Val: D->getCapturedVLAType())))
4173 return std::move(Err);
4174
4175 FieldDecl *ToField;
4176 if (GetImportedOrCreateDecl(ToD&: ToField, FromD: D, args&: Importer.getToContext(), args&: DC,
4177 args&: ToInnerLocStart, args&: Loc, args: Name.getAsIdentifierInfo(),
4178 args&: ToType, args&: ToTInfo, args&: ToBitWidth, args: D->isMutable(),
4179 args: D->getInClassInitStyle()))
4180 return ToField;
4181
4182 // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before
4183 // we add fields in CXXRecordDecl::addedMember, otherwise record will be
4184 // marked as having non-zero size.
4185 Err = Importer.ImportAttrs(ToD: ToField, FromD: D);
4186 if (Err)
4187 return std::move(Err);
4188 ToField->setAccess(D->getAccess());
4189 ToField->setLexicalDeclContext(LexicalDC);
4190 ToField->setImplicit(D->isImplicit());
4191 if (ToCapturedVLAType)
4192 ToField->setCapturedVLAType(cast<VariableArrayType>(Val: ToCapturedVLAType));
4193 LexicalDC->addDeclInternal(D: ToField);
4194 // Import initializer only after the field was created, it may have recursive
4195 // reference to the field.
4196 auto ToInitializer = importChecked(Err, From: D->getInClassInitializer());
4197 if (Err)
4198 return std::move(Err);
4199 if (ToInitializer) {
4200 auto *AlreadyImported = ToField->getInClassInitializer();
4201 if (AlreadyImported)
4202 assert(ToInitializer == AlreadyImported &&
4203 "Duplicate import of in-class initializer.");
4204 else
4205 ToField->setInClassInitializer(ToInitializer);
4206 }
4207
4208 return ToField;
4209}
4210
4211ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
4212 // Import the major distinguishing characteristics of a variable.
4213 DeclContext *DC, *LexicalDC;
4214 DeclarationName Name;
4215 SourceLocation Loc;
4216 NamedDecl *ToD;
4217 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4218 return std::move(Err);
4219 if (ToD)
4220 return ToD;
4221
4222 // Determine whether we've already imported this field.
4223 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4224 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4225 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(Val: FoundDecls[I])) {
4226 // For anonymous indirect fields, match up by index.
4227 if (!Name &&
4228 ASTImporter::getFieldIndex(F: D) !=
4229 ASTImporter::getFieldIndex(F: FoundField))
4230 continue;
4231
4232 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4233 To: FoundField->getType(),
4234 Complain: !Name.isEmpty())) {
4235 Importer.MapImported(From: D, To: FoundField);
4236 return FoundField;
4237 }
4238
4239 // If there are more anonymous fields to check, continue.
4240 if (!Name && I < N-1)
4241 continue;
4242
4243 // FIXME: Why is this case not handled with calling HandleNameConflict?
4244 Importer.ToDiag(Loc, DiagID: diag::warn_odr_field_type_inconsistent)
4245 << Name << D->getType() << FoundField->getType();
4246 Importer.ToDiag(Loc: FoundField->getLocation(), DiagID: diag::note_odr_value_here)
4247 << FoundField->getType();
4248
4249 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4250 }
4251 }
4252
4253 // Import the type.
4254 auto TypeOrErr = import(From: D->getType());
4255 if (!TypeOrErr)
4256 return TypeOrErr.takeError();
4257
4258 auto **NamedChain =
4259 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
4260
4261 unsigned i = 0;
4262 for (auto *PI : D->chain())
4263 if (Expected<NamedDecl *> ToD = import(From: PI))
4264 NamedChain[i++] = *ToD;
4265 else
4266 return ToD.takeError();
4267
4268 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
4269 IndirectFieldDecl *ToIndirectField;
4270 if (GetImportedOrCreateDecl(ToD&: ToIndirectField, FromD: D, args&: Importer.getToContext(), args&: DC,
4271 args&: Loc, args: Name.getAsIdentifierInfo(), args&: *TypeOrErr, args&: CH))
4272 // FIXME here we leak `NamedChain` which is allocated before
4273 return ToIndirectField;
4274
4275 ToIndirectField->setAccess(D->getAccess());
4276 ToIndirectField->setLexicalDeclContext(LexicalDC);
4277 LexicalDC->addDeclInternal(D: ToIndirectField);
4278 return ToIndirectField;
4279}
4280
4281/// Used as return type of getFriendCountAndPosition.
4282struct FriendCountAndPosition {
4283 /// Number of similar looking friends.
4284 unsigned int TotalCount;
4285 /// Index of the specific FriendDecl.
4286 unsigned int IndexOfDecl;
4287};
4288
4289static bool IsEquivalentFriend(ASTImporter &Importer, FriendDecl *FD1,
4290 FriendDecl *FD2) {
4291 if ((!FD1->getFriendType()) != (!FD2->getFriendType()))
4292 return false;
4293
4294 if (const TypeSourceInfo *TSI = FD1->getFriendType())
4295 return Importer.IsStructurallyEquivalent(
4296 From: TSI->getType(), To: FD2->getFriendType()->getType(), /*Complain=*/false);
4297
4298 ASTImporter::NonEquivalentDeclSet NonEquivalentDecls;
4299 StructuralEquivalenceContext Ctx(
4300 FD1->getASTContext(), FD2->getASTContext(), NonEquivalentDecls,
4301 StructuralEquivalenceKind::Default,
4302 /* StrictTypeSpelling = */ false, /* Complain = */ false);
4303 return Ctx.IsEquivalent(D1: FD1, D2: FD2);
4304}
4305
4306static FriendCountAndPosition getFriendCountAndPosition(ASTImporter &Importer,
4307 FriendDecl *FD) {
4308 unsigned int FriendCount = 0;
4309 std::optional<unsigned int> FriendPosition;
4310 const auto *RD = cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
4311
4312 for (FriendDecl *FoundFriend : RD->friends()) {
4313 if (FoundFriend == FD) {
4314 FriendPosition = FriendCount;
4315 ++FriendCount;
4316 } else if (IsEquivalentFriend(Importer, FD1: FD, FD2: FoundFriend)) {
4317 ++FriendCount;
4318 }
4319 }
4320
4321 assert(FriendPosition && "Friend decl not found in own parent.");
4322
4323 return {.TotalCount: FriendCount, .IndexOfDecl: *FriendPosition};
4324}
4325
4326ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
4327 // Import the major distinguishing characteristics of a declaration.
4328 DeclContext *DC, *LexicalDC;
4329 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
4330 return std::move(Err);
4331
4332 // Determine whether we've already imported this decl.
4333 // FriendDecl is not a NamedDecl so we cannot use lookup.
4334 // We try to maintain order and count of redundant friend declarations.
4335 const auto *RD = cast<CXXRecordDecl>(Val: DC);
4336 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
4337 for (FriendDecl *ImportedFriend : RD->friends())
4338 if (IsEquivalentFriend(Importer, FD1: D, FD2: ImportedFriend))
4339 ImportedEquivalentFriends.push_back(Elt: ImportedFriend);
4340
4341 FriendCountAndPosition CountAndPosition =
4342 getFriendCountAndPosition(Importer, FD: D);
4343
4344 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
4345 "Class with non-matching friends is imported, ODR check wrong?");
4346 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
4347 return Importer.MapImported(
4348 From: D, To: ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
4349
4350 // Not found. Create it.
4351 // The declarations will be put into order later by ImportDeclContext.
4352 FriendDecl::FriendUnion ToFU;
4353 if (NamedDecl *FriendD = D->getFriendDecl()) {
4354 NamedDecl *ToFriendD;
4355 if (Error Err = importInto(To&: ToFriendD, From: FriendD))
4356 return std::move(Err);
4357
4358 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
4359 !(FriendD->isInIdentifierNamespace(NS: Decl::IDNS_NonMemberOperator)))
4360 ToFriendD->setObjectOfFriendDecl(false);
4361
4362 ToFU = ToFriendD;
4363 } else { // The friend is a type, not a decl.
4364 if (auto TSIOrErr = import(From: D->getFriendType()))
4365 ToFU = *TSIOrErr;
4366 else
4367 return TSIOrErr.takeError();
4368 }
4369
4370 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
4371 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
4372 for (unsigned I = 0; I < D->NumTPLists; I++) {
4373 if (auto ListOrErr = import(From: FromTPLists[I]))
4374 ToTPLists[I] = *ListOrErr;
4375 else
4376 return ListOrErr.takeError();
4377 }
4378
4379 auto LocationOrErr = import(From: D->getLocation());
4380 if (!LocationOrErr)
4381 return LocationOrErr.takeError();
4382 auto FriendLocOrErr = import(From: D->getFriendLoc());
4383 if (!FriendLocOrErr)
4384 return FriendLocOrErr.takeError();
4385
4386 FriendDecl *FrD;
4387 if (GetImportedOrCreateDecl(ToD&: FrD, FromD: D, args&: Importer.getToContext(), args&: DC,
4388 args&: *LocationOrErr, args&: ToFU,
4389 args&: *FriendLocOrErr, args&: ToTPLists))
4390 return FrD;
4391
4392 FrD->setAccess(D->getAccess());
4393 FrD->setLexicalDeclContext(LexicalDC);
4394 LexicalDC->addDeclInternal(D: FrD);
4395 return FrD;
4396}
4397
4398ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
4399 // Import the major distinguishing characteristics of an ivar.
4400 DeclContext *DC, *LexicalDC;
4401 DeclarationName Name;
4402 SourceLocation Loc;
4403 NamedDecl *ToD;
4404 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4405 return std::move(Err);
4406 if (ToD)
4407 return ToD;
4408
4409 // Determine whether we've already imported this ivar
4410 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4411 for (auto *FoundDecl : FoundDecls) {
4412 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(Val: FoundDecl)) {
4413 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4414 To: FoundIvar->getType())) {
4415 Importer.MapImported(From: D, To: FoundIvar);
4416 return FoundIvar;
4417 }
4418
4419 Importer.ToDiag(Loc, DiagID: diag::warn_odr_ivar_type_inconsistent)
4420 << Name << D->getType() << FoundIvar->getType();
4421 Importer.ToDiag(Loc: FoundIvar->getLocation(), DiagID: diag::note_odr_value_here)
4422 << FoundIvar->getType();
4423
4424 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4425 }
4426 }
4427
4428 Error Err = Error::success();
4429 auto ToType = importChecked(Err, From: D->getType());
4430 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
4431 auto ToBitWidth = importChecked(Err, From: D->getBitWidth());
4432 auto ToInnerLocStart = importChecked(Err, From: D->getInnerLocStart());
4433 if (Err)
4434 return std::move(Err);
4435
4436 ObjCIvarDecl *ToIvar;
4437 if (GetImportedOrCreateDecl(
4438 ToD&: ToIvar, FromD: D, args&: Importer.getToContext(), args: cast<ObjCContainerDecl>(Val: DC),
4439 args&: ToInnerLocStart, args&: Loc, args: Name.getAsIdentifierInfo(),
4440 args&: ToType, args&: ToTypeSourceInfo,
4441 args: D->getAccessControl(),args&: ToBitWidth, args: D->getSynthesize()))
4442 return ToIvar;
4443
4444 ToIvar->setLexicalDeclContext(LexicalDC);
4445 LexicalDC->addDeclInternal(D: ToIvar);
4446 return ToIvar;
4447}
4448
4449ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
4450
4451 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
4452 auto RedeclIt = Redecls.begin();
4453 // Import the first part of the decl chain. I.e. import all previous
4454 // declarations starting from the canonical decl.
4455 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4456 ExpectedDecl RedeclOrErr = import(From: *RedeclIt);
4457 if (!RedeclOrErr)
4458 return RedeclOrErr.takeError();
4459 }
4460 assert(*RedeclIt == D);
4461
4462 // Import the major distinguishing characteristics of a variable.
4463 DeclContext *DC, *LexicalDC;
4464 DeclarationName Name;
4465 SourceLocation Loc;
4466 NamedDecl *ToD;
4467 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4468 return std::move(Err);
4469 if (ToD)
4470 return ToD;
4471
4472 // Try to find a variable in our own ("to") context with the same name and
4473 // in the same context as the variable we're importing.
4474 VarDecl *FoundByLookup = nullptr;
4475 if (D->isFileVarDecl()) {
4476 SmallVector<NamedDecl *, 4> ConflictingDecls;
4477 unsigned IDNS = Decl::IDNS_Ordinary;
4478 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4479 for (auto *FoundDecl : FoundDecls) {
4480 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
4481 continue;
4482
4483 if (auto *FoundVar = dyn_cast<VarDecl>(Val: FoundDecl)) {
4484 if (!hasSameVisibilityContextAndLinkage(Found: FoundVar, From: D))
4485 continue;
4486 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4487 To: FoundVar->getType())) {
4488
4489 // The VarDecl in the "From" context has a definition, but in the
4490 // "To" context we already have a definition.
4491 VarDecl *FoundDef = FoundVar->getDefinition();
4492 if (D->isThisDeclarationADefinition() && FoundDef)
4493 // FIXME Check for ODR error if the two definitions have
4494 // different initializers?
4495 return Importer.MapImported(From: D, To: FoundDef);
4496
4497 // The VarDecl in the "From" context has an initializer, but in the
4498 // "To" context we already have an initializer.
4499 const VarDecl *FoundDInit = nullptr;
4500 if (D->getInit() && FoundVar->getAnyInitializer(D&: FoundDInit))
4501 // FIXME Diagnose ODR error if the two initializers are different?
4502 return Importer.MapImported(From: D, To: const_cast<VarDecl*>(FoundDInit));
4503
4504 FoundByLookup = FoundVar;
4505 break;
4506 }
4507
4508 const ArrayType *FoundArray
4509 = Importer.getToContext().getAsArrayType(T: FoundVar->getType());
4510 const ArrayType *TArray
4511 = Importer.getToContext().getAsArrayType(T: D->getType());
4512 if (FoundArray && TArray) {
4513 if (isa<IncompleteArrayType>(Val: FoundArray) &&
4514 isa<ConstantArrayType>(Val: TArray)) {
4515 // Import the type.
4516 if (auto TyOrErr = import(From: D->getType()))
4517 FoundVar->setType(*TyOrErr);
4518 else
4519 return TyOrErr.takeError();
4520
4521 FoundByLookup = FoundVar;
4522 break;
4523 } else if (isa<IncompleteArrayType>(Val: TArray) &&
4524 isa<ConstantArrayType>(Val: FoundArray)) {
4525 FoundByLookup = FoundVar;
4526 break;
4527 }
4528 }
4529
4530 Importer.ToDiag(Loc, DiagID: diag::warn_odr_variable_type_inconsistent)
4531 << Name << D->getType() << FoundVar->getType();
4532 Importer.ToDiag(Loc: FoundVar->getLocation(), DiagID: diag::note_odr_value_here)
4533 << FoundVar->getType();
4534 ConflictingDecls.push_back(Elt: FoundDecl);
4535 }
4536 }
4537
4538 if (!ConflictingDecls.empty()) {
4539 ExpectedName NameOrErr = Importer.HandleNameConflict(
4540 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
4541 if (NameOrErr)
4542 Name = NameOrErr.get();
4543 else
4544 return NameOrErr.takeError();
4545 }
4546 }
4547
4548 Error Err = Error::success();
4549 auto ToType = importChecked(Err, From: D->getType());
4550 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
4551 auto ToInnerLocStart = importChecked(Err, From: D->getInnerLocStart());
4552 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
4553 if (Err)
4554 return std::move(Err);
4555
4556 VarDecl *ToVar;
4557 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(Val: D)) {
4558 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4559 if (Error Err =
4560 ImportArrayChecked(InContainer: FromDecomp->bindings(), Obegin: Bindings.begin()))
4561 return std::move(Err);
4562 DecompositionDecl *ToDecomp;
4563 if (GetImportedOrCreateDecl(
4564 ToD&: ToDecomp, FromD: FromDecomp, args&: Importer.getToContext(), args&: DC, args&: ToInnerLocStart,
4565 args&: Loc, args&: ToType, args&: ToTypeSourceInfo, args: D->getStorageClass(), args&: Bindings))
4566 return ToDecomp;
4567 ToVar = ToDecomp;
4568 } else {
4569 // Create the imported variable.
4570 if (GetImportedOrCreateDecl(ToD&: ToVar, FromD: D, args&: Importer.getToContext(), args&: DC,
4571 args&: ToInnerLocStart, args&: Loc,
4572 args: Name.getAsIdentifierInfo(), args&: ToType,
4573 args&: ToTypeSourceInfo, args: D->getStorageClass()))
4574 return ToVar;
4575 }
4576
4577 ToVar->setTSCSpec(D->getTSCSpec());
4578 ToVar->setQualifierInfo(ToQualifierLoc);
4579 ToVar->setAccess(D->getAccess());
4580 ToVar->setLexicalDeclContext(LexicalDC);
4581 if (D->isInlineSpecified())
4582 ToVar->setInlineSpecified();
4583 if (D->isInline())
4584 ToVar->setImplicitlyInline();
4585
4586 if (FoundByLookup) {
4587 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4588 ToVar->setPreviousDecl(Recent);
4589 }
4590
4591 // Import the described template, if any.
4592 if (D->getDescribedVarTemplate()) {
4593 auto ToVTOrErr = import(From: D->getDescribedVarTemplate());
4594 if (!ToVTOrErr)
4595 return ToVTOrErr.takeError();
4596 } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) {
4597 TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
4598 VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
4599 if (Expected<VarDecl *> ToInstOrErr = import(From: FromInst))
4600 ToVar->setInstantiationOfStaticDataMember(VD: *ToInstOrErr, TSK: SK);
4601 else
4602 return ToInstOrErr.takeError();
4603 if (ExpectedSLoc POIOrErr = import(From: MSI->getPointOfInstantiation()))
4604 ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
4605 else
4606 return POIOrErr.takeError();
4607 }
4608
4609 if (Error Err = ImportInitializer(From: D, To: ToVar))
4610 return std::move(Err);
4611
4612 if (D->isConstexpr())
4613 ToVar->setConstexpr(true);
4614
4615 addDeclToContexts(FromD: D, ToD: ToVar);
4616
4617 // Import the rest of the chain. I.e. import all subsequent declarations.
4618 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4619 ExpectedDecl RedeclOrErr = import(From: *RedeclIt);
4620 if (!RedeclOrErr)
4621 return RedeclOrErr.takeError();
4622 }
4623
4624 return ToVar;
4625}
4626
4627ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
4628 // Parameters are created in the translation unit's context, then moved
4629 // into the function declaration's context afterward.
4630 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4631
4632 Error Err = Error::success();
4633 auto ToDeclName = importChecked(Err, From: D->getDeclName());
4634 auto ToLocation = importChecked(Err, From: D->getLocation());
4635 auto ToType = importChecked(Err, From: D->getType());
4636 if (Err)
4637 return std::move(Err);
4638
4639 // Create the imported parameter.
4640 ImplicitParamDecl *ToParm = nullptr;
4641 if (GetImportedOrCreateDecl(ToD&: ToParm, FromD: D, args&: Importer.getToContext(), args&: DC,
4642 args&: ToLocation, args: ToDeclName.getAsIdentifierInfo(),
4643 args&: ToType, args: D->getParameterKind()))
4644 return ToParm;
4645 return ToParm;
4646}
4647
4648Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
4649 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4650 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4651 ToParam->setExplicitObjectParameterLoc(
4652 FromParam->getExplicitObjectParamThisLoc());
4653 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4654
4655 if (FromParam->hasUninstantiatedDefaultArg()) {
4656 if (auto ToDefArgOrErr = import(From: FromParam->getUninstantiatedDefaultArg()))
4657 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4658 else
4659 return ToDefArgOrErr.takeError();
4660 } else if (FromParam->hasUnparsedDefaultArg()) {
4661 ToParam->setUnparsedDefaultArg();
4662 } else if (FromParam->hasDefaultArg()) {
4663 if (auto ToDefArgOrErr = import(From: FromParam->getDefaultArg()))
4664 ToParam->setDefaultArg(*ToDefArgOrErr);
4665 else
4666 return ToDefArgOrErr.takeError();
4667 }
4668
4669 return Error::success();
4670}
4671
4672Expected<InheritedConstructor>
4673ASTNodeImporter::ImportInheritedConstructor(const InheritedConstructor &From) {
4674 Error Err = Error::success();
4675 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From: From.getConstructor());
4676 ConstructorUsingShadowDecl *ToShadow =
4677 importChecked(Err, From: From.getShadowDecl());
4678 if (Err)
4679 return std::move(Err);
4680 return InheritedConstructor(ToShadow, ToBaseCtor);
4681}
4682
4683ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
4684 // Parameters are created in the translation unit's context, then moved
4685 // into the function declaration's context afterward.
4686 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4687
4688 Error Err = Error::success();
4689 auto ToDeclName = importChecked(Err, From: D->getDeclName());
4690 auto ToLocation = importChecked(Err, From: D->getLocation());
4691 auto ToInnerLocStart = importChecked(Err, From: D->getInnerLocStart());
4692 auto ToType = importChecked(Err, From: D->getType());
4693 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
4694 if (Err)
4695 return std::move(Err);
4696
4697 ParmVarDecl *ToParm;
4698 if (GetImportedOrCreateDecl(ToD&: ToParm, FromD: D, args&: Importer.getToContext(), args&: DC,
4699 args&: ToInnerLocStart, args&: ToLocation,
4700 args: ToDeclName.getAsIdentifierInfo(), args&: ToType,
4701 args&: ToTypeSourceInfo, args: D->getStorageClass(),
4702 /*DefaultArg*/ args: nullptr))
4703 return ToParm;
4704
4705 // Set the default argument. It should be no problem if it was already done.
4706 // Do not import the default expression before GetImportedOrCreateDecl call
4707 // to avoid possible infinite import loop because circular dependency.
4708 if (Error Err = ImportDefaultArgOfParmVarDecl(FromParam: D, ToParam: ToParm))
4709 return std::move(Err);
4710
4711 if (D->isObjCMethodParameter()) {
4712 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4713 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4714 } else {
4715 ToParm->setScopeInfo(scopeDepth: D->getFunctionScopeDepth(),
4716 parameterIndex: D->getFunctionScopeIndex());
4717 }
4718
4719 return ToParm;
4720}
4721
4722ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
4723 // Import the major distinguishing characteristics of a method.
4724 DeclContext *DC, *LexicalDC;
4725 DeclarationName Name;
4726 SourceLocation Loc;
4727 NamedDecl *ToD;
4728 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4729 return std::move(Err);
4730 if (ToD)
4731 return ToD;
4732
4733 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4734 for (auto *FoundDecl : FoundDecls) {
4735 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(Val: FoundDecl)) {
4736 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4737 continue;
4738
4739 // Check return types.
4740 if (!Importer.IsStructurallyEquivalent(From: D->getReturnType(),
4741 To: FoundMethod->getReturnType())) {
4742 Importer.ToDiag(Loc, DiagID: diag::warn_odr_objc_method_result_type_inconsistent)
4743 << D->isInstanceMethod() << Name << D->getReturnType()
4744 << FoundMethod->getReturnType();
4745 Importer.ToDiag(Loc: FoundMethod->getLocation(),
4746 DiagID: diag::note_odr_objc_method_here)
4747 << D->isInstanceMethod() << Name;
4748
4749 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4750 }
4751
4752 // Check the number of parameters.
4753 if (D->param_size() != FoundMethod->param_size()) {
4754 Importer.ToDiag(Loc, DiagID: diag::warn_odr_objc_method_num_params_inconsistent)
4755 << D->isInstanceMethod() << Name
4756 << D->param_size() << FoundMethod->param_size();
4757 Importer.ToDiag(Loc: FoundMethod->getLocation(),
4758 DiagID: diag::note_odr_objc_method_here)
4759 << D->isInstanceMethod() << Name;
4760
4761 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4762 }
4763
4764 // Check parameter types.
4765 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4766 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4767 P != PEnd; ++P, ++FoundP) {
4768 if (!Importer.IsStructurallyEquivalent(From: (*P)->getType(),
4769 To: (*FoundP)->getType())) {
4770 Importer.FromDiag(Loc: (*P)->getLocation(),
4771 DiagID: diag::warn_odr_objc_method_param_type_inconsistent)
4772 << D->isInstanceMethod() << Name
4773 << (*P)->getType() << (*FoundP)->getType();
4774 Importer.ToDiag(Loc: (*FoundP)->getLocation(), DiagID: diag::note_odr_value_here)
4775 << (*FoundP)->getType();
4776
4777 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4778 }
4779 }
4780
4781 // Check variadic/non-variadic.
4782 // Check the number of parameters.
4783 if (D->isVariadic() != FoundMethod->isVariadic()) {
4784 Importer.ToDiag(Loc, DiagID: diag::warn_odr_objc_method_variadic_inconsistent)
4785 << D->isInstanceMethod() << Name;
4786 Importer.ToDiag(Loc: FoundMethod->getLocation(),
4787 DiagID: diag::note_odr_objc_method_here)
4788 << D->isInstanceMethod() << Name;
4789
4790 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4791 }
4792
4793 // FIXME: Any other bits we need to merge?
4794 return Importer.MapImported(From: D, To: FoundMethod);
4795 }
4796 }
4797
4798 Error Err = Error::success();
4799 auto ToEndLoc = importChecked(Err, From: D->getEndLoc());
4800 auto ToReturnType = importChecked(Err, From: D->getReturnType());
4801 auto ToReturnTypeSourceInfo =
4802 importChecked(Err, From: D->getReturnTypeSourceInfo());
4803 if (Err)
4804 return std::move(Err);
4805
4806 ObjCMethodDecl *ToMethod;
4807 if (GetImportedOrCreateDecl(
4808 ToD&: ToMethod, FromD: D, args&: Importer.getToContext(), args&: Loc, args&: ToEndLoc,
4809 args: Name.getObjCSelector(), args&: ToReturnType, args&: ToReturnTypeSourceInfo, args&: DC,
4810 args: D->isInstanceMethod(), args: D->isVariadic(), args: D->isPropertyAccessor(),
4811 args: D->isSynthesizedAccessorStub(), args: D->isImplicit(), args: D->isDefined(),
4812 args: D->getImplementationControl(), args: D->hasRelatedResultType()))
4813 return ToMethod;
4814
4815 // FIXME: When we decide to merge method definitions, we'll need to
4816 // deal with implicit parameters.
4817
4818 // Import the parameters
4819 SmallVector<ParmVarDecl *, 5> ToParams;
4820 for (auto *FromP : D->parameters()) {
4821 if (Expected<ParmVarDecl *> ToPOrErr = import(From: FromP))
4822 ToParams.push_back(Elt: *ToPOrErr);
4823 else
4824 return ToPOrErr.takeError();
4825 }
4826
4827 // Set the parameters.
4828 for (auto *ToParam : ToParams) {
4829 ToParam->setOwningFunction(ToMethod);
4830 ToMethod->addDeclInternal(D: ToParam);
4831 }
4832
4833 SmallVector<SourceLocation, 12> FromSelLocs;
4834 D->getSelectorLocs(SelLocs&: FromSelLocs);
4835 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4836 if (Error Err = ImportContainerChecked(InContainer: FromSelLocs, OutContainer&: ToSelLocs))
4837 return std::move(Err);
4838
4839 ToMethod->setMethodParams(C&: Importer.getToContext(), Params: ToParams, SelLocs: ToSelLocs);
4840
4841 ToMethod->setLexicalDeclContext(LexicalDC);
4842 LexicalDC->addDeclInternal(D: ToMethod);
4843
4844 // Implicit params are declared when Sema encounters the definition but this
4845 // never happens when the method is imported. Manually declare the implicit
4846 // params now that the MethodDecl knows its class interface.
4847 if (D->getSelfDecl())
4848 ToMethod->createImplicitParams(Context&: Importer.getToContext(),
4849 ID: ToMethod->getClassInterface());
4850
4851 return ToMethod;
4852}
4853
4854ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
4855 // Import the major distinguishing characteristics of a category.
4856 DeclContext *DC, *LexicalDC;
4857 DeclarationName Name;
4858 SourceLocation Loc;
4859 NamedDecl *ToD;
4860 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4861 return std::move(Err);
4862 if (ToD)
4863 return ToD;
4864
4865 Error Err = Error::success();
4866 auto ToVarianceLoc = importChecked(Err, From: D->getVarianceLoc());
4867 auto ToLocation = importChecked(Err, From: D->getLocation());
4868 auto ToColonLoc = importChecked(Err, From: D->getColonLoc());
4869 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
4870 if (Err)
4871 return std::move(Err);
4872
4873 ObjCTypeParamDecl *Result;
4874 if (GetImportedOrCreateDecl(
4875 ToD&: Result, FromD: D, args&: Importer.getToContext(), args&: DC, args: D->getVariance(),
4876 args&: ToVarianceLoc, args: D->getIndex(),
4877 args&: ToLocation, args: Name.getAsIdentifierInfo(),
4878 args&: ToColonLoc, args&: ToTypeSourceInfo))
4879 return Result;
4880
4881 // Only import 'ObjCTypeParamType' after the decl is created.
4882 auto ToTypeForDecl = importChecked(Err, From: D->getTypeForDecl());
4883 if (Err)
4884 return std::move(Err);
4885 Result->setTypeForDecl(ToTypeForDecl);
4886 Result->setLexicalDeclContext(LexicalDC);
4887 return Result;
4888}
4889
4890ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
4891 // Import the major distinguishing characteristics of a category.
4892 DeclContext *DC, *LexicalDC;
4893 DeclarationName Name;
4894 SourceLocation Loc;
4895 NamedDecl *ToD;
4896 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4897 return std::move(Err);
4898 if (ToD)
4899 return ToD;
4900
4901 ObjCInterfaceDecl *ToInterface;
4902 if (Error Err = importInto(To&: ToInterface, From: D->getClassInterface()))
4903 return std::move(Err);
4904
4905 // Determine if we've already encountered this category.
4906 ObjCCategoryDecl *MergeWithCategory
4907 = ToInterface->FindCategoryDeclaration(CategoryId: Name.getAsIdentifierInfo());
4908 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4909 if (!ToCategory) {
4910
4911 Error Err = Error::success();
4912 auto ToAtStartLoc = importChecked(Err, From: D->getAtStartLoc());
4913 auto ToCategoryNameLoc = importChecked(Err, From: D->getCategoryNameLoc());
4914 auto ToIvarLBraceLoc = importChecked(Err, From: D->getIvarLBraceLoc());
4915 auto ToIvarRBraceLoc = importChecked(Err, From: D->getIvarRBraceLoc());
4916 if (Err)
4917 return std::move(Err);
4918
4919 if (GetImportedOrCreateDecl(ToD&: ToCategory, FromD: D, args&: Importer.getToContext(), args&: DC,
4920 args&: ToAtStartLoc, args&: Loc,
4921 args&: ToCategoryNameLoc,
4922 args: Name.getAsIdentifierInfo(), args&: ToInterface,
4923 /*TypeParamList=*/args: nullptr,
4924 args&: ToIvarLBraceLoc,
4925 args&: ToIvarRBraceLoc))
4926 return ToCategory;
4927
4928 ToCategory->setLexicalDeclContext(LexicalDC);
4929 LexicalDC->addDeclInternal(D: ToCategory);
4930 // Import the type parameter list after MapImported, to avoid
4931 // loops when bringing in their DeclContext.
4932 if (auto PListOrErr = ImportObjCTypeParamList(list: D->getTypeParamList()))
4933 ToCategory->setTypeParamList(*PListOrErr);
4934 else
4935 return PListOrErr.takeError();
4936
4937 // Import protocols
4938 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4939 SmallVector<SourceLocation, 4> ProtocolLocs;
4940 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4941 = D->protocol_loc_begin();
4942 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4943 FromProtoEnd = D->protocol_end();
4944 FromProto != FromProtoEnd;
4945 ++FromProto, ++FromProtoLoc) {
4946 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(From: *FromProto))
4947 Protocols.push_back(Elt: *ToProtoOrErr);
4948 else
4949 return ToProtoOrErr.takeError();
4950
4951 if (ExpectedSLoc ToProtoLocOrErr = import(From: *FromProtoLoc))
4952 ProtocolLocs.push_back(Elt: *ToProtoLocOrErr);
4953 else
4954 return ToProtoLocOrErr.takeError();
4955 }
4956
4957 // FIXME: If we're merging, make sure that the protocol list is the same.
4958 ToCategory->setProtocolList(List: Protocols.data(), Num: Protocols.size(),
4959 Locs: ProtocolLocs.data(), C&: Importer.getToContext());
4960
4961 } else {
4962 Importer.MapImported(From: D, To: ToCategory);
4963 }
4964
4965 // Import all of the members of this category.
4966 if (Error Err = ImportDeclContext(FromDC: D))
4967 return std::move(Err);
4968
4969 // If we have an implementation, import it as well.
4970 if (D->getImplementation()) {
4971 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4972 import(From: D->getImplementation()))
4973 ToCategory->setImplementation(*ToImplOrErr);
4974 else
4975 return ToImplOrErr.takeError();
4976 }
4977
4978 return ToCategory;
4979}
4980
4981Error ASTNodeImporter::ImportDefinition(
4982 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4983 if (To->getDefinition()) {
4984 if (shouldForceImportDeclContext(IDK: Kind))
4985 if (Error Err = ImportDeclContext(FromDC: From))
4986 return Err;
4987 return Error::success();
4988 }
4989
4990 // Start the protocol definition
4991 To->startDefinition();
4992
4993 // Import protocols
4994 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4995 SmallVector<SourceLocation, 4> ProtocolLocs;
4996 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4997 From->protocol_loc_begin();
4998 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4999 FromProtoEnd = From->protocol_end();
5000 FromProto != FromProtoEnd;
5001 ++FromProto, ++FromProtoLoc) {
5002 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(From: *FromProto))
5003 Protocols.push_back(Elt: *ToProtoOrErr);
5004 else
5005 return ToProtoOrErr.takeError();
5006
5007 if (ExpectedSLoc ToProtoLocOrErr = import(From: *FromProtoLoc))
5008 ProtocolLocs.push_back(Elt: *ToProtoLocOrErr);
5009 else
5010 return ToProtoLocOrErr.takeError();
5011
5012 }
5013
5014 // FIXME: If we're merging, make sure that the protocol list is the same.
5015 To->setProtocolList(List: Protocols.data(), Num: Protocols.size(),
5016 Locs: ProtocolLocs.data(), C&: Importer.getToContext());
5017
5018 if (shouldForceImportDeclContext(IDK: Kind)) {
5019 // Import all of the members of this protocol.
5020 if (Error Err = ImportDeclContext(FromDC: From, /*ForceImport=*/true))
5021 return Err;
5022 }
5023 return Error::success();
5024}
5025
5026ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
5027 // If this protocol has a definition in the translation unit we're coming
5028 // from, but this particular declaration is not that definition, import the
5029 // definition and map to that.
5030 ObjCProtocolDecl *Definition = D->getDefinition();
5031 if (Definition && Definition != D) {
5032 if (ExpectedDecl ImportedDefOrErr = import(From: Definition))
5033 return Importer.MapImported(From: D, To: *ImportedDefOrErr);
5034 else
5035 return ImportedDefOrErr.takeError();
5036 }
5037
5038 // Import the major distinguishing characteristics of a protocol.
5039 DeclContext *DC, *LexicalDC;
5040 DeclarationName Name;
5041 SourceLocation Loc;
5042 NamedDecl *ToD;
5043 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5044 return std::move(Err);
5045 if (ToD)
5046 return ToD;
5047
5048 ObjCProtocolDecl *MergeWithProtocol = nullptr;
5049 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5050 for (auto *FoundDecl : FoundDecls) {
5051 if (!FoundDecl->isInIdentifierNamespace(NS: Decl::IDNS_ObjCProtocol))
5052 continue;
5053
5054 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(Val: FoundDecl)))
5055 break;
5056 }
5057
5058 ObjCProtocolDecl *ToProto = MergeWithProtocol;
5059 if (!ToProto) {
5060 auto ToAtBeginLocOrErr = import(From: D->getAtStartLoc());
5061 if (!ToAtBeginLocOrErr)
5062 return ToAtBeginLocOrErr.takeError();
5063
5064 if (GetImportedOrCreateDecl(ToD&: ToProto, FromD: D, args&: Importer.getToContext(), args&: DC,
5065 args: Name.getAsIdentifierInfo(), args&: Loc,
5066 args&: *ToAtBeginLocOrErr,
5067 /*PrevDecl=*/args: nullptr))
5068 return ToProto;
5069 ToProto->setLexicalDeclContext(LexicalDC);
5070 LexicalDC->addDeclInternal(D: ToProto);
5071 }
5072
5073 Importer.MapImported(From: D, To: ToProto);
5074
5075 if (D->isThisDeclarationADefinition())
5076 if (Error Err = ImportDefinition(From: D, To: ToProto))
5077 return std::move(Err);
5078
5079 return ToProto;
5080}
5081
5082ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
5083 DeclContext *DC, *LexicalDC;
5084 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
5085 return std::move(Err);
5086
5087 ExpectedSLoc ExternLocOrErr = import(From: D->getExternLoc());
5088 if (!ExternLocOrErr)
5089 return ExternLocOrErr.takeError();
5090
5091 ExpectedSLoc LangLocOrErr = import(From: D->getLocation());
5092 if (!LangLocOrErr)
5093 return LangLocOrErr.takeError();
5094
5095 bool HasBraces = D->hasBraces();
5096
5097 LinkageSpecDecl *ToLinkageSpec;
5098 if (GetImportedOrCreateDecl(ToD&: ToLinkageSpec, FromD: D, args&: Importer.getToContext(), args&: DC,
5099 args&: *ExternLocOrErr, args&: *LangLocOrErr,
5100 args: D->getLanguage(), args&: HasBraces))
5101 return ToLinkageSpec;
5102
5103 if (HasBraces) {
5104 ExpectedSLoc RBraceLocOrErr = import(From: D->getRBraceLoc());
5105 if (!RBraceLocOrErr)
5106 return RBraceLocOrErr.takeError();
5107 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
5108 }
5109
5110 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
5111 LexicalDC->addDeclInternal(D: ToLinkageSpec);
5112
5113 return ToLinkageSpec;
5114}
5115
5116ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D,
5117 BaseUsingDecl *ToSI) {
5118 for (UsingShadowDecl *FromShadow : D->shadows()) {
5119 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(From: FromShadow))
5120 ToSI->addShadowDecl(S: *ToShadowOrErr);
5121 else
5122 // FIXME: We return error here but the definition is already created
5123 // and available with lookups. How to fix this?..
5124 return ToShadowOrErr.takeError();
5125 }
5126 return ToSI;
5127}
5128
5129ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
5130 DeclContext *DC, *LexicalDC;
5131 DeclarationName Name;
5132 SourceLocation Loc;
5133 NamedDecl *ToD = nullptr;
5134 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5135 return std::move(Err);
5136 if (ToD)
5137 return ToD;
5138
5139 Error Err = Error::success();
5140 auto ToLoc = importChecked(Err, From: D->getNameInfo().getLoc());
5141 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5142 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5143 if (Err)
5144 return std::move(Err);
5145
5146 DeclarationNameInfo NameInfo(Name, ToLoc);
5147 if (Error Err = ImportDeclarationNameLoc(From: D->getNameInfo(), To&: NameInfo))
5148 return std::move(Err);
5149
5150 UsingDecl *ToUsing;
5151 if (GetImportedOrCreateDecl(ToD&: ToUsing, FromD: D, args&: Importer.getToContext(), args&: DC,
5152 args&: ToUsingLoc, args&: ToQualifierLoc, args&: NameInfo,
5153 args: D->hasTypename()))
5154 return ToUsing;
5155
5156 ToUsing->setLexicalDeclContext(LexicalDC);
5157 LexicalDC->addDeclInternal(D: ToUsing);
5158
5159 if (NamedDecl *FromPattern =
5160 Importer.getFromContext().getInstantiatedFromUsingDecl(Inst: D)) {
5161 if (Expected<NamedDecl *> ToPatternOrErr = import(From: FromPattern))
5162 Importer.getToContext().setInstantiatedFromUsingDecl(
5163 Inst: ToUsing, Pattern: *ToPatternOrErr);
5164 else
5165 return ToPatternOrErr.takeError();
5166 }
5167
5168 return ImportUsingShadowDecls(D, ToSI: ToUsing);
5169}
5170
5171ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) {
5172 DeclContext *DC, *LexicalDC;
5173 DeclarationName Name;
5174 SourceLocation Loc;
5175 NamedDecl *ToD = nullptr;
5176 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5177 return std::move(Err);
5178 if (ToD)
5179 return ToD;
5180
5181 Error Err = Error::success();
5182 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5183 auto ToEnumLoc = importChecked(Err, From: D->getEnumLoc());
5184 auto ToNameLoc = importChecked(Err, From: D->getLocation());
5185 auto *ToEnumType = importChecked(Err, From: D->getEnumType());
5186 if (Err)
5187 return std::move(Err);
5188
5189 UsingEnumDecl *ToUsingEnum;
5190 if (GetImportedOrCreateDecl(ToD&: ToUsingEnum, FromD: D, args&: Importer.getToContext(), args&: DC,
5191 args&: ToUsingLoc, args&: ToEnumLoc, args&: ToNameLoc, args&: ToEnumType))
5192 return ToUsingEnum;
5193
5194 ToUsingEnum->setLexicalDeclContext(LexicalDC);
5195 LexicalDC->addDeclInternal(D: ToUsingEnum);
5196
5197 if (UsingEnumDecl *FromPattern =
5198 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(Inst: D)) {
5199 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(From: FromPattern))
5200 Importer.getToContext().setInstantiatedFromUsingEnumDecl(Inst: ToUsingEnum,
5201 Pattern: *ToPatternOrErr);
5202 else
5203 return ToPatternOrErr.takeError();
5204 }
5205
5206 return ImportUsingShadowDecls(D, ToSI: ToUsingEnum);
5207}
5208
5209ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
5210 DeclContext *DC, *LexicalDC;
5211 DeclarationName Name;
5212 SourceLocation Loc;
5213 NamedDecl *ToD = nullptr;
5214 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5215 return std::move(Err);
5216 if (ToD)
5217 return ToD;
5218
5219 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(From: D->getIntroducer());
5220 if (!ToIntroducerOrErr)
5221 return ToIntroducerOrErr.takeError();
5222
5223 Expected<NamedDecl *> ToTargetOrErr = import(From: D->getTargetDecl());
5224 if (!ToTargetOrErr)
5225 return ToTargetOrErr.takeError();
5226
5227 UsingShadowDecl *ToShadow;
5228 if (auto *FromConstructorUsingShadow =
5229 dyn_cast<ConstructorUsingShadowDecl>(Val: D)) {
5230 Error Err = Error::success();
5231 ConstructorUsingShadowDecl *Nominated = importChecked(
5232 Err, From: FromConstructorUsingShadow->getNominatedBaseClassShadowDecl());
5233 if (Err)
5234 return std::move(Err);
5235 // The 'Target' parameter of ConstructorUsingShadowDecl constructor
5236 // is really the "NominatedBaseClassShadowDecl" value if it exists
5237 // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl).
5238 // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to
5239 // get the correct values.
5240 if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>(
5241 ToD&: ToShadow, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
5242 args: cast<UsingDecl>(Val: *ToIntroducerOrErr),
5243 args: Nominated ? Nominated : *ToTargetOrErr,
5244 args: FromConstructorUsingShadow->constructsVirtualBase()))
5245 return ToShadow;
5246 } else {
5247 if (GetImportedOrCreateDecl(ToD&: ToShadow, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
5248 args&: Name, args&: *ToIntroducerOrErr, args&: *ToTargetOrErr))
5249 return ToShadow;
5250 }
5251
5252 ToShadow->setLexicalDeclContext(LexicalDC);
5253 ToShadow->setAccess(D->getAccess());
5254
5255 if (UsingShadowDecl *FromPattern =
5256 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(Inst: D)) {
5257 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(From: FromPattern))
5258 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
5259 Inst: ToShadow, Pattern: *ToPatternOrErr);
5260 else
5261 // FIXME: We return error here but the definition is already created
5262 // and available with lookups. How to fix this?..
5263 return ToPatternOrErr.takeError();
5264 }
5265
5266 LexicalDC->addDeclInternal(D: ToShadow);
5267
5268 return ToShadow;
5269}
5270
5271ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
5272 DeclContext *DC, *LexicalDC;
5273 DeclarationName Name;
5274 SourceLocation Loc;
5275 NamedDecl *ToD = nullptr;
5276 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5277 return std::move(Err);
5278 if (ToD)
5279 return ToD;
5280
5281 auto ToComAncestorOrErr = Importer.ImportContext(FromDC: D->getCommonAncestor());
5282 if (!ToComAncestorOrErr)
5283 return ToComAncestorOrErr.takeError();
5284
5285 Error Err = Error::success();
5286 auto ToNominatedNamespace = importChecked(Err, From: D->getNominatedNamespace());
5287 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5288 auto ToNamespaceKeyLocation =
5289 importChecked(Err, From: D->getNamespaceKeyLocation());
5290 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5291 auto ToIdentLocation = importChecked(Err, From: D->getIdentLocation());
5292 if (Err)
5293 return std::move(Err);
5294
5295 UsingDirectiveDecl *ToUsingDir;
5296 if (GetImportedOrCreateDecl(ToD&: ToUsingDir, FromD: D, args&: Importer.getToContext(), args&: DC,
5297 args&: ToUsingLoc,
5298 args&: ToNamespaceKeyLocation,
5299 args&: ToQualifierLoc,
5300 args&: ToIdentLocation,
5301 args&: ToNominatedNamespace, args&: *ToComAncestorOrErr))
5302 return ToUsingDir;
5303
5304 ToUsingDir->setLexicalDeclContext(LexicalDC);
5305 LexicalDC->addDeclInternal(D: ToUsingDir);
5306
5307 return ToUsingDir;
5308}
5309
5310ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) {
5311 DeclContext *DC, *LexicalDC;
5312 DeclarationName Name;
5313 SourceLocation Loc;
5314 NamedDecl *ToD = nullptr;
5315 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5316 return std::move(Err);
5317 if (ToD)
5318 return ToD;
5319
5320 auto ToInstantiatedFromUsingOrErr =
5321 Importer.Import(FromD: D->getInstantiatedFromUsingDecl());
5322 if (!ToInstantiatedFromUsingOrErr)
5323 return ToInstantiatedFromUsingOrErr.takeError();
5324 SmallVector<NamedDecl *, 4> Expansions(D->expansions().size());
5325 if (Error Err = ImportArrayChecked(InContainer: D->expansions(), Obegin: Expansions.begin()))
5326 return std::move(Err);
5327
5328 UsingPackDecl *ToUsingPack;
5329 if (GetImportedOrCreateDecl(ToD&: ToUsingPack, FromD: D, args&: Importer.getToContext(), args&: DC,
5330 args: cast<NamedDecl>(Val: *ToInstantiatedFromUsingOrErr),
5331 args&: Expansions))
5332 return ToUsingPack;
5333
5334 addDeclToContexts(FromD: D, ToD: ToUsingPack);
5335
5336 return ToUsingPack;
5337}
5338
5339ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
5340 UnresolvedUsingValueDecl *D) {
5341 DeclContext *DC, *LexicalDC;
5342 DeclarationName Name;
5343 SourceLocation Loc;
5344 NamedDecl *ToD = nullptr;
5345 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5346 return std::move(Err);
5347 if (ToD)
5348 return ToD;
5349
5350 Error Err = Error::success();
5351 auto ToLoc = importChecked(Err, From: D->getNameInfo().getLoc());
5352 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5353 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5354 auto ToEllipsisLoc = importChecked(Err, From: D->getEllipsisLoc());
5355 if (Err)
5356 return std::move(Err);
5357
5358 DeclarationNameInfo NameInfo(Name, ToLoc);
5359 if (Error Err = ImportDeclarationNameLoc(From: D->getNameInfo(), To&: NameInfo))
5360 return std::move(Err);
5361
5362 UnresolvedUsingValueDecl *ToUsingValue;
5363 if (GetImportedOrCreateDecl(ToD&: ToUsingValue, FromD: D, args&: Importer.getToContext(), args&: DC,
5364 args&: ToUsingLoc, args&: ToQualifierLoc, args&: NameInfo,
5365 args&: ToEllipsisLoc))
5366 return ToUsingValue;
5367
5368 ToUsingValue->setAccess(D->getAccess());
5369 ToUsingValue->setLexicalDeclContext(LexicalDC);
5370 LexicalDC->addDeclInternal(D: ToUsingValue);
5371
5372 return ToUsingValue;
5373}
5374
5375ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
5376 UnresolvedUsingTypenameDecl *D) {
5377 DeclContext *DC, *LexicalDC;
5378 DeclarationName Name;
5379 SourceLocation Loc;
5380 NamedDecl *ToD = nullptr;
5381 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5382 return std::move(Err);
5383 if (ToD)
5384 return ToD;
5385
5386 Error Err = Error::success();
5387 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5388 auto ToTypenameLoc = importChecked(Err, From: D->getTypenameLoc());
5389 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5390 auto ToEllipsisLoc = importChecked(Err, From: D->getEllipsisLoc());
5391 if (Err)
5392 return std::move(Err);
5393
5394 UnresolvedUsingTypenameDecl *ToUsing;
5395 if (GetImportedOrCreateDecl(ToD&: ToUsing, FromD: D, args&: Importer.getToContext(), args&: DC,
5396 args&: ToUsingLoc, args&: ToTypenameLoc,
5397 args&: ToQualifierLoc, args&: Loc, args&: Name, args&: ToEllipsisLoc))
5398 return ToUsing;
5399
5400 ToUsing->setAccess(D->getAccess());
5401 ToUsing->setLexicalDeclContext(LexicalDC);
5402 LexicalDC->addDeclInternal(D: ToUsing);
5403
5404 return ToUsing;
5405}
5406
5407ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
5408 Decl* ToD = nullptr;
5409 switch (D->getBuiltinTemplateKind()) {
5410 case BuiltinTemplateKind::BTK__make_integer_seq:
5411 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
5412 break;
5413 case BuiltinTemplateKind::BTK__type_pack_element:
5414 ToD = Importer.getToContext().getTypePackElementDecl();
5415 break;
5416 }
5417 assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
5418 Importer.MapImported(From: D, To: ToD);
5419 return ToD;
5420}
5421
5422Error ASTNodeImporter::ImportDefinition(
5423 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
5424 if (To->getDefinition()) {
5425 // Check consistency of superclass.
5426 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
5427 if (FromSuper) {
5428 if (auto FromSuperOrErr = import(From: FromSuper))
5429 FromSuper = *FromSuperOrErr;
5430 else
5431 return FromSuperOrErr.takeError();
5432 }
5433
5434 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
5435 if ((bool)FromSuper != (bool)ToSuper ||
5436 (FromSuper && !declaresSameEntity(D1: FromSuper, D2: ToSuper))) {
5437 Importer.ToDiag(Loc: To->getLocation(),
5438 DiagID: diag::warn_odr_objc_superclass_inconsistent)
5439 << To->getDeclName();
5440 if (ToSuper)
5441 Importer.ToDiag(Loc: To->getSuperClassLoc(), DiagID: diag::note_odr_objc_superclass)
5442 << To->getSuperClass()->getDeclName();
5443 else
5444 Importer.ToDiag(Loc: To->getLocation(),
5445 DiagID: diag::note_odr_objc_missing_superclass);
5446 if (From->getSuperClass())
5447 Importer.FromDiag(Loc: From->getSuperClassLoc(),
5448 DiagID: diag::note_odr_objc_superclass)
5449 << From->getSuperClass()->getDeclName();
5450 else
5451 Importer.FromDiag(Loc: From->getLocation(),
5452 DiagID: diag::note_odr_objc_missing_superclass);
5453 }
5454
5455 if (shouldForceImportDeclContext(IDK: Kind))
5456 if (Error Err = ImportDeclContext(FromDC: From))
5457 return Err;
5458 return Error::success();
5459 }
5460
5461 // Start the definition.
5462 To->startDefinition();
5463
5464 // If this class has a superclass, import it.
5465 if (From->getSuperClass()) {
5466 if (auto SuperTInfoOrErr = import(From: From->getSuperClassTInfo()))
5467 To->setSuperClass(*SuperTInfoOrErr);
5468 else
5469 return SuperTInfoOrErr.takeError();
5470 }
5471
5472 // Import protocols
5473 SmallVector<ObjCProtocolDecl *, 4> Protocols;
5474 SmallVector<SourceLocation, 4> ProtocolLocs;
5475 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
5476 From->protocol_loc_begin();
5477
5478 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
5479 FromProtoEnd = From->protocol_end();
5480 FromProto != FromProtoEnd;
5481 ++FromProto, ++FromProtoLoc) {
5482 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(From: *FromProto))
5483 Protocols.push_back(Elt: *ToProtoOrErr);
5484 else
5485 return ToProtoOrErr.takeError();
5486
5487 if (ExpectedSLoc ToProtoLocOrErr = import(From: *FromProtoLoc))
5488 ProtocolLocs.push_back(Elt: *ToProtoLocOrErr);
5489 else
5490 return ToProtoLocOrErr.takeError();
5491
5492 }
5493
5494 // FIXME: If we're merging, make sure that the protocol list is the same.
5495 To->setProtocolList(List: Protocols.data(), Num: Protocols.size(),
5496 Locs: ProtocolLocs.data(), C&: Importer.getToContext());
5497
5498 // Import categories. When the categories themselves are imported, they'll
5499 // hook themselves into this interface.
5500 for (auto *Cat : From->known_categories()) {
5501 auto ToCatOrErr = import(From: Cat);
5502 if (!ToCatOrErr)
5503 return ToCatOrErr.takeError();
5504 }
5505
5506 // If we have an @implementation, import it as well.
5507 if (From->getImplementation()) {
5508 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
5509 import(From: From->getImplementation()))
5510 To->setImplementation(*ToImplOrErr);
5511 else
5512 return ToImplOrErr.takeError();
5513 }
5514
5515 // Import all of the members of this class.
5516 if (Error Err = ImportDeclContext(FromDC: From, /*ForceImport=*/true))
5517 return Err;
5518
5519 return Error::success();
5520}
5521
5522Expected<ObjCTypeParamList *>
5523ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
5524 if (!list)
5525 return nullptr;
5526
5527 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
5528 for (auto *fromTypeParam : *list) {
5529 if (auto toTypeParamOrErr = import(From: fromTypeParam))
5530 toTypeParams.push_back(Elt: *toTypeParamOrErr);
5531 else
5532 return toTypeParamOrErr.takeError();
5533 }
5534
5535 auto LAngleLocOrErr = import(From: list->getLAngleLoc());
5536 if (!LAngleLocOrErr)
5537 return LAngleLocOrErr.takeError();
5538
5539 auto RAngleLocOrErr = import(From: list->getRAngleLoc());
5540 if (!RAngleLocOrErr)
5541 return RAngleLocOrErr.takeError();
5542
5543 return ObjCTypeParamList::create(ctx&: Importer.getToContext(),
5544 lAngleLoc: *LAngleLocOrErr,
5545 typeParams: toTypeParams,
5546 rAngleLoc: *RAngleLocOrErr);
5547}
5548
5549ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
5550 // If this class has a definition in the translation unit we're coming from,
5551 // but this particular declaration is not that definition, import the
5552 // definition and map to that.
5553 ObjCInterfaceDecl *Definition = D->getDefinition();
5554 if (Definition && Definition != D) {
5555 if (ExpectedDecl ImportedDefOrErr = import(From: Definition))
5556 return Importer.MapImported(From: D, To: *ImportedDefOrErr);
5557 else
5558 return ImportedDefOrErr.takeError();
5559 }
5560
5561 // Import the major distinguishing characteristics of an @interface.
5562 DeclContext *DC, *LexicalDC;
5563 DeclarationName Name;
5564 SourceLocation Loc;
5565 NamedDecl *ToD;
5566 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5567 return std::move(Err);
5568 if (ToD)
5569 return ToD;
5570
5571 // Look for an existing interface with the same name.
5572 ObjCInterfaceDecl *MergeWithIface = nullptr;
5573 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5574 for (auto *FoundDecl : FoundDecls) {
5575 if (!FoundDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
5576 continue;
5577
5578 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(Val: FoundDecl)))
5579 break;
5580 }
5581
5582 // Create an interface declaration, if one does not already exist.
5583 ObjCInterfaceDecl *ToIface = MergeWithIface;
5584 if (!ToIface) {
5585 ExpectedSLoc AtBeginLocOrErr = import(From: D->getAtStartLoc());
5586 if (!AtBeginLocOrErr)
5587 return AtBeginLocOrErr.takeError();
5588
5589 if (GetImportedOrCreateDecl(
5590 ToD&: ToIface, FromD: D, args&: Importer.getToContext(), args&: DC,
5591 args&: *AtBeginLocOrErr, args: Name.getAsIdentifierInfo(),
5592 /*TypeParamList=*/args: nullptr,
5593 /*PrevDecl=*/args: nullptr, args&: Loc, args: D->isImplicitInterfaceDecl()))
5594 return ToIface;
5595 ToIface->setLexicalDeclContext(LexicalDC);
5596 LexicalDC->addDeclInternal(D: ToIface);
5597 }
5598 Importer.MapImported(From: D, To: ToIface);
5599 // Import the type parameter list after MapImported, to avoid
5600 // loops when bringing in their DeclContext.
5601 if (auto ToPListOrErr =
5602 ImportObjCTypeParamList(list: D->getTypeParamListAsWritten()))
5603 ToIface->setTypeParamList(*ToPListOrErr);
5604 else
5605 return ToPListOrErr.takeError();
5606
5607 if (D->isThisDeclarationADefinition())
5608 if (Error Err = ImportDefinition(From: D, To: ToIface))
5609 return std::move(Err);
5610
5611 return ToIface;
5612}
5613
5614ExpectedDecl
5615ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
5616 ObjCCategoryDecl *Category;
5617 if (Error Err = importInto(To&: Category, From: D->getCategoryDecl()))
5618 return std::move(Err);
5619
5620 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5621 if (!ToImpl) {
5622 DeclContext *DC, *LexicalDC;
5623 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
5624 return std::move(Err);
5625
5626 Error Err = Error::success();
5627 auto ToLocation = importChecked(Err, From: D->getLocation());
5628 auto ToAtStartLoc = importChecked(Err, From: D->getAtStartLoc());
5629 auto ToCategoryNameLoc = importChecked(Err, From: D->getCategoryNameLoc());
5630 if (Err)
5631 return std::move(Err);
5632
5633 if (GetImportedOrCreateDecl(
5634 ToD&: ToImpl, FromD: D, args&: Importer.getToContext(), args&: DC,
5635 args: Importer.Import(FromId: D->getIdentifier()), args: Category->getClassInterface(),
5636 args&: ToLocation, args&: ToAtStartLoc, args&: ToCategoryNameLoc))
5637 return ToImpl;
5638
5639 ToImpl->setLexicalDeclContext(LexicalDC);
5640 LexicalDC->addDeclInternal(D: ToImpl);
5641 Category->setImplementation(ToImpl);
5642 }
5643
5644 Importer.MapImported(From: D, To: ToImpl);
5645 if (Error Err = ImportDeclContext(FromDC: D))
5646 return std::move(Err);
5647
5648 return ToImpl;
5649}
5650
5651ExpectedDecl
5652ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
5653 // Find the corresponding interface.
5654 ObjCInterfaceDecl *Iface;
5655 if (Error Err = importInto(To&: Iface, From: D->getClassInterface()))
5656 return std::move(Err);
5657
5658 // Import the superclass, if any.
5659 ObjCInterfaceDecl *Super;
5660 if (Error Err = importInto(To&: Super, From: D->getSuperClass()))
5661 return std::move(Err);
5662
5663 ObjCImplementationDecl *Impl = Iface->getImplementation();
5664 if (!Impl) {
5665 // We haven't imported an implementation yet. Create a new @implementation
5666 // now.
5667 DeclContext *DC, *LexicalDC;
5668 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
5669 return std::move(Err);
5670
5671 Error Err = Error::success();
5672 auto ToLocation = importChecked(Err, From: D->getLocation());
5673 auto ToAtStartLoc = importChecked(Err, From: D->getAtStartLoc());
5674 auto ToSuperClassLoc = importChecked(Err, From: D->getSuperClassLoc());
5675 auto ToIvarLBraceLoc = importChecked(Err, From: D->getIvarLBraceLoc());
5676 auto ToIvarRBraceLoc = importChecked(Err, From: D->getIvarRBraceLoc());
5677 if (Err)
5678 return std::move(Err);
5679
5680 if (GetImportedOrCreateDecl(ToD&: Impl, FromD: D, args&: Importer.getToContext(),
5681 args&: DC, args&: Iface, args&: Super,
5682 args&: ToLocation,
5683 args&: ToAtStartLoc,
5684 args&: ToSuperClassLoc,
5685 args&: ToIvarLBraceLoc,
5686 args&: ToIvarRBraceLoc))
5687 return Impl;
5688
5689 Impl->setLexicalDeclContext(LexicalDC);
5690
5691 // Associate the implementation with the class it implements.
5692 Iface->setImplementation(Impl);
5693 Importer.MapImported(From: D, To: Iface->getImplementation());
5694 } else {
5695 Importer.MapImported(From: D, To: Iface->getImplementation());
5696
5697 // Verify that the existing @implementation has the same superclass.
5698 if ((Super && !Impl->getSuperClass()) ||
5699 (!Super && Impl->getSuperClass()) ||
5700 (Super && Impl->getSuperClass() &&
5701 !declaresSameEntity(D1: Super->getCanonicalDecl(),
5702 D2: Impl->getSuperClass()))) {
5703 Importer.ToDiag(Loc: Impl->getLocation(),
5704 DiagID: diag::warn_odr_objc_superclass_inconsistent)
5705 << Iface->getDeclName();
5706 // FIXME: It would be nice to have the location of the superclass
5707 // below.
5708 if (Impl->getSuperClass())
5709 Importer.ToDiag(Loc: Impl->getLocation(),
5710 DiagID: diag::note_odr_objc_superclass)
5711 << Impl->getSuperClass()->getDeclName();
5712 else
5713 Importer.ToDiag(Loc: Impl->getLocation(),
5714 DiagID: diag::note_odr_objc_missing_superclass);
5715 if (D->getSuperClass())
5716 Importer.FromDiag(Loc: D->getLocation(),
5717 DiagID: diag::note_odr_objc_superclass)
5718 << D->getSuperClass()->getDeclName();
5719 else
5720 Importer.FromDiag(Loc: D->getLocation(),
5721 DiagID: diag::note_odr_objc_missing_superclass);
5722
5723 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5724 }
5725 }
5726
5727 // Import all of the members of this @implementation.
5728 if (Error Err = ImportDeclContext(FromDC: D))
5729 return std::move(Err);
5730
5731 return Impl;
5732}
5733
5734ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
5735 // Import the major distinguishing characteristics of an @property.
5736 DeclContext *DC, *LexicalDC;
5737 DeclarationName Name;
5738 SourceLocation Loc;
5739 NamedDecl *ToD;
5740 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5741 return std::move(Err);
5742 if (ToD)
5743 return ToD;
5744
5745 // Check whether we have already imported this property.
5746 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5747 for (auto *FoundDecl : FoundDecls) {
5748 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(Val: FoundDecl)) {
5749 // Instance and class properties can share the same name but are different
5750 // declarations.
5751 if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5752 continue;
5753
5754 // Check property types.
5755 if (!Importer.IsStructurallyEquivalent(From: D->getType(),
5756 To: FoundProp->getType())) {
5757 Importer.ToDiag(Loc, DiagID: diag::warn_odr_objc_property_type_inconsistent)
5758 << Name << D->getType() << FoundProp->getType();
5759 Importer.ToDiag(Loc: FoundProp->getLocation(), DiagID: diag::note_odr_value_here)
5760 << FoundProp->getType();
5761
5762 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5763 }
5764
5765 // FIXME: Check property attributes, getters, setters, etc.?
5766
5767 // Consider these properties to be equivalent.
5768 Importer.MapImported(From: D, To: FoundProp);
5769 return FoundProp;
5770 }
5771 }
5772
5773 Error Err = Error::success();
5774 auto ToType = importChecked(Err, From: D->getType());
5775 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
5776 auto ToAtLoc = importChecked(Err, From: D->getAtLoc());
5777 auto ToLParenLoc = importChecked(Err, From: D->getLParenLoc());
5778 if (Err)
5779 return std::move(Err);
5780
5781 // Create the new property.
5782 ObjCPropertyDecl *ToProperty;
5783 if (GetImportedOrCreateDecl(
5784 ToD&: ToProperty, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
5785 args: Name.getAsIdentifierInfo(), args&: ToAtLoc,
5786 args&: ToLParenLoc, args&: ToType,
5787 args&: ToTypeSourceInfo, args: D->getPropertyImplementation()))
5788 return ToProperty;
5789
5790 auto ToGetterName = importChecked(Err, From: D->getGetterName());
5791 auto ToSetterName = importChecked(Err, From: D->getSetterName());
5792 auto ToGetterNameLoc = importChecked(Err, From: D->getGetterNameLoc());
5793 auto ToSetterNameLoc = importChecked(Err, From: D->getSetterNameLoc());
5794 auto ToGetterMethodDecl = importChecked(Err, From: D->getGetterMethodDecl());
5795 auto ToSetterMethodDecl = importChecked(Err, From: D->getSetterMethodDecl());
5796 auto ToPropertyIvarDecl = importChecked(Err, From: D->getPropertyIvarDecl());
5797 if (Err)
5798 return std::move(Err);
5799
5800 ToProperty->setLexicalDeclContext(LexicalDC);
5801 LexicalDC->addDeclInternal(D: ToProperty);
5802
5803 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5804 ToProperty->setPropertyAttributesAsWritten(
5805 D->getPropertyAttributesAsWritten());
5806 ToProperty->setGetterName(Sel: ToGetterName, Loc: ToGetterNameLoc);
5807 ToProperty->setSetterName(Sel: ToSetterName, Loc: ToSetterNameLoc);
5808 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5809 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5810 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5811 return ToProperty;
5812}
5813
5814ExpectedDecl
5815ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
5816 ObjCPropertyDecl *Property;
5817 if (Error Err = importInto(To&: Property, From: D->getPropertyDecl()))
5818 return std::move(Err);
5819
5820 DeclContext *DC, *LexicalDC;
5821 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
5822 return std::move(Err);
5823
5824 auto *InImpl = cast<ObjCImplDecl>(Val: LexicalDC);
5825
5826 // Import the ivar (for an @synthesize).
5827 ObjCIvarDecl *Ivar = nullptr;
5828 if (Error Err = importInto(To&: Ivar, From: D->getPropertyIvarDecl()))
5829 return std::move(Err);
5830
5831 ObjCPropertyImplDecl *ToImpl
5832 = InImpl->FindPropertyImplDecl(propertyId: Property->getIdentifier(),
5833 queryKind: Property->getQueryKind());
5834 if (!ToImpl) {
5835
5836 Error Err = Error::success();
5837 auto ToBeginLoc = importChecked(Err, From: D->getBeginLoc());
5838 auto ToLocation = importChecked(Err, From: D->getLocation());
5839 auto ToPropertyIvarDeclLoc =
5840 importChecked(Err, From: D->getPropertyIvarDeclLoc());
5841 if (Err)
5842 return std::move(Err);
5843
5844 if (GetImportedOrCreateDecl(ToD&: ToImpl, FromD: D, args&: Importer.getToContext(), args&: DC,
5845 args&: ToBeginLoc,
5846 args&: ToLocation, args&: Property,
5847 args: D->getPropertyImplementation(), args&: Ivar,
5848 args&: ToPropertyIvarDeclLoc))
5849 return ToImpl;
5850
5851 ToImpl->setLexicalDeclContext(LexicalDC);
5852 LexicalDC->addDeclInternal(D: ToImpl);
5853 } else {
5854 // Check that we have the same kind of property implementation (@synthesize
5855 // vs. @dynamic).
5856 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5857 Importer.ToDiag(Loc: ToImpl->getLocation(),
5858 DiagID: diag::warn_odr_objc_property_impl_kind_inconsistent)
5859 << Property->getDeclName()
5860 << (ToImpl->getPropertyImplementation()
5861 == ObjCPropertyImplDecl::Dynamic);
5862 Importer.FromDiag(Loc: D->getLocation(),
5863 DiagID: diag::note_odr_objc_property_impl_kind)
5864 << D->getPropertyDecl()->getDeclName()
5865 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5866
5867 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5868 }
5869
5870 // For @synthesize, check that we have the same
5871 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5872 Ivar != ToImpl->getPropertyIvarDecl()) {
5873 Importer.ToDiag(Loc: ToImpl->getPropertyIvarDeclLoc(),
5874 DiagID: diag::warn_odr_objc_synthesize_ivar_inconsistent)
5875 << Property->getDeclName()
5876 << ToImpl->getPropertyIvarDecl()->getDeclName()
5877 << Ivar->getDeclName();
5878 Importer.FromDiag(Loc: D->getPropertyIvarDeclLoc(),
5879 DiagID: diag::note_odr_objc_synthesize_ivar_here)
5880 << D->getPropertyIvarDecl()->getDeclName();
5881
5882 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5883 }
5884
5885 // Merge the existing implementation with the new implementation.
5886 Importer.MapImported(From: D, To: ToImpl);
5887 }
5888
5889 return ToImpl;
5890}
5891
5892ExpectedDecl
5893ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
5894 // For template arguments, we adopt the translation unit as our declaration
5895 // context. This context will be fixed when the actual template declaration
5896 // is created.
5897
5898 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
5899 if (!BeginLocOrErr)
5900 return BeginLocOrErr.takeError();
5901
5902 ExpectedSLoc LocationOrErr = import(From: D->getLocation());
5903 if (!LocationOrErr)
5904 return LocationOrErr.takeError();
5905
5906 TemplateTypeParmDecl *ToD = nullptr;
5907 if (GetImportedOrCreateDecl(
5908 ToD, FromD: D, args&: Importer.getToContext(),
5909 args: Importer.getToContext().getTranslationUnitDecl(),
5910 args&: *BeginLocOrErr, args&: *LocationOrErr,
5911 args: D->getDepth(), args: D->getIndex(), args: Importer.Import(FromId: D->getIdentifier()),
5912 args: D->wasDeclaredWithTypename(), args: D->isParameterPack(),
5913 args: D->hasTypeConstraint()))
5914 return ToD;
5915
5916 // Import the type-constraint
5917 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5918
5919 Error Err = Error::success();
5920 auto ToConceptRef = importChecked(Err, From: TC->getConceptReference());
5921 auto ToIDC = importChecked(Err, From: TC->getImmediatelyDeclaredConstraint());
5922 if (Err)
5923 return std::move(Err);
5924
5925 ToD->setTypeConstraint(CR: ToConceptRef, ImmediatelyDeclaredConstraint: ToIDC);
5926 }
5927
5928 if (D->hasDefaultArgument()) {
5929 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5930 import(TALoc: D->getDefaultArgument());
5931 if (!ToDefaultArgOrErr)
5932 return ToDefaultArgOrErr.takeError();
5933 ToD->setDefaultArgument(C: ToD->getASTContext(), DefArg: *ToDefaultArgOrErr);
5934 }
5935
5936 return ToD;
5937}
5938
5939ExpectedDecl
5940ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
5941
5942 Error Err = Error::success();
5943 auto ToDeclName = importChecked(Err, From: D->getDeclName());
5944 auto ToLocation = importChecked(Err, From: D->getLocation());
5945 auto ToType = importChecked(Err, From: D->getType());
5946 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
5947 auto ToInnerLocStart = importChecked(Err, From: D->getInnerLocStart());
5948 if (Err)
5949 return std::move(Err);
5950
5951 NonTypeTemplateParmDecl *ToD = nullptr;
5952 if (GetImportedOrCreateDecl(ToD, FromD: D, args&: Importer.getToContext(),
5953 args: Importer.getToContext().getTranslationUnitDecl(),
5954 args&: ToInnerLocStart, args&: ToLocation, args: D->getDepth(),
5955 args: D->getPosition(),
5956 args: ToDeclName.getAsIdentifierInfo(), args&: ToType,
5957 args: D->isParameterPack(), args&: ToTypeSourceInfo))
5958 return ToD;
5959
5960 if (D->hasDefaultArgument()) {
5961 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5962 import(TALoc: D->getDefaultArgument());
5963 if (!ToDefaultArgOrErr)
5964 return ToDefaultArgOrErr.takeError();
5965 ToD->setDefaultArgument(C: Importer.getToContext(), DefArg: *ToDefaultArgOrErr);
5966 }
5967
5968 return ToD;
5969}
5970
5971ExpectedDecl
5972ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
5973 // Import the name of this declaration.
5974 auto NameOrErr = import(From: D->getDeclName());
5975 if (!NameOrErr)
5976 return NameOrErr.takeError();
5977
5978 // Import the location of this declaration.
5979 ExpectedSLoc LocationOrErr = import(From: D->getLocation());
5980 if (!LocationOrErr)
5981 return LocationOrErr.takeError();
5982
5983 // Import template parameters.
5984 auto TemplateParamsOrErr = import(From: D->getTemplateParameters());
5985 if (!TemplateParamsOrErr)
5986 return TemplateParamsOrErr.takeError();
5987
5988 TemplateTemplateParmDecl *ToD = nullptr;
5989 if (GetImportedOrCreateDecl(
5990 ToD, FromD: D, args&: Importer.getToContext(),
5991 args: Importer.getToContext().getTranslationUnitDecl(), args&: *LocationOrErr,
5992 args: D->getDepth(), args: D->getPosition(), args: D->isParameterPack(),
5993 args: (*NameOrErr).getAsIdentifierInfo(), args: D->wasDeclaredWithTypename(),
5994 args&: *TemplateParamsOrErr))
5995 return ToD;
5996
5997 if (D->hasDefaultArgument()) {
5998 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5999 import(TALoc: D->getDefaultArgument());
6000 if (!ToDefaultArgOrErr)
6001 return ToDefaultArgOrErr.takeError();
6002 ToD->setDefaultArgument(C: Importer.getToContext(), DefArg: *ToDefaultArgOrErr);
6003 }
6004
6005 return ToD;
6006}
6007
6008// Returns the definition for a (forward) declaration of a TemplateDecl, if
6009// it has any definition in the redecl chain.
6010template <typename T> static auto getTemplateDefinition(T *D) -> T * {
6011 assert(D->getTemplatedDecl() && "Should be called on templates only");
6012 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
6013 if (!ToTemplatedDef)
6014 return nullptr;
6015 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
6016 return cast_or_null<T>(TemplateWithDef);
6017}
6018
6019ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
6020
6021 // Import the major distinguishing characteristics of this class template.
6022 DeclContext *DC, *LexicalDC;
6023 DeclarationName Name;
6024 SourceLocation Loc;
6025 NamedDecl *ToD;
6026 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6027 return std::move(Err);
6028 if (ToD)
6029 return ToD;
6030
6031 // Should check if a declaration is friend in a dependent context.
6032 // Such templates are not linked together in a declaration chain.
6033 // The ASTImporter strategy is to map existing forward declarations to
6034 // imported ones only if strictly necessary, otherwise import these as new
6035 // forward declarations. In case of the "dependent friend" declarations, new
6036 // declarations are created, but not linked in a declaration chain.
6037 auto IsDependentFriend = [](ClassTemplateDecl *TD) {
6038 return TD->getFriendObjectKind() != Decl::FOK_None &&
6039 TD->getLexicalDeclContext()->isDependentContext();
6040 };
6041 bool DependentFriend = IsDependentFriend(D);
6042
6043 ClassTemplateDecl *FoundByLookup = nullptr;
6044
6045 // We may already have a template of the same name; try to find and match it.
6046 if (!DC->isFunctionOrMethod()) {
6047 SmallVector<NamedDecl *, 4> ConflictingDecls;
6048 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6049 for (auto *FoundDecl : FoundDecls) {
6050 if (!FoundDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary |
6051 Decl::IDNS_TagFriend))
6052 continue;
6053
6054 Decl *Found = FoundDecl;
6055 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Val: Found);
6056 if (FoundTemplate) {
6057 if (!hasSameVisibilityContextAndLinkage(Found: FoundTemplate, From: D))
6058 continue;
6059
6060 // FIXME: sufficient conditon for 'IgnoreTemplateParmDepth'?
6061 bool IgnoreTemplateParmDepth =
6062 (FoundTemplate->getFriendObjectKind() != Decl::FOK_None) !=
6063 (D->getFriendObjectKind() != Decl::FOK_None);
6064 if (IsStructuralMatch(From: D, To: FoundTemplate, /*Complain=*/true,
6065 IgnoreTemplateParmDepth)) {
6066 if (DependentFriend || IsDependentFriend(FoundTemplate))
6067 continue;
6068
6069 ClassTemplateDecl *TemplateWithDef =
6070 getTemplateDefinition(D: FoundTemplate);
6071 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6072 return Importer.MapImported(From: D, To: TemplateWithDef);
6073 if (!FoundByLookup)
6074 FoundByLookup = FoundTemplate;
6075 // Search in all matches because there may be multiple decl chains,
6076 // see ASTTests test ImportExistingFriendClassTemplateDef.
6077 continue;
6078 }
6079 ConflictingDecls.push_back(Elt: FoundDecl);
6080 }
6081 }
6082
6083 if (!ConflictingDecls.empty()) {
6084 ExpectedName NameOrErr = Importer.HandleNameConflict(
6085 Name, DC, IDNS: Decl::IDNS_Ordinary, Decls: ConflictingDecls.data(),
6086 NumDecls: ConflictingDecls.size());
6087 if (NameOrErr)
6088 Name = NameOrErr.get();
6089 else
6090 return NameOrErr.takeError();
6091 }
6092 }
6093
6094 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
6095
6096 auto TemplateParamsOrErr = import(From: D->getTemplateParameters());
6097 if (!TemplateParamsOrErr)
6098 return TemplateParamsOrErr.takeError();
6099
6100 // Create the declaration that is being templated.
6101 CXXRecordDecl *ToTemplated;
6102 if (Error Err = importInto(To&: ToTemplated, From: FromTemplated))
6103 return std::move(Err);
6104
6105 // Create the class template declaration itself.
6106 ClassTemplateDecl *D2;
6107 if (GetImportedOrCreateDecl(ToD&: D2, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc, args&: Name,
6108 args&: *TemplateParamsOrErr, args&: ToTemplated))
6109 return D2;
6110
6111 ToTemplated->setDescribedClassTemplate(D2);
6112
6113 D2->setAccess(D->getAccess());
6114 D2->setLexicalDeclContext(LexicalDC);
6115
6116 addDeclToContexts(FromD: D, ToD: D2);
6117 updateLookupTableForTemplateParameters(Params&: **TemplateParamsOrErr);
6118
6119 if (FoundByLookup) {
6120 auto *Recent =
6121 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6122
6123 // It is possible that during the import of the class template definition
6124 // we start the import of a fwd friend decl of the very same class template
6125 // and we add the fwd friend decl to the lookup table. But the ToTemplated
6126 // had been created earlier and by that time the lookup could not find
6127 // anything existing, so it has no previous decl. Later, (still during the
6128 // import of the fwd friend decl) we start to import the definition again
6129 // and this time the lookup finds the previous fwd friend class template.
6130 // In this case we must set up the previous decl for the templated decl.
6131 if (!ToTemplated->getPreviousDecl()) {
6132 assert(FoundByLookup->getTemplatedDecl() &&
6133 "Found decl must have its templated decl set");
6134 CXXRecordDecl *PrevTemplated =
6135 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6136 if (ToTemplated != PrevTemplated)
6137 ToTemplated->setPreviousDecl(PrevTemplated);
6138 }
6139
6140 D2->setPreviousDecl(Recent);
6141 }
6142
6143 return D2;
6144}
6145
6146ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
6147 ClassTemplateSpecializationDecl *D) {
6148 ClassTemplateDecl *ClassTemplate;
6149 if (Error Err = importInto(To&: ClassTemplate, From: D->getSpecializedTemplate()))
6150 return std::move(Err);
6151
6152 // Import the context of this declaration.
6153 DeclContext *DC, *LexicalDC;
6154 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
6155 return std::move(Err);
6156
6157 // Import template arguments.
6158 SmallVector<TemplateArgument, 2> TemplateArgs;
6159 if (Error Err =
6160 ImportTemplateArguments(FromArgs: D->getTemplateArgs().asArray(), ToArgs&: TemplateArgs))
6161 return std::move(Err);
6162 // Try to find an existing specialization with these template arguments and
6163 // template parameter list.
6164 void *InsertPos = nullptr;
6165 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6166 ClassTemplatePartialSpecializationDecl *PartialSpec =
6167 dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D);
6168
6169 // Import template parameters.
6170 TemplateParameterList *ToTPList = nullptr;
6171
6172 if (PartialSpec) {
6173 auto ToTPListOrErr = import(From: PartialSpec->getTemplateParameters());
6174 if (!ToTPListOrErr)
6175 return ToTPListOrErr.takeError();
6176 ToTPList = *ToTPListOrErr;
6177 PrevDecl = ClassTemplate->findPartialSpecialization(Args: TemplateArgs,
6178 TPL: *ToTPListOrErr,
6179 InsertPos);
6180 } else
6181 PrevDecl = ClassTemplate->findSpecialization(Args: TemplateArgs, InsertPos);
6182
6183 if (PrevDecl) {
6184 if (IsStructuralMatch(From: D, To: PrevDecl)) {
6185 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
6186 if (D->isThisDeclarationADefinition() && PrevDefinition) {
6187 Importer.MapImported(From: D, To: PrevDefinition);
6188 // Import those default field initializers which have been
6189 // instantiated in the "From" context, but not in the "To" context.
6190 for (auto *FromField : D->fields()) {
6191 auto ToOrErr = import(From: FromField);
6192 if (!ToOrErr)
6193 return ToOrErr.takeError();
6194 }
6195
6196 // Import those methods which have been instantiated in the
6197 // "From" context, but not in the "To" context.
6198 for (CXXMethodDecl *FromM : D->methods()) {
6199 auto ToOrErr = import(From: FromM);
6200 if (!ToOrErr)
6201 return ToOrErr.takeError();
6202 }
6203
6204 // TODO Import instantiated default arguments.
6205 // TODO Import instantiated exception specifications.
6206 //
6207 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
6208 // what else could be fused during an AST merge.
6209 return PrevDefinition;
6210 }
6211 } else { // ODR violation.
6212 // FIXME HandleNameConflict
6213 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
6214 }
6215 }
6216
6217 // Import the location of this declaration.
6218 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
6219 if (!BeginLocOrErr)
6220 return BeginLocOrErr.takeError();
6221 ExpectedSLoc IdLocOrErr = import(From: D->getLocation());
6222 if (!IdLocOrErr)
6223 return IdLocOrErr.takeError();
6224
6225 // Import TemplateArgumentListInfo.
6226 TemplateArgumentListInfo ToTAInfo;
6227 if (const auto *ASTTemplateArgs = D->getTemplateArgsAsWritten()) {
6228 if (Error Err = ImportTemplateArgumentListInfo(From: *ASTTemplateArgs, Result&: ToTAInfo))
6229 return std::move(Err);
6230 }
6231
6232 // Create the specialization.
6233 ClassTemplateSpecializationDecl *D2 = nullptr;
6234 if (PartialSpec) {
6235 QualType CanonInjType;
6236 if (Error Err = importInto(
6237 To&: CanonInjType, From: PartialSpec->getInjectedSpecializationType()))
6238 return std::move(Err);
6239 CanonInjType = CanonInjType.getCanonicalType();
6240
6241 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
6242 ToD&: D2, FromD: D, args&: Importer.getToContext(), args: D->getTagKind(), args&: DC, args&: *BeginLocOrErr,
6243 args&: *IdLocOrErr, args&: ToTPList, args&: ClassTemplate,
6244 args: llvm::ArrayRef(TemplateArgs.data(), TemplateArgs.size()),
6245 args&: CanonInjType,
6246 args: cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl)))
6247 return D2;
6248
6249 // Update InsertPos, because preceding import calls may have invalidated
6250 // it by adding new specializations.
6251 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(Val: D2);
6252 if (!ClassTemplate->findPartialSpecialization(Args: TemplateArgs, TPL: ToTPList,
6253 InsertPos))
6254 // Add this partial specialization to the class template.
6255 ClassTemplate->AddPartialSpecialization(D: PartSpec2, InsertPos);
6256 if (Expected<ClassTemplatePartialSpecializationDecl *> ToInstOrErr =
6257 import(From: PartialSpec->getInstantiatedFromMember()))
6258 PartSpec2->setInstantiatedFromMember(*ToInstOrErr);
6259 else
6260 return ToInstOrErr.takeError();
6261
6262 updateLookupTableForTemplateParameters(Params&: *ToTPList);
6263 } else { // Not a partial specialization.
6264 if (GetImportedOrCreateDecl(
6265 ToD&: D2, FromD: D, args&: Importer.getToContext(), args: D->getTagKind(), args&: DC,
6266 args&: *BeginLocOrErr, args&: *IdLocOrErr, args&: ClassTemplate, args&: TemplateArgs,
6267 args&: PrevDecl))
6268 return D2;
6269
6270 // Update InsertPos, because preceding import calls may have invalidated
6271 // it by adding new specializations.
6272 if (!ClassTemplate->findSpecialization(Args: TemplateArgs, InsertPos))
6273 // Add this specialization to the class template.
6274 ClassTemplate->AddSpecialization(D: D2, InsertPos);
6275 }
6276
6277 D2->setSpecializationKind(D->getSpecializationKind());
6278
6279 // Set the context of this specialization/instantiation.
6280 D2->setLexicalDeclContext(LexicalDC);
6281
6282 // Add to the DC only if it was an explicit specialization/instantiation.
6283 if (D2->isExplicitInstantiationOrSpecialization()) {
6284 LexicalDC->addDeclInternal(D: D2);
6285 }
6286
6287 if (auto BraceRangeOrErr = import(From: D->getBraceRange()))
6288 D2->setBraceRange(*BraceRangeOrErr);
6289 else
6290 return BraceRangeOrErr.takeError();
6291
6292 if (Error Err = ImportTemplateParameterLists(FromD: D, ToD: D2))
6293 return std::move(Err);
6294
6295 // Import the qualifier, if any.
6296 if (auto LocOrErr = import(From: D->getQualifierLoc()))
6297 D2->setQualifierInfo(*LocOrErr);
6298 else
6299 return LocOrErr.takeError();
6300
6301 if (D->getTemplateArgsAsWritten())
6302 D2->setTemplateArgsAsWritten(ToTAInfo);
6303
6304 if (auto LocOrErr = import(From: D->getTemplateKeywordLoc()))
6305 D2->setTemplateKeywordLoc(*LocOrErr);
6306 else
6307 return LocOrErr.takeError();
6308
6309 if (auto LocOrErr = import(From: D->getExternKeywordLoc()))
6310 D2->setExternKeywordLoc(*LocOrErr);
6311 else
6312 return LocOrErr.takeError();
6313
6314 if (D->getPointOfInstantiation().isValid()) {
6315 if (auto POIOrErr = import(From: D->getPointOfInstantiation()))
6316 D2->setPointOfInstantiation(*POIOrErr);
6317 else
6318 return POIOrErr.takeError();
6319 }
6320
6321 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
6322
6323 if (auto P = D->getInstantiatedFrom()) {
6324 if (auto *CTD = P.dyn_cast<ClassTemplateDecl *>()) {
6325 if (auto CTDorErr = import(From: CTD))
6326 D2->setInstantiationOf(*CTDorErr);
6327 } else {
6328 auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl *>(Val&: P);
6329 auto CTPSDOrErr = import(From: CTPSD);
6330 if (!CTPSDOrErr)
6331 return CTPSDOrErr.takeError();
6332 const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs();
6333 SmallVector<TemplateArgument, 2> D2ArgsVec(DArgs.size());
6334 for (unsigned I = 0; I < DArgs.size(); ++I) {
6335 const TemplateArgument &DArg = DArgs[I];
6336 if (auto ArgOrErr = import(From: DArg))
6337 D2ArgsVec[I] = *ArgOrErr;
6338 else
6339 return ArgOrErr.takeError();
6340 }
6341 D2->setInstantiationOf(
6342 PartialSpec: *CTPSDOrErr,
6343 TemplateArgs: TemplateArgumentList::CreateCopy(Context&: Importer.getToContext(), Args: D2ArgsVec));
6344 }
6345 }
6346
6347 if (D->isCompleteDefinition())
6348 if (Error Err = ImportDefinition(From: D, To: D2))
6349 return std::move(Err);
6350
6351 return D2;
6352}
6353
6354ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
6355 // Import the major distinguishing characteristics of this variable template.
6356 DeclContext *DC, *LexicalDC;
6357 DeclarationName Name;
6358 SourceLocation Loc;
6359 NamedDecl *ToD;
6360 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6361 return std::move(Err);
6362 if (ToD)
6363 return ToD;
6364
6365 // We may already have a template of the same name; try to find and match it.
6366 assert(!DC->isFunctionOrMethod() &&
6367 "Variable templates cannot be declared at function scope");
6368
6369 SmallVector<NamedDecl *, 4> ConflictingDecls;
6370 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6371 VarTemplateDecl *FoundByLookup = nullptr;
6372 for (auto *FoundDecl : FoundDecls) {
6373 if (!FoundDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
6374 continue;
6375
6376 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Val: FoundDecl)) {
6377 // Use the templated decl, some linkage flags are set only there.
6378 if (!hasSameVisibilityContextAndLinkage(Found: FoundTemplate->getTemplatedDecl(),
6379 From: D->getTemplatedDecl()))
6380 continue;
6381 if (IsStructuralMatch(From: D, To: FoundTemplate)) {
6382 // FIXME Check for ODR error if the two definitions have
6383 // different initializers?
6384 VarTemplateDecl *FoundDef = getTemplateDefinition(D: FoundTemplate);
6385 if (D->getDeclContext()->isRecord()) {
6386 assert(FoundTemplate->getDeclContext()->isRecord() &&
6387 "Member variable template imported as non-member, "
6388 "inconsistent imported AST?");
6389 if (FoundDef)
6390 return Importer.MapImported(From: D, To: FoundDef);
6391 if (!D->isThisDeclarationADefinition())
6392 return Importer.MapImported(From: D, To: FoundTemplate);
6393 } else {
6394 if (FoundDef && D->isThisDeclarationADefinition())
6395 return Importer.MapImported(From: D, To: FoundDef);
6396 }
6397 FoundByLookup = FoundTemplate;
6398 break;
6399 }
6400 ConflictingDecls.push_back(Elt: FoundDecl);
6401 }
6402 }
6403
6404 if (!ConflictingDecls.empty()) {
6405 ExpectedName NameOrErr = Importer.HandleNameConflict(
6406 Name, DC, IDNS: Decl::IDNS_Ordinary, Decls: ConflictingDecls.data(),
6407 NumDecls: ConflictingDecls.size());
6408 if (NameOrErr)
6409 Name = NameOrErr.get();
6410 else
6411 return NameOrErr.takeError();
6412 }
6413
6414 VarDecl *DTemplated = D->getTemplatedDecl();
6415
6416 // Import the type.
6417 // FIXME: Value not used?
6418 ExpectedType TypeOrErr = import(From: DTemplated->getType());
6419 if (!TypeOrErr)
6420 return TypeOrErr.takeError();
6421
6422 // Create the declaration that is being templated.
6423 VarDecl *ToTemplated;
6424 if (Error Err = importInto(To&: ToTemplated, From: DTemplated))
6425 return std::move(Err);
6426
6427 // Create the variable template declaration itself.
6428 auto TemplateParamsOrErr = import(From: D->getTemplateParameters());
6429 if (!TemplateParamsOrErr)
6430 return TemplateParamsOrErr.takeError();
6431
6432 VarTemplateDecl *ToVarTD;
6433 if (GetImportedOrCreateDecl(ToD&: ToVarTD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
6434 args&: Name, args&: *TemplateParamsOrErr, args&: ToTemplated))
6435 return ToVarTD;
6436
6437 ToTemplated->setDescribedVarTemplate(ToVarTD);
6438
6439 ToVarTD->setAccess(D->getAccess());
6440 ToVarTD->setLexicalDeclContext(LexicalDC);
6441 LexicalDC->addDeclInternal(D: ToVarTD);
6442 if (DC != Importer.getToContext().getTranslationUnitDecl())
6443 updateLookupTableForTemplateParameters(Params&: **TemplateParamsOrErr);
6444
6445 if (FoundByLookup) {
6446 auto *Recent =
6447 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6448 if (!ToTemplated->getPreviousDecl()) {
6449 auto *PrevTemplated =
6450 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6451 if (ToTemplated != PrevTemplated)
6452 ToTemplated->setPreviousDecl(PrevTemplated);
6453 }
6454 ToVarTD->setPreviousDecl(Recent);
6455 }
6456
6457 return ToVarTD;
6458}
6459
6460ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
6461 VarTemplateSpecializationDecl *D) {
6462 // A VarTemplateSpecializationDecl inherits from VarDecl, the import is done
6463 // in an analog way (but specialized for this case).
6464
6465 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
6466 auto RedeclIt = Redecls.begin();
6467 // Import the first part of the decl chain. I.e. import all previous
6468 // declarations starting from the canonical decl.
6469 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
6470 ExpectedDecl RedeclOrErr = import(From: *RedeclIt);
6471 if (!RedeclOrErr)
6472 return RedeclOrErr.takeError();
6473 }
6474 assert(*RedeclIt == D);
6475
6476 VarTemplateDecl *VarTemplate = nullptr;
6477 if (Error Err = importInto(To&: VarTemplate, From: D->getSpecializedTemplate()))
6478 return std::move(Err);
6479
6480 // Import the context of this declaration.
6481 DeclContext *DC, *LexicalDC;
6482 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
6483 return std::move(Err);
6484
6485 // Import the location of this declaration.
6486 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
6487 if (!BeginLocOrErr)
6488 return BeginLocOrErr.takeError();
6489
6490 auto IdLocOrErr = import(From: D->getLocation());
6491 if (!IdLocOrErr)
6492 return IdLocOrErr.takeError();
6493
6494 // Import template arguments.
6495 SmallVector<TemplateArgument, 2> TemplateArgs;
6496 if (Error Err =
6497 ImportTemplateArguments(FromArgs: D->getTemplateArgs().asArray(), ToArgs&: TemplateArgs))
6498 return std::move(Err);
6499
6500 // Try to find an existing specialization with these template arguments.
6501 void *InsertPos = nullptr;
6502 VarTemplateSpecializationDecl *FoundSpecialization =
6503 VarTemplate->findSpecialization(Args: TemplateArgs, InsertPos);
6504 if (FoundSpecialization) {
6505 if (IsStructuralMatch(From: D, To: FoundSpecialization)) {
6506 VarDecl *FoundDef = FoundSpecialization->getDefinition();
6507 if (D->getDeclContext()->isRecord()) {
6508 // In a record, it is allowed only to have one optional declaration and
6509 // one definition of the (static or constexpr) variable template.
6510 assert(
6511 FoundSpecialization->getDeclContext()->isRecord() &&
6512 "Member variable template specialization imported as non-member, "
6513 "inconsistent imported AST?");
6514 if (FoundDef)
6515 return Importer.MapImported(From: D, To: FoundDef);
6516 if (!D->isThisDeclarationADefinition())
6517 return Importer.MapImported(From: D, To: FoundSpecialization);
6518 } else {
6519 // If definition is imported and there is already one, map to it.
6520 // Otherwise create a new variable and link it to the existing.
6521 if (FoundDef && D->isThisDeclarationADefinition())
6522 return Importer.MapImported(From: D, To: FoundDef);
6523 }
6524 } else {
6525 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
6526 }
6527 }
6528
6529 VarTemplateSpecializationDecl *D2 = nullptr;
6530
6531 TemplateArgumentListInfo ToTAInfo;
6532 if (const auto *Args = D->getTemplateArgsAsWritten()) {
6533 if (Error Err = ImportTemplateArgumentListInfo(From: *Args, Result&: ToTAInfo))
6534 return std::move(Err);
6535 }
6536
6537 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
6538 // Create a new specialization.
6539 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(Val: D)) {
6540 auto ToTPListOrErr = import(From: FromPartial->getTemplateParameters());
6541 if (!ToTPListOrErr)
6542 return ToTPListOrErr.takeError();
6543
6544 PartVarSpecDecl *ToPartial;
6545 if (GetImportedOrCreateDecl(ToD&: ToPartial, FromD: D, args&: Importer.getToContext(), args&: DC,
6546 args&: *BeginLocOrErr, args&: *IdLocOrErr, args&: *ToTPListOrErr,
6547 args&: VarTemplate, args: QualType(), args: nullptr,
6548 args: D->getStorageClass(), args&: TemplateArgs))
6549 return ToPartial;
6550
6551 if (Expected<PartVarSpecDecl *> ToInstOrErr =
6552 import(From: FromPartial->getInstantiatedFromMember()))
6553 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
6554 else
6555 return ToInstOrErr.takeError();
6556
6557 if (FromPartial->isMemberSpecialization())
6558 ToPartial->setMemberSpecialization();
6559
6560 D2 = ToPartial;
6561
6562 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed
6563 // to adopt template parameters.
6564 // updateLookupTableForTemplateParameters(**ToTPListOrErr);
6565 } else { // Full specialization
6566 if (GetImportedOrCreateDecl(ToD&: D2, FromD: D, args&: Importer.getToContext(), args&: DC,
6567 args&: *BeginLocOrErr, args&: *IdLocOrErr, args&: VarTemplate,
6568 args: QualType(), args: nullptr, args: D->getStorageClass(),
6569 args&: TemplateArgs))
6570 return D2;
6571 }
6572
6573 // Update InsertPos, because preceding import calls may have invalidated
6574 // it by adding new specializations.
6575 if (!VarTemplate->findSpecialization(Args: TemplateArgs, InsertPos))
6576 VarTemplate->AddSpecialization(D: D2, InsertPos);
6577
6578 QualType T;
6579 if (Error Err = importInto(To&: T, From: D->getType()))
6580 return std::move(Err);
6581 D2->setType(T);
6582
6583 auto TInfoOrErr = import(From: D->getTypeSourceInfo());
6584 if (!TInfoOrErr)
6585 return TInfoOrErr.takeError();
6586 D2->setTypeSourceInfo(*TInfoOrErr);
6587
6588 if (D->getPointOfInstantiation().isValid()) {
6589 if (ExpectedSLoc POIOrErr = import(From: D->getPointOfInstantiation()))
6590 D2->setPointOfInstantiation(*POIOrErr);
6591 else
6592 return POIOrErr.takeError();
6593 }
6594
6595 D2->setSpecializationKind(D->getSpecializationKind());
6596
6597 if (D->getTemplateArgsAsWritten())
6598 D2->setTemplateArgsAsWritten(ToTAInfo);
6599
6600 if (auto LocOrErr = import(From: D->getQualifierLoc()))
6601 D2->setQualifierInfo(*LocOrErr);
6602 else
6603 return LocOrErr.takeError();
6604
6605 if (D->isConstexpr())
6606 D2->setConstexpr(true);
6607
6608 D2->setAccess(D->getAccess());
6609
6610 if (Error Err = ImportInitializer(From: D, To: D2))
6611 return std::move(Err);
6612
6613 if (FoundSpecialization)
6614 D2->setPreviousDecl(FoundSpecialization->getMostRecentDecl());
6615
6616 addDeclToContexts(FromD: D, ToD: D2);
6617
6618 // Import the rest of the chain. I.e. import all subsequent declarations.
6619 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
6620 ExpectedDecl RedeclOrErr = import(From: *RedeclIt);
6621 if (!RedeclOrErr)
6622 return RedeclOrErr.takeError();
6623 }
6624
6625 return D2;
6626}
6627
6628ExpectedDecl
6629ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
6630 DeclContext *DC, *LexicalDC;
6631 DeclarationName Name;
6632 SourceLocation Loc;
6633 NamedDecl *ToD;
6634
6635 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6636 return std::move(Err);
6637
6638 if (ToD)
6639 return ToD;
6640
6641 const FunctionTemplateDecl *FoundByLookup = nullptr;
6642
6643 // Try to find a function in our own ("to") context with the same name, same
6644 // type, and in the same context as the function we're importing.
6645 // FIXME Split this into a separate function.
6646 if (!LexicalDC->isFunctionOrMethod()) {
6647 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
6648 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6649 for (auto *FoundDecl : FoundDecls) {
6650 if (!FoundDecl->isInIdentifierNamespace(NS: IDNS))
6651 continue;
6652
6653 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(Val: FoundDecl)) {
6654 if (!hasSameVisibilityContextAndLinkage(Found: FoundTemplate, From: D))
6655 continue;
6656 if (IsStructuralMatch(From: D, To: FoundTemplate)) {
6657 FunctionTemplateDecl *TemplateWithDef =
6658 getTemplateDefinition(D: FoundTemplate);
6659 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6660 return Importer.MapImported(From: D, To: TemplateWithDef);
6661
6662 FoundByLookup = FoundTemplate;
6663 break;
6664 // TODO: handle conflicting names
6665 }
6666 }
6667 }
6668 }
6669
6670 auto ParamsOrErr = import(From: D->getTemplateParameters());
6671 if (!ParamsOrErr)
6672 return ParamsOrErr.takeError();
6673 TemplateParameterList *Params = *ParamsOrErr;
6674
6675 FunctionDecl *TemplatedFD;
6676 if (Error Err = importInto(To&: TemplatedFD, From: D->getTemplatedDecl()))
6677 return std::move(Err);
6678
6679 // At creation of the template the template parameters are "adopted"
6680 // (DeclContext is changed). After this possible change the lookup table
6681 // must be updated.
6682 // At deduction guides the DeclContext of the template parameters may be
6683 // different from what we would expect, it may be the class template, or a
6684 // probably different CXXDeductionGuideDecl. This may come from the fact that
6685 // the template parameter objects may be shared between deduction guides or
6686 // the class template, and at creation of multiple FunctionTemplateDecl
6687 // objects (for deduction guides) the same parameters are re-used. The
6688 // "adoption" happens multiple times with different parent, even recursively
6689 // for TemplateTemplateParmDecl. The same happens at import when the
6690 // FunctionTemplateDecl objects are created, but in different order.
6691 // In this way the DeclContext of these template parameters is not necessarily
6692 // the same as in the "from" context.
6693 SmallVector<DeclContext *, 2> OldParamDC;
6694 OldParamDC.reserve(N: Params->size());
6695 llvm::transform(Range&: *Params, d_first: std::back_inserter(x&: OldParamDC),
6696 F: [](NamedDecl *ND) { return ND->getDeclContext(); });
6697
6698 FunctionTemplateDecl *ToFunc;
6699 if (GetImportedOrCreateDecl(ToD&: ToFunc, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc, args&: Name,
6700 args&: Params, args&: TemplatedFD))
6701 return ToFunc;
6702
6703 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
6704
6705 ToFunc->setAccess(D->getAccess());
6706 ToFunc->setLexicalDeclContext(LexicalDC);
6707 addDeclToContexts(FromD: D, ToD: ToFunc);
6708
6709 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
6710 if (LT && !OldParamDC.empty()) {
6711 for (unsigned int I = 0; I < OldParamDC.size(); ++I)
6712 LT->updateForced(ND: Params->getParam(Idx: I), OldDC: OldParamDC[I]);
6713 }
6714
6715 if (FoundByLookup) {
6716 auto *Recent =
6717 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6718 if (!TemplatedFD->getPreviousDecl()) {
6719 assert(FoundByLookup->getTemplatedDecl() &&
6720 "Found decl must have its templated decl set");
6721 auto *PrevTemplated =
6722 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6723 if (TemplatedFD != PrevTemplated)
6724 TemplatedFD->setPreviousDecl(PrevTemplated);
6725 }
6726 ToFunc->setPreviousDecl(Recent);
6727 }
6728
6729 return ToFunc;
6730}
6731
6732//----------------------------------------------------------------------------
6733// Import Statements
6734//----------------------------------------------------------------------------
6735
6736ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
6737 Importer.FromDiag(Loc: S->getBeginLoc(), DiagID: diag::err_unsupported_ast_node)
6738 << S->getStmtClassName();
6739 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
6740}
6741
6742
6743ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
6744 if (Importer.returnWithErrorInTest())
6745 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
6746 SmallVector<IdentifierInfo *, 4> Names;
6747 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6748 IdentifierInfo *ToII = Importer.Import(FromId: S->getOutputIdentifier(i: I));
6749 // ToII is nullptr when no symbolic name is given for output operand
6750 // see ParseStmtAsm::ParseAsmOperandsOpt
6751 Names.push_back(Elt: ToII);
6752 }
6753
6754 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6755 IdentifierInfo *ToII = Importer.Import(FromId: S->getInputIdentifier(i: I));
6756 // ToII is nullptr when no symbolic name is given for input operand
6757 // see ParseStmtAsm::ParseAsmOperandsOpt
6758 Names.push_back(Elt: ToII);
6759 }
6760
6761 SmallVector<StringLiteral *, 4> Clobbers;
6762 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
6763 if (auto ClobberOrErr = import(From: S->getClobberStringLiteral(i: I)))
6764 Clobbers.push_back(Elt: *ClobberOrErr);
6765 else
6766 return ClobberOrErr.takeError();
6767
6768 }
6769
6770 SmallVector<StringLiteral *, 4> Constraints;
6771 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6772 if (auto OutputOrErr = import(From: S->getOutputConstraintLiteral(i: I)))
6773 Constraints.push_back(Elt: *OutputOrErr);
6774 else
6775 return OutputOrErr.takeError();
6776 }
6777
6778 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6779 if (auto InputOrErr = import(From: S->getInputConstraintLiteral(i: I)))
6780 Constraints.push_back(Elt: *InputOrErr);
6781 else
6782 return InputOrErr.takeError();
6783 }
6784
6785 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
6786 S->getNumLabels());
6787 if (Error Err = ImportContainerChecked(InContainer: S->outputs(), OutContainer&: Exprs))
6788 return std::move(Err);
6789
6790 if (Error Err =
6791 ImportArrayChecked(InContainer: S->inputs(), Obegin: Exprs.begin() + S->getNumOutputs()))
6792 return std::move(Err);
6793
6794 if (Error Err = ImportArrayChecked(
6795 InContainer: S->labels(), Obegin: Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
6796 return std::move(Err);
6797
6798 ExpectedSLoc AsmLocOrErr = import(From: S->getAsmLoc());
6799 if (!AsmLocOrErr)
6800 return AsmLocOrErr.takeError();
6801 auto AsmStrOrErr = import(From: S->getAsmString());
6802 if (!AsmStrOrErr)
6803 return AsmStrOrErr.takeError();
6804 ExpectedSLoc RParenLocOrErr = import(From: S->getRParenLoc());
6805 if (!RParenLocOrErr)
6806 return RParenLocOrErr.takeError();
6807
6808 return new (Importer.getToContext()) GCCAsmStmt(
6809 Importer.getToContext(),
6810 *AsmLocOrErr,
6811 S->isSimple(),
6812 S->isVolatile(),
6813 S->getNumOutputs(),
6814 S->getNumInputs(),
6815 Names.data(),
6816 Constraints.data(),
6817 Exprs.data(),
6818 *AsmStrOrErr,
6819 S->getNumClobbers(),
6820 Clobbers.data(),
6821 S->getNumLabels(),
6822 *RParenLocOrErr);
6823}
6824
6825ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
6826
6827 Error Err = Error::success();
6828 auto ToDG = importChecked(Err, From: S->getDeclGroup());
6829 auto ToBeginLoc = importChecked(Err, From: S->getBeginLoc());
6830 auto ToEndLoc = importChecked(Err, From: S->getEndLoc());
6831 if (Err)
6832 return std::move(Err);
6833 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
6834}
6835
6836ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
6837 ExpectedSLoc ToSemiLocOrErr = import(From: S->getSemiLoc());
6838 if (!ToSemiLocOrErr)
6839 return ToSemiLocOrErr.takeError();
6840 return new (Importer.getToContext()) NullStmt(
6841 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
6842}
6843
6844ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
6845 SmallVector<Stmt *, 8> ToStmts(S->size());
6846
6847 if (Error Err = ImportContainerChecked(InContainer: S->body(), OutContainer&: ToStmts))
6848 return std::move(Err);
6849
6850 ExpectedSLoc ToLBracLocOrErr = import(From: S->getLBracLoc());
6851 if (!ToLBracLocOrErr)
6852 return ToLBracLocOrErr.takeError();
6853
6854 ExpectedSLoc ToRBracLocOrErr = import(From: S->getRBracLoc());
6855 if (!ToRBracLocOrErr)
6856 return ToRBracLocOrErr.takeError();
6857
6858 FPOptionsOverride FPO =
6859 S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride();
6860 return CompoundStmt::Create(C: Importer.getToContext(), Stmts: ToStmts, FPFeatures: FPO,
6861 LB: *ToLBracLocOrErr, RB: *ToRBracLocOrErr);
6862}
6863
6864ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
6865
6866 Error Err = Error::success();
6867 auto ToLHS = importChecked(Err, From: S->getLHS());
6868 auto ToRHS = importChecked(Err, From: S->getRHS());
6869 auto ToSubStmt = importChecked(Err, From: S->getSubStmt());
6870 auto ToCaseLoc = importChecked(Err, From: S->getCaseLoc());
6871 auto ToEllipsisLoc = importChecked(Err, From: S->getEllipsisLoc());
6872 auto ToColonLoc = importChecked(Err, From: S->getColonLoc());
6873 if (Err)
6874 return std::move(Err);
6875
6876 auto *ToStmt = CaseStmt::Create(Ctx: Importer.getToContext(), lhs: ToLHS, rhs: ToRHS,
6877 caseLoc: ToCaseLoc, ellipsisLoc: ToEllipsisLoc, colonLoc: ToColonLoc);
6878 ToStmt->setSubStmt(ToSubStmt);
6879
6880 return ToStmt;
6881}
6882
6883ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
6884
6885 Error Err = Error::success();
6886 auto ToDefaultLoc = importChecked(Err, From: S->getDefaultLoc());
6887 auto ToColonLoc = importChecked(Err, From: S->getColonLoc());
6888 auto ToSubStmt = importChecked(Err, From: S->getSubStmt());
6889 if (Err)
6890 return std::move(Err);
6891
6892 return new (Importer.getToContext()) DefaultStmt(
6893 ToDefaultLoc, ToColonLoc, ToSubStmt);
6894}
6895
6896ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
6897
6898 Error Err = Error::success();
6899 auto ToIdentLoc = importChecked(Err, From: S->getIdentLoc());
6900 auto ToLabelDecl = importChecked(Err, From: S->getDecl());
6901 auto ToSubStmt = importChecked(Err, From: S->getSubStmt());
6902 if (Err)
6903 return std::move(Err);
6904
6905 return new (Importer.getToContext()) LabelStmt(
6906 ToIdentLoc, ToLabelDecl, ToSubStmt);
6907}
6908
6909ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
6910 ExpectedSLoc ToAttrLocOrErr = import(From: S->getAttrLoc());
6911 if (!ToAttrLocOrErr)
6912 return ToAttrLocOrErr.takeError();
6913 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
6914 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
6915 if (Error Err = ImportContainerChecked(InContainer: FromAttrs, OutContainer&: ToAttrs))
6916 return std::move(Err);
6917 ExpectedStmt ToSubStmtOrErr = import(From: S->getSubStmt());
6918 if (!ToSubStmtOrErr)
6919 return ToSubStmtOrErr.takeError();
6920
6921 return AttributedStmt::Create(
6922 C: Importer.getToContext(), Loc: *ToAttrLocOrErr, Attrs: ToAttrs, SubStmt: *ToSubStmtOrErr);
6923}
6924
6925ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
6926
6927 Error Err = Error::success();
6928 auto ToIfLoc = importChecked(Err, From: S->getIfLoc());
6929 auto ToInit = importChecked(Err, From: S->getInit());
6930 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
6931 auto ToCond = importChecked(Err, From: S->getCond());
6932 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
6933 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6934 auto ToThen = importChecked(Err, From: S->getThen());
6935 auto ToElseLoc = importChecked(Err, From: S->getElseLoc());
6936 auto ToElse = importChecked(Err, From: S->getElse());
6937 if (Err)
6938 return std::move(Err);
6939
6940 return IfStmt::Create(Ctx: Importer.getToContext(), IL: ToIfLoc, Kind: S->getStatementKind(),
6941 Init: ToInit, Var: ToConditionVariable, Cond: ToCond, LPL: ToLParenLoc,
6942 RPL: ToRParenLoc, Then: ToThen, EL: ToElseLoc, Else: ToElse);
6943}
6944
6945ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
6946
6947 Error Err = Error::success();
6948 auto ToInit = importChecked(Err, From: S->getInit());
6949 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
6950 auto ToCond = importChecked(Err, From: S->getCond());
6951 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
6952 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6953 auto ToBody = importChecked(Err, From: S->getBody());
6954 auto ToSwitchLoc = importChecked(Err, From: S->getSwitchLoc());
6955 if (Err)
6956 return std::move(Err);
6957
6958 auto *ToStmt =
6959 SwitchStmt::Create(Ctx: Importer.getToContext(), Init: ToInit, Var: ToConditionVariable,
6960 Cond: ToCond, LParenLoc: ToLParenLoc, RParenLoc: ToRParenLoc);
6961 ToStmt->setBody(ToBody);
6962 ToStmt->setSwitchLoc(ToSwitchLoc);
6963
6964 // Now we have to re-chain the cases.
6965 SwitchCase *LastChainedSwitchCase = nullptr;
6966 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
6967 SC = SC->getNextSwitchCase()) {
6968 Expected<SwitchCase *> ToSCOrErr = import(From: SC);
6969 if (!ToSCOrErr)
6970 return ToSCOrErr.takeError();
6971 if (LastChainedSwitchCase)
6972 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
6973 else
6974 ToStmt->setSwitchCaseList(*ToSCOrErr);
6975 LastChainedSwitchCase = *ToSCOrErr;
6976 }
6977
6978 return ToStmt;
6979}
6980
6981ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
6982
6983 Error Err = Error::success();
6984 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
6985 auto ToCond = importChecked(Err, From: S->getCond());
6986 auto ToBody = importChecked(Err, From: S->getBody());
6987 auto ToWhileLoc = importChecked(Err, From: S->getWhileLoc());
6988 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
6989 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6990 if (Err)
6991 return std::move(Err);
6992
6993 return WhileStmt::Create(Ctx: Importer.getToContext(), Var: ToConditionVariable, Cond: ToCond,
6994 Body: ToBody, WL: ToWhileLoc, LParenLoc: ToLParenLoc, RParenLoc: ToRParenLoc);
6995}
6996
6997ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
6998
6999 Error Err = Error::success();
7000 auto ToBody = importChecked(Err, From: S->getBody());
7001 auto ToCond = importChecked(Err, From: S->getCond());
7002 auto ToDoLoc = importChecked(Err, From: S->getDoLoc());
7003 auto ToWhileLoc = importChecked(Err, From: S->getWhileLoc());
7004 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7005 if (Err)
7006 return std::move(Err);
7007
7008 return new (Importer.getToContext()) DoStmt(
7009 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
7010}
7011
7012ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
7013
7014 Error Err = Error::success();
7015 auto ToInit = importChecked(Err, From: S->getInit());
7016 auto ToCond = importChecked(Err, From: S->getCond());
7017 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
7018 auto ToInc = importChecked(Err, From: S->getInc());
7019 auto ToBody = importChecked(Err, From: S->getBody());
7020 auto ToForLoc = importChecked(Err, From: S->getForLoc());
7021 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
7022 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7023 if (Err)
7024 return std::move(Err);
7025
7026 return new (Importer.getToContext()) ForStmt(
7027 Importer.getToContext(),
7028 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
7029 ToRParenLoc);
7030}
7031
7032ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
7033
7034 Error Err = Error::success();
7035 auto ToLabel = importChecked(Err, From: S->getLabel());
7036 auto ToGotoLoc = importChecked(Err, From: S->getGotoLoc());
7037 auto ToLabelLoc = importChecked(Err, From: S->getLabelLoc());
7038 if (Err)
7039 return std::move(Err);
7040
7041 return new (Importer.getToContext()) GotoStmt(
7042 ToLabel, ToGotoLoc, ToLabelLoc);
7043}
7044
7045ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
7046
7047 Error Err = Error::success();
7048 auto ToGotoLoc = importChecked(Err, From: S->getGotoLoc());
7049 auto ToStarLoc = importChecked(Err, From: S->getStarLoc());
7050 auto ToTarget = importChecked(Err, From: S->getTarget());
7051 if (Err)
7052 return std::move(Err);
7053
7054 return new (Importer.getToContext()) IndirectGotoStmt(
7055 ToGotoLoc, ToStarLoc, ToTarget);
7056}
7057
7058ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
7059 ExpectedSLoc ToContinueLocOrErr = import(From: S->getContinueLoc());
7060 if (!ToContinueLocOrErr)
7061 return ToContinueLocOrErr.takeError();
7062 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
7063}
7064
7065ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
7066 auto ToBreakLocOrErr = import(From: S->getBreakLoc());
7067 if (!ToBreakLocOrErr)
7068 return ToBreakLocOrErr.takeError();
7069 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
7070}
7071
7072ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
7073
7074 Error Err = Error::success();
7075 auto ToReturnLoc = importChecked(Err, From: S->getReturnLoc());
7076 auto ToRetValue = importChecked(Err, From: S->getRetValue());
7077 auto ToNRVOCandidate = importChecked(Err, From: S->getNRVOCandidate());
7078 if (Err)
7079 return std::move(Err);
7080
7081 return ReturnStmt::Create(Ctx: Importer.getToContext(), RL: ToReturnLoc, E: ToRetValue,
7082 NRVOCandidate: ToNRVOCandidate);
7083}
7084
7085ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
7086
7087 Error Err = Error::success();
7088 auto ToCatchLoc = importChecked(Err, From: S->getCatchLoc());
7089 auto ToExceptionDecl = importChecked(Err, From: S->getExceptionDecl());
7090 auto ToHandlerBlock = importChecked(Err, From: S->getHandlerBlock());
7091 if (Err)
7092 return std::move(Err);
7093
7094 return new (Importer.getToContext()) CXXCatchStmt (
7095 ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
7096}
7097
7098ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
7099 ExpectedSLoc ToTryLocOrErr = import(From: S->getTryLoc());
7100 if (!ToTryLocOrErr)
7101 return ToTryLocOrErr.takeError();
7102
7103 ExpectedStmt ToTryBlockOrErr = import(From: S->getTryBlock());
7104 if (!ToTryBlockOrErr)
7105 return ToTryBlockOrErr.takeError();
7106
7107 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
7108 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
7109 CXXCatchStmt *FromHandler = S->getHandler(i: HI);
7110 if (auto ToHandlerOrErr = import(From: FromHandler))
7111 ToHandlers[HI] = *ToHandlerOrErr;
7112 else
7113 return ToHandlerOrErr.takeError();
7114 }
7115
7116 return CXXTryStmt::Create(C: Importer.getToContext(), tryLoc: *ToTryLocOrErr,
7117 tryBlock: cast<CompoundStmt>(Val: *ToTryBlockOrErr), handlers: ToHandlers);
7118}
7119
7120ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
7121
7122 Error Err = Error::success();
7123 auto ToInit = importChecked(Err, From: S->getInit());
7124 auto ToRangeStmt = importChecked(Err, From: S->getRangeStmt());
7125 auto ToBeginStmt = importChecked(Err, From: S->getBeginStmt());
7126 auto ToEndStmt = importChecked(Err, From: S->getEndStmt());
7127 auto ToCond = importChecked(Err, From: S->getCond());
7128 auto ToInc = importChecked(Err, From: S->getInc());
7129 auto ToLoopVarStmt = importChecked(Err, From: S->getLoopVarStmt());
7130 auto ToBody = importChecked(Err, From: S->getBody());
7131 auto ToForLoc = importChecked(Err, From: S->getForLoc());
7132 auto ToCoawaitLoc = importChecked(Err, From: S->getCoawaitLoc());
7133 auto ToColonLoc = importChecked(Err, From: S->getColonLoc());
7134 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7135 if (Err)
7136 return std::move(Err);
7137
7138 return new (Importer.getToContext()) CXXForRangeStmt(
7139 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
7140 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
7141}
7142
7143ExpectedStmt
7144ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
7145 Error Err = Error::success();
7146 auto ToElement = importChecked(Err, From: S->getElement());
7147 auto ToCollection = importChecked(Err, From: S->getCollection());
7148 auto ToBody = importChecked(Err, From: S->getBody());
7149 auto ToForLoc = importChecked(Err, From: S->getForLoc());
7150 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7151 if (Err)
7152 return std::move(Err);
7153
7154 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
7155 ToCollection,
7156 ToBody,
7157 ToForLoc,
7158 ToRParenLoc);
7159}
7160
7161ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7162
7163 Error Err = Error::success();
7164 auto ToAtCatchLoc = importChecked(Err, From: S->getAtCatchLoc());
7165 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7166 auto ToCatchParamDecl = importChecked(Err, From: S->getCatchParamDecl());
7167 auto ToCatchBody = importChecked(Err, From: S->getCatchBody());
7168 if (Err)
7169 return std::move(Err);
7170
7171 return new (Importer.getToContext()) ObjCAtCatchStmt (
7172 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
7173}
7174
7175ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7176 ExpectedSLoc ToAtFinallyLocOrErr = import(From: S->getAtFinallyLoc());
7177 if (!ToAtFinallyLocOrErr)
7178 return ToAtFinallyLocOrErr.takeError();
7179 ExpectedStmt ToAtFinallyStmtOrErr = import(From: S->getFinallyBody());
7180 if (!ToAtFinallyStmtOrErr)
7181 return ToAtFinallyStmtOrErr.takeError();
7182 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
7183 *ToAtFinallyStmtOrErr);
7184}
7185
7186ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
7187
7188 Error Err = Error::success();
7189 auto ToAtTryLoc = importChecked(Err, From: S->getAtTryLoc());
7190 auto ToTryBody = importChecked(Err, From: S->getTryBody());
7191 auto ToFinallyStmt = importChecked(Err, From: S->getFinallyStmt());
7192 if (Err)
7193 return std::move(Err);
7194
7195 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
7196 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
7197 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(I: CI);
7198 if (ExpectedStmt ToCatchStmtOrErr = import(From: FromCatchStmt))
7199 ToCatchStmts[CI] = *ToCatchStmtOrErr;
7200 else
7201 return ToCatchStmtOrErr.takeError();
7202 }
7203
7204 return ObjCAtTryStmt::Create(Context: Importer.getToContext(),
7205 atTryLoc: ToAtTryLoc, atTryStmt: ToTryBody,
7206 CatchStmts: ToCatchStmts.begin(), NumCatchStmts: ToCatchStmts.size(),
7207 atFinallyStmt: ToFinallyStmt);
7208}
7209
7210ExpectedStmt
7211ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
7212
7213 Error Err = Error::success();
7214 auto ToAtSynchronizedLoc = importChecked(Err, From: S->getAtSynchronizedLoc());
7215 auto ToSynchExpr = importChecked(Err, From: S->getSynchExpr());
7216 auto ToSynchBody = importChecked(Err, From: S->getSynchBody());
7217 if (Err)
7218 return std::move(Err);
7219
7220 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
7221 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
7222}
7223
7224ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7225 ExpectedSLoc ToThrowLocOrErr = import(From: S->getThrowLoc());
7226 if (!ToThrowLocOrErr)
7227 return ToThrowLocOrErr.takeError();
7228 ExpectedExpr ToThrowExprOrErr = import(From: S->getThrowExpr());
7229 if (!ToThrowExprOrErr)
7230 return ToThrowExprOrErr.takeError();
7231 return new (Importer.getToContext()) ObjCAtThrowStmt(
7232 *ToThrowLocOrErr, *ToThrowExprOrErr);
7233}
7234
7235ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
7236 ObjCAutoreleasePoolStmt *S) {
7237 ExpectedSLoc ToAtLocOrErr = import(From: S->getAtLoc());
7238 if (!ToAtLocOrErr)
7239 return ToAtLocOrErr.takeError();
7240 ExpectedStmt ToSubStmtOrErr = import(From: S->getSubStmt());
7241 if (!ToSubStmtOrErr)
7242 return ToSubStmtOrErr.takeError();
7243 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
7244 *ToSubStmtOrErr);
7245}
7246
7247//----------------------------------------------------------------------------
7248// Import Expressions
7249//----------------------------------------------------------------------------
7250ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
7251 Importer.FromDiag(Loc: E->getBeginLoc(), DiagID: diag::err_unsupported_ast_node)
7252 << E->getStmtClassName();
7253 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
7254}
7255
7256ExpectedStmt ASTNodeImporter::VisitSourceLocExpr(SourceLocExpr *E) {
7257 Error Err = Error::success();
7258 auto ToType = importChecked(Err, From: E->getType());
7259 auto BLoc = importChecked(Err, From: E->getBeginLoc());
7260 auto RParenLoc = importChecked(Err, From: E->getEndLoc());
7261 if (Err)
7262 return std::move(Err);
7263 auto ParentContextOrErr = Importer.ImportContext(FromDC: E->getParentContext());
7264 if (!ParentContextOrErr)
7265 return ParentContextOrErr.takeError();
7266
7267 return new (Importer.getToContext())
7268 SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc,
7269 RParenLoc, *ParentContextOrErr);
7270}
7271
7272ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
7273
7274 Error Err = Error::success();
7275 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7276 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7277 auto ToWrittenTypeInfo = importChecked(Err, From: E->getWrittenTypeInfo());
7278 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7279 auto ToType = importChecked(Err, From: E->getType());
7280 if (Err)
7281 return std::move(Err);
7282
7283 return new (Importer.getToContext()) VAArgExpr(
7284 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
7285 E->isMicrosoftABI());
7286}
7287
7288ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
7289
7290 Error Err = Error::success();
7291 auto ToCond = importChecked(Err, From: E->getCond());
7292 auto ToLHS = importChecked(Err, From: E->getLHS());
7293 auto ToRHS = importChecked(Err, From: E->getRHS());
7294 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7295 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7296 auto ToType = importChecked(Err, From: E->getType());
7297 if (Err)
7298 return std::move(Err);
7299
7300 ExprValueKind VK = E->getValueKind();
7301 ExprObjectKind OK = E->getObjectKind();
7302
7303 // The value of CondIsTrue only matters if the value is not
7304 // condition-dependent.
7305 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
7306
7307 return new (Importer.getToContext())
7308 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
7309 ToRParenLoc, CondIsTrue);
7310}
7311
7312ExpectedStmt ASTNodeImporter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
7313 Error Err = Error::success();
7314 auto *ToSrcExpr = importChecked(Err, From: E->getSrcExpr());
7315 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7316 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7317 auto ToType = importChecked(Err, From: E->getType());
7318 auto *ToTSI = importChecked(Err, From: E->getTypeSourceInfo());
7319 if (Err)
7320 return std::move(Err);
7321
7322 return new (Importer.getToContext())
7323 ConvertVectorExpr(ToSrcExpr, ToTSI, ToType, E->getValueKind(),
7324 E->getObjectKind(), ToBuiltinLoc, ToRParenLoc);
7325}
7326
7327ExpectedStmt ASTNodeImporter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
7328 Error Err = Error::success();
7329 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7330 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7331 auto ToType = importChecked(Err, From: E->getType());
7332 const unsigned NumSubExprs = E->getNumSubExprs();
7333
7334 llvm::SmallVector<Expr *, 8> ToSubExprs;
7335 llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs);
7336 ToSubExprs.resize(N: NumSubExprs);
7337
7338 if ((Err = ImportContainerChecked(InContainer: FromSubExprs, OutContainer&: ToSubExprs)))
7339 return std::move(Err);
7340
7341 return new (Importer.getToContext()) ShuffleVectorExpr(
7342 Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc);
7343}
7344
7345ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
7346 ExpectedType TypeOrErr = import(From: E->getType());
7347 if (!TypeOrErr)
7348 return TypeOrErr.takeError();
7349
7350 ExpectedSLoc BeginLocOrErr = import(From: E->getBeginLoc());
7351 if (!BeginLocOrErr)
7352 return BeginLocOrErr.takeError();
7353
7354 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
7355}
7356
7357ExpectedStmt
7358ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
7359 Error Err = Error::success();
7360 auto ToGenericLoc = importChecked(Err, From: E->getGenericLoc());
7361 Expr *ToControllingExpr = nullptr;
7362 TypeSourceInfo *ToControllingType = nullptr;
7363 if (E->isExprPredicate())
7364 ToControllingExpr = importChecked(Err, From: E->getControllingExpr());
7365 else
7366 ToControllingType = importChecked(Err, From: E->getControllingType());
7367 assert((ToControllingExpr || ToControllingType) &&
7368 "Either the controlling expr or type must be nonnull");
7369 auto ToDefaultLoc = importChecked(Err, From: E->getDefaultLoc());
7370 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7371 if (Err)
7372 return std::move(Err);
7373
7374 ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos());
7375 SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size());
7376 if (Error Err = ImportContainerChecked(InContainer: FromAssocTypes, OutContainer&: ToAssocTypes))
7377 return std::move(Err);
7378
7379 ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs());
7380 SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size());
7381 if (Error Err = ImportContainerChecked(InContainer: FromAssocExprs, OutContainer&: ToAssocExprs))
7382 return std::move(Err);
7383
7384 const ASTContext &ToCtx = Importer.getToContext();
7385 if (E->isResultDependent()) {
7386 if (ToControllingExpr) {
7387 return GenericSelectionExpr::Create(
7388 Context: ToCtx, GenericLoc: ToGenericLoc, ControllingExpr: ToControllingExpr, AssocTypes: llvm::ArrayRef(ToAssocTypes),
7389 AssocExprs: llvm::ArrayRef(ToAssocExprs), DefaultLoc: ToDefaultLoc, RParenLoc: ToRParenLoc,
7390 ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack());
7391 }
7392 return GenericSelectionExpr::Create(
7393 Context: ToCtx, GenericLoc: ToGenericLoc, ControllingType: ToControllingType, AssocTypes: llvm::ArrayRef(ToAssocTypes),
7394 AssocExprs: llvm::ArrayRef(ToAssocExprs), DefaultLoc: ToDefaultLoc, RParenLoc: ToRParenLoc,
7395 ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack());
7396 }
7397
7398 if (ToControllingExpr) {
7399 return GenericSelectionExpr::Create(
7400 Context: ToCtx, GenericLoc: ToGenericLoc, ControllingExpr: ToControllingExpr, AssocTypes: llvm::ArrayRef(ToAssocTypes),
7401 AssocExprs: llvm::ArrayRef(ToAssocExprs), DefaultLoc: ToDefaultLoc, RParenLoc: ToRParenLoc,
7402 ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack(), ResultIndex: E->getResultIndex());
7403 }
7404 return GenericSelectionExpr::Create(
7405 Context: ToCtx, GenericLoc: ToGenericLoc, ControllingType: ToControllingType, AssocTypes: llvm::ArrayRef(ToAssocTypes),
7406 AssocExprs: llvm::ArrayRef(ToAssocExprs), DefaultLoc: ToDefaultLoc, RParenLoc: ToRParenLoc,
7407 ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack(), ResultIndex: E->getResultIndex());
7408}
7409
7410ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
7411
7412 Error Err = Error::success();
7413 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7414 auto ToType = importChecked(Err, From: E->getType());
7415 auto ToFunctionName = importChecked(Err, From: E->getFunctionName());
7416 if (Err)
7417 return std::move(Err);
7418
7419 return PredefinedExpr::Create(Ctx: Importer.getToContext(), L: ToBeginLoc, FNTy: ToType,
7420 IK: E->getIdentKind(), IsTransparent: E->isTransparent(),
7421 SL: ToFunctionName);
7422}
7423
7424ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
7425
7426 Error Err = Error::success();
7427 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
7428 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
7429 auto ToDecl = importChecked(Err, From: E->getDecl());
7430 auto ToLocation = importChecked(Err, From: E->getLocation());
7431 auto ToType = importChecked(Err, From: E->getType());
7432 if (Err)
7433 return std::move(Err);
7434
7435 NamedDecl *ToFoundD = nullptr;
7436 if (E->getDecl() != E->getFoundDecl()) {
7437 auto FoundDOrErr = import(From: E->getFoundDecl());
7438 if (!FoundDOrErr)
7439 return FoundDOrErr.takeError();
7440 ToFoundD = *FoundDOrErr;
7441 }
7442
7443 TemplateArgumentListInfo ToTAInfo;
7444 TemplateArgumentListInfo *ToResInfo = nullptr;
7445 if (E->hasExplicitTemplateArgs()) {
7446 if (Error Err =
7447 ImportTemplateArgumentListInfo(FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(),
7448 Container: E->template_arguments(), Result&: ToTAInfo))
7449 return std::move(Err);
7450 ToResInfo = &ToTAInfo;
7451 }
7452
7453 auto *ToE = DeclRefExpr::Create(
7454 Context: Importer.getToContext(), QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc, D: ToDecl,
7455 RefersToEnclosingVariableOrCapture: E->refersToEnclosingVariableOrCapture(), NameLoc: ToLocation, T: ToType,
7456 VK: E->getValueKind(), FoundD: ToFoundD, TemplateArgs: ToResInfo, NOUR: E->isNonOdrUse());
7457 if (E->hadMultipleCandidates())
7458 ToE->setHadMultipleCandidates(true);
7459 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
7460 return ToE;
7461}
7462
7463ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
7464 ExpectedType TypeOrErr = import(From: E->getType());
7465 if (!TypeOrErr)
7466 return TypeOrErr.takeError();
7467
7468 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
7469}
7470
7471ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
7472 ExpectedExpr ToInitOrErr = import(From: E->getInit());
7473 if (!ToInitOrErr)
7474 return ToInitOrErr.takeError();
7475
7476 ExpectedSLoc ToEqualOrColonLocOrErr = import(From: E->getEqualOrColonLoc());
7477 if (!ToEqualOrColonLocOrErr)
7478 return ToEqualOrColonLocOrErr.takeError();
7479
7480 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
7481 // List elements from the second, the first is Init itself
7482 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
7483 if (ExpectedExpr ToArgOrErr = import(From: E->getSubExpr(Idx: I)))
7484 ToIndexExprs[I - 1] = *ToArgOrErr;
7485 else
7486 return ToArgOrErr.takeError();
7487 }
7488
7489 SmallVector<Designator, 4> ToDesignators(E->size());
7490 if (Error Err = ImportContainerChecked(InContainer: E->designators(), OutContainer&: ToDesignators))
7491 return std::move(Err);
7492
7493 return DesignatedInitExpr::Create(
7494 C: Importer.getToContext(), Designators: ToDesignators,
7495 IndexExprs: ToIndexExprs, EqualOrColonLoc: *ToEqualOrColonLocOrErr,
7496 GNUSyntax: E->usesGNUSyntax(), Init: *ToInitOrErr);
7497}
7498
7499ExpectedStmt
7500ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
7501 ExpectedType ToTypeOrErr = import(From: E->getType());
7502 if (!ToTypeOrErr)
7503 return ToTypeOrErr.takeError();
7504
7505 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7506 if (!ToLocationOrErr)
7507 return ToLocationOrErr.takeError();
7508
7509 return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
7510 *ToTypeOrErr, *ToLocationOrErr);
7511}
7512
7513ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
7514 ExpectedType ToTypeOrErr = import(From: E->getType());
7515 if (!ToTypeOrErr)
7516 return ToTypeOrErr.takeError();
7517
7518 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7519 if (!ToLocationOrErr)
7520 return ToLocationOrErr.takeError();
7521
7522 return IntegerLiteral::Create(
7523 C: Importer.getToContext(), V: E->getValue(), type: *ToTypeOrErr, l: *ToLocationOrErr);
7524}
7525
7526
7527ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
7528 ExpectedType ToTypeOrErr = import(From: E->getType());
7529 if (!ToTypeOrErr)
7530 return ToTypeOrErr.takeError();
7531
7532 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7533 if (!ToLocationOrErr)
7534 return ToLocationOrErr.takeError();
7535
7536 return FloatingLiteral::Create(
7537 C: Importer.getToContext(), V: E->getValue(), isexact: E->isExact(),
7538 Type: *ToTypeOrErr, L: *ToLocationOrErr);
7539}
7540
7541ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
7542 auto ToTypeOrErr = import(From: E->getType());
7543 if (!ToTypeOrErr)
7544 return ToTypeOrErr.takeError();
7545
7546 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
7547 if (!ToSubExprOrErr)
7548 return ToSubExprOrErr.takeError();
7549
7550 return new (Importer.getToContext()) ImaginaryLiteral(
7551 *ToSubExprOrErr, *ToTypeOrErr);
7552}
7553
7554ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) {
7555 auto ToTypeOrErr = import(From: E->getType());
7556 if (!ToTypeOrErr)
7557 return ToTypeOrErr.takeError();
7558
7559 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7560 if (!ToLocationOrErr)
7561 return ToLocationOrErr.takeError();
7562
7563 return new (Importer.getToContext()) FixedPointLiteral(
7564 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr,
7565 Importer.getToContext().getFixedPointScale(Ty: *ToTypeOrErr));
7566}
7567
7568ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
7569 ExpectedType ToTypeOrErr = import(From: E->getType());
7570 if (!ToTypeOrErr)
7571 return ToTypeOrErr.takeError();
7572
7573 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7574 if (!ToLocationOrErr)
7575 return ToLocationOrErr.takeError();
7576
7577 return new (Importer.getToContext()) CharacterLiteral(
7578 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
7579}
7580
7581ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
7582 ExpectedType ToTypeOrErr = import(From: E->getType());
7583 if (!ToTypeOrErr)
7584 return ToTypeOrErr.takeError();
7585
7586 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
7587 if (Error Err = ImportArrayChecked(
7588 Ibegin: E->tokloc_begin(), Iend: E->tokloc_end(), Obegin: ToLocations.begin()))
7589 return std::move(Err);
7590
7591 return StringLiteral::Create(
7592 Ctx: Importer.getToContext(), Str: E->getBytes(), Kind: E->getKind(), Pascal: E->isPascal(),
7593 Ty: *ToTypeOrErr, Loc: ToLocations.data(), NumConcatenated: ToLocations.size());
7594}
7595
7596ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
7597
7598 Error Err = Error::success();
7599 auto ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
7600 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
7601 auto ToType = importChecked(Err, From: E->getType());
7602 auto ToInitializer = importChecked(Err, From: E->getInitializer());
7603 if (Err)
7604 return std::move(Err);
7605
7606 return new (Importer.getToContext()) CompoundLiteralExpr(
7607 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
7608 ToInitializer, E->isFileScope());
7609}
7610
7611ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
7612
7613 Error Err = Error::success();
7614 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7615 auto ToType = importChecked(Err, From: E->getType());
7616 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7617 if (Err)
7618 return std::move(Err);
7619
7620 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
7621 if (Error Err = ImportArrayChecked(
7622 Ibegin: E->getSubExprs(), Iend: E->getSubExprs() + E->getNumSubExprs(),
7623 Obegin: ToExprs.begin()))
7624 return std::move(Err);
7625
7626 return new (Importer.getToContext()) AtomicExpr(
7627
7628 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
7629}
7630
7631ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
7632 Error Err = Error::success();
7633 auto ToAmpAmpLoc = importChecked(Err, From: E->getAmpAmpLoc());
7634 auto ToLabelLoc = importChecked(Err, From: E->getLabelLoc());
7635 auto ToLabel = importChecked(Err, From: E->getLabel());
7636 auto ToType = importChecked(Err, From: E->getType());
7637 if (Err)
7638 return std::move(Err);
7639
7640 return new (Importer.getToContext()) AddrLabelExpr(
7641 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
7642}
7643ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
7644 Error Err = Error::success();
7645 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7646 auto ToResult = importChecked(Err, From: E->getAPValueResult());
7647 if (Err)
7648 return std::move(Err);
7649
7650 return ConstantExpr::Create(Context: Importer.getToContext(), E: ToSubExpr, Result: ToResult);
7651}
7652ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
7653 Error Err = Error::success();
7654 auto ToLParen = importChecked(Err, From: E->getLParen());
7655 auto ToRParen = importChecked(Err, From: E->getRParen());
7656 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7657 if (Err)
7658 return std::move(Err);
7659
7660 return new (Importer.getToContext())
7661 ParenExpr(ToLParen, ToRParen, ToSubExpr);
7662}
7663
7664ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
7665 SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
7666 if (Error Err = ImportContainerChecked(InContainer: E->exprs(), OutContainer&: ToExprs))
7667 return std::move(Err);
7668
7669 ExpectedSLoc ToLParenLocOrErr = import(From: E->getLParenLoc());
7670 if (!ToLParenLocOrErr)
7671 return ToLParenLocOrErr.takeError();
7672
7673 ExpectedSLoc ToRParenLocOrErr = import(From: E->getRParenLoc());
7674 if (!ToRParenLocOrErr)
7675 return ToRParenLocOrErr.takeError();
7676
7677 return ParenListExpr::Create(Ctx: Importer.getToContext(), LParenLoc: *ToLParenLocOrErr,
7678 Exprs: ToExprs, RParenLoc: *ToRParenLocOrErr);
7679}
7680
7681ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
7682 Error Err = Error::success();
7683 auto ToSubStmt = importChecked(Err, From: E->getSubStmt());
7684 auto ToType = importChecked(Err, From: E->getType());
7685 auto ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
7686 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7687 if (Err)
7688 return std::move(Err);
7689
7690 return new (Importer.getToContext())
7691 StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc,
7692 E->getTemplateDepth());
7693}
7694
7695ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
7696 Error Err = Error::success();
7697 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7698 auto ToType = importChecked(Err, From: E->getType());
7699 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7700 if (Err)
7701 return std::move(Err);
7702
7703 auto *UO = UnaryOperator::CreateEmpty(C: Importer.getToContext(),
7704 hasFPFeatures: E->hasStoredFPFeatures());
7705 UO->setType(ToType);
7706 UO->setSubExpr(ToSubExpr);
7707 UO->setOpcode(E->getOpcode());
7708 UO->setOperatorLoc(ToOperatorLoc);
7709 UO->setCanOverflow(E->canOverflow());
7710 if (E->hasStoredFPFeatures())
7711 UO->setStoredFPFeatures(E->getStoredFPFeatures());
7712
7713 return UO;
7714}
7715
7716ExpectedStmt
7717
7718ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
7719 Error Err = Error::success();
7720 auto ToType = importChecked(Err, From: E->getType());
7721 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7722 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7723 if (Err)
7724 return std::move(Err);
7725
7726 if (E->isArgumentType()) {
7727 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
7728 import(From: E->getArgumentTypeInfo());
7729 if (!ToArgumentTypeInfoOrErr)
7730 return ToArgumentTypeInfoOrErr.takeError();
7731
7732 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7733 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
7734 ToRParenLoc);
7735 }
7736
7737 ExpectedExpr ToArgumentExprOrErr = import(From: E->getArgumentExpr());
7738 if (!ToArgumentExprOrErr)
7739 return ToArgumentExprOrErr.takeError();
7740
7741 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7742 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
7743}
7744
7745ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
7746 Error Err = Error::success();
7747 auto ToLHS = importChecked(Err, From: E->getLHS());
7748 auto ToRHS = importChecked(Err, From: E->getRHS());
7749 auto ToType = importChecked(Err, From: E->getType());
7750 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7751 if (Err)
7752 return std::move(Err);
7753
7754 return BinaryOperator::Create(
7755 C: Importer.getToContext(), lhs: ToLHS, rhs: ToRHS, opc: E->getOpcode(), ResTy: ToType,
7756 VK: E->getValueKind(), OK: E->getObjectKind(), opLoc: ToOperatorLoc,
7757 FPFeatures: E->getFPFeatures());
7758}
7759
7760ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
7761 Error Err = Error::success();
7762 auto ToCond = importChecked(Err, From: E->getCond());
7763 auto ToQuestionLoc = importChecked(Err, From: E->getQuestionLoc());
7764 auto ToLHS = importChecked(Err, From: E->getLHS());
7765 auto ToColonLoc = importChecked(Err, From: E->getColonLoc());
7766 auto ToRHS = importChecked(Err, From: E->getRHS());
7767 auto ToType = importChecked(Err, From: E->getType());
7768 if (Err)
7769 return std::move(Err);
7770
7771 return new (Importer.getToContext()) ConditionalOperator(
7772 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
7773 E->getValueKind(), E->getObjectKind());
7774}
7775
7776ExpectedStmt
7777ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
7778 Error Err = Error::success();
7779 auto ToCommon = importChecked(Err, From: E->getCommon());
7780 auto ToOpaqueValue = importChecked(Err, From: E->getOpaqueValue());
7781 auto ToCond = importChecked(Err, From: E->getCond());
7782 auto ToTrueExpr = importChecked(Err, From: E->getTrueExpr());
7783 auto ToFalseExpr = importChecked(Err, From: E->getFalseExpr());
7784 auto ToQuestionLoc = importChecked(Err, From: E->getQuestionLoc());
7785 auto ToColonLoc = importChecked(Err, From: E->getColonLoc());
7786 auto ToType = importChecked(Err, From: E->getType());
7787 if (Err)
7788 return std::move(Err);
7789
7790 return new (Importer.getToContext()) BinaryConditionalOperator(
7791 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
7792 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
7793 E->getObjectKind());
7794}
7795
7796ExpectedStmt ASTNodeImporter::VisitCXXRewrittenBinaryOperator(
7797 CXXRewrittenBinaryOperator *E) {
7798 Error Err = Error::success();
7799 auto ToSemanticForm = importChecked(Err, From: E->getSemanticForm());
7800 if (Err)
7801 return std::move(Err);
7802
7803 return new (Importer.getToContext())
7804 CXXRewrittenBinaryOperator(ToSemanticForm, E->isReversed());
7805}
7806
7807ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
7808 Error Err = Error::success();
7809 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7810 auto ToQueriedTypeSourceInfo =
7811 importChecked(Err, From: E->getQueriedTypeSourceInfo());
7812 auto ToDimensionExpression = importChecked(Err, From: E->getDimensionExpression());
7813 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
7814 auto ToType = importChecked(Err, From: E->getType());
7815 if (Err)
7816 return std::move(Err);
7817
7818 return new (Importer.getToContext()) ArrayTypeTraitExpr(
7819 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
7820 ToDimensionExpression, ToEndLoc, ToType);
7821}
7822
7823ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
7824 Error Err = Error::success();
7825 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7826 auto ToQueriedExpression = importChecked(Err, From: E->getQueriedExpression());
7827 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
7828 auto ToType = importChecked(Err, From: E->getType());
7829 if (Err)
7830 return std::move(Err);
7831
7832 return new (Importer.getToContext()) ExpressionTraitExpr(
7833 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
7834 ToEndLoc, ToType);
7835}
7836
7837ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
7838 Error Err = Error::success();
7839 auto ToLocation = importChecked(Err, From: E->getLocation());
7840 auto ToType = importChecked(Err, From: E->getType());
7841 auto ToSourceExpr = importChecked(Err, From: E->getSourceExpr());
7842 if (Err)
7843 return std::move(Err);
7844
7845 return new (Importer.getToContext()) OpaqueValueExpr(
7846 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
7847}
7848
7849ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
7850 Error Err = Error::success();
7851 auto ToLHS = importChecked(Err, From: E->getLHS());
7852 auto ToRHS = importChecked(Err, From: E->getRHS());
7853 auto ToType = importChecked(Err, From: E->getType());
7854 auto ToRBracketLoc = importChecked(Err, From: E->getRBracketLoc());
7855 if (Err)
7856 return std::move(Err);
7857
7858 return new (Importer.getToContext()) ArraySubscriptExpr(
7859 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
7860 ToRBracketLoc);
7861}
7862
7863ExpectedStmt
7864ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
7865 Error Err = Error::success();
7866 auto ToLHS = importChecked(Err, From: E->getLHS());
7867 auto ToRHS = importChecked(Err, From: E->getRHS());
7868 auto ToType = importChecked(Err, From: E->getType());
7869 auto ToComputationLHSType = importChecked(Err, From: E->getComputationLHSType());
7870 auto ToComputationResultType =
7871 importChecked(Err, From: E->getComputationResultType());
7872 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7873 if (Err)
7874 return std::move(Err);
7875
7876 return CompoundAssignOperator::Create(
7877 C: Importer.getToContext(), lhs: ToLHS, rhs: ToRHS, opc: E->getOpcode(), ResTy: ToType,
7878 VK: E->getValueKind(), OK: E->getObjectKind(), opLoc: ToOperatorLoc,
7879 FPFeatures: E->getFPFeatures(),
7880 CompLHSType: ToComputationLHSType, CompResultType: ToComputationResultType);
7881}
7882
7883Expected<CXXCastPath>
7884ASTNodeImporter::ImportCastPath(CastExpr *CE) {
7885 CXXCastPath Path;
7886 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
7887 if (auto SpecOrErr = import(From: *I))
7888 Path.push_back(Elt: *SpecOrErr);
7889 else
7890 return SpecOrErr.takeError();
7891 }
7892 return Path;
7893}
7894
7895ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
7896 ExpectedType ToTypeOrErr = import(From: E->getType());
7897 if (!ToTypeOrErr)
7898 return ToTypeOrErr.takeError();
7899
7900 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
7901 if (!ToSubExprOrErr)
7902 return ToSubExprOrErr.takeError();
7903
7904 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(CE: E);
7905 if (!ToBasePathOrErr)
7906 return ToBasePathOrErr.takeError();
7907
7908 return ImplicitCastExpr::Create(
7909 Context: Importer.getToContext(), T: *ToTypeOrErr, Kind: E->getCastKind(), Operand: *ToSubExprOrErr,
7910 BasePath: &(*ToBasePathOrErr), Cat: E->getValueKind(), FPO: E->getFPFeatures());
7911}
7912
7913ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
7914 Error Err = Error::success();
7915 auto ToType = importChecked(Err, From: E->getType());
7916 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7917 auto ToTypeInfoAsWritten = importChecked(Err, From: E->getTypeInfoAsWritten());
7918 if (Err)
7919 return std::move(Err);
7920
7921 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(CE: E);
7922 if (!ToBasePathOrErr)
7923 return ToBasePathOrErr.takeError();
7924 CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
7925
7926 switch (E->getStmtClass()) {
7927 case Stmt::CStyleCastExprClass: {
7928 auto *CCE = cast<CStyleCastExpr>(Val: E);
7929 ExpectedSLoc ToLParenLocOrErr = import(From: CCE->getLParenLoc());
7930 if (!ToLParenLocOrErr)
7931 return ToLParenLocOrErr.takeError();
7932 ExpectedSLoc ToRParenLocOrErr = import(From: CCE->getRParenLoc());
7933 if (!ToRParenLocOrErr)
7934 return ToRParenLocOrErr.takeError();
7935 return CStyleCastExpr::Create(
7936 Context: Importer.getToContext(), T: ToType, VK: E->getValueKind(), K: E->getCastKind(),
7937 Op: ToSubExpr, BasePath: ToBasePath, FPO: CCE->getFPFeatures(), WrittenTy: ToTypeInfoAsWritten,
7938 L: *ToLParenLocOrErr, R: *ToRParenLocOrErr);
7939 }
7940
7941 case Stmt::CXXFunctionalCastExprClass: {
7942 auto *FCE = cast<CXXFunctionalCastExpr>(Val: E);
7943 ExpectedSLoc ToLParenLocOrErr = import(From: FCE->getLParenLoc());
7944 if (!ToLParenLocOrErr)
7945 return ToLParenLocOrErr.takeError();
7946 ExpectedSLoc ToRParenLocOrErr = import(From: FCE->getRParenLoc());
7947 if (!ToRParenLocOrErr)
7948 return ToRParenLocOrErr.takeError();
7949 return CXXFunctionalCastExpr::Create(
7950 Context: Importer.getToContext(), T: ToType, VK: E->getValueKind(), Written: ToTypeInfoAsWritten,
7951 Kind: E->getCastKind(), Op: ToSubExpr, Path: ToBasePath, FPO: FCE->getFPFeatures(),
7952 LPLoc: *ToLParenLocOrErr, RPLoc: *ToRParenLocOrErr);
7953 }
7954
7955 case Stmt::ObjCBridgedCastExprClass: {
7956 auto *OCE = cast<ObjCBridgedCastExpr>(Val: E);
7957 ExpectedSLoc ToLParenLocOrErr = import(From: OCE->getLParenLoc());
7958 if (!ToLParenLocOrErr)
7959 return ToLParenLocOrErr.takeError();
7960 ExpectedSLoc ToBridgeKeywordLocOrErr = import(From: OCE->getBridgeKeywordLoc());
7961 if (!ToBridgeKeywordLocOrErr)
7962 return ToBridgeKeywordLocOrErr.takeError();
7963 return new (Importer.getToContext()) ObjCBridgedCastExpr(
7964 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
7965 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
7966 }
7967 case Stmt::BuiltinBitCastExprClass: {
7968 auto *BBC = cast<BuiltinBitCastExpr>(Val: E);
7969 ExpectedSLoc ToKWLocOrErr = import(From: BBC->getBeginLoc());
7970 if (!ToKWLocOrErr)
7971 return ToKWLocOrErr.takeError();
7972 ExpectedSLoc ToRParenLocOrErr = import(From: BBC->getEndLoc());
7973 if (!ToRParenLocOrErr)
7974 return ToRParenLocOrErr.takeError();
7975 return new (Importer.getToContext()) BuiltinBitCastExpr(
7976 ToType, E->getValueKind(), E->getCastKind(), ToSubExpr,
7977 ToTypeInfoAsWritten, *ToKWLocOrErr, *ToRParenLocOrErr);
7978 }
7979 default:
7980 llvm_unreachable("Cast expression of unsupported type!");
7981 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
7982 }
7983}
7984
7985ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) {
7986 SmallVector<OffsetOfNode, 4> ToNodes;
7987 for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
7988 const OffsetOfNode &FromNode = E->getComponent(Idx: I);
7989
7990 SourceLocation ToBeginLoc, ToEndLoc;
7991
7992 if (FromNode.getKind() != OffsetOfNode::Base) {
7993 Error Err = Error::success();
7994 ToBeginLoc = importChecked(Err, From: FromNode.getBeginLoc());
7995 ToEndLoc = importChecked(Err, From: FromNode.getEndLoc());
7996 if (Err)
7997 return std::move(Err);
7998 }
7999
8000 switch (FromNode.getKind()) {
8001 case OffsetOfNode::Array:
8002 ToNodes.push_back(
8003 Elt: OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
8004 break;
8005 case OffsetOfNode::Base: {
8006 auto ToBSOrErr = import(From: FromNode.getBase());
8007 if (!ToBSOrErr)
8008 return ToBSOrErr.takeError();
8009 ToNodes.push_back(Elt: OffsetOfNode(*ToBSOrErr));
8010 break;
8011 }
8012 case OffsetOfNode::Field: {
8013 auto ToFieldOrErr = import(From: FromNode.getField());
8014 if (!ToFieldOrErr)
8015 return ToFieldOrErr.takeError();
8016 ToNodes.push_back(Elt: OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
8017 break;
8018 }
8019 case OffsetOfNode::Identifier: {
8020 IdentifierInfo *ToII = Importer.Import(FromId: FromNode.getFieldName());
8021 ToNodes.push_back(Elt: OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
8022 break;
8023 }
8024 }
8025 }
8026
8027 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
8028 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
8029 ExpectedExpr ToIndexExprOrErr = import(From: E->getIndexExpr(Idx: I));
8030 if (!ToIndexExprOrErr)
8031 return ToIndexExprOrErr.takeError();
8032 ToExprs[I] = *ToIndexExprOrErr;
8033 }
8034
8035 Error Err = Error::success();
8036 auto ToType = importChecked(Err, From: E->getType());
8037 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8038 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8039 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8040 if (Err)
8041 return std::move(Err);
8042
8043 return OffsetOfExpr::Create(
8044 C: Importer.getToContext(), type: ToType, OperatorLoc: ToOperatorLoc, tsi: ToTypeSourceInfo, comps: ToNodes,
8045 exprs: ToExprs, RParenLoc: ToRParenLoc);
8046}
8047
8048ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
8049 Error Err = Error::success();
8050 auto ToType = importChecked(Err, From: E->getType());
8051 auto ToOperand = importChecked(Err, From: E->getOperand());
8052 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
8053 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
8054 if (Err)
8055 return std::move(Err);
8056
8057 CanThrowResult ToCanThrow;
8058 if (E->isValueDependent())
8059 ToCanThrow = CT_Dependent;
8060 else
8061 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
8062
8063 return new (Importer.getToContext()) CXXNoexceptExpr(
8064 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
8065}
8066
8067ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
8068 Error Err = Error::success();
8069 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
8070 auto ToType = importChecked(Err, From: E->getType());
8071 auto ToThrowLoc = importChecked(Err, From: E->getThrowLoc());
8072 if (Err)
8073 return std::move(Err);
8074
8075 return new (Importer.getToContext()) CXXThrowExpr(
8076 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
8077}
8078
8079ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8080 ExpectedSLoc ToUsedLocOrErr = import(From: E->getUsedLocation());
8081 if (!ToUsedLocOrErr)
8082 return ToUsedLocOrErr.takeError();
8083
8084 auto ToParamOrErr = import(From: E->getParam());
8085 if (!ToParamOrErr)
8086 return ToParamOrErr.takeError();
8087
8088 auto UsedContextOrErr = Importer.ImportContext(FromDC: E->getUsedContext());
8089 if (!UsedContextOrErr)
8090 return UsedContextOrErr.takeError();
8091
8092 // Import the default arg if it was not imported yet.
8093 // This is needed because it can happen that during the import of the
8094 // default expression (from VisitParmVarDecl) the same ParmVarDecl is
8095 // encountered here. The default argument for a ParmVarDecl is set in the
8096 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here,
8097 // see VisitParmVarDecl).
8098 ParmVarDecl *ToParam = *ToParamOrErr;
8099 if (!ToParam->getDefaultArg()) {
8100 std::optional<ParmVarDecl *> FromParam =
8101 Importer.getImportedFromDecl(ToD: ToParam);
8102 assert(FromParam && "ParmVarDecl was not imported?");
8103
8104 if (Error Err = ImportDefaultArgOfParmVarDecl(FromParam: *FromParam, ToParam))
8105 return std::move(Err);
8106 }
8107 Expr *RewrittenInit = nullptr;
8108 if (E->hasRewrittenInit()) {
8109 ExpectedExpr ExprOrErr = import(From: E->getRewrittenExpr());
8110 if (!ExprOrErr)
8111 return ExprOrErr.takeError();
8112 RewrittenInit = ExprOrErr.get();
8113 }
8114 return CXXDefaultArgExpr::Create(C: Importer.getToContext(), Loc: *ToUsedLocOrErr,
8115 Param: *ToParamOrErr, RewrittenExpr: RewrittenInit,
8116 UsedContext: *UsedContextOrErr);
8117}
8118
8119ExpectedStmt
8120ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
8121 Error Err = Error::success();
8122 auto ToType = importChecked(Err, From: E->getType());
8123 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8124 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8125 if (Err)
8126 return std::move(Err);
8127
8128 return new (Importer.getToContext()) CXXScalarValueInitExpr(
8129 ToType, ToTypeSourceInfo, ToRParenLoc);
8130}
8131
8132ExpectedStmt
8133ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
8134 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
8135 if (!ToSubExprOrErr)
8136 return ToSubExprOrErr.takeError();
8137
8138 auto ToDtorOrErr = import(From: E->getTemporary()->getDestructor());
8139 if (!ToDtorOrErr)
8140 return ToDtorOrErr.takeError();
8141
8142 ASTContext &ToCtx = Importer.getToContext();
8143 CXXTemporary *Temp = CXXTemporary::Create(C: ToCtx, Destructor: *ToDtorOrErr);
8144 return CXXBindTemporaryExpr::Create(C: ToCtx, Temp, SubExpr: *ToSubExprOrErr);
8145}
8146
8147ExpectedStmt
8148
8149ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
8150 Error Err = Error::success();
8151 auto ToConstructor = importChecked(Err, From: E->getConstructor());
8152 auto ToType = importChecked(Err, From: E->getType());
8153 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8154 auto ToParenOrBraceRange = importChecked(Err, From: E->getParenOrBraceRange());
8155 if (Err)
8156 return std::move(Err);
8157
8158 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8159 if (Error Err = ImportContainerChecked(InContainer: E->arguments(), OutContainer&: ToArgs))
8160 return std::move(Err);
8161
8162 return CXXTemporaryObjectExpr::Create(
8163 Ctx: Importer.getToContext(), Cons: ToConstructor, Ty: ToType, TSI: ToTypeSourceInfo, Args: ToArgs,
8164 ParenOrBraceRange: ToParenOrBraceRange, HadMultipleCandidates: E->hadMultipleCandidates(),
8165 ListInitialization: E->isListInitialization(), StdInitListInitialization: E->isStdInitListInitialization(),
8166 ZeroInitialization: E->requiresZeroInitialization());
8167}
8168
8169ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl(
8170 LifetimeExtendedTemporaryDecl *D) {
8171 DeclContext *DC, *LexicalDC;
8172 if (Error Err = ImportDeclContext(FromD: D, ToDC&: DC, ToLexicalDC&: LexicalDC))
8173 return std::move(Err);
8174
8175 Error Err = Error::success();
8176 auto Temporary = importChecked(Err, From: D->getTemporaryExpr());
8177 auto ExtendingDecl = importChecked(Err, From: D->getExtendingDecl());
8178 if (Err)
8179 return std::move(Err);
8180 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
8181
8182 LifetimeExtendedTemporaryDecl *To;
8183 if (GetImportedOrCreateDecl(ToD&: To, FromD: D, args&: Temporary, args&: ExtendingDecl,
8184 args: D->getManglingNumber()))
8185 return To;
8186
8187 To->setLexicalDeclContext(LexicalDC);
8188 LexicalDC->addDeclInternal(D: To);
8189 return To;
8190}
8191
8192ExpectedStmt
8193ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
8194 Error Err = Error::success();
8195 auto ToType = importChecked(Err, From: E->getType());
8196 Expr *ToTemporaryExpr = importChecked(
8197 Err, From: E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr());
8198 auto ToMaterializedDecl =
8199 importChecked(Err, From: E->getLifetimeExtendedTemporaryDecl());
8200 if (Err)
8201 return std::move(Err);
8202
8203 if (!ToTemporaryExpr)
8204 ToTemporaryExpr = cast<Expr>(Val: ToMaterializedDecl->getTemporaryExpr());
8205
8206 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
8207 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(),
8208 ToMaterializedDecl);
8209
8210 return ToMTE;
8211}
8212
8213ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
8214 Error Err = Error::success();
8215 auto ToType = importChecked(Err, From: E->getType());
8216 auto ToPattern = importChecked(Err, From: E->getPattern());
8217 auto ToEllipsisLoc = importChecked(Err, From: E->getEllipsisLoc());
8218 if (Err)
8219 return std::move(Err);
8220
8221 return new (Importer.getToContext()) PackExpansionExpr(
8222 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
8223}
8224
8225ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
8226 Error Err = Error::success();
8227 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8228 auto ToPack = importChecked(Err, From: E->getPack());
8229 auto ToPackLoc = importChecked(Err, From: E->getPackLoc());
8230 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8231 if (Err)
8232 return std::move(Err);
8233
8234 std::optional<unsigned> Length;
8235 if (!E->isValueDependent())
8236 Length = E->getPackLength();
8237
8238 SmallVector<TemplateArgument, 8> ToPartialArguments;
8239 if (E->isPartiallySubstituted()) {
8240 if (Error Err = ImportTemplateArguments(FromArgs: E->getPartialArguments(),
8241 ToArgs&: ToPartialArguments))
8242 return std::move(Err);
8243 }
8244
8245 return SizeOfPackExpr::Create(
8246 Context&: Importer.getToContext(), OperatorLoc: ToOperatorLoc, Pack: ToPack, PackLoc: ToPackLoc, RParenLoc: ToRParenLoc,
8247 Length, PartialArgs: ToPartialArguments);
8248}
8249
8250
8251ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) {
8252 Error Err = Error::success();
8253 auto ToOperatorNew = importChecked(Err, From: E->getOperatorNew());
8254 auto ToOperatorDelete = importChecked(Err, From: E->getOperatorDelete());
8255 auto ToTypeIdParens = importChecked(Err, From: E->getTypeIdParens());
8256 auto ToArraySize = importChecked(Err, From: E->getArraySize());
8257 auto ToInitializer = importChecked(Err, From: E->getInitializer());
8258 auto ToType = importChecked(Err, From: E->getType());
8259 auto ToAllocatedTypeSourceInfo =
8260 importChecked(Err, From: E->getAllocatedTypeSourceInfo());
8261 auto ToSourceRange = importChecked(Err, From: E->getSourceRange());
8262 auto ToDirectInitRange = importChecked(Err, From: E->getDirectInitRange());
8263 if (Err)
8264 return std::move(Err);
8265
8266 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
8267 if (Error Err =
8268 ImportContainerChecked(InContainer: E->placement_arguments(), OutContainer&: ToPlacementArgs))
8269 return std::move(Err);
8270
8271 return CXXNewExpr::Create(
8272 Ctx: Importer.getToContext(), IsGlobalNew: E->isGlobalNew(), OperatorNew: ToOperatorNew,
8273 OperatorDelete: ToOperatorDelete, ShouldPassAlignment: E->passAlignment(), UsualArrayDeleteWantsSize: E->doesUsualArrayDeleteWantSize(),
8274 PlacementArgs: ToPlacementArgs, TypeIdParens: ToTypeIdParens, ArraySize: ToArraySize, InitializationStyle: E->getInitializationStyle(),
8275 Initializer: ToInitializer, Ty: ToType, AllocatedTypeInfo: ToAllocatedTypeSourceInfo, Range: ToSourceRange,
8276 DirectInitRange: ToDirectInitRange);
8277}
8278
8279ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
8280 Error Err = Error::success();
8281 auto ToType = importChecked(Err, From: E->getType());
8282 auto ToOperatorDelete = importChecked(Err, From: E->getOperatorDelete());
8283 auto ToArgument = importChecked(Err, From: E->getArgument());
8284 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
8285 if (Err)
8286 return std::move(Err);
8287
8288 return new (Importer.getToContext()) CXXDeleteExpr(
8289 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
8290 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
8291 ToBeginLoc);
8292}
8293
8294ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
8295 Error Err = Error::success();
8296 auto ToType = importChecked(Err, From: E->getType());
8297 auto ToLocation = importChecked(Err, From: E->getLocation());
8298 auto ToConstructor = importChecked(Err, From: E->getConstructor());
8299 auto ToParenOrBraceRange = importChecked(Err, From: E->getParenOrBraceRange());
8300 if (Err)
8301 return std::move(Err);
8302
8303 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
8304 if (Error Err = ImportContainerChecked(InContainer: E->arguments(), OutContainer&: ToArgs))
8305 return std::move(Err);
8306
8307 CXXConstructExpr *ToE = CXXConstructExpr::Create(
8308 Ctx: Importer.getToContext(), Ty: ToType, Loc: ToLocation, Ctor: ToConstructor,
8309 Elidable: E->isElidable(), Args: ToArgs, HadMultipleCandidates: E->hadMultipleCandidates(),
8310 ListInitialization: E->isListInitialization(), StdInitListInitialization: E->isStdInitListInitialization(),
8311 ZeroInitialization: E->requiresZeroInitialization(), ConstructKind: E->getConstructionKind(),
8312 ParenOrBraceRange: ToParenOrBraceRange);
8313 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
8314 return ToE;
8315}
8316
8317ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) {
8318 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
8319 if (!ToSubExprOrErr)
8320 return ToSubExprOrErr.takeError();
8321
8322 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
8323 if (Error Err = ImportContainerChecked(InContainer: E->getObjects(), OutContainer&: ToObjects))
8324 return std::move(Err);
8325
8326 return ExprWithCleanups::Create(
8327 C: Importer.getToContext(), subexpr: *ToSubExprOrErr, CleanupsHaveSideEffects: E->cleanupsHaveSideEffects(),
8328 objects: ToObjects);
8329}
8330
8331ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
8332 Error Err = Error::success();
8333 auto ToCallee = importChecked(Err, From: E->getCallee());
8334 auto ToType = importChecked(Err, From: E->getType());
8335 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8336 if (Err)
8337 return std::move(Err);
8338
8339 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
8340 if (Error Err = ImportContainerChecked(InContainer: E->arguments(), OutContainer&: ToArgs))
8341 return std::move(Err);
8342
8343 return CXXMemberCallExpr::Create(Ctx: Importer.getToContext(), Fn: ToCallee, Args: ToArgs,
8344 Ty: ToType, VK: E->getValueKind(), RP: ToRParenLoc,
8345 FPFeatures: E->getFPFeatures());
8346}
8347
8348ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
8349 ExpectedType ToTypeOrErr = import(From: E->getType());
8350 if (!ToTypeOrErr)
8351 return ToTypeOrErr.takeError();
8352
8353 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
8354 if (!ToLocationOrErr)
8355 return ToLocationOrErr.takeError();
8356
8357 return CXXThisExpr::Create(Ctx: Importer.getToContext(), L: *ToLocationOrErr,
8358 Ty: *ToTypeOrErr, IsImplicit: E->isImplicit());
8359}
8360
8361ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8362 ExpectedType ToTypeOrErr = import(From: E->getType());
8363 if (!ToTypeOrErr)
8364 return ToTypeOrErr.takeError();
8365
8366 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
8367 if (!ToLocationOrErr)
8368 return ToLocationOrErr.takeError();
8369
8370 return CXXBoolLiteralExpr::Create(C: Importer.getToContext(), Val: E->getValue(),
8371 Ty: *ToTypeOrErr, Loc: *ToLocationOrErr);
8372}
8373
8374ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
8375 Error Err = Error::success();
8376 auto ToBase = importChecked(Err, From: E->getBase());
8377 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8378 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8379 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8380 auto ToMemberDecl = importChecked(Err, From: E->getMemberDecl());
8381 auto ToType = importChecked(Err, From: E->getType());
8382 auto ToDecl = importChecked(Err, From: E->getFoundDecl().getDecl());
8383 auto ToName = importChecked(Err, From: E->getMemberNameInfo().getName());
8384 auto ToLoc = importChecked(Err, From: E->getMemberNameInfo().getLoc());
8385 if (Err)
8386 return std::move(Err);
8387
8388 DeclAccessPair ToFoundDecl =
8389 DeclAccessPair::make(D: ToDecl, AS: E->getFoundDecl().getAccess());
8390
8391 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
8392
8393 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8394 if (E->hasExplicitTemplateArgs()) {
8395 if (Error Err =
8396 ImportTemplateArgumentListInfo(FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(),
8397 Container: E->template_arguments(), Result&: ToTAInfo))
8398 return std::move(Err);
8399 ResInfo = &ToTAInfo;
8400 }
8401
8402 return MemberExpr::Create(C: Importer.getToContext(), Base: ToBase, IsArrow: E->isArrow(),
8403 OperatorLoc: ToOperatorLoc, QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc,
8404 MemberDecl: ToMemberDecl, FoundDecl: ToFoundDecl, MemberNameInfo: ToMemberNameInfo,
8405 TemplateArgs: ResInfo, T: ToType, VK: E->getValueKind(),
8406 OK: E->getObjectKind(), NOUR: E->isNonOdrUse());
8407}
8408
8409ExpectedStmt
8410ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
8411 Error Err = Error::success();
8412 auto ToBase = importChecked(Err, From: E->getBase());
8413 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8414 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8415 auto ToScopeTypeInfo = importChecked(Err, From: E->getScopeTypeInfo());
8416 auto ToColonColonLoc = importChecked(Err, From: E->getColonColonLoc());
8417 auto ToTildeLoc = importChecked(Err, From: E->getTildeLoc());
8418 if (Err)
8419 return std::move(Err);
8420
8421 PseudoDestructorTypeStorage Storage;
8422 if (const IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
8423 const IdentifierInfo *ToII = Importer.Import(FromId: FromII);
8424 ExpectedSLoc ToDestroyedTypeLocOrErr = import(From: E->getDestroyedTypeLoc());
8425 if (!ToDestroyedTypeLocOrErr)
8426 return ToDestroyedTypeLocOrErr.takeError();
8427 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
8428 } else {
8429 if (auto ToTIOrErr = import(From: E->getDestroyedTypeInfo()))
8430 Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
8431 else
8432 return ToTIOrErr.takeError();
8433 }
8434
8435 return new (Importer.getToContext()) CXXPseudoDestructorExpr(
8436 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
8437 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
8438}
8439
8440ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
8441 CXXDependentScopeMemberExpr *E) {
8442 Error Err = Error::success();
8443 auto ToType = importChecked(Err, From: E->getType());
8444 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8445 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8446 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8447 auto ToFirstQualifierFoundInScope =
8448 importChecked(Err, From: E->getFirstQualifierFoundInScope());
8449 if (Err)
8450 return std::move(Err);
8451
8452 Expr *ToBase = nullptr;
8453 if (!E->isImplicitAccess()) {
8454 if (ExpectedExpr ToBaseOrErr = import(From: E->getBase()))
8455 ToBase = *ToBaseOrErr;
8456 else
8457 return ToBaseOrErr.takeError();
8458 }
8459
8460 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8461
8462 if (E->hasExplicitTemplateArgs()) {
8463 if (Error Err =
8464 ImportTemplateArgumentListInfo(FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(),
8465 Container: E->template_arguments(), Result&: ToTAInfo))
8466 return std::move(Err);
8467 ResInfo = &ToTAInfo;
8468 }
8469 auto ToMember = importChecked(Err, From: E->getMember());
8470 auto ToMemberLoc = importChecked(Err, From: E->getMemberLoc());
8471 if (Err)
8472 return std::move(Err);
8473 DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc);
8474
8475 // Import additional name location/type info.
8476 if (Error Err =
8477 ImportDeclarationNameLoc(From: E->getMemberNameInfo(), To&: ToMemberNameInfo))
8478 return std::move(Err);
8479
8480 return CXXDependentScopeMemberExpr::Create(
8481 Ctx: Importer.getToContext(), Base: ToBase, BaseType: ToType, IsArrow: E->isArrow(), OperatorLoc: ToOperatorLoc,
8482 QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc, FirstQualifierFoundInScope: ToFirstQualifierFoundInScope,
8483 MemberNameInfo: ToMemberNameInfo, TemplateArgs: ResInfo);
8484}
8485
8486ExpectedStmt
8487ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
8488 Error Err = Error::success();
8489 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8490 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8491 auto ToDeclName = importChecked(Err, From: E->getDeclName());
8492 auto ToNameLoc = importChecked(Err, From: E->getNameInfo().getLoc());
8493 auto ToLAngleLoc = importChecked(Err, From: E->getLAngleLoc());
8494 auto ToRAngleLoc = importChecked(Err, From: E->getRAngleLoc());
8495 if (Err)
8496 return std::move(Err);
8497
8498 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc);
8499 if (Error Err = ImportDeclarationNameLoc(From: E->getNameInfo(), To&: ToNameInfo))
8500 return std::move(Err);
8501
8502 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
8503 TemplateArgumentListInfo *ResInfo = nullptr;
8504 if (E->hasExplicitTemplateArgs()) {
8505 if (Error Err =
8506 ImportTemplateArgumentListInfo(Container: E->template_arguments(), ToTAInfo))
8507 return std::move(Err);
8508 ResInfo = &ToTAInfo;
8509 }
8510
8511 return DependentScopeDeclRefExpr::Create(
8512 Context: Importer.getToContext(), QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc,
8513 NameInfo: ToNameInfo, TemplateArgs: ResInfo);
8514}
8515
8516ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
8517 CXXUnresolvedConstructExpr *E) {
8518 Error Err = Error::success();
8519 auto ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
8520 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8521 auto ToType = importChecked(Err, From: E->getType());
8522 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8523 if (Err)
8524 return std::move(Err);
8525
8526 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8527 if (Error Err =
8528 ImportArrayChecked(Ibegin: E->arg_begin(), Iend: E->arg_end(), Obegin: ToArgs.begin()))
8529 return std::move(Err);
8530
8531 return CXXUnresolvedConstructExpr::Create(
8532 Context: Importer.getToContext(), T: ToType, TSI: ToTypeSourceInfo, LParenLoc: ToLParenLoc,
8533 Args: llvm::ArrayRef(ToArgs), RParenLoc: ToRParenLoc, IsListInit: E->isListInitialization());
8534}
8535
8536ExpectedStmt
8537ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
8538 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(From: E->getNamingClass());
8539 if (!ToNamingClassOrErr)
8540 return ToNamingClassOrErr.takeError();
8541
8542 auto ToQualifierLocOrErr = import(From: E->getQualifierLoc());
8543 if (!ToQualifierLocOrErr)
8544 return ToQualifierLocOrErr.takeError();
8545
8546 Error Err = Error::success();
8547 auto ToName = importChecked(Err, From: E->getName());
8548 auto ToNameLoc = importChecked(Err, From: E->getNameLoc());
8549 if (Err)
8550 return std::move(Err);
8551 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8552
8553 // Import additional name location/type info.
8554 if (Error Err = ImportDeclarationNameLoc(From: E->getNameInfo(), To&: ToNameInfo))
8555 return std::move(Err);
8556
8557 UnresolvedSet<8> ToDecls;
8558 for (auto *D : E->decls())
8559 if (auto ToDOrErr = import(From: D))
8560 ToDecls.addDecl(D: cast<NamedDecl>(Val: *ToDOrErr));
8561 else
8562 return ToDOrErr.takeError();
8563
8564 if (E->hasExplicitTemplateArgs()) {
8565 TemplateArgumentListInfo ToTAInfo;
8566 if (Error Err = ImportTemplateArgumentListInfo(
8567 FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(), Container: E->template_arguments(),
8568 Result&: ToTAInfo))
8569 return std::move(Err);
8570
8571 ExpectedSLoc ToTemplateKeywordLocOrErr = import(From: E->getTemplateKeywordLoc());
8572 if (!ToTemplateKeywordLocOrErr)
8573 return ToTemplateKeywordLocOrErr.takeError();
8574
8575 const bool KnownDependent =
8576 (E->getDependence() & ExprDependence::TypeValue) ==
8577 ExprDependence::TypeValue;
8578 return UnresolvedLookupExpr::Create(
8579 Context: Importer.getToContext(), NamingClass: *ToNamingClassOrErr, QualifierLoc: *ToQualifierLocOrErr,
8580 TemplateKWLoc: *ToTemplateKeywordLocOrErr, NameInfo: ToNameInfo, RequiresADL: E->requiresADL(), Args: &ToTAInfo,
8581 Begin: ToDecls.begin(), End: ToDecls.end(), KnownDependent,
8582 /*KnownInstantiationDependent=*/E->isInstantiationDependent());
8583 }
8584
8585 return UnresolvedLookupExpr::Create(
8586 Context: Importer.getToContext(), NamingClass: *ToNamingClassOrErr, QualifierLoc: *ToQualifierLocOrErr,
8587 NameInfo: ToNameInfo, RequiresADL: E->requiresADL(), Begin: ToDecls.begin(), End: ToDecls.end(),
8588 /*KnownDependent=*/E->isTypeDependent(),
8589 /*KnownInstantiationDependent=*/E->isInstantiationDependent());
8590}
8591
8592ExpectedStmt
8593ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
8594 Error Err = Error::success();
8595 auto ToType = importChecked(Err, From: E->getType());
8596 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8597 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8598 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8599 auto ToName = importChecked(Err, From: E->getName());
8600 auto ToNameLoc = importChecked(Err, From: E->getNameLoc());
8601 if (Err)
8602 return std::move(Err);
8603
8604 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8605 // Import additional name location/type info.
8606 if (Error Err = ImportDeclarationNameLoc(From: E->getNameInfo(), To&: ToNameInfo))
8607 return std::move(Err);
8608
8609 UnresolvedSet<8> ToDecls;
8610 for (Decl *D : E->decls())
8611 if (auto ToDOrErr = import(From: D))
8612 ToDecls.addDecl(D: cast<NamedDecl>(Val: *ToDOrErr));
8613 else
8614 return ToDOrErr.takeError();
8615
8616 TemplateArgumentListInfo ToTAInfo;
8617 TemplateArgumentListInfo *ResInfo = nullptr;
8618 if (E->hasExplicitTemplateArgs()) {
8619 TemplateArgumentListInfo FromTAInfo;
8620 E->copyTemplateArgumentsInto(List&: FromTAInfo);
8621 if (Error Err = ImportTemplateArgumentListInfo(From: FromTAInfo, Result&: ToTAInfo))
8622 return std::move(Err);
8623 ResInfo = &ToTAInfo;
8624 }
8625
8626 Expr *ToBase = nullptr;
8627 if (!E->isImplicitAccess()) {
8628 if (ExpectedExpr ToBaseOrErr = import(From: E->getBase()))
8629 ToBase = *ToBaseOrErr;
8630 else
8631 return ToBaseOrErr.takeError();
8632 }
8633
8634 return UnresolvedMemberExpr::Create(
8635 Context: Importer.getToContext(), HasUnresolvedUsing: E->hasUnresolvedUsing(), Base: ToBase, BaseType: ToType,
8636 IsArrow: E->isArrow(), OperatorLoc: ToOperatorLoc, QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc,
8637 MemberNameInfo: ToNameInfo, TemplateArgs: ResInfo, Begin: ToDecls.begin(), End: ToDecls.end());
8638}
8639
8640ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) {
8641 Error Err = Error::success();
8642 auto ToCallee = importChecked(Err, From: E->getCallee());
8643 auto ToType = importChecked(Err, From: E->getType());
8644 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8645 if (Err)
8646 return std::move(Err);
8647
8648 unsigned NumArgs = E->getNumArgs();
8649 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
8650 if (Error Err = ImportContainerChecked(InContainer: E->arguments(), OutContainer&: ToArgs))
8651 return std::move(Err);
8652
8653 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
8654 return CXXOperatorCallExpr::Create(
8655 Ctx: Importer.getToContext(), OpKind: OCE->getOperator(), Fn: ToCallee, Args: ToArgs, Ty: ToType,
8656 VK: OCE->getValueKind(), OperatorLoc: ToRParenLoc, FPFeatures: OCE->getFPFeatures(),
8657 UsesADL: OCE->getADLCallKind());
8658 }
8659
8660 return CallExpr::Create(Ctx: Importer.getToContext(), Fn: ToCallee, Args: ToArgs, Ty: ToType,
8661 VK: E->getValueKind(), RParenLoc: ToRParenLoc, FPFeatures: E->getFPFeatures(),
8662 /*MinNumArgs=*/0, UsesADL: E->getADLCallKind());
8663}
8664
8665ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) {
8666 CXXRecordDecl *FromClass = E->getLambdaClass();
8667 auto ToClassOrErr = import(From: FromClass);
8668 if (!ToClassOrErr)
8669 return ToClassOrErr.takeError();
8670 CXXRecordDecl *ToClass = *ToClassOrErr;
8671
8672 auto ToCallOpOrErr = import(From: E->getCallOperator());
8673 if (!ToCallOpOrErr)
8674 return ToCallOpOrErr.takeError();
8675
8676 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
8677 if (Error Err = ImportContainerChecked(InContainer: E->capture_inits(), OutContainer&: ToCaptureInits))
8678 return std::move(Err);
8679
8680 Error Err = Error::success();
8681 auto ToIntroducerRange = importChecked(Err, From: E->getIntroducerRange());
8682 auto ToCaptureDefaultLoc = importChecked(Err, From: E->getCaptureDefaultLoc());
8683 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
8684 if (Err)
8685 return std::move(Err);
8686
8687 return LambdaExpr::Create(C: Importer.getToContext(), Class: ToClass, IntroducerRange: ToIntroducerRange,
8688 CaptureDefault: E->getCaptureDefault(), CaptureDefaultLoc: ToCaptureDefaultLoc,
8689 ExplicitParams: E->hasExplicitParameters(),
8690 ExplicitResultType: E->hasExplicitResultType(), CaptureInits: ToCaptureInits,
8691 ClosingBrace: ToEndLoc, ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack());
8692}
8693
8694
8695ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) {
8696 Error Err = Error::success();
8697 auto ToLBraceLoc = importChecked(Err, From: E->getLBraceLoc());
8698 auto ToRBraceLoc = importChecked(Err, From: E->getRBraceLoc());
8699 auto ToType = importChecked(Err, From: E->getType());
8700 if (Err)
8701 return std::move(Err);
8702
8703 SmallVector<Expr *, 4> ToExprs(E->getNumInits());
8704 if (Error Err = ImportContainerChecked(InContainer: E->inits(), OutContainer&: ToExprs))
8705 return std::move(Err);
8706
8707 ASTContext &ToCtx = Importer.getToContext();
8708 InitListExpr *To = new (ToCtx) InitListExpr(
8709 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
8710 To->setType(ToType);
8711
8712 if (E->hasArrayFiller()) {
8713 if (ExpectedExpr ToFillerOrErr = import(From: E->getArrayFiller()))
8714 To->setArrayFiller(*ToFillerOrErr);
8715 else
8716 return ToFillerOrErr.takeError();
8717 }
8718
8719 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
8720 if (auto ToFDOrErr = import(From: FromFD))
8721 To->setInitializedFieldInUnion(*ToFDOrErr);
8722 else
8723 return ToFDOrErr.takeError();
8724 }
8725
8726 if (InitListExpr *SyntForm = E->getSyntacticForm()) {
8727 if (auto ToSyntFormOrErr = import(From: SyntForm))
8728 To->setSyntacticForm(*ToSyntFormOrErr);
8729 else
8730 return ToSyntFormOrErr.takeError();
8731 }
8732
8733 // Copy InitListExprBitfields, which are not handled in the ctor of
8734 // InitListExpr.
8735 To->sawArrayRangeDesignator(ARD: E->hadArrayRangeDesignator());
8736
8737 return To;
8738}
8739
8740ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr(
8741 CXXStdInitializerListExpr *E) {
8742 ExpectedType ToTypeOrErr = import(From: E->getType());
8743 if (!ToTypeOrErr)
8744 return ToTypeOrErr.takeError();
8745
8746 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
8747 if (!ToSubExprOrErr)
8748 return ToSubExprOrErr.takeError();
8749
8750 return new (Importer.getToContext()) CXXStdInitializerListExpr(
8751 *ToTypeOrErr, *ToSubExprOrErr);
8752}
8753
8754ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
8755 CXXInheritedCtorInitExpr *E) {
8756 Error Err = Error::success();
8757 auto ToLocation = importChecked(Err, From: E->getLocation());
8758 auto ToType = importChecked(Err, From: E->getType());
8759 auto ToConstructor = importChecked(Err, From: E->getConstructor());
8760 if (Err)
8761 return std::move(Err);
8762
8763 return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
8764 ToLocation, ToType, ToConstructor, E->constructsVBase(),
8765 E->inheritedFromVBase());
8766}
8767
8768ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
8769 Error Err = Error::success();
8770 auto ToType = importChecked(Err, From: E->getType());
8771 auto ToCommonExpr = importChecked(Err, From: E->getCommonExpr());
8772 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
8773 if (Err)
8774 return std::move(Err);
8775
8776 return new (Importer.getToContext()) ArrayInitLoopExpr(
8777 ToType, ToCommonExpr, ToSubExpr);
8778}
8779
8780ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
8781 ExpectedType ToTypeOrErr = import(From: E->getType());
8782 if (!ToTypeOrErr)
8783 return ToTypeOrErr.takeError();
8784 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
8785}
8786
8787ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8788 ExpectedSLoc ToBeginLocOrErr = import(From: E->getBeginLoc());
8789 if (!ToBeginLocOrErr)
8790 return ToBeginLocOrErr.takeError();
8791
8792 auto ToFieldOrErr = import(From: E->getField());
8793 if (!ToFieldOrErr)
8794 return ToFieldOrErr.takeError();
8795
8796 auto UsedContextOrErr = Importer.ImportContext(FromDC: E->getUsedContext());
8797 if (!UsedContextOrErr)
8798 return UsedContextOrErr.takeError();
8799
8800 FieldDecl *ToField = *ToFieldOrErr;
8801 assert(ToField->hasInClassInitializer() &&
8802 "Field should have in-class initializer if there is a default init "
8803 "expression that uses it.");
8804 if (!ToField->getInClassInitializer()) {
8805 // The in-class initializer may be not yet set in "To" AST even if the
8806 // field is already there. This must be set here to make construction of
8807 // CXXDefaultInitExpr work.
8808 auto ToInClassInitializerOrErr =
8809 import(From: E->getField()->getInClassInitializer());
8810 if (!ToInClassInitializerOrErr)
8811 return ToInClassInitializerOrErr.takeError();
8812 ToField->setInClassInitializer(*ToInClassInitializerOrErr);
8813 }
8814
8815 Expr *RewrittenInit = nullptr;
8816 if (E->hasRewrittenInit()) {
8817 ExpectedExpr ExprOrErr = import(From: E->getRewrittenExpr());
8818 if (!ExprOrErr)
8819 return ExprOrErr.takeError();
8820 RewrittenInit = ExprOrErr.get();
8821 }
8822
8823 return CXXDefaultInitExpr::Create(Ctx: Importer.getToContext(), Loc: *ToBeginLocOrErr,
8824 Field: ToField, UsedContext: *UsedContextOrErr, RewrittenInitExpr: RewrittenInit);
8825}
8826
8827ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
8828 Error Err = Error::success();
8829 auto ToType = importChecked(Err, From: E->getType());
8830 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
8831 auto ToTypeInfoAsWritten = importChecked(Err, From: E->getTypeInfoAsWritten());
8832 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8833 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8834 auto ToAngleBrackets = importChecked(Err, From: E->getAngleBrackets());
8835 if (Err)
8836 return std::move(Err);
8837
8838 ExprValueKind VK = E->getValueKind();
8839 CastKind CK = E->getCastKind();
8840 auto ToBasePathOrErr = ImportCastPath(CE: E);
8841 if (!ToBasePathOrErr)
8842 return ToBasePathOrErr.takeError();
8843
8844 if (auto CCE = dyn_cast<CXXStaticCastExpr>(Val: E)) {
8845 return CXXStaticCastExpr::Create(
8846 Context: Importer.getToContext(), T: ToType, VK, K: CK, Op: ToSubExpr, Path: &(*ToBasePathOrErr),
8847 Written: ToTypeInfoAsWritten, FPO: CCE->getFPFeatures(), L: ToOperatorLoc, RParenLoc: ToRParenLoc,
8848 AngleBrackets: ToAngleBrackets);
8849 } else if (isa<CXXDynamicCastExpr>(Val: E)) {
8850 return CXXDynamicCastExpr::Create(
8851 Context: Importer.getToContext(), T: ToType, VK, Kind: CK, Op: ToSubExpr, Path: &(*ToBasePathOrErr),
8852 Written: ToTypeInfoAsWritten, L: ToOperatorLoc, RParenLoc: ToRParenLoc, AngleBrackets: ToAngleBrackets);
8853 } else if (isa<CXXReinterpretCastExpr>(Val: E)) {
8854 return CXXReinterpretCastExpr::Create(
8855 Context: Importer.getToContext(), T: ToType, VK, Kind: CK, Op: ToSubExpr, Path: &(*ToBasePathOrErr),
8856 WrittenTy: ToTypeInfoAsWritten, L: ToOperatorLoc, RParenLoc: ToRParenLoc, AngleBrackets: ToAngleBrackets);
8857 } else if (isa<CXXConstCastExpr>(Val: E)) {
8858 return CXXConstCastExpr::Create(
8859 Context: Importer.getToContext(), T: ToType, VK, Op: ToSubExpr, WrittenTy: ToTypeInfoAsWritten,
8860 L: ToOperatorLoc, RParenLoc: ToRParenLoc, AngleBrackets: ToAngleBrackets);
8861 } else {
8862 llvm_unreachable("Unknown cast type");
8863 return make_error<ASTImportError>();
8864 }
8865}
8866
8867ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
8868 SubstNonTypeTemplateParmExpr *E) {
8869 Error Err = Error::success();
8870 auto ToType = importChecked(Err, From: E->getType());
8871 auto ToExprLoc = importChecked(Err, From: E->getExprLoc());
8872 auto ToAssociatedDecl = importChecked(Err, From: E->getAssociatedDecl());
8873 auto ToReplacement = importChecked(Err, From: E->getReplacement());
8874 if (Err)
8875 return std::move(Err);
8876
8877 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
8878 ToType, E->getValueKind(), ToExprLoc, ToReplacement, ToAssociatedDecl,
8879 E->getIndex(), E->getPackIndex(), E->isReferenceParameter());
8880}
8881
8882ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
8883 Error Err = Error::success();
8884 auto ToType = importChecked(Err, From: E->getType());
8885 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
8886 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
8887 if (Err)
8888 return std::move(Err);
8889
8890 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
8891 if (Error Err = ImportContainerChecked(InContainer: E->getArgs(), OutContainer&: ToArgs))
8892 return std::move(Err);
8893
8894 // According to Sema::BuildTypeTrait(), if E is value-dependent,
8895 // Value is always false.
8896 bool ToValue = (E->isValueDependent() ? false : E->getValue());
8897
8898 return TypeTraitExpr::Create(
8899 C: Importer.getToContext(), T: ToType, Loc: ToBeginLoc, Kind: E->getTrait(), Args: ToArgs,
8900 RParenLoc: ToEndLoc, Value: ToValue);
8901}
8902
8903ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
8904 ExpectedType ToTypeOrErr = import(From: E->getType());
8905 if (!ToTypeOrErr)
8906 return ToTypeOrErr.takeError();
8907
8908 auto ToSourceRangeOrErr = import(From: E->getSourceRange());
8909 if (!ToSourceRangeOrErr)
8910 return ToSourceRangeOrErr.takeError();
8911
8912 if (E->isTypeOperand()) {
8913 if (auto ToTSIOrErr = import(From: E->getTypeOperandSourceInfo()))
8914 return new (Importer.getToContext()) CXXTypeidExpr(
8915 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
8916 else
8917 return ToTSIOrErr.takeError();
8918 }
8919
8920 ExpectedExpr ToExprOperandOrErr = import(From: E->getExprOperand());
8921 if (!ToExprOperandOrErr)
8922 return ToExprOperandOrErr.takeError();
8923
8924 return new (Importer.getToContext()) CXXTypeidExpr(
8925 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
8926}
8927
8928ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
8929 Error Err = Error::success();
8930
8931 QualType ToType = importChecked(Err, From: E->getType());
8932 UnresolvedLookupExpr *ToCallee = importChecked(Err, From: E->getCallee());
8933 SourceLocation ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
8934 Expr *ToLHS = importChecked(Err, From: E->getLHS());
8935 SourceLocation ToEllipsisLoc = importChecked(Err, From: E->getEllipsisLoc());
8936 Expr *ToRHS = importChecked(Err, From: E->getRHS());
8937 SourceLocation ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8938
8939 if (Err)
8940 return std::move(Err);
8941
8942 return new (Importer.getToContext())
8943 CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
8944 ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
8945}
8946
8947Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
8948 CXXMethodDecl *FromMethod) {
8949 Error ImportErrors = Error::success();
8950 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
8951 if (auto ImportedOrErr = import(From: FromOverriddenMethod))
8952 ToMethod->getCanonicalDecl()->addOverriddenMethod(MD: cast<CXXMethodDecl>(
8953 Val: (*ImportedOrErr)->getCanonicalDecl()));
8954 else
8955 ImportErrors =
8956 joinErrors(E1: std::move(ImportErrors), E2: ImportedOrErr.takeError());
8957 }
8958 return ImportErrors;
8959}
8960
8961ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
8962 ASTContext &FromContext, FileManager &FromFileManager,
8963 bool MinimalImport,
8964 std::shared_ptr<ASTImporterSharedState> SharedState)
8965 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
8966 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
8967 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) {
8968
8969 // Create a default state without the lookup table: LLDB case.
8970 if (!SharedState) {
8971 this->SharedState = std::make_shared<ASTImporterSharedState>();
8972 }
8973
8974 ImportedDecls[FromContext.getTranslationUnitDecl()] =
8975 ToContext.getTranslationUnitDecl();
8976}
8977
8978ASTImporter::~ASTImporter() = default;
8979
8980std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
8981 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
8982 "Try to get field index for non-field.");
8983
8984 auto *Owner = dyn_cast<RecordDecl>(Val: F->getDeclContext());
8985 if (!Owner)
8986 return std::nullopt;
8987
8988 unsigned Index = 0;
8989 for (const auto *D : Owner->decls()) {
8990 if (D == F)
8991 return Index;
8992
8993 if (isa<FieldDecl>(Val: *D) || isa<IndirectFieldDecl>(Val: *D))
8994 ++Index;
8995 }
8996
8997 llvm_unreachable("Field was not found in its parent context.");
8998
8999 return std::nullopt;
9000}
9001
9002ASTImporter::FoundDeclsTy
9003ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
9004 // We search in the redecl context because of transparent contexts.
9005 // E.g. a simple C language enum is a transparent context:
9006 // enum E { A, B };
9007 // Now if we had a global variable in the TU
9008 // int A;
9009 // then the enum constant 'A' and the variable 'A' violates ODR.
9010 // We can diagnose this only if we search in the redecl context.
9011 DeclContext *ReDC = DC->getRedeclContext();
9012 if (SharedState->getLookupTable()) {
9013 ASTImporterLookupTable::LookupResult LookupResult =
9014 SharedState->getLookupTable()->lookup(DC: ReDC, Name);
9015 return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
9016 } else {
9017 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
9018 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
9019 // We must search by the slow case of localUncachedLookup because that is
9020 // working even if there is no LookupPtr for the DC. We could use
9021 // DC::buildLookup() to create the LookupPtr, but that would load external
9022 // decls again, we must avoid that case.
9023 // Also, even if we had the LookupPtr, we must find Decls which are not
9024 // in the LookupPtr, so we need the slow case.
9025 // These cases are handled in ASTImporterLookupTable, but we cannot use
9026 // that with LLDB since that traverses through the AST which initiates the
9027 // load of external decls again via DC::decls(). And again, we must avoid
9028 // loading external decls during the import.
9029 if (Result.empty())
9030 ReDC->localUncachedLookup(Name, Results&: Result);
9031 return Result;
9032 }
9033}
9034
9035void ASTImporter::AddToLookupTable(Decl *ToD) {
9036 SharedState->addDeclToLookup(D: ToD);
9037}
9038
9039Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) {
9040 // Import the decl using ASTNodeImporter.
9041 ASTNodeImporter Importer(*this);
9042 return Importer.Visit(D: FromD);
9043}
9044
9045void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) {
9046 MapImported(From: FromD, To: ToD);
9047}
9048
9049llvm::Expected<ExprWithCleanups::CleanupObject>
9050ASTImporter::Import(ExprWithCleanups::CleanupObject From) {
9051 if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) {
9052 if (Expected<Expr *> R = Import(FromE: CLE))
9053 return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(Val: *R));
9054 }
9055
9056 // FIXME: Handle BlockDecl when we implement importing BlockExpr in
9057 // ASTNodeImporter.
9058 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
9059}
9060
9061ExpectedTypePtr ASTImporter::Import(const Type *FromT) {
9062 if (!FromT)
9063 return FromT;
9064
9065 // Check whether we've already imported this type.
9066 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
9067 ImportedTypes.find(Val: FromT);
9068 if (Pos != ImportedTypes.end())
9069 return Pos->second;
9070
9071 // Import the type.
9072 ASTNodeImporter Importer(*this);
9073 ExpectedType ToTOrErr = Importer.Visit(T: FromT);
9074 if (!ToTOrErr)
9075 return ToTOrErr.takeError();
9076
9077 // Record the imported type.
9078 ImportedTypes[FromT] = ToTOrErr->getTypePtr();
9079
9080 return ToTOrErr->getTypePtr();
9081}
9082
9083Expected<QualType> ASTImporter::Import(QualType FromT) {
9084 if (FromT.isNull())
9085 return QualType{};
9086
9087 ExpectedTypePtr ToTyOrErr = Import(FromT: FromT.getTypePtr());
9088 if (!ToTyOrErr)
9089 return ToTyOrErr.takeError();
9090
9091 return ToContext.getQualifiedType(T: *ToTyOrErr, Qs: FromT.getLocalQualifiers());
9092}
9093
9094Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) {
9095 if (!FromTSI)
9096 return FromTSI;
9097
9098 // FIXME: For now we just create a "trivial" type source info based
9099 // on the type and a single location. Implement a real version of this.
9100 ExpectedType TOrErr = Import(FromT: FromTSI->getType());
9101 if (!TOrErr)
9102 return TOrErr.takeError();
9103 ExpectedSLoc BeginLocOrErr = Import(FromLoc: FromTSI->getTypeLoc().getBeginLoc());
9104 if (!BeginLocOrErr)
9105 return BeginLocOrErr.takeError();
9106
9107 return ToContext.getTrivialTypeSourceInfo(T: *TOrErr, Loc: *BeginLocOrErr);
9108}
9109
9110namespace {
9111// To use this object, it should be created before the new attribute is created,
9112// and destructed after it is created. The construction already performs the
9113// import of the data.
9114template <typename T> struct AttrArgImporter {
9115 AttrArgImporter(const AttrArgImporter<T> &) = delete;
9116 AttrArgImporter(AttrArgImporter<T> &&) = default;
9117 AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete;
9118 AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default;
9119
9120 AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From)
9121 : To(I.importChecked(Err, From)) {}
9122
9123 const T &value() { return To; }
9124
9125private:
9126 T To;
9127};
9128
9129// To use this object, it should be created before the new attribute is created,
9130// and destructed after it is created. The construction already performs the
9131// import of the data. The array data is accessible in a pointer form, this form
9132// is used by the attribute classes. This object should be created once for the
9133// array data to be imported (the array size is not imported, just copied).
9134template <typename T> struct AttrArgArrayImporter {
9135 AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete;
9136 AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default;
9137 AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete;
9138 AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default;
9139
9140 AttrArgArrayImporter(ASTNodeImporter &I, Error &Err,
9141 const llvm::iterator_range<T *> &From,
9142 unsigned ArraySize) {
9143 if (Err)
9144 return;
9145 To.reserve(ArraySize);
9146 Err = I.ImportContainerChecked(From, To);
9147 }
9148
9149 T *value() { return To.data(); }
9150
9151private:
9152 llvm::SmallVector<T, 2> To;
9153};
9154
9155class AttrImporter {
9156 Error Err{Error::success()};
9157 Attr *ToAttr = nullptr;
9158 ASTImporter &Importer;
9159 ASTNodeImporter NImporter;
9160
9161public:
9162 AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {}
9163
9164 // Useful for accessing the imported attribute.
9165 template <typename T> T *castAttrAs() { return cast<T>(ToAttr); }
9166 template <typename T> const T *castAttrAs() const { return cast<T>(ToAttr); }
9167
9168 // Create an "importer" for an attribute parameter.
9169 // Result of the 'value()' of that object is to be passed to the function
9170 // 'importAttr', in the order that is expected by the attribute class.
9171 template <class T> AttrArgImporter<T> importArg(const T &From) {
9172 return AttrArgImporter<T>(NImporter, Err, From);
9173 }
9174
9175 // Create an "importer" for an attribute parameter that has array type.
9176 // Result of the 'value()' of that object is to be passed to the function
9177 // 'importAttr', then the size of the array as next argument.
9178 template <typename T>
9179 AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From,
9180 unsigned ArraySize) {
9181 return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize);
9182 }
9183
9184 // Create an attribute object with the specified arguments.
9185 // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg'
9186 // should be values that are passed to the 'Create' function of the attribute.
9187 // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is
9188 // used here.) As much data is copied or imported from the old attribute
9189 // as possible. The passed arguments should be already imported.
9190 // If an import error happens, the internal error is set to it, and any
9191 // further import attempt is ignored.
9192 template <typename T, typename... Arg>
9193 void importAttr(const T *FromAttr, Arg &&...ImportedArg) {
9194 static_assert(std::is_base_of<Attr, T>::value,
9195 "T should be subclass of Attr.");
9196 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9197
9198 const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName());
9199 const IdentifierInfo *ToScopeName =
9200 Importer.Import(FromAttr->getScopeName());
9201 SourceRange ToAttrRange =
9202 NImporter.importChecked(Err, FromAttr->getRange());
9203 SourceLocation ToScopeLoc =
9204 NImporter.importChecked(Err, FromAttr->getScopeLoc());
9205
9206 if (Err)
9207 return;
9208
9209 AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc,
9210 FromAttr->getParsedKind(), FromAttr->getForm());
9211 // The "SemanticSpelling" is not needed to be passed to the constructor.
9212 // That value is recalculated from the SpellingListIndex if needed.
9213 ToAttr = T::Create(Importer.getToContext(),
9214 std::forward<Arg>(ImportedArg)..., ToI);
9215
9216 ToAttr->setImplicit(FromAttr->isImplicit());
9217 ToAttr->setPackExpansion(FromAttr->isPackExpansion());
9218 if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(Val: ToAttr))
9219 ToInheritableAttr->setInherited(FromAttr->isInherited());
9220 }
9221
9222 // Create a clone of the 'FromAttr' and import its source range only.
9223 // This causes objects with invalid references to be created if the 'FromAttr'
9224 // contains other data that should be imported.
9225 void cloneAttr(const Attr *FromAttr) {
9226 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9227
9228 SourceRange ToRange = NImporter.importChecked(Err, From: FromAttr->getRange());
9229 if (Err)
9230 return;
9231
9232 ToAttr = FromAttr->clone(C&: Importer.getToContext());
9233 ToAttr->setRange(ToRange);
9234 ToAttr->setAttrName(Importer.Import(FromId: FromAttr->getAttrName()));
9235 }
9236
9237 // Get the result of the previous import attempt (can be used only once).
9238 llvm::Expected<Attr *> getResult() && {
9239 if (Err)
9240 return std::move(Err);
9241 assert(ToAttr && "Attribute should be created.");
9242 return ToAttr;
9243 }
9244};
9245} // namespace
9246
9247Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) {
9248 AttrImporter AI(*this);
9249
9250 // FIXME: Is there some kind of AttrVisitor to use here?
9251 switch (FromAttr->getKind()) {
9252 case attr::Aligned: {
9253 auto *From = cast<AlignedAttr>(Val: FromAttr);
9254 if (From->isAlignmentExpr())
9255 AI.importAttr(FromAttr: From, ImportedArg: true, ImportedArg: AI.importArg(From: From->getAlignmentExpr()).value());
9256 else
9257 AI.importAttr(FromAttr: From, ImportedArg: false,
9258 ImportedArg: AI.importArg(From: From->getAlignmentType()).value());
9259 break;
9260 }
9261
9262 case attr::AlignValue: {
9263 auto *From = cast<AlignValueAttr>(Val: FromAttr);
9264 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getAlignment()).value());
9265 break;
9266 }
9267
9268 case attr::Format: {
9269 const auto *From = cast<FormatAttr>(Val: FromAttr);
9270 AI.importAttr(FromAttr: From, ImportedArg: Import(FromId: From->getType()), ImportedArg: From->getFormatIdx(),
9271 ImportedArg: From->getFirstArg());
9272 break;
9273 }
9274
9275 case attr::EnableIf: {
9276 const auto *From = cast<EnableIfAttr>(Val: FromAttr);
9277 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getCond()).value(),
9278 ImportedArg: From->getMessage());
9279 break;
9280 }
9281
9282 case attr::AssertCapability: {
9283 const auto *From = cast<AssertCapabilityAttr>(Val: FromAttr);
9284 AI.importAttr(FromAttr: From,
9285 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9286 ImportedArg: From->args_size());
9287 break;
9288 }
9289 case attr::AcquireCapability: {
9290 const auto *From = cast<AcquireCapabilityAttr>(Val: FromAttr);
9291 AI.importAttr(FromAttr: From,
9292 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9293 ImportedArg: From->args_size());
9294 break;
9295 }
9296 case attr::TryAcquireCapability: {
9297 const auto *From = cast<TryAcquireCapabilityAttr>(Val: FromAttr);
9298 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getSuccessValue()).value(),
9299 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9300 ImportedArg: From->args_size());
9301 break;
9302 }
9303 case attr::ReleaseCapability: {
9304 const auto *From = cast<ReleaseCapabilityAttr>(Val: FromAttr);
9305 AI.importAttr(FromAttr: From,
9306 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9307 ImportedArg: From->args_size());
9308 break;
9309 }
9310 case attr::RequiresCapability: {
9311 const auto *From = cast<RequiresCapabilityAttr>(Val: FromAttr);
9312 AI.importAttr(FromAttr: From,
9313 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9314 ImportedArg: From->args_size());
9315 break;
9316 }
9317 case attr::GuardedBy: {
9318 const auto *From = cast<GuardedByAttr>(Val: FromAttr);
9319 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getArg()).value());
9320 break;
9321 }
9322 case attr::PtGuardedBy: {
9323 const auto *From = cast<PtGuardedByAttr>(Val: FromAttr);
9324 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getArg()).value());
9325 break;
9326 }
9327 case attr::AcquiredAfter: {
9328 const auto *From = cast<AcquiredAfterAttr>(Val: FromAttr);
9329 AI.importAttr(FromAttr: From,
9330 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9331 ImportedArg: From->args_size());
9332 break;
9333 }
9334 case attr::AcquiredBefore: {
9335 const auto *From = cast<AcquiredBeforeAttr>(Val: FromAttr);
9336 AI.importAttr(FromAttr: From,
9337 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9338 ImportedArg: From->args_size());
9339 break;
9340 }
9341 case attr::AssertExclusiveLock: {
9342 const auto *From = cast<AssertExclusiveLockAttr>(Val: FromAttr);
9343 AI.importAttr(FromAttr: From,
9344 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9345 ImportedArg: From->args_size());
9346 break;
9347 }
9348 case attr::AssertSharedLock: {
9349 const auto *From = cast<AssertSharedLockAttr>(Val: FromAttr);
9350 AI.importAttr(FromAttr: From,
9351 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9352 ImportedArg: From->args_size());
9353 break;
9354 }
9355 case attr::ExclusiveTrylockFunction: {
9356 const auto *From = cast<ExclusiveTrylockFunctionAttr>(Val: FromAttr);
9357 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getSuccessValue()).value(),
9358 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9359 ImportedArg: From->args_size());
9360 break;
9361 }
9362 case attr::SharedTrylockFunction: {
9363 const auto *From = cast<SharedTrylockFunctionAttr>(Val: FromAttr);
9364 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getSuccessValue()).value(),
9365 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9366 ImportedArg: From->args_size());
9367 break;
9368 }
9369 case attr::LockReturned: {
9370 const auto *From = cast<LockReturnedAttr>(Val: FromAttr);
9371 AI.importAttr(FromAttr: From, ImportedArg: AI.importArg(From: From->getArg()).value());
9372 break;
9373 }
9374 case attr::LocksExcluded: {
9375 const auto *From = cast<LocksExcludedAttr>(Val: FromAttr);
9376 AI.importAttr(FromAttr: From,
9377 ImportedArg: AI.importArrayArg(From: From->args(), ArraySize: From->args_size()).value(),
9378 ImportedArg: From->args_size());
9379 break;
9380 }
9381 default: {
9382 // The default branch works for attributes that have no arguments to import.
9383 // FIXME: Handle every attribute type that has arguments of type to import
9384 // (most often Expr* or Decl* or type) in the switch above.
9385 AI.cloneAttr(FromAttr);
9386 break;
9387 }
9388 }
9389
9390 return std::move(AI).getResult();
9391}
9392
9393Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const {
9394 return ImportedDecls.lookup(Val: FromD);
9395}
9396
9397TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) {
9398 auto FromDPos = ImportedFromDecls.find(Val: ToD);
9399 if (FromDPos == ImportedFromDecls.end())
9400 return nullptr;
9401 return FromDPos->second->getTranslationUnitDecl();
9402}
9403
9404Error ASTImporter::ImportAttrs(Decl *ToD, Decl *FromD) {
9405 if (!FromD->hasAttrs() || ToD->hasAttrs())
9406 return Error::success();
9407 for (const Attr *FromAttr : FromD->getAttrs()) {
9408 auto ToAttrOrErr = Import(FromAttr);
9409 if (ToAttrOrErr)
9410 ToD->addAttr(A: *ToAttrOrErr);
9411 else
9412 return ToAttrOrErr.takeError();
9413 }
9414 return Error::success();
9415}
9416
9417Expected<Decl *> ASTImporter::Import(Decl *FromD) {
9418 if (!FromD)
9419 return nullptr;
9420
9421 // Push FromD to the stack, and remove that when we return.
9422 ImportPath.push(D: FromD);
9423 auto ImportPathBuilder =
9424 llvm::make_scope_exit(F: [this]() { ImportPath.pop(); });
9425
9426 // Check whether there was a previous failed import.
9427 // If yes return the existing error.
9428 if (auto Error = getImportDeclErrorIfAny(FromD))
9429 return make_error<ASTImportError>(Args&: *Error);
9430
9431 // Check whether we've already imported this declaration.
9432 Decl *ToD = GetAlreadyImportedOrNull(FromD);
9433 if (ToD) {
9434 // Already imported (possibly from another TU) and with an error.
9435 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9436 setImportDeclError(From: FromD, Error: *Error);
9437 return make_error<ASTImportError>(Args&: *Error);
9438 }
9439
9440 // If FromD has some updated flags after last import, apply it.
9441 updateFlags(From: FromD, To: ToD);
9442 // If we encounter a cycle during an import then we save the relevant part
9443 // of the import path associated to the Decl.
9444 if (ImportPath.hasCycleAtBack())
9445 SavedImportPaths[FromD].push_back(Elt: ImportPath.copyCycleAtBack());
9446 return ToD;
9447 }
9448
9449 // Import the declaration.
9450 ExpectedDecl ToDOrErr = ImportImpl(FromD);
9451 if (!ToDOrErr) {
9452 // Failed to import.
9453
9454 auto Pos = ImportedDecls.find(Val: FromD);
9455 if (Pos != ImportedDecls.end()) {
9456 // Import failed after the object was created.
9457 // Remove all references to it.
9458 auto *ToD = Pos->second;
9459 ImportedDecls.erase(I: Pos);
9460
9461 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen
9462 // (e.g. with namespaces) that several decls from the 'from' context are
9463 // mapped to the same decl in the 'to' context. If we removed entries
9464 // from the LookupTable here then we may end up removing them multiple
9465 // times.
9466
9467 // The Lookuptable contains decls only which are in the 'to' context.
9468 // Remove from the Lookuptable only if it is *imported* into the 'to'
9469 // context (and do not remove it if it was added during the initial
9470 // traverse of the 'to' context).
9471 auto PosF = ImportedFromDecls.find(Val: ToD);
9472 if (PosF != ImportedFromDecls.end()) {
9473 // In the case of TypedefNameDecl we create the Decl first and only
9474 // then we import and set its DeclContext. So, the DC might not be set
9475 // when we reach here.
9476 if (ToD->getDeclContext())
9477 SharedState->removeDeclFromLookup(D: ToD);
9478 ImportedFromDecls.erase(I: PosF);
9479 }
9480
9481 // FIXME: AST may contain remaining references to the failed object.
9482 // However, the ImportDeclErrors in the shared state contains all the
9483 // failed objects together with their error.
9484 }
9485
9486 // Error encountered for the first time.
9487 // After takeError the error is not usable any more in ToDOrErr.
9488 // Get a copy of the error object (any more simple solution for this?).
9489 ASTImportError ErrOut;
9490 handleAllErrors(E: ToDOrErr.takeError(),
9491 Handlers: [&ErrOut](const ASTImportError &E) { ErrOut = E; });
9492 setImportDeclError(From: FromD, Error: ErrOut);
9493 // Set the error for the mapped to Decl, which is in the "to" context.
9494 if (Pos != ImportedDecls.end())
9495 SharedState->setImportDeclError(To: Pos->second, Error: ErrOut);
9496
9497 // Set the error for all nodes which have been created before we
9498 // recognized the error.
9499 for (const auto &Path : SavedImportPaths[FromD]) {
9500 // The import path contains import-dependency nodes first.
9501 // Save the node that was imported as dependency of the current node.
9502 Decl *PrevFromDi = FromD;
9503 for (Decl *FromDi : Path) {
9504 // Begin and end of the path equals 'FromD', skip it.
9505 if (FromDi == FromD)
9506 continue;
9507 // We should not set import error on a node and all following nodes in
9508 // the path if child import errors are ignored.
9509 if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent(
9510 FromChildD: PrevFromDi))
9511 break;
9512 PrevFromDi = FromDi;
9513 setImportDeclError(From: FromDi, Error: ErrOut);
9514 //FIXME Should we remove these Decls from ImportedDecls?
9515 // Set the error for the mapped to Decl, which is in the "to" context.
9516 auto Ii = ImportedDecls.find(Val: FromDi);
9517 if (Ii != ImportedDecls.end())
9518 SharedState->setImportDeclError(To: Ii->second, Error: ErrOut);
9519 // FIXME Should we remove these Decls from the LookupTable,
9520 // and from ImportedFromDecls?
9521 }
9522 }
9523 SavedImportPaths.erase(Val: FromD);
9524
9525 // Do not return ToDOrErr, error was taken out of it.
9526 return make_error<ASTImportError>(Args&: ErrOut);
9527 }
9528
9529 ToD = *ToDOrErr;
9530
9531 // FIXME: Handle the "already imported with error" case. We can get here
9532 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a
9533 // previously failed create was requested).
9534 // Later GetImportedOrCreateDecl can be updated to return the error.
9535 if (!ToD) {
9536 auto Err = getImportDeclErrorIfAny(FromD);
9537 assert(Err);
9538 return make_error<ASTImportError>(Args&: *Err);
9539 }
9540
9541 // We could import from the current TU without error. But previously we
9542 // already had imported a Decl as `ToD` from another TU (with another
9543 // ASTImporter object) and with an error.
9544 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9545 setImportDeclError(From: FromD, Error: *Error);
9546 return make_error<ASTImportError>(Args&: *Error);
9547 }
9548 // Make sure that ImportImpl registered the imported decl.
9549 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
9550 if (auto Error = ImportAttrs(ToD, FromD))
9551 return std::move(Error);
9552
9553 // Notify subclasses.
9554 Imported(From: FromD, To: ToD);
9555
9556 updateFlags(From: FromD, To: ToD);
9557 SavedImportPaths.erase(Val: FromD);
9558 return ToDOrErr;
9559}
9560
9561llvm::Expected<InheritedConstructor>
9562ASTImporter::Import(const InheritedConstructor &From) {
9563 return ASTNodeImporter(*this).ImportInheritedConstructor(From);
9564}
9565
9566Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) {
9567 if (!FromDC)
9568 return FromDC;
9569
9570 ExpectedDecl ToDCOrErr = Import(FromD: cast<Decl>(Val: FromDC));
9571 if (!ToDCOrErr)
9572 return ToDCOrErr.takeError();
9573 auto *ToDC = cast<DeclContext>(Val: *ToDCOrErr);
9574
9575 // When we're using a record/enum/Objective-C class/protocol as a context, we
9576 // need it to have a definition.
9577 if (auto *ToRecord = dyn_cast<RecordDecl>(Val: ToDC)) {
9578 auto *FromRecord = cast<RecordDecl>(Val: FromDC);
9579 if (ToRecord->isCompleteDefinition())
9580 return ToDC;
9581
9582 // If FromRecord is not defined we need to force it to be.
9583 // Simply calling CompleteDecl(...) for a RecordDecl will break some cases
9584 // it will start the definition but we never finish it.
9585 // If there are base classes they won't be imported and we will
9586 // be missing anything that we inherit from those bases.
9587 if (FromRecord->getASTContext().getExternalSource() &&
9588 !FromRecord->isCompleteDefinition())
9589 FromRecord->getASTContext().getExternalSource()->CompleteType(Tag: FromRecord);
9590
9591 if (FromRecord->isCompleteDefinition())
9592 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9593 From: FromRecord, To: ToRecord, Kind: ASTNodeImporter::IDK_Basic))
9594 return std::move(Err);
9595 } else if (auto *ToEnum = dyn_cast<EnumDecl>(Val: ToDC)) {
9596 auto *FromEnum = cast<EnumDecl>(Val: FromDC);
9597 if (ToEnum->isCompleteDefinition()) {
9598 // Do nothing.
9599 } else if (FromEnum->isCompleteDefinition()) {
9600 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9601 From: FromEnum, To: ToEnum, Kind: ASTNodeImporter::IDK_Basic))
9602 return std::move(Err);
9603 } else {
9604 CompleteDecl(D: ToEnum);
9605 }
9606 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(Val: ToDC)) {
9607 auto *FromClass = cast<ObjCInterfaceDecl>(Val: FromDC);
9608 if (ToClass->getDefinition()) {
9609 // Do nothing.
9610 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
9611 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9612 From: FromDef, To: ToClass, Kind: ASTNodeImporter::IDK_Basic))
9613 return std::move(Err);
9614 } else {
9615 CompleteDecl(D: ToClass);
9616 }
9617 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(Val: ToDC)) {
9618 auto *FromProto = cast<ObjCProtocolDecl>(Val: FromDC);
9619 if (ToProto->getDefinition()) {
9620 // Do nothing.
9621 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
9622 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9623 From: FromDef, To: ToProto, Kind: ASTNodeImporter::IDK_Basic))
9624 return std::move(Err);
9625 } else {
9626 CompleteDecl(D: ToProto);
9627 }
9628 }
9629
9630 return ToDC;
9631}
9632
9633Expected<Expr *> ASTImporter::Import(Expr *FromE) {
9634 if (ExpectedStmt ToSOrErr = Import(FromS: cast_or_null<Stmt>(Val: FromE)))
9635 return cast_or_null<Expr>(Val: *ToSOrErr);
9636 else
9637 return ToSOrErr.takeError();
9638}
9639
9640Expected<Stmt *> ASTImporter::Import(Stmt *FromS) {
9641 if (!FromS)
9642 return nullptr;
9643
9644 // Check whether we've already imported this statement.
9645 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(Val: FromS);
9646 if (Pos != ImportedStmts.end())
9647 return Pos->second;
9648
9649 // Import the statement.
9650 ASTNodeImporter Importer(*this);
9651 ExpectedStmt ToSOrErr = Importer.Visit(S: FromS);
9652 if (!ToSOrErr)
9653 return ToSOrErr;
9654
9655 if (auto *ToE = dyn_cast<Expr>(Val: *ToSOrErr)) {
9656 auto *FromE = cast<Expr>(Val: FromS);
9657 // Copy ExprBitfields, which may not be handled in Expr subclasses
9658 // constructors.
9659 ToE->setValueKind(FromE->getValueKind());
9660 ToE->setObjectKind(FromE->getObjectKind());
9661 ToE->setDependence(FromE->getDependence());
9662 }
9663
9664 // Record the imported statement object.
9665 ImportedStmts[FromS] = *ToSOrErr;
9666 return ToSOrErr;
9667}
9668
9669Expected<NestedNameSpecifier *>
9670ASTImporter::Import(NestedNameSpecifier *FromNNS) {
9671 if (!FromNNS)
9672 return nullptr;
9673
9674 NestedNameSpecifier *Prefix = nullptr;
9675 if (Error Err = importInto(To&: Prefix, From: FromNNS->getPrefix()))
9676 return std::move(Err);
9677
9678 switch (FromNNS->getKind()) {
9679 case NestedNameSpecifier::Identifier:
9680 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
9681 return NestedNameSpecifier::Create(Context: ToContext, Prefix,
9682 II: Import(FromId: FromNNS->getAsIdentifier()));
9683
9684 case NestedNameSpecifier::Namespace:
9685 if (ExpectedDecl NSOrErr = Import(FromD: FromNNS->getAsNamespace())) {
9686 return NestedNameSpecifier::Create(Context: ToContext, Prefix,
9687 NS: cast<NamespaceDecl>(Val: *NSOrErr));
9688 } else
9689 return NSOrErr.takeError();
9690
9691 case NestedNameSpecifier::NamespaceAlias:
9692 if (ExpectedDecl NSADOrErr = Import(FromD: FromNNS->getAsNamespaceAlias()))
9693 return NestedNameSpecifier::Create(Context: ToContext, Prefix,
9694 Alias: cast<NamespaceAliasDecl>(Val: *NSADOrErr));
9695 else
9696 return NSADOrErr.takeError();
9697
9698 case NestedNameSpecifier::Global:
9699 return NestedNameSpecifier::GlobalSpecifier(Context: ToContext);
9700
9701 case NestedNameSpecifier::Super:
9702 if (ExpectedDecl RDOrErr = Import(FromD: FromNNS->getAsRecordDecl()))
9703 return NestedNameSpecifier::SuperSpecifier(Context: ToContext,
9704 RD: cast<CXXRecordDecl>(Val: *RDOrErr));
9705 else
9706 return RDOrErr.takeError();
9707
9708 case NestedNameSpecifier::TypeSpec:
9709 case NestedNameSpecifier::TypeSpecWithTemplate:
9710 if (ExpectedTypePtr TyOrErr = Import(FromT: FromNNS->getAsType())) {
9711 bool TSTemplate =
9712 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate;
9713 return NestedNameSpecifier::Create(Context: ToContext, Prefix, Template: TSTemplate,
9714 T: *TyOrErr);
9715 } else {
9716 return TyOrErr.takeError();
9717 }
9718 }
9719
9720 llvm_unreachable("Invalid nested name specifier kind");
9721}
9722
9723Expected<NestedNameSpecifierLoc>
9724ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
9725 // Copied from NestedNameSpecifier mostly.
9726 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
9727 NestedNameSpecifierLoc NNS = FromNNS;
9728
9729 // Push each of the nested-name-specifiers's onto a stack for
9730 // serialization in reverse order.
9731 while (NNS) {
9732 NestedNames.push_back(Elt: NNS);
9733 NNS = NNS.getPrefix();
9734 }
9735
9736 NestedNameSpecifierLocBuilder Builder;
9737
9738 while (!NestedNames.empty()) {
9739 NNS = NestedNames.pop_back_val();
9740 NestedNameSpecifier *Spec = nullptr;
9741 if (Error Err = importInto(To&: Spec, From: NNS.getNestedNameSpecifier()))
9742 return std::move(Err);
9743
9744 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
9745
9746 SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
9747 if (Kind != NestedNameSpecifier::Super) {
9748 if (Error Err = importInto(To&: ToLocalBeginLoc, From: NNS.getLocalBeginLoc()))
9749 return std::move(Err);
9750
9751 if (Kind != NestedNameSpecifier::Global)
9752 if (Error Err = importInto(To&: ToLocalEndLoc, From: NNS.getLocalEndLoc()))
9753 return std::move(Err);
9754 }
9755
9756 switch (Kind) {
9757 case NestedNameSpecifier::Identifier:
9758 Builder.Extend(Context&: getToContext(), Identifier: Spec->getAsIdentifier(), IdentifierLoc: ToLocalBeginLoc,
9759 ColonColonLoc: ToLocalEndLoc);
9760 break;
9761
9762 case NestedNameSpecifier::Namespace:
9763 Builder.Extend(Context&: getToContext(), Namespace: Spec->getAsNamespace(), NamespaceLoc: ToLocalBeginLoc,
9764 ColonColonLoc: ToLocalEndLoc);
9765 break;
9766
9767 case NestedNameSpecifier::NamespaceAlias:
9768 Builder.Extend(Context&: getToContext(), Alias: Spec->getAsNamespaceAlias(),
9769 AliasLoc: ToLocalBeginLoc, ColonColonLoc: ToLocalEndLoc);
9770 break;
9771
9772 case NestedNameSpecifier::TypeSpec:
9773 case NestedNameSpecifier::TypeSpecWithTemplate: {
9774 SourceLocation ToTLoc;
9775 if (Error Err = importInto(To&: ToTLoc, From: NNS.getTypeLoc().getBeginLoc()))
9776 return std::move(Err);
9777 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
9778 T: QualType(Spec->getAsType(), 0), Loc: ToTLoc);
9779 if (Kind == NestedNameSpecifier::TypeSpecWithTemplate)
9780 // ToLocalBeginLoc is here the location of the 'template' keyword.
9781 Builder.Extend(Context&: getToContext(), TemplateKWLoc: ToLocalBeginLoc, TL: TSI->getTypeLoc(),
9782 ColonColonLoc: ToLocalEndLoc);
9783 else
9784 // No location for 'template' keyword here.
9785 Builder.Extend(Context&: getToContext(), TemplateKWLoc: SourceLocation{}, TL: TSI->getTypeLoc(),
9786 ColonColonLoc: ToLocalEndLoc);
9787 break;
9788 }
9789
9790 case NestedNameSpecifier::Global:
9791 Builder.MakeGlobal(Context&: getToContext(), ColonColonLoc: ToLocalBeginLoc);
9792 break;
9793
9794 case NestedNameSpecifier::Super: {
9795 auto ToSourceRangeOrErr = Import(FromRange: NNS.getSourceRange());
9796 if (!ToSourceRangeOrErr)
9797 return ToSourceRangeOrErr.takeError();
9798
9799 Builder.MakeSuper(Context&: getToContext(), RD: Spec->getAsRecordDecl(),
9800 SuperLoc: ToSourceRangeOrErr->getBegin(),
9801 ColonColonLoc: ToSourceRangeOrErr->getEnd());
9802 }
9803 }
9804 }
9805
9806 return Builder.getWithLocInContext(Context&: getToContext());
9807}
9808
9809Expected<TemplateName> ASTImporter::Import(TemplateName From) {
9810 switch (From.getKind()) {
9811 case TemplateName::Template:
9812 if (ExpectedDecl ToTemplateOrErr = Import(FromD: From.getAsTemplateDecl()))
9813 return TemplateName(cast<TemplateDecl>(Val: (*ToTemplateOrErr)->getCanonicalDecl()));
9814 else
9815 return ToTemplateOrErr.takeError();
9816
9817 case TemplateName::OverloadedTemplate: {
9818 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
9819 UnresolvedSet<2> ToTemplates;
9820 for (auto *I : *FromStorage) {
9821 if (auto ToOrErr = Import(FromD: I))
9822 ToTemplates.addDecl(D: cast<NamedDecl>(Val: *ToOrErr));
9823 else
9824 return ToOrErr.takeError();
9825 }
9826 return ToContext.getOverloadedTemplateName(Begin: ToTemplates.begin(),
9827 End: ToTemplates.end());
9828 }
9829
9830 case TemplateName::AssumedTemplate: {
9831 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName();
9832 auto DeclNameOrErr = Import(FromName: FromStorage->getDeclName());
9833 if (!DeclNameOrErr)
9834 return DeclNameOrErr.takeError();
9835 return ToContext.getAssumedTemplateName(Name: *DeclNameOrErr);
9836 }
9837
9838 case TemplateName::QualifiedTemplate: {
9839 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
9840 auto QualifierOrErr = Import(FromNNS: QTN->getQualifier());
9841 if (!QualifierOrErr)
9842 return QualifierOrErr.takeError();
9843 auto TNOrErr = Import(From: QTN->getUnderlyingTemplate());
9844 if (!TNOrErr)
9845 return TNOrErr.takeError();
9846 return ToContext.getQualifiedTemplateName(
9847 NNS: *QualifierOrErr, TemplateKeyword: QTN->hasTemplateKeyword(), Template: *TNOrErr);
9848 }
9849
9850 case TemplateName::DependentTemplate: {
9851 DependentTemplateName *DTN = From.getAsDependentTemplateName();
9852 auto QualifierOrErr = Import(FromNNS: DTN->getQualifier());
9853 if (!QualifierOrErr)
9854 return QualifierOrErr.takeError();
9855
9856 if (DTN->isIdentifier()) {
9857 return ToContext.getDependentTemplateName(NNS: *QualifierOrErr,
9858 Name: Import(FromId: DTN->getIdentifier()));
9859 }
9860
9861 return ToContext.getDependentTemplateName(NNS: *QualifierOrErr,
9862 Operator: DTN->getOperator());
9863 }
9864
9865 case TemplateName::SubstTemplateTemplateParm: {
9866 SubstTemplateTemplateParmStorage *Subst =
9867 From.getAsSubstTemplateTemplateParm();
9868 auto ReplacementOrErr = Import(From: Subst->getReplacement());
9869 if (!ReplacementOrErr)
9870 return ReplacementOrErr.takeError();
9871
9872 auto AssociatedDeclOrErr = Import(FromD: Subst->getAssociatedDecl());
9873 if (!AssociatedDeclOrErr)
9874 return AssociatedDeclOrErr.takeError();
9875
9876 return ToContext.getSubstTemplateTemplateParm(
9877 replacement: *ReplacementOrErr, AssociatedDecl: *AssociatedDeclOrErr, Index: Subst->getIndex(),
9878 PackIndex: Subst->getPackIndex());
9879 }
9880
9881 case TemplateName::SubstTemplateTemplateParmPack: {
9882 SubstTemplateTemplateParmPackStorage *SubstPack =
9883 From.getAsSubstTemplateTemplateParmPack();
9884 ASTNodeImporter Importer(*this);
9885 auto ArgPackOrErr =
9886 Importer.ImportTemplateArgument(From: SubstPack->getArgumentPack());
9887 if (!ArgPackOrErr)
9888 return ArgPackOrErr.takeError();
9889
9890 auto AssociatedDeclOrErr = Import(FromD: SubstPack->getAssociatedDecl());
9891 if (!AssociatedDeclOrErr)
9892 return AssociatedDeclOrErr.takeError();
9893
9894 return ToContext.getSubstTemplateTemplateParmPack(
9895 ArgPack: *ArgPackOrErr, AssociatedDecl: *AssociatedDeclOrErr, Index: SubstPack->getIndex(),
9896 Final: SubstPack->getFinal());
9897 }
9898 case TemplateName::UsingTemplate: {
9899 auto UsingOrError = Import(FromD: From.getAsUsingShadowDecl());
9900 if (!UsingOrError)
9901 return UsingOrError.takeError();
9902 return TemplateName(cast<UsingShadowDecl>(Val: *UsingOrError));
9903 }
9904 }
9905
9906 llvm_unreachable("Invalid template name kind");
9907}
9908
9909Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) {
9910 if (FromLoc.isInvalid())
9911 return SourceLocation{};
9912
9913 SourceManager &FromSM = FromContext.getSourceManager();
9914 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(Loc: FromLoc);
9915
9916 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(Loc: FromLoc);
9917 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
9918 if (!ToFileIDOrErr)
9919 return ToFileIDOrErr.takeError();
9920 SourceManager &ToSM = ToContext.getSourceManager();
9921 return ToSM.getComposedLoc(FID: *ToFileIDOrErr, Offset: Decomposed.second);
9922}
9923
9924Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) {
9925 SourceLocation ToBegin, ToEnd;
9926 if (Error Err = importInto(To&: ToBegin, From: FromRange.getBegin()))
9927 return std::move(Err);
9928 if (Error Err = importInto(To&: ToEnd, From: FromRange.getEnd()))
9929 return std::move(Err);
9930
9931 return SourceRange(ToBegin, ToEnd);
9932}
9933
9934Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
9935 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(Val: FromID);
9936 if (Pos != ImportedFileIDs.end())
9937 return Pos->second;
9938
9939 SourceManager &FromSM = FromContext.getSourceManager();
9940 SourceManager &ToSM = ToContext.getSourceManager();
9941 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FID: FromID);
9942
9943 // Map the FromID to the "to" source manager.
9944 FileID ToID;
9945 if (FromSLoc.isExpansion()) {
9946 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
9947 ExpectedSLoc ToSpLoc = Import(FromLoc: FromEx.getSpellingLoc());
9948 if (!ToSpLoc)
9949 return ToSpLoc.takeError();
9950 ExpectedSLoc ToExLocS = Import(FromLoc: FromEx.getExpansionLocStart());
9951 if (!ToExLocS)
9952 return ToExLocS.takeError();
9953 unsigned ExLength = FromSM.getFileIDSize(FID: FromID);
9954 SourceLocation MLoc;
9955 if (FromEx.isMacroArgExpansion()) {
9956 MLoc = ToSM.createMacroArgExpansionLoc(SpellingLoc: *ToSpLoc, ExpansionLoc: *ToExLocS, Length: ExLength);
9957 } else {
9958 if (ExpectedSLoc ToExLocE = Import(FromLoc: FromEx.getExpansionLocEnd()))
9959 MLoc = ToSM.createExpansionLoc(SpellingLoc: *ToSpLoc, ExpansionLocStart: *ToExLocS, ExpansionLocEnd: *ToExLocE, Length: ExLength,
9960 ExpansionIsTokenRange: FromEx.isExpansionTokenRange());
9961 else
9962 return ToExLocE.takeError();
9963 }
9964 ToID = ToSM.getFileID(SpellingLoc: MLoc);
9965 } else {
9966 const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache();
9967
9968 if (!IsBuiltin && !Cache->BufferOverridden) {
9969 // Include location of this file.
9970 ExpectedSLoc ToIncludeLoc = Import(FromLoc: FromSLoc.getFile().getIncludeLoc());
9971 if (!ToIncludeLoc)
9972 return ToIncludeLoc.takeError();
9973
9974 // Every FileID that is not the main FileID needs to have a valid include
9975 // location so that the include chain points to the main FileID. When
9976 // importing the main FileID (which has no include location), we need to
9977 // create a fake include location in the main file to keep this property
9978 // intact.
9979 SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc;
9980 if (FromID == FromSM.getMainFileID())
9981 ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(FID: ToSM.getMainFileID());
9982
9983 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
9984 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
9985 // disk again
9986 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
9987 // than mmap the files several times.
9988 auto Entry =
9989 ToFileManager.getOptionalFileRef(Filename: Cache->OrigEntry->getName());
9990 // FIXME: The filename may be a virtual name that does probably not
9991 // point to a valid file and we get no Entry here. In this case try with
9992 // the memory buffer below.
9993 if (Entry)
9994 ToID = ToSM.createFileID(SourceFile: *Entry, IncludePos: ToIncludeLocOrFakeLoc,
9995 FileCharacter: FromSLoc.getFile().getFileCharacteristic());
9996 }
9997 }
9998
9999 if (ToID.isInvalid() || IsBuiltin) {
10000 // FIXME: We want to re-use the existing MemoryBuffer!
10001 std::optional<llvm::MemoryBufferRef> FromBuf =
10002 Cache->getBufferOrNone(Diag&: FromContext.getDiagnostics(),
10003 FM&: FromSM.getFileManager(), Loc: SourceLocation{});
10004 if (!FromBuf)
10005 return llvm::make_error<ASTImportError>(Args: ASTImportError::Unknown);
10006
10007 std::unique_ptr<llvm::MemoryBuffer> ToBuf =
10008 llvm::MemoryBuffer::getMemBufferCopy(InputData: FromBuf->getBuffer(),
10009 BufferName: FromBuf->getBufferIdentifier());
10010 ToID = ToSM.createFileID(Buffer: std::move(ToBuf),
10011 FileCharacter: FromSLoc.getFile().getFileCharacteristic());
10012 }
10013 }
10014
10015 assert(ToID.isValid() && "Unexpected invalid fileID was created.");
10016
10017 ImportedFileIDs[FromID] = ToID;
10018 return ToID;
10019}
10020
10021Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) {
10022 ExpectedExpr ToExprOrErr = Import(FromE: From->getInit());
10023 if (!ToExprOrErr)
10024 return ToExprOrErr.takeError();
10025
10026 auto LParenLocOrErr = Import(FromLoc: From->getLParenLoc());
10027 if (!LParenLocOrErr)
10028 return LParenLocOrErr.takeError();
10029
10030 auto RParenLocOrErr = Import(FromLoc: From->getRParenLoc());
10031 if (!RParenLocOrErr)
10032 return RParenLocOrErr.takeError();
10033
10034 if (From->isBaseInitializer()) {
10035 auto ToTInfoOrErr = Import(FromTSI: From->getTypeSourceInfo());
10036 if (!ToTInfoOrErr)
10037 return ToTInfoOrErr.takeError();
10038
10039 SourceLocation EllipsisLoc;
10040 if (From->isPackExpansion())
10041 if (Error Err = importInto(To&: EllipsisLoc, From: From->getEllipsisLoc()))
10042 return std::move(Err);
10043
10044 return new (ToContext) CXXCtorInitializer(
10045 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
10046 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
10047 } else if (From->isMemberInitializer()) {
10048 ExpectedDecl ToFieldOrErr = Import(FromD: From->getMember());
10049 if (!ToFieldOrErr)
10050 return ToFieldOrErr.takeError();
10051
10052 auto MemberLocOrErr = Import(FromLoc: From->getMemberLocation());
10053 if (!MemberLocOrErr)
10054 return MemberLocOrErr.takeError();
10055
10056 return new (ToContext) CXXCtorInitializer(
10057 ToContext, cast_or_null<FieldDecl>(Val: *ToFieldOrErr), *MemberLocOrErr,
10058 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
10059 } else if (From->isIndirectMemberInitializer()) {
10060 ExpectedDecl ToIFieldOrErr = Import(FromD: From->getIndirectMember());
10061 if (!ToIFieldOrErr)
10062 return ToIFieldOrErr.takeError();
10063
10064 auto MemberLocOrErr = Import(FromLoc: From->getMemberLocation());
10065 if (!MemberLocOrErr)
10066 return MemberLocOrErr.takeError();
10067
10068 return new (ToContext) CXXCtorInitializer(
10069 ToContext, cast_or_null<IndirectFieldDecl>(Val: *ToIFieldOrErr),
10070 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
10071 } else if (From->isDelegatingInitializer()) {
10072 auto ToTInfoOrErr = Import(FromTSI: From->getTypeSourceInfo());
10073 if (!ToTInfoOrErr)
10074 return ToTInfoOrErr.takeError();
10075
10076 return new (ToContext)
10077 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
10078 *ToExprOrErr, *RParenLocOrErr);
10079 } else {
10080 // FIXME: assert?
10081 return make_error<ASTImportError>();
10082 }
10083}
10084
10085Expected<CXXBaseSpecifier *>
10086ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
10087 auto Pos = ImportedCXXBaseSpecifiers.find(Val: BaseSpec);
10088 if (Pos != ImportedCXXBaseSpecifiers.end())
10089 return Pos->second;
10090
10091 Expected<SourceRange> ToSourceRange = Import(FromRange: BaseSpec->getSourceRange());
10092 if (!ToSourceRange)
10093 return ToSourceRange.takeError();
10094 Expected<TypeSourceInfo *> ToTSI = Import(FromTSI: BaseSpec->getTypeSourceInfo());
10095 if (!ToTSI)
10096 return ToTSI.takeError();
10097 ExpectedSLoc ToEllipsisLoc = Import(FromLoc: BaseSpec->getEllipsisLoc());
10098 if (!ToEllipsisLoc)
10099 return ToEllipsisLoc.takeError();
10100 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
10101 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
10102 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
10103 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
10104 return Imported;
10105}
10106
10107llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) {
10108 ASTNodeImporter Importer(*this);
10109 return Importer.ImportAPValue(FromValue);
10110}
10111
10112Error ASTImporter::ImportDefinition(Decl *From) {
10113 ExpectedDecl ToOrErr = Import(FromD: From);
10114 if (!ToOrErr)
10115 return ToOrErr.takeError();
10116 Decl *To = *ToOrErr;
10117
10118 auto *FromDC = cast<DeclContext>(Val: From);
10119 ASTNodeImporter Importer(*this);
10120
10121 if (auto *ToRecord = dyn_cast<RecordDecl>(Val: To)) {
10122 if (!ToRecord->getDefinition()) {
10123 return Importer.ImportDefinition(
10124 From: cast<RecordDecl>(Val: FromDC), To: ToRecord,
10125 Kind: ASTNodeImporter::IDK_Everything);
10126 }
10127 }
10128
10129 if (auto *ToEnum = dyn_cast<EnumDecl>(Val: To)) {
10130 if (!ToEnum->getDefinition()) {
10131 return Importer.ImportDefinition(
10132 From: cast<EnumDecl>(Val: FromDC), To: ToEnum, Kind: ASTNodeImporter::IDK_Everything);
10133 }
10134 }
10135
10136 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(Val: To)) {
10137 if (!ToIFace->getDefinition()) {
10138 return Importer.ImportDefinition(
10139 From: cast<ObjCInterfaceDecl>(Val: FromDC), To: ToIFace,
10140 Kind: ASTNodeImporter::IDK_Everything);
10141 }
10142 }
10143
10144 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(Val: To)) {
10145 if (!ToProto->getDefinition()) {
10146 return Importer.ImportDefinition(
10147 From: cast<ObjCProtocolDecl>(Val: FromDC), To: ToProto,
10148 Kind: ASTNodeImporter::IDK_Everything);
10149 }
10150 }
10151
10152 return Importer.ImportDeclContext(FromDC, ForceImport: true);
10153}
10154
10155Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) {
10156 if (!FromName)
10157 return DeclarationName{};
10158
10159 switch (FromName.getNameKind()) {
10160 case DeclarationName::Identifier:
10161 return DeclarationName(Import(FromId: FromName.getAsIdentifierInfo()));
10162
10163 case DeclarationName::ObjCZeroArgSelector:
10164 case DeclarationName::ObjCOneArgSelector:
10165 case DeclarationName::ObjCMultiArgSelector:
10166 if (auto ToSelOrErr = Import(FromSel: FromName.getObjCSelector()))
10167 return DeclarationName(*ToSelOrErr);
10168 else
10169 return ToSelOrErr.takeError();
10170
10171 case DeclarationName::CXXConstructorName: {
10172 if (auto ToTyOrErr = Import(FromT: FromName.getCXXNameType()))
10173 return ToContext.DeclarationNames.getCXXConstructorName(
10174 Ty: ToContext.getCanonicalType(T: *ToTyOrErr));
10175 else
10176 return ToTyOrErr.takeError();
10177 }
10178
10179 case DeclarationName::CXXDestructorName: {
10180 if (auto ToTyOrErr = Import(FromT: FromName.getCXXNameType()))
10181 return ToContext.DeclarationNames.getCXXDestructorName(
10182 Ty: ToContext.getCanonicalType(T: *ToTyOrErr));
10183 else
10184 return ToTyOrErr.takeError();
10185 }
10186
10187 case DeclarationName::CXXDeductionGuideName: {
10188 if (auto ToTemplateOrErr = Import(FromD: FromName.getCXXDeductionGuideTemplate()))
10189 return ToContext.DeclarationNames.getCXXDeductionGuideName(
10190 TD: cast<TemplateDecl>(Val: *ToTemplateOrErr));
10191 else
10192 return ToTemplateOrErr.takeError();
10193 }
10194
10195 case DeclarationName::CXXConversionFunctionName: {
10196 if (auto ToTyOrErr = Import(FromT: FromName.getCXXNameType()))
10197 return ToContext.DeclarationNames.getCXXConversionFunctionName(
10198 Ty: ToContext.getCanonicalType(T: *ToTyOrErr));
10199 else
10200 return ToTyOrErr.takeError();
10201 }
10202
10203 case DeclarationName::CXXOperatorName:
10204 return ToContext.DeclarationNames.getCXXOperatorName(
10205 Op: FromName.getCXXOverloadedOperator());
10206
10207 case DeclarationName::CXXLiteralOperatorName:
10208 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
10209 II: Import(FromId: FromName.getCXXLiteralIdentifier()));
10210
10211 case DeclarationName::CXXUsingDirective:
10212 // FIXME: STATICS!
10213 return DeclarationName::getUsingDirectiveName();
10214 }
10215
10216 llvm_unreachable("Invalid DeclarationName Kind!");
10217}
10218
10219IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
10220 if (!FromId)
10221 return nullptr;
10222
10223 IdentifierInfo *ToId = &ToContext.Idents.get(Name: FromId->getName());
10224
10225 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
10226 ToId->setBuiltinID(FromId->getBuiltinID());
10227
10228 return ToId;
10229}
10230
10231Expected<Selector> ASTImporter::Import(Selector FromSel) {
10232 if (FromSel.isNull())
10233 return Selector{};
10234
10235 SmallVector<const IdentifierInfo *, 4> Idents;
10236 Idents.push_back(Elt: Import(FromId: FromSel.getIdentifierInfoForSlot(argIndex: 0)));
10237 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
10238 Idents.push_back(Elt: Import(FromId: FromSel.getIdentifierInfoForSlot(argIndex: I)));
10239 return ToContext.Selectors.getSelector(NumArgs: FromSel.getNumArgs(), IIV: Idents.data());
10240}
10241
10242llvm::Expected<APValue>
10243ASTNodeImporter::ImportAPValue(const APValue &FromValue) {
10244 APValue Result;
10245 llvm::Error Err = llvm::Error::success();
10246 auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) {
10247 for (unsigned Idx = 0; Idx < Size; Idx++) {
10248 APValue Tmp = importChecked(Err, From: From[Idx]);
10249 To[Idx] = Tmp;
10250 }
10251 };
10252 switch (FromValue.getKind()) {
10253 case APValue::None:
10254 case APValue::Indeterminate:
10255 case APValue::Int:
10256 case APValue::Float:
10257 case APValue::FixedPoint:
10258 case APValue::ComplexInt:
10259 case APValue::ComplexFloat:
10260 Result = FromValue;
10261 break;
10262 case APValue::Vector: {
10263 Result.MakeVector();
10264 MutableArrayRef<APValue> Elts =
10265 Result.setVectorUninit(FromValue.getVectorLength());
10266 ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts,
10267 Elts.data(), FromValue.getVectorLength());
10268 break;
10269 }
10270 case APValue::Array:
10271 Result.MakeArray(InitElts: FromValue.getArrayInitializedElts(),
10272 Size: FromValue.getArraySize());
10273 ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts,
10274 ((const APValue::Arr *)(const char *)&Result.Data)->Elts,
10275 FromValue.getArrayInitializedElts());
10276 break;
10277 case APValue::Struct:
10278 Result.MakeStruct(B: FromValue.getStructNumBases(),
10279 M: FromValue.getStructNumFields());
10280 ImportLoop(
10281 ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts,
10282 ((const APValue::StructData *)(const char *)&Result.Data)->Elts,
10283 FromValue.getStructNumBases() + FromValue.getStructNumFields());
10284 break;
10285 case APValue::Union: {
10286 Result.MakeUnion();
10287 const Decl *ImpFDecl = importChecked(Err, From: FromValue.getUnionField());
10288 APValue ImpValue = importChecked(Err, From: FromValue.getUnionValue());
10289 if (Err)
10290 return std::move(Err);
10291 Result.setUnion(Field: cast<FieldDecl>(Val: ImpFDecl), Value: ImpValue);
10292 break;
10293 }
10294 case APValue::AddrLabelDiff: {
10295 Result.MakeAddrLabelDiff();
10296 const Expr *ImpLHS = importChecked(Err, From: FromValue.getAddrLabelDiffLHS());
10297 const Expr *ImpRHS = importChecked(Err, From: FromValue.getAddrLabelDiffRHS());
10298 if (Err)
10299 return std::move(Err);
10300 Result.setAddrLabelDiff(LHSExpr: cast<AddrLabelExpr>(Val: ImpLHS),
10301 RHSExpr: cast<AddrLabelExpr>(Val: ImpRHS));
10302 break;
10303 }
10304 case APValue::MemberPointer: {
10305 const Decl *ImpMemPtrDecl =
10306 importChecked(Err, From: FromValue.getMemberPointerDecl());
10307 if (Err)
10308 return std::move(Err);
10309 MutableArrayRef<const CXXRecordDecl *> ToPath =
10310 Result.setMemberPointerUninit(
10311 Member: cast<const ValueDecl>(Val: ImpMemPtrDecl),
10312 IsDerivedMember: FromValue.isMemberPointerToDerivedMember(),
10313 Size: FromValue.getMemberPointerPath().size());
10314 llvm::ArrayRef<const CXXRecordDecl *> FromPath =
10315 Result.getMemberPointerPath();
10316 for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size();
10317 Idx++) {
10318 const Decl *ImpDecl = importChecked(Err, From: FromPath[Idx]);
10319 if (Err)
10320 return std::move(Err);
10321 ToPath[Idx] = cast<const CXXRecordDecl>(Val: ImpDecl->getCanonicalDecl());
10322 }
10323 break;
10324 }
10325 case APValue::LValue:
10326 APValue::LValueBase Base;
10327 QualType FromElemTy;
10328 if (FromValue.getLValueBase()) {
10329 assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() &&
10330 "in C++20 dynamic allocation are transient so they shouldn't "
10331 "appear in the AST");
10332 if (!FromValue.getLValueBase().is<TypeInfoLValue>()) {
10333 if (const auto *E =
10334 FromValue.getLValueBase().dyn_cast<const Expr *>()) {
10335 FromElemTy = E->getType();
10336 const Expr *ImpExpr = importChecked(Err, From: E);
10337 if (Err)
10338 return std::move(Err);
10339 Base = APValue::LValueBase(ImpExpr,
10340 FromValue.getLValueBase().getCallIndex(),
10341 FromValue.getLValueBase().getVersion());
10342 } else {
10343 FromElemTy =
10344 FromValue.getLValueBase().get<const ValueDecl *>()->getType();
10345 const Decl *ImpDecl = importChecked(
10346 Err, From: FromValue.getLValueBase().get<const ValueDecl *>());
10347 if (Err)
10348 return std::move(Err);
10349 Base = APValue::LValueBase(cast<ValueDecl>(Val: ImpDecl),
10350 FromValue.getLValueBase().getCallIndex(),
10351 FromValue.getLValueBase().getVersion());
10352 }
10353 } else {
10354 FromElemTy = FromValue.getLValueBase().getTypeInfoType();
10355 const Type *ImpTypeInfo = importChecked(
10356 Err, From: FromValue.getLValueBase().get<TypeInfoLValue>().getType());
10357 QualType ImpType =
10358 importChecked(Err, From: FromValue.getLValueBase().getTypeInfoType());
10359 if (Err)
10360 return std::move(Err);
10361 Base = APValue::LValueBase::getTypeInfo(LV: TypeInfoLValue(ImpTypeInfo),
10362 TypeInfo: ImpType);
10363 }
10364 }
10365 CharUnits Offset = FromValue.getLValueOffset();
10366 unsigned PathLength = FromValue.getLValuePath().size();
10367 Result.MakeLValue();
10368 if (FromValue.hasLValuePath()) {
10369 MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit(
10370 B: Base, O: Offset, Size: PathLength, OnePastTheEnd: FromValue.isLValueOnePastTheEnd(),
10371 IsNullPtr: FromValue.isNullPointer());
10372 llvm::ArrayRef<APValue::LValuePathEntry> FromPath =
10373 FromValue.getLValuePath();
10374 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) {
10375 if (FromElemTy->isRecordType()) {
10376 const Decl *FromDecl =
10377 FromPath[LoopIdx].getAsBaseOrMember().getPointer();
10378 const Decl *ImpDecl = importChecked(Err, From: FromDecl);
10379 if (Err)
10380 return std::move(Err);
10381 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FromDecl))
10382 FromElemTy = Importer.FromContext.getRecordType(Decl: RD);
10383 else
10384 FromElemTy = cast<ValueDecl>(Val: FromDecl)->getType();
10385 ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType(
10386 ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt()));
10387 } else {
10388 FromElemTy =
10389 Importer.FromContext.getAsArrayType(T: FromElemTy)->getElementType();
10390 ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex(
10391 Index: FromPath[LoopIdx].getAsArrayIndex());
10392 }
10393 }
10394 } else
10395 Result.setLValue(B: Base, O: Offset, APValue::NoLValuePath{},
10396 IsNullPtr: FromValue.isNullPointer());
10397 }
10398 if (Err)
10399 return std::move(Err);
10400 return Result;
10401}
10402
10403Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name,
10404 DeclContext *DC,
10405 unsigned IDNS,
10406 NamedDecl **Decls,
10407 unsigned NumDecls) {
10408 if (ODRHandling == ODRHandlingType::Conservative)
10409 // Report error at any name conflict.
10410 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
10411 else
10412 // Allow to create the new Decl with the same name.
10413 return Name;
10414}
10415
10416DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
10417 if (LastDiagFromFrom)
10418 ToContext.getDiagnostics().notePriorDiagnosticFrom(
10419 Other: FromContext.getDiagnostics());
10420 LastDiagFromFrom = false;
10421 return ToContext.getDiagnostics().Report(Loc, DiagID);
10422}
10423
10424DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
10425 if (!LastDiagFromFrom)
10426 FromContext.getDiagnostics().notePriorDiagnosticFrom(
10427 Other: ToContext.getDiagnostics());
10428 LastDiagFromFrom = true;
10429 return FromContext.getDiagnostics().Report(Loc, DiagID);
10430}
10431
10432void ASTImporter::CompleteDecl (Decl *D) {
10433 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
10434 if (!ID->getDefinition())
10435 ID->startDefinition();
10436 }
10437 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(Val: D)) {
10438 if (!PD->getDefinition())
10439 PD->startDefinition();
10440 }
10441 else if (auto *TD = dyn_cast<TagDecl>(Val: D)) {
10442 if (!TD->getDefinition() && !TD->isBeingDefined()) {
10443 TD->startDefinition();
10444 TD->setCompleteDefinition(true);
10445 }
10446 }
10447 else {
10448 assert(0 && "CompleteDecl called on a Decl that can't be completed");
10449 }
10450}
10451
10452Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
10453 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(Val: From);
10454 assert((Pos == ImportedDecls.end() || Pos->second == To) &&
10455 "Try to import an already imported Decl");
10456 if (Pos != ImportedDecls.end())
10457 return Pos->second;
10458 ImportedDecls[From] = To;
10459 // This mapping should be maintained only in this function. Therefore do not
10460 // check for additional consistency.
10461 ImportedFromDecls[To] = From;
10462 // In the case of TypedefNameDecl we create the Decl first and only then we
10463 // import and set its DeclContext. So, the DC is still not set when we reach
10464 // here from GetImportedOrCreateDecl.
10465 if (To->getDeclContext())
10466 AddToLookupTable(ToD: To);
10467 return To;
10468}
10469
10470std::optional<ASTImportError>
10471ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const {
10472 auto Pos = ImportDeclErrors.find(Val: FromD);
10473 if (Pos != ImportDeclErrors.end())
10474 return Pos->second;
10475 else
10476 return std::nullopt;
10477}
10478
10479void ASTImporter::setImportDeclError(Decl *From, ASTImportError Error) {
10480 auto InsertRes = ImportDeclErrors.insert(KV: {From, Error});
10481 (void)InsertRes;
10482 // Either we set the error for the first time, or we already had set one and
10483 // now we want to set the same error.
10484 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
10485}
10486
10487bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
10488 bool Complain) {
10489 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
10490 ImportedTypes.find(Val: From.getTypePtr());
10491 if (Pos != ImportedTypes.end()) {
10492 if (ExpectedType ToFromOrErr = Import(FromT: From)) {
10493 if (ToContext.hasSameType(T1: *ToFromOrErr, T2: To))
10494 return true;
10495 } else {
10496 llvm::consumeError(Err: ToFromOrErr.takeError());
10497 }
10498 }
10499
10500 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
10501 getStructuralEquivalenceKind(Importer: *this), false,
10502 Complain);
10503 return Ctx.IsEquivalent(T1: From, T2: To);
10504}
10505