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