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