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