1 //===-- ClangASTImporter.cpp ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/Module.h"
10 #include "lldb/Utility/LLDBAssert.h"
11 #include "lldb/Utility/LLDBLog.h"
12 #include "lldb/Utility/Log.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/Sema.h"
18 #include "llvm/Support/raw_ostream.h"
20 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
21 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
22 #include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
23 #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
24 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
25 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
30 using namespace lldb_private
;
31 using namespace clang
;
33 CompilerType
ClangASTImporter::CopyType(TypeSystemClang
&dst_ast
,
34 const CompilerType
&src_type
) {
35 clang::ASTContext
&dst_clang_ast
= dst_ast
.getASTContext();
37 auto src_ast
= src_type
.GetTypeSystem().dyn_cast_or_null
<TypeSystemClang
>();
39 return CompilerType();
41 clang::ASTContext
&src_clang_ast
= src_ast
->getASTContext();
43 clang::QualType src_qual_type
= ClangUtil::GetQualType(src_type
);
45 ImporterDelegateSP
delegate_sp(GetDelegate(&dst_clang_ast
, &src_clang_ast
));
47 return CompilerType();
49 ASTImporterDelegate::CxxModuleScope
std_scope(*delegate_sp
, &dst_clang_ast
);
51 llvm::Expected
<QualType
> ret_or_error
= delegate_sp
->Import(src_qual_type
);
53 Log
*log
= GetLog(LLDBLog::Expressions
);
54 LLDB_LOG_ERROR(log
, ret_or_error
.takeError(),
55 "Couldn't import type: {0}");
56 return CompilerType();
59 lldb::opaque_compiler_type_t dst_clang_type
= ret_or_error
->getAsOpaquePtr();
62 return CompilerType(dst_ast
.weak_from_this(), dst_clang_type
);
63 return CompilerType();
66 clang::Decl
*ClangASTImporter::CopyDecl(clang::ASTContext
*dst_ast
,
68 ImporterDelegateSP delegate_sp
;
70 clang::ASTContext
*src_ast
= &decl
->getASTContext();
71 delegate_sp
= GetDelegate(dst_ast
, src_ast
);
73 ASTImporterDelegate::CxxModuleScope
std_scope(*delegate_sp
, dst_ast
);
78 llvm::Expected
<clang::Decl
*> result
= delegate_sp
->Import(decl
);
80 Log
*log
= GetLog(LLDBLog::Expressions
);
81 LLDB_LOG_ERROR(log
, result
.takeError(), "Couldn't import decl: {0}");
83 lldb::user_id_t user_id
= LLDB_INVALID_UID
;
84 ClangASTMetadata
*metadata
= GetDeclMetadata(decl
);
86 user_id
= metadata
->GetUserID();
88 if (NamedDecl
*named_decl
= dyn_cast
<NamedDecl
>(decl
))
90 " [ClangASTImporter] WARNING: Failed to import a {0} "
91 "'{1}', metadata {2}",
92 decl
->getDeclKindName(), named_decl
->getNameAsString(),
96 " [ClangASTImporter] WARNING: Failed to import a {0}, "
98 decl
->getDeclKindName(), user_id
);
106 class DeclContextOverride
{
109 clang::DeclContext
*decl_context
;
110 clang::DeclContext
*lexical_decl_context
;
113 llvm::DenseMap
<clang::Decl
*, Backup
> m_backups
;
115 void OverrideOne(clang::Decl
*decl
) {
116 if (m_backups
.contains(decl
)) {
120 m_backups
[decl
] = {decl
->getDeclContext(), decl
->getLexicalDeclContext()};
122 decl
->setDeclContext(decl
->getASTContext().getTranslationUnitDecl());
123 decl
->setLexicalDeclContext(decl
->getASTContext().getTranslationUnitDecl());
126 bool ChainPassesThrough(
127 clang::Decl
*decl
, clang::DeclContext
*base
,
128 clang::DeclContext
*(clang::Decl::*contextFromDecl
)(),
129 clang::DeclContext
*(clang::DeclContext::*contextFromContext
)()) {
130 for (DeclContext
*decl_ctx
= (decl
->*contextFromDecl
)(); decl_ctx
;
131 decl_ctx
= (decl_ctx
->*contextFromContext
)()) {
132 if (decl_ctx
== base
) {
140 clang::Decl
*GetEscapedChild(clang::Decl
*decl
,
141 clang::DeclContext
*base
= nullptr) {
143 // decl's DeclContext chains must pass through base.
145 if (!ChainPassesThrough(decl
, base
, &clang::Decl::getDeclContext
,
146 &clang::DeclContext::getParent
) ||
147 !ChainPassesThrough(decl
, base
, &clang::Decl::getLexicalDeclContext
,
148 &clang::DeclContext::getLexicalParent
)) {
152 base
= clang::dyn_cast
<clang::DeclContext
>(decl
);
159 if (clang::DeclContext
*context
=
160 clang::dyn_cast
<clang::DeclContext
>(decl
)) {
161 for (clang::Decl
*decl
: context
->decls()) {
162 if (clang::Decl
*escaped_child
= GetEscapedChild(decl
)) {
163 return escaped_child
;
171 void Override(clang::Decl
*decl
) {
172 if (clang::Decl
*escaped_child
= GetEscapedChild(decl
)) {
173 Log
*log
= GetLog(LLDBLog::Expressions
);
176 " [ClangASTImporter] DeclContextOverride couldn't "
177 "override ({0}Decl*){1} - its child ({2}Decl*){3} escapes",
178 decl
->getDeclKindName(), decl
, escaped_child
->getDeclKindName(),
180 lldbassert(0 && "Couldn't override!");
187 DeclContextOverride() = default;
189 void OverrideAllDeclsFromContainingFunction(clang::Decl
*decl
) {
190 for (DeclContext
*decl_context
= decl
->getLexicalDeclContext();
191 decl_context
; decl_context
= decl_context
->getLexicalParent()) {
192 DeclContext
*redecl_context
= decl_context
->getRedeclContext();
194 if (llvm::isa
<FunctionDecl
>(redecl_context
) &&
195 llvm::isa
<TranslationUnitDecl
>(redecl_context
->getLexicalParent())) {
196 for (clang::Decl
*child_decl
: decl_context
->decls()) {
197 Override(child_decl
);
203 ~DeclContextOverride() {
204 for (const std::pair
<clang::Decl
*, Backup
> &backup
: m_backups
) {
205 backup
.first
->setDeclContext(backup
.second
.decl_context
);
206 backup
.first
->setLexicalDeclContext(backup
.second
.lexical_decl_context
);
212 /// Completes all imported TagDecls at the end of the scope.
214 /// While in a CompleteTagDeclsScope, every decl that could be completed will
215 /// be completed at the end of the scope (including all Decls that are
216 /// imported while completing the original Decls).
217 class CompleteTagDeclsScope
: public ClangASTImporter::NewDeclListener
{
218 ClangASTImporter::ImporterDelegateSP m_delegate
;
219 /// List of declarations in the target context that need to be completed.
220 /// Every declaration should only be completed once and therefore should only
221 /// be once in this list.
222 llvm::SetVector
<NamedDecl
*> m_decls_to_complete
;
223 /// Set of declarations that already were successfully completed (not just
224 /// added to m_decls_to_complete).
225 llvm::SmallPtrSet
<NamedDecl
*, 32> m_decls_already_completed
;
226 clang::ASTContext
*m_dst_ctx
;
227 clang::ASTContext
*m_src_ctx
;
228 ClangASTImporter
&importer
;
231 /// Constructs a CompleteTagDeclsScope.
232 /// \param importer The ClangASTImporter that we should observe.
233 /// \param dst_ctx The ASTContext to which Decls are imported.
234 /// \param src_ctx The ASTContext from which Decls are imported.
235 explicit CompleteTagDeclsScope(ClangASTImporter
&importer
,
236 clang::ASTContext
*dst_ctx
,
237 clang::ASTContext
*src_ctx
)
238 : m_delegate(importer
.GetDelegate(dst_ctx
, src_ctx
)), m_dst_ctx(dst_ctx
),
239 m_src_ctx(src_ctx
), importer(importer
) {
240 m_delegate
->SetImportListener(this);
243 ~CompleteTagDeclsScope() override
{
244 ClangASTImporter::ASTContextMetadataSP to_context_md
=
245 importer
.GetContextMetadata(m_dst_ctx
);
247 // Complete all decls we collected until now.
248 while (!m_decls_to_complete
.empty()) {
249 NamedDecl
*decl
= m_decls_to_complete
.pop_back_val();
250 m_decls_already_completed
.insert(decl
);
252 // The decl that should be completed has to be imported into the target
253 // context from some other context.
254 assert(to_context_md
->hasOrigin(decl
));
255 // We should only complete decls coming from the source context.
256 assert(to_context_md
->getOrigin(decl
).ctx
== m_src_ctx
);
258 Decl
*original_decl
= to_context_md
->getOrigin(decl
).decl
;
260 // Complete the decl now.
261 TypeSystemClang::GetCompleteDecl(m_src_ctx
, original_decl
);
262 if (auto *tag_decl
= dyn_cast
<TagDecl
>(decl
)) {
263 if (auto *original_tag_decl
= dyn_cast
<TagDecl
>(original_decl
)) {
264 if (original_tag_decl
->isCompleteDefinition()) {
265 m_delegate
->ImportDefinitionTo(tag_decl
, original_tag_decl
);
266 tag_decl
->setCompleteDefinition(true);
270 tag_decl
->setHasExternalLexicalStorage(false);
271 tag_decl
->setHasExternalVisibleStorage(false);
272 } else if (auto *container_decl
= dyn_cast
<ObjCContainerDecl
>(decl
)) {
273 container_decl
->setHasExternalLexicalStorage(false);
274 container_decl
->setHasExternalVisibleStorage(false);
277 to_context_md
->removeOrigin(decl
);
280 // Stop listening to imported decls. We do this after clearing the
281 // Decls we needed to import to catch all Decls they might have pulled in.
282 m_delegate
->RemoveImportListener();
285 void NewDeclImported(clang::Decl
*from
, clang::Decl
*to
) override
{
286 // Filter out decls that we can't complete later.
287 if (!isa
<TagDecl
>(to
) && !isa
<ObjCInterfaceDecl
>(to
))
289 RecordDecl
*from_record_decl
= dyn_cast
<RecordDecl
>(from
);
290 // We don't need to complete injected class name decls.
291 if (from_record_decl
&& from_record_decl
->isInjectedClassName())
294 NamedDecl
*to_named_decl
= dyn_cast
<NamedDecl
>(to
);
295 // Check if we already completed this type.
296 if (m_decls_already_completed
.contains(to_named_decl
))
298 // Queue this type to be completed.
299 m_decls_to_complete
.insert(to_named_decl
);
304 CompilerType
ClangASTImporter::DeportType(TypeSystemClang
&dst
,
305 const CompilerType
&src_type
) {
306 Log
*log
= GetLog(LLDBLog::Expressions
);
308 auto src_ctxt
= src_type
.GetTypeSystem().dyn_cast_or_null
<TypeSystemClang
>();
313 " [ClangASTImporter] DeportType called on ({0}Type*){1} "
314 "from (ASTContext*){2} to (ASTContext*){3}",
315 src_type
.GetTypeName(), src_type
.GetOpaqueQualType(),
316 &src_ctxt
->getASTContext(), &dst
.getASTContext());
318 DeclContextOverride decl_context_override
;
320 if (auto *t
= ClangUtil::GetQualType(src_type
)->getAs
<TagType
>())
321 decl_context_override
.OverrideAllDeclsFromContainingFunction(t
->getDecl());
323 CompleteTagDeclsScope
complete_scope(*this, &dst
.getASTContext(),
324 &src_ctxt
->getASTContext());
325 return CopyType(dst
, src_type
);
328 clang::Decl
*ClangASTImporter::DeportDecl(clang::ASTContext
*dst_ctx
,
330 Log
*log
= GetLog(LLDBLog::Expressions
);
332 clang::ASTContext
*src_ctx
= &decl
->getASTContext();
334 " [ClangASTImporter] DeportDecl called on ({0}Decl*){1} from "
335 "(ASTContext*){2} to (ASTContext*){3}",
336 decl
->getDeclKindName(), decl
, src_ctx
, dst_ctx
);
338 DeclContextOverride decl_context_override
;
340 decl_context_override
.OverrideAllDeclsFromContainingFunction(decl
);
344 CompleteTagDeclsScope
complete_scope(*this, dst_ctx
, src_ctx
);
345 result
= CopyDecl(dst_ctx
, decl
);
352 " [ClangASTImporter] DeportDecl deported ({0}Decl*){1} to "
354 decl
->getDeclKindName(), decl
, result
->getDeclKindName(), result
);
359 bool ClangASTImporter::CanImport(const CompilerType
&type
) {
360 if (!ClangUtil::IsClangType(type
))
363 clang::QualType
qual_type(
364 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type
)));
366 const clang::Type::TypeClass type_class
= qual_type
->getTypeClass();
367 switch (type_class
) {
368 case clang::Type::Record
: {
369 const clang::CXXRecordDecl
*cxx_record_decl
=
370 qual_type
->getAsCXXRecordDecl();
371 if (cxx_record_decl
) {
372 if (GetDeclOrigin(cxx_record_decl
).Valid())
377 case clang::Type::Enum
: {
378 clang::EnumDecl
*enum_decl
=
379 llvm::cast
<clang::EnumType
>(qual_type
)->getDecl();
381 if (GetDeclOrigin(enum_decl
).Valid())
386 case clang::Type::ObjCObject
:
387 case clang::Type::ObjCInterface
: {
388 const clang::ObjCObjectType
*objc_class_type
=
389 llvm::dyn_cast
<clang::ObjCObjectType
>(qual_type
);
390 if (objc_class_type
) {
391 clang::ObjCInterfaceDecl
*class_interface_decl
=
392 objc_class_type
->getInterface();
393 // We currently can't complete objective C types through the newly added
394 // ASTContext because it only supports TagDecl objects right now...
395 if (class_interface_decl
) {
396 if (GetDeclOrigin(class_interface_decl
).Valid())
402 case clang::Type::Typedef
:
403 return CanImport(CompilerType(type
.GetTypeSystem(),
404 llvm::cast
<clang::TypedefType
>(qual_type
)
406 ->getUnderlyingType()
409 case clang::Type::Auto
:
410 return CanImport(CompilerType(type
.GetTypeSystem(),
411 llvm::cast
<clang::AutoType
>(qual_type
)
415 case clang::Type::Elaborated
:
416 return CanImport(CompilerType(type
.GetTypeSystem(),
417 llvm::cast
<clang::ElaboratedType
>(qual_type
)
421 case clang::Type::Paren
:
422 return CanImport(CompilerType(
423 type
.GetTypeSystem(),
424 llvm::cast
<clang::ParenType
>(qual_type
)->desugar().getAsOpaquePtr()));
433 bool ClangASTImporter::Import(const CompilerType
&type
) {
434 if (!ClangUtil::IsClangType(type
))
437 clang::QualType
qual_type(
438 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type
)));
440 const clang::Type::TypeClass type_class
= qual_type
->getTypeClass();
441 switch (type_class
) {
442 case clang::Type::Record
: {
443 const clang::CXXRecordDecl
*cxx_record_decl
=
444 qual_type
->getAsCXXRecordDecl();
445 if (cxx_record_decl
) {
446 if (GetDeclOrigin(cxx_record_decl
).Valid())
447 return CompleteAndFetchChildren(qual_type
);
451 case clang::Type::Enum
: {
452 clang::EnumDecl
*enum_decl
=
453 llvm::cast
<clang::EnumType
>(qual_type
)->getDecl();
455 if (GetDeclOrigin(enum_decl
).Valid())
456 return CompleteAndFetchChildren(qual_type
);
460 case clang::Type::ObjCObject
:
461 case clang::Type::ObjCInterface
: {
462 const clang::ObjCObjectType
*objc_class_type
=
463 llvm::dyn_cast
<clang::ObjCObjectType
>(qual_type
);
464 if (objc_class_type
) {
465 clang::ObjCInterfaceDecl
*class_interface_decl
=
466 objc_class_type
->getInterface();
467 // We currently can't complete objective C types through the newly added
468 // ASTContext because it only supports TagDecl objects right now...
469 if (class_interface_decl
) {
470 if (GetDeclOrigin(class_interface_decl
).Valid())
471 return CompleteAndFetchChildren(qual_type
);
476 case clang::Type::Typedef
:
477 return Import(CompilerType(type
.GetTypeSystem(),
478 llvm::cast
<clang::TypedefType
>(qual_type
)
480 ->getUnderlyingType()
483 case clang::Type::Auto
:
484 return Import(CompilerType(type
.GetTypeSystem(),
485 llvm::cast
<clang::AutoType
>(qual_type
)
489 case clang::Type::Elaborated
:
490 return Import(CompilerType(type
.GetTypeSystem(),
491 llvm::cast
<clang::ElaboratedType
>(qual_type
)
495 case clang::Type::Paren
:
496 return Import(CompilerType(
497 type
.GetTypeSystem(),
498 llvm::cast
<clang::ParenType
>(qual_type
)->desugar().getAsOpaquePtr()));
506 bool ClangASTImporter::CompleteType(const CompilerType
&compiler_type
) {
507 if (!CanImport(compiler_type
))
510 if (Import(compiler_type
)) {
511 TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type
);
515 TypeSystemClang::SetHasExternalStorage(compiler_type
.GetOpaqueQualType(),
520 bool ClangASTImporter::LayoutRecordType(
521 const clang::RecordDecl
*record_decl
, uint64_t &bit_size
,
523 llvm::DenseMap
<const clang::FieldDecl
*, uint64_t> &field_offsets
,
524 llvm::DenseMap
<const clang::CXXRecordDecl
*, clang::CharUnits
>
526 llvm::DenseMap
<const clang::CXXRecordDecl
*, clang::CharUnits
>
528 RecordDeclToLayoutMap::iterator pos
=
529 m_record_decl_to_layout_map
.find(record_decl
);
530 bool success
= false;
531 base_offsets
.clear();
532 vbase_offsets
.clear();
533 if (pos
!= m_record_decl_to_layout_map
.end()) {
534 bit_size
= pos
->second
.bit_size
;
535 alignment
= pos
->second
.alignment
;
536 field_offsets
.swap(pos
->second
.field_offsets
);
537 base_offsets
.swap(pos
->second
.base_offsets
);
538 vbase_offsets
.swap(pos
->second
.vbase_offsets
);
539 m_record_decl_to_layout_map
.erase(pos
);
544 field_offsets
.clear();
549 void ClangASTImporter::SetRecordLayout(clang::RecordDecl
*decl
,
550 const LayoutInfo
&layout
) {
551 m_record_decl_to_layout_map
.insert(std::make_pair(decl
, layout
));
554 bool ClangASTImporter::CompleteTagDecl(clang::TagDecl
*decl
) {
555 DeclOrigin decl_origin
= GetDeclOrigin(decl
);
557 if (!decl_origin
.Valid())
560 if (!TypeSystemClang::GetCompleteDecl(decl_origin
.ctx
, decl_origin
.decl
))
563 ImporterDelegateSP
delegate_sp(
564 GetDelegate(&decl
->getASTContext(), decl_origin
.ctx
));
566 ASTImporterDelegate::CxxModuleScope
std_scope(*delegate_sp
,
567 &decl
->getASTContext());
569 delegate_sp
->ImportDefinitionTo(decl
, decl_origin
.decl
);
574 bool ClangASTImporter::CompleteTagDeclWithOrigin(clang::TagDecl
*decl
,
575 clang::TagDecl
*origin_decl
) {
576 clang::ASTContext
*origin_ast_ctx
= &origin_decl
->getASTContext();
578 if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx
, origin_decl
))
581 ImporterDelegateSP
delegate_sp(
582 GetDelegate(&decl
->getASTContext(), origin_ast_ctx
));
585 delegate_sp
->ImportDefinitionTo(decl
, origin_decl
);
587 ASTContextMetadataSP context_md
= GetContextMetadata(&decl
->getASTContext());
589 context_md
->setOrigin(decl
, DeclOrigin(origin_ast_ctx
, origin_decl
));
593 bool ClangASTImporter::CompleteObjCInterfaceDecl(
594 clang::ObjCInterfaceDecl
*interface_decl
) {
595 DeclOrigin decl_origin
= GetDeclOrigin(interface_decl
);
597 if (!decl_origin
.Valid())
600 if (!TypeSystemClang::GetCompleteDecl(decl_origin
.ctx
, decl_origin
.decl
))
603 ImporterDelegateSP
delegate_sp(
604 GetDelegate(&interface_decl
->getASTContext(), decl_origin
.ctx
));
607 delegate_sp
->ImportDefinitionTo(interface_decl
, decl_origin
.decl
);
609 if (ObjCInterfaceDecl
*super_class
= interface_decl
->getSuperClass())
610 RequireCompleteType(clang::QualType(super_class
->getTypeForDecl(), 0));
615 bool ClangASTImporter::CompleteAndFetchChildren(clang::QualType type
) {
616 if (!RequireCompleteType(type
))
619 Log
*log
= GetLog(LLDBLog::Expressions
);
621 if (const TagType
*tag_type
= type
->getAs
<TagType
>()) {
622 TagDecl
*tag_decl
= tag_type
->getDecl();
624 DeclOrigin decl_origin
= GetDeclOrigin(tag_decl
);
626 if (!decl_origin
.Valid())
629 ImporterDelegateSP
delegate_sp(
630 GetDelegate(&tag_decl
->getASTContext(), decl_origin
.ctx
));
632 ASTImporterDelegate::CxxModuleScope
std_scope(*delegate_sp
,
633 &tag_decl
->getASTContext());
635 TagDecl
*origin_tag_decl
= llvm::dyn_cast
<TagDecl
>(decl_origin
.decl
);
637 for (Decl
*origin_child_decl
: origin_tag_decl
->decls()) {
638 llvm::Expected
<Decl
*> imported_or_err
=
639 delegate_sp
->Import(origin_child_decl
);
640 if (!imported_or_err
) {
641 LLDB_LOG_ERROR(log
, imported_or_err
.takeError(),
642 "Couldn't import decl: {0}");
647 if (RecordDecl
*record_decl
= dyn_cast
<RecordDecl
>(origin_tag_decl
))
648 record_decl
->setHasLoadedFieldsFromExternalStorage(true);
653 if (const ObjCObjectType
*objc_object_type
= type
->getAs
<ObjCObjectType
>()) {
654 if (ObjCInterfaceDecl
*objc_interface_decl
=
655 objc_object_type
->getInterface()) {
656 DeclOrigin decl_origin
= GetDeclOrigin(objc_interface_decl
);
658 if (!decl_origin
.Valid())
661 ImporterDelegateSP
delegate_sp(
662 GetDelegate(&objc_interface_decl
->getASTContext(), decl_origin
.ctx
));
664 ObjCInterfaceDecl
*origin_interface_decl
=
665 llvm::dyn_cast
<ObjCInterfaceDecl
>(decl_origin
.decl
);
667 for (Decl
*origin_child_decl
: origin_interface_decl
->decls()) {
668 llvm::Expected
<Decl
*> imported_or_err
=
669 delegate_sp
->Import(origin_child_decl
);
670 if (!imported_or_err
) {
671 LLDB_LOG_ERROR(log
, imported_or_err
.takeError(),
672 "Couldn't import decl: {0}");
685 bool ClangASTImporter::RequireCompleteType(clang::QualType type
) {
689 if (const TagType
*tag_type
= type
->getAs
<TagType
>()) {
690 TagDecl
*tag_decl
= tag_type
->getDecl();
692 if (tag_decl
->getDefinition() || tag_decl
->isBeingDefined())
695 return CompleteTagDecl(tag_decl
);
697 if (const ObjCObjectType
*objc_object_type
= type
->getAs
<ObjCObjectType
>()) {
698 if (ObjCInterfaceDecl
*objc_interface_decl
=
699 objc_object_type
->getInterface())
700 return CompleteObjCInterfaceDecl(objc_interface_decl
);
703 if (const ArrayType
*array_type
= type
->getAsArrayTypeUnsafe())
704 return RequireCompleteType(array_type
->getElementType());
705 if (const AtomicType
*atomic_type
= type
->getAs
<AtomicType
>())
706 return RequireCompleteType(atomic_type
->getPointeeType());
711 ClangASTMetadata
*ClangASTImporter::GetDeclMetadata(const clang::Decl
*decl
) {
712 DeclOrigin decl_origin
= GetDeclOrigin(decl
);
714 if (decl_origin
.Valid()) {
715 TypeSystemClang
*ast
= TypeSystemClang::GetASTContext(decl_origin
.ctx
);
716 return ast
->GetMetadata(decl_origin
.decl
);
718 TypeSystemClang
*ast
= TypeSystemClang::GetASTContext(&decl
->getASTContext());
719 return ast
->GetMetadata(decl
);
722 ClangASTImporter::DeclOrigin
723 ClangASTImporter::GetDeclOrigin(const clang::Decl
*decl
) {
724 ASTContextMetadataSP context_md
= GetContextMetadata(&decl
->getASTContext());
726 return context_md
->getOrigin(decl
);
729 void ClangASTImporter::SetDeclOrigin(const clang::Decl
*decl
,
730 clang::Decl
*original_decl
) {
731 ASTContextMetadataSP context_md
= GetContextMetadata(&decl
->getASTContext());
732 context_md
->setOrigin(
733 decl
, DeclOrigin(&original_decl
->getASTContext(), original_decl
));
736 void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl
*decl
,
737 NamespaceMapSP
&namespace_map
) {
738 ASTContextMetadataSP context_md
= GetContextMetadata(&decl
->getASTContext());
740 context_md
->m_namespace_maps
[decl
] = namespace_map
;
743 ClangASTImporter::NamespaceMapSP
744 ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl
*decl
) {
745 ASTContextMetadataSP context_md
= GetContextMetadata(&decl
->getASTContext());
747 NamespaceMetaMap
&namespace_maps
= context_md
->m_namespace_maps
;
749 NamespaceMetaMap::iterator iter
= namespace_maps
.find(decl
);
751 if (iter
!= namespace_maps
.end())
753 return NamespaceMapSP();
756 void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl
*decl
) {
758 ASTContextMetadataSP context_md
= GetContextMetadata(&decl
->getASTContext());
760 const DeclContext
*parent_context
= decl
->getDeclContext();
761 const NamespaceDecl
*parent_namespace
=
762 dyn_cast
<NamespaceDecl
>(parent_context
);
763 NamespaceMapSP parent_map
;
765 if (parent_namespace
)
766 parent_map
= GetNamespaceMap(parent_namespace
);
768 NamespaceMapSP new_map
;
770 new_map
= std::make_shared
<NamespaceMap
>();
772 if (context_md
->m_map_completer
) {
773 std::string namespace_string
= decl
->getDeclName().getAsString();
775 context_md
->m_map_completer
->CompleteNamespaceMap(
776 new_map
, ConstString(namespace_string
.c_str()), parent_map
);
779 context_md
->m_namespace_maps
[decl
] = new_map
;
782 void ClangASTImporter::ForgetDestination(clang::ASTContext
*dst_ast
) {
783 Log
*log
= GetLog(LLDBLog::Expressions
);
786 " [ClangASTImporter] Forgetting destination (ASTContext*){0}",
789 m_metadata_map
.erase(dst_ast
);
792 void ClangASTImporter::ForgetSource(clang::ASTContext
*dst_ast
,
793 clang::ASTContext
*src_ast
) {
794 ASTContextMetadataSP md
= MaybeGetContextMetadata(dst_ast
);
796 Log
*log
= GetLog(LLDBLog::Expressions
);
799 " [ClangASTImporter] Forgetting source->dest "
800 "(ASTContext*){0}->(ASTContext*){1}",
806 md
->m_delegates
.erase(src_ast
);
807 md
->removeOriginsWithContext(src_ast
);
810 ClangASTImporter::MapCompleter::~MapCompleter() = default;
812 llvm::Expected
<Decl
*>
813 ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl
*From
) {
815 std::optional
<Decl
*> D
= m_std_handler
->Import(From
);
817 // Make sure we don't use this decl later to map it back to it's original
818 // decl. The decl the CxxModuleHandler created has nothing to do with
819 // the one from debug info, and linking those two would just cause the
820 // ASTImporter to try 'updating' the module decl with the minimal one from
822 m_decls_to_ignore
.insert(*D
);
827 // Check which ASTContext this declaration originally came from.
828 DeclOrigin origin
= m_main
.GetDeclOrigin(From
);
830 // Prevent infinite recursion when the origin tracking contains a cycle.
831 assert(origin
.decl
!= From
&& "Origin points to itself?");
833 // If it originally came from the target ASTContext then we can just
834 // pretend that the original is the one we imported. This can happen for
835 // example when inspecting a persistent declaration from the scratch
836 // ASTContext (which will provide the declaration when parsing the
837 // expression and then we later try to copy the declaration back to the
838 // scratch ASTContext to store the result).
839 // Without this check we would ask the ASTImporter to import a declaration
840 // into the same ASTContext where it came from (which doesn't make a lot of
842 if (origin
.Valid() && origin
.ctx
== &getToContext()) {
843 RegisterImportedDecl(From
, origin
.decl
);
847 // This declaration came originally from another ASTContext. Instead of
848 // copying our potentially incomplete 'From' Decl we instead go to the
849 // original ASTContext and copy the original to the target. This is not
850 // only faster than first completing our current decl and then copying it
851 // to the target, but it also prevents that indirectly copying the same
852 // declaration to the same target requires the ASTImporter to merge all
853 // the different decls that appear to come from different ASTContexts (even
854 // though all these different source ASTContexts just got a copy from
856 if (origin
.Valid()) {
857 auto R
= m_main
.CopyDecl(&getToContext(), origin
.decl
);
859 RegisterImportedDecl(From
, R
);
864 // If we have a forcefully completed type, try to find an actual definition
865 // for it in other modules.
866 const ClangASTMetadata
*md
= m_main
.GetDeclMetadata(From
);
867 auto *td
= dyn_cast
<TagDecl
>(From
);
868 if (td
&& md
&& md
->IsForcefullyCompleted()) {
869 Log
*log
= GetLog(LLDBLog::Expressions
);
871 "[ClangASTImporter] Searching for a complete definition of {0} in "
874 Expected
<DeclContext
*> dc_or_err
= ImportContext(td
->getDeclContext());
876 return dc_or_err
.takeError();
877 Expected
<DeclarationName
> dn_or_err
= Import(td
->getDeclName());
879 return dn_or_err
.takeError();
880 DeclContext
*dc
= *dc_or_err
;
881 DeclContext::lookup_result lr
= dc
->lookup(*dn_or_err
);
882 for (clang::Decl
*candidate
: lr
) {
883 if (candidate
->getKind() == From
->getKind()) {
884 RegisterImportedDecl(From
, candidate
);
885 m_decls_to_ignore
.insert(candidate
);
889 LLDB_LOG(log
, "[ClangASTImporter] Complete definition not found");
892 return ASTImporter::ImportImpl(From
);
895 void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(
896 clang::Decl
*to
, clang::Decl
*from
) {
897 // We might have a forward declaration from a shared library that we
898 // gave external lexical storage so that Clang asks us about the full
899 // definition when it needs it. In this case the ASTImporter isn't aware
900 // that the forward decl from the shared library is the actual import
901 // target but would create a second declaration that would then be defined.
902 // We want that 'to' is actually complete after this function so let's
903 // tell the ASTImporter that 'to' was imported from 'from'.
904 MapImported(from
, to
);
906 Log
*log
= GetLog(LLDBLog::Expressions
);
908 if (llvm::Error err
= ImportDefinition(from
)) {
909 LLDB_LOG_ERROR(log
, std::move(err
),
910 "[ClangASTImporter] Error during importing definition: {0}");
914 if (clang::TagDecl
*to_tag
= dyn_cast
<clang::TagDecl
>(to
)) {
915 if (clang::TagDecl
*from_tag
= dyn_cast
<clang::TagDecl
>(from
)) {
916 to_tag
->setCompleteDefinition(from_tag
->isCompleteDefinition());
918 if (Log
*log_ast
= GetLog(LLDBLog::AST
)) {
919 std::string name_string
;
920 if (NamedDecl
*from_named_decl
= dyn_cast
<clang::NamedDecl
>(from
)) {
921 llvm::raw_string_ostream
name_stream(name_string
);
922 from_named_decl
->printName(name_stream
);
925 LLDB_LOG(log_ast
, "==== [ClangASTImporter][TUDecl: {0}] Imported "
926 "({1}Decl*){2}, named {3} (from "
928 static_cast<void *>(to
->getTranslationUnitDecl()),
929 from
->getDeclKindName(), static_cast<void *>(to
), name_string
,
930 static_cast<void *>(from
));
932 // Log the AST of the TU.
933 std::string ast_string
;
934 llvm::raw_string_ostream
ast_stream(ast_string
);
935 to
->getTranslationUnitDecl()->dump(ast_stream
);
936 LLDB_LOG(log_ast
, "{0}", ast_string
);
941 // If we're dealing with an Objective-C class, ensure that the inheritance
942 // has been set up correctly. The ASTImporter may not do this correctly if
943 // the class was originally sourced from symbols.
945 if (ObjCInterfaceDecl
*to_objc_interface
= dyn_cast
<ObjCInterfaceDecl
>(to
)) {
947 ObjCInterfaceDecl
*to_superclass
= to_objc_interface
->getSuperClass();
950 break; // we're not going to override it if it's set
952 ObjCInterfaceDecl
*from_objc_interface
=
953 dyn_cast
<ObjCInterfaceDecl
>(from
);
955 if (!from_objc_interface
)
958 ObjCInterfaceDecl
*from_superclass
= from_objc_interface
->getSuperClass();
960 if (!from_superclass
)
963 llvm::Expected
<Decl
*> imported_from_superclass_decl
=
964 Import(from_superclass
);
966 if (!imported_from_superclass_decl
) {
967 LLDB_LOG_ERROR(log
, imported_from_superclass_decl
.takeError(),
968 "Couldn't import decl: {0}");
972 ObjCInterfaceDecl
*imported_from_superclass
=
973 dyn_cast
<ObjCInterfaceDecl
>(*imported_from_superclass_decl
);
975 if (!imported_from_superclass
)
978 if (!to_objc_interface
->hasDefinition())
979 to_objc_interface
->startDefinition();
981 to_objc_interface
->setSuperClass(m_source_ctx
->getTrivialTypeSourceInfo(
982 m_source_ctx
->getObjCInterfaceType(imported_from_superclass
)));
987 /// Takes a CXXMethodDecl and completes the return type if necessary. This
988 /// is currently only necessary for virtual functions with covariant return
989 /// types where Clang's CodeGen expects that the underlying records are already
991 static void MaybeCompleteReturnType(ClangASTImporter
&importer
,
992 CXXMethodDecl
*to_method
) {
993 if (!to_method
->isVirtual())
995 QualType return_type
= to_method
->getReturnType();
996 if (!return_type
->isPointerType() && !return_type
->isReferenceType())
999 clang::RecordDecl
*rd
= return_type
->getPointeeType()->getAsRecordDecl();
1002 if (rd
->getDefinition())
1005 importer
.CompleteTagDecl(rd
);
1008 /// Recreate a module with its parents in \p to_source and return its id.
1009 static OptionalClangModuleID
1010 RemapModule(OptionalClangModuleID from_id
,
1011 ClangExternalASTSourceCallbacks
&from_source
,
1012 ClangExternalASTSourceCallbacks
&to_source
) {
1013 if (!from_id
.HasValue())
1015 clang::Module
*module
= from_source
.getModule(from_id
.GetValue());
1016 OptionalClangModuleID parent
= RemapModule(
1017 from_source
.GetIDForModule(module
->Parent
), from_source
, to_source
);
1018 TypeSystemClang
&to_ts
= to_source
.GetTypeSystem();
1019 return to_ts
.GetOrCreateClangModule(module
->Name
, parent
, module
->IsFramework
,
1020 module
->IsExplicit
);
1023 void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl
*from
,
1025 Log
*log
= GetLog(LLDBLog::Expressions
);
1027 // Some decls shouldn't be tracked here because they were not created by
1028 // copying 'from' to 'to'. Just exit early for those.
1029 if (m_decls_to_ignore
.count(to
))
1032 // Transfer module ownership information.
1033 auto *from_source
= llvm::dyn_cast_or_null
<ClangExternalASTSourceCallbacks
>(
1034 getFromContext().getExternalSource());
1035 // Can also be a ClangASTSourceProxy.
1036 auto *to_source
= llvm::dyn_cast_or_null
<ClangExternalASTSourceCallbacks
>(
1037 getToContext().getExternalSource());
1038 if (from_source
&& to_source
) {
1039 OptionalClangModuleID
from_id(from
->getOwningModuleID());
1040 OptionalClangModuleID to_id
=
1041 RemapModule(from_id
, *from_source
, *to_source
);
1042 TypeSystemClang
&to_ts
= to_source
->GetTypeSystem();
1043 to_ts
.SetOwningModule(to
, to_id
);
1046 lldb::user_id_t user_id
= LLDB_INVALID_UID
;
1047 ClangASTMetadata
*metadata
= m_main
.GetDeclMetadata(from
);
1049 user_id
= metadata
->GetUserID();
1052 if (NamedDecl
*from_named_decl
= dyn_cast
<clang::NamedDecl
>(from
)) {
1053 std::string name_string
;
1054 llvm::raw_string_ostream
name_stream(name_string
);
1055 from_named_decl
->printName(name_stream
);
1056 name_stream
.flush();
1059 " [ClangASTImporter] Imported ({0}Decl*){1}, named {2} (from "
1060 "(Decl*){3}), metadata {4}",
1061 from
->getDeclKindName(), to
, name_string
, from
, user_id
);
1064 " [ClangASTImporter] Imported ({0}Decl*){1} (from "
1065 "(Decl*){2}), metadata {3}",
1066 from
->getDeclKindName(), to
, from
, user_id
);
1070 ASTContextMetadataSP to_context_md
=
1071 m_main
.GetContextMetadata(&to
->getASTContext());
1072 ASTContextMetadataSP from_context_md
=
1073 m_main
.MaybeGetContextMetadata(m_source_ctx
);
1075 if (from_context_md
) {
1076 DeclOrigin origin
= from_context_md
->getOrigin(from
);
1078 if (origin
.Valid()) {
1079 if (origin
.ctx
!= &to
->getASTContext()) {
1080 if (!to_context_md
->hasOrigin(to
) || user_id
!= LLDB_INVALID_UID
)
1081 to_context_md
->setOrigin(to
, origin
);
1084 " [ClangASTImporter] Propagated origin "
1085 "(Decl*){0}/(ASTContext*){1} from (ASTContext*){2} to "
1087 origin
.decl
, origin
.ctx
, &from
->getASTContext(),
1088 &to
->getASTContext());
1091 if (m_new_decl_listener
)
1092 m_new_decl_listener
->NewDeclImported(from
, to
);
1094 if (!to_context_md
->hasOrigin(to
) || user_id
!= LLDB_INVALID_UID
)
1095 to_context_md
->setOrigin(to
, DeclOrigin(m_source_ctx
, from
));
1098 " [ClangASTImporter] Decl has no origin information in "
1100 &from
->getASTContext());
1103 if (auto *to_namespace
= dyn_cast
<clang::NamespaceDecl
>(to
)) {
1104 auto *from_namespace
= cast
<clang::NamespaceDecl
>(from
);
1106 NamespaceMetaMap
&namespace_maps
= from_context_md
->m_namespace_maps
;
1108 NamespaceMetaMap::iterator namespace_map_iter
=
1109 namespace_maps
.find(from_namespace
);
1111 if (namespace_map_iter
!= namespace_maps
.end())
1112 to_context_md
->m_namespace_maps
[to_namespace
] =
1113 namespace_map_iter
->second
;
1116 to_context_md
->setOrigin(to
, DeclOrigin(m_source_ctx
, from
));
1119 " [ClangASTImporter] Sourced origin "
1120 "(Decl*){0}/(ASTContext*){1} into (ASTContext*){2}",
1121 from
, m_source_ctx
, &to
->getASTContext());
1124 if (auto *to_tag_decl
= dyn_cast
<TagDecl
>(to
)) {
1125 to_tag_decl
->setHasExternalLexicalStorage();
1126 to_tag_decl
->getPrimaryContext()->setMustBuildLookupTable();
1127 auto from_tag_decl
= cast
<TagDecl
>(from
);
1131 " [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",
1132 (to_tag_decl
->hasExternalLexicalStorage() ? " Lexical" : ""),
1133 (to_tag_decl
->hasExternalVisibleStorage() ? " Visible" : ""),
1134 (from_tag_decl
->isCompleteDefinition() ? "complete" : "incomplete"),
1135 (to_tag_decl
->isCompleteDefinition() ? "complete" : "incomplete"));
1138 if (auto *to_namespace_decl
= dyn_cast
<NamespaceDecl
>(to
)) {
1139 m_main
.BuildNamespaceMap(to_namespace_decl
);
1140 to_namespace_decl
->setHasExternalVisibleStorage();
1143 if (auto *to_container_decl
= dyn_cast
<ObjCContainerDecl
>(to
)) {
1144 to_container_decl
->setHasExternalLexicalStorage();
1145 to_container_decl
->setHasExternalVisibleStorage();
1148 if (ObjCInterfaceDecl
*to_interface_decl
=
1149 llvm::dyn_cast
<ObjCInterfaceDecl
>(to_container_decl
)) {
1152 " [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1154 (to_interface_decl
->hasExternalLexicalStorage() ? " Lexical" : ""),
1155 (to_interface_decl
->hasExternalVisibleStorage() ? " Visible" : ""),
1156 (to_interface_decl
->hasDefinition() ? " HasDefinition" : ""));
1159 log
, " [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",
1160 ((Decl
*)to_container_decl
)->getDeclKindName(),
1161 (to_container_decl
->hasExternalLexicalStorage() ? " Lexical" : ""),
1162 (to_container_decl
->hasExternalVisibleStorage() ? " Visible" : ""));
1167 if (clang::CXXMethodDecl
*to_method
= dyn_cast
<CXXMethodDecl
>(to
))
1168 MaybeCompleteReturnType(m_main
, to_method
);
1172 ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl
*To
) {
1173 return m_main
.GetDeclOrigin(To
).decl
;