Path: blob/main/contrib/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
39654 views
//===-- ClangASTImporter.cpp ----------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Core/Module.h"9#include "lldb/Utility/LLDBAssert.h"10#include "lldb/Utility/LLDBLog.h"11#include "lldb/Utility/Log.h"12#include "clang/AST/ASTContext.h"13#include "clang/AST/Decl.h"14#include "clang/AST/DeclCXX.h"15#include "clang/AST/DeclObjC.h"16#include "clang/AST/RecordLayout.h"17#include "clang/Sema/Lookup.h"18#include "clang/Sema/Sema.h"19#include "llvm/Support/raw_ostream.h"2021#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"22#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"23#include "Plugins/ExpressionParser/Clang/ClangASTSource.h"24#include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"25#include "Plugins/ExpressionParser/Clang/ClangUtil.h"26#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"2728#include <memory>29#include <optional>30#include <type_traits>3132using namespace lldb_private;33using namespace clang;3435CompilerType ClangASTImporter::CopyType(TypeSystemClang &dst_ast,36const CompilerType &src_type) {37clang::ASTContext &dst_clang_ast = dst_ast.getASTContext();3839auto src_ast = src_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();40if (!src_ast)41return CompilerType();4243clang::ASTContext &src_clang_ast = src_ast->getASTContext();4445clang::QualType src_qual_type = ClangUtil::GetQualType(src_type);4647ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast));48if (!delegate_sp)49return CompilerType();5051ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast);5253llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type);54if (!ret_or_error) {55Log *log = GetLog(LLDBLog::Expressions);56LLDB_LOG_ERROR(log, ret_or_error.takeError(),57"Couldn't import type: {0}");58return CompilerType();59}6061lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr();6263if (dst_clang_type)64return CompilerType(dst_ast.weak_from_this(), dst_clang_type);65return CompilerType();66}6768clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast,69clang::Decl *decl) {70ImporterDelegateSP delegate_sp;7172clang::ASTContext *src_ast = &decl->getASTContext();73delegate_sp = GetDelegate(dst_ast, src_ast);7475ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);7677if (!delegate_sp)78return nullptr;7980llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl);81if (!result) {82Log *log = GetLog(LLDBLog::Expressions);83LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");84if (log) {85lldb::user_id_t user_id = LLDB_INVALID_UID;86ClangASTMetadata *metadata = GetDeclMetadata(decl);87if (metadata)88user_id = metadata->GetUserID();8990if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl))91LLDB_LOG(log,92" [ClangASTImporter] WARNING: Failed to import a {0} "93"'{1}', metadata {2}",94decl->getDeclKindName(), named_decl->getNameAsString(),95user_id);96else97LLDB_LOG(log,98" [ClangASTImporter] WARNING: Failed to import a {0}, "99"metadata {1}",100decl->getDeclKindName(), user_id);101}102return nullptr;103}104105return *result;106}107108class DeclContextOverride {109private:110struct Backup {111clang::DeclContext *decl_context;112clang::DeclContext *lexical_decl_context;113};114115llvm::DenseMap<clang::Decl *, Backup> m_backups;116117void OverrideOne(clang::Decl *decl) {118if (m_backups.contains(decl)) {119return;120}121122m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()};123124decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl());125decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl());126}127128bool ChainPassesThrough(129clang::Decl *decl, clang::DeclContext *base,130clang::DeclContext *(clang::Decl::*contextFromDecl)(),131clang::DeclContext *(clang::DeclContext::*contextFromContext)()) {132for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx;133decl_ctx = (decl_ctx->*contextFromContext)()) {134if (decl_ctx == base) {135return true;136}137}138139return false;140}141142clang::Decl *GetEscapedChild(clang::Decl *decl,143clang::DeclContext *base = nullptr) {144if (base) {145// decl's DeclContext chains must pass through base.146147if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext,148&clang::DeclContext::getParent) ||149!ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext,150&clang::DeclContext::getLexicalParent)) {151return decl;152}153} else {154base = clang::dyn_cast<clang::DeclContext>(decl);155156if (!base) {157return nullptr;158}159}160161if (clang::DeclContext *context =162clang::dyn_cast<clang::DeclContext>(decl)) {163for (clang::Decl *decl : context->decls()) {164if (clang::Decl *escaped_child = GetEscapedChild(decl)) {165return escaped_child;166}167}168}169170return nullptr;171}172173void Override(clang::Decl *decl) {174if (clang::Decl *escaped_child = GetEscapedChild(decl)) {175Log *log = GetLog(LLDBLog::Expressions);176177LLDB_LOG(log,178" [ClangASTImporter] DeclContextOverride couldn't "179"override ({0}Decl*){1} - its child ({2}Decl*){3} escapes",180decl->getDeclKindName(), decl, escaped_child->getDeclKindName(),181escaped_child);182lldbassert(0 && "Couldn't override!");183}184185OverrideOne(decl);186}187188public:189DeclContextOverride() = default;190191void OverrideAllDeclsFromContainingFunction(clang::Decl *decl) {192for (DeclContext *decl_context = decl->getLexicalDeclContext();193decl_context; decl_context = decl_context->getLexicalParent()) {194DeclContext *redecl_context = decl_context->getRedeclContext();195196if (llvm::isa<FunctionDecl>(redecl_context) &&197llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())) {198for (clang::Decl *child_decl : decl_context->decls()) {199Override(child_decl);200}201}202}203}204205~DeclContextOverride() {206for (const std::pair<clang::Decl *, Backup> &backup : m_backups) {207backup.first->setDeclContext(backup.second.decl_context);208backup.first->setLexicalDeclContext(backup.second.lexical_decl_context);209}210}211};212213namespace {214/// Completes all imported TagDecls at the end of the scope.215///216/// While in a CompleteTagDeclsScope, every decl that could be completed will217/// be completed at the end of the scope (including all Decls that are218/// imported while completing the original Decls).219class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener {220ClangASTImporter::ImporterDelegateSP m_delegate;221/// List of declarations in the target context that need to be completed.222/// Every declaration should only be completed once and therefore should only223/// be once in this list.224llvm::SetVector<NamedDecl *> m_decls_to_complete;225/// Set of declarations that already were successfully completed (not just226/// added to m_decls_to_complete).227llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed;228clang::ASTContext *m_dst_ctx;229clang::ASTContext *m_src_ctx;230ClangASTImporter &importer;231232public:233/// Constructs a CompleteTagDeclsScope.234/// \param importer The ClangASTImporter that we should observe.235/// \param dst_ctx The ASTContext to which Decls are imported.236/// \param src_ctx The ASTContext from which Decls are imported.237explicit CompleteTagDeclsScope(ClangASTImporter &importer,238clang::ASTContext *dst_ctx,239clang::ASTContext *src_ctx)240: m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx),241m_src_ctx(src_ctx), importer(importer) {242m_delegate->SetImportListener(this);243}244245~CompleteTagDeclsScope() override {246ClangASTImporter::ASTContextMetadataSP to_context_md =247importer.GetContextMetadata(m_dst_ctx);248249// Complete all decls we collected until now.250while (!m_decls_to_complete.empty()) {251NamedDecl *decl = m_decls_to_complete.pop_back_val();252m_decls_already_completed.insert(decl);253254// The decl that should be completed has to be imported into the target255// context from some other context.256assert(to_context_md->hasOrigin(decl));257// We should only complete decls coming from the source context.258assert(to_context_md->getOrigin(decl).ctx == m_src_ctx);259260Decl *original_decl = to_context_md->getOrigin(decl).decl;261262// Complete the decl now.263TypeSystemClang::GetCompleteDecl(m_src_ctx, original_decl);264if (auto *tag_decl = dyn_cast<TagDecl>(decl)) {265if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {266if (original_tag_decl->isCompleteDefinition()) {267m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl);268tag_decl->setCompleteDefinition(true);269}270}271272tag_decl->setHasExternalLexicalStorage(false);273tag_decl->setHasExternalVisibleStorage(false);274} else if (auto *container_decl = dyn_cast<ObjCContainerDecl>(decl)) {275container_decl->setHasExternalLexicalStorage(false);276container_decl->setHasExternalVisibleStorage(false);277}278279to_context_md->removeOrigin(decl);280}281282// Stop listening to imported decls. We do this after clearing the283// Decls we needed to import to catch all Decls they might have pulled in.284m_delegate->RemoveImportListener();285}286287void NewDeclImported(clang::Decl *from, clang::Decl *to) override {288// Filter out decls that we can't complete later.289if (!isa<TagDecl>(to) && !isa<ObjCInterfaceDecl>(to))290return;291RecordDecl *from_record_decl = dyn_cast<RecordDecl>(from);292// We don't need to complete injected class name decls.293if (from_record_decl && from_record_decl->isInjectedClassName())294return;295296NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to);297// Check if we already completed this type.298if (m_decls_already_completed.contains(to_named_decl))299return;300// Queue this type to be completed.301m_decls_to_complete.insert(to_named_decl);302}303};304} // namespace305306CompilerType ClangASTImporter::DeportType(TypeSystemClang &dst,307const CompilerType &src_type) {308Log *log = GetLog(LLDBLog::Expressions);309310auto src_ctxt = src_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();311if (!src_ctxt)312return {};313314LLDB_LOG(log,315" [ClangASTImporter] DeportType called on ({0}Type*){1:x} "316"from (ASTContext*){2:x} to (ASTContext*){3:x}",317src_type.GetTypeName(), src_type.GetOpaqueQualType(),318&src_ctxt->getASTContext(), &dst.getASTContext());319320DeclContextOverride decl_context_override;321322if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>())323decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl());324325CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),326&src_ctxt->getASTContext());327return CopyType(dst, src_type);328}329330clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,331clang::Decl *decl) {332Log *log = GetLog(LLDBLog::Expressions);333334clang::ASTContext *src_ctx = &decl->getASTContext();335LLDB_LOG(log,336" [ClangASTImporter] DeportDecl called on ({0}Decl*){1:x} from "337"(ASTContext*){2:x} to (ASTContext*){3:x}",338decl->getDeclKindName(), decl, src_ctx, dst_ctx);339340DeclContextOverride decl_context_override;341342decl_context_override.OverrideAllDeclsFromContainingFunction(decl);343344clang::Decl *result;345{346CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);347result = CopyDecl(dst_ctx, decl);348}349350if (!result)351return nullptr;352353LLDB_LOG(log,354" [ClangASTImporter] DeportDecl deported ({0}Decl*){1:x} to "355"({2}Decl*){3:x}",356decl->getDeclKindName(), decl, result->getDeclKindName(), result);357358return result;359}360361bool ClangASTImporter::CanImport(const CompilerType &type) {362if (!ClangUtil::IsClangType(type))363return false;364365clang::QualType qual_type(366ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));367368const clang::Type::TypeClass type_class = qual_type->getTypeClass();369switch (type_class) {370case clang::Type::Record: {371const clang::CXXRecordDecl *cxx_record_decl =372qual_type->getAsCXXRecordDecl();373if (cxx_record_decl) {374if (GetDeclOrigin(cxx_record_decl).Valid())375return true;376}377} break;378379case clang::Type::Enum: {380clang::EnumDecl *enum_decl =381llvm::cast<clang::EnumType>(qual_type)->getDecl();382if (enum_decl) {383if (GetDeclOrigin(enum_decl).Valid())384return true;385}386} break;387388case clang::Type::ObjCObject:389case clang::Type::ObjCInterface: {390const clang::ObjCObjectType *objc_class_type =391llvm::dyn_cast<clang::ObjCObjectType>(qual_type);392if (objc_class_type) {393clang::ObjCInterfaceDecl *class_interface_decl =394objc_class_type->getInterface();395// We currently can't complete objective C types through the newly added396// ASTContext because it only supports TagDecl objects right now...397if (class_interface_decl) {398if (GetDeclOrigin(class_interface_decl).Valid())399return true;400}401}402} break;403404case clang::Type::Typedef:405return CanImport(CompilerType(type.GetTypeSystem(),406llvm::cast<clang::TypedefType>(qual_type)407->getDecl()408->getUnderlyingType()409.getAsOpaquePtr()));410411case clang::Type::Auto:412return CanImport(CompilerType(type.GetTypeSystem(),413llvm::cast<clang::AutoType>(qual_type)414->getDeducedType()415.getAsOpaquePtr()));416417case clang::Type::Elaborated:418return CanImport(CompilerType(type.GetTypeSystem(),419llvm::cast<clang::ElaboratedType>(qual_type)420->getNamedType()421.getAsOpaquePtr()));422423case clang::Type::Paren:424return CanImport(CompilerType(425type.GetTypeSystem(),426llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));427428default:429break;430}431432return false;433}434435bool ClangASTImporter::Import(const CompilerType &type) {436if (!ClangUtil::IsClangType(type))437return false;438439clang::QualType qual_type(440ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));441442const clang::Type::TypeClass type_class = qual_type->getTypeClass();443switch (type_class) {444case clang::Type::Record: {445const clang::CXXRecordDecl *cxx_record_decl =446qual_type->getAsCXXRecordDecl();447if (cxx_record_decl) {448if (GetDeclOrigin(cxx_record_decl).Valid())449return CompleteAndFetchChildren(qual_type);450}451} break;452453case clang::Type::Enum: {454clang::EnumDecl *enum_decl =455llvm::cast<clang::EnumType>(qual_type)->getDecl();456if (enum_decl) {457if (GetDeclOrigin(enum_decl).Valid())458return CompleteAndFetchChildren(qual_type);459}460} break;461462case clang::Type::ObjCObject:463case clang::Type::ObjCInterface: {464const clang::ObjCObjectType *objc_class_type =465llvm::dyn_cast<clang::ObjCObjectType>(qual_type);466if (objc_class_type) {467clang::ObjCInterfaceDecl *class_interface_decl =468objc_class_type->getInterface();469// We currently can't complete objective C types through the newly added470// ASTContext because it only supports TagDecl objects right now...471if (class_interface_decl) {472if (GetDeclOrigin(class_interface_decl).Valid())473return CompleteAndFetchChildren(qual_type);474}475}476} break;477478case clang::Type::Typedef:479return Import(CompilerType(type.GetTypeSystem(),480llvm::cast<clang::TypedefType>(qual_type)481->getDecl()482->getUnderlyingType()483.getAsOpaquePtr()));484485case clang::Type::Auto:486return Import(CompilerType(type.GetTypeSystem(),487llvm::cast<clang::AutoType>(qual_type)488->getDeducedType()489.getAsOpaquePtr()));490491case clang::Type::Elaborated:492return Import(CompilerType(type.GetTypeSystem(),493llvm::cast<clang::ElaboratedType>(qual_type)494->getNamedType()495.getAsOpaquePtr()));496497case clang::Type::Paren:498return Import(CompilerType(499type.GetTypeSystem(),500llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));501502default:503break;504}505return false;506}507508bool ClangASTImporter::CompleteType(const CompilerType &compiler_type) {509if (!CanImport(compiler_type))510return false;511512if (Import(compiler_type)) {513TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type);514return true;515}516517TypeSystemClang::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),518false);519return false;520}521522/// Copy layout information from \ref source_map to the \ref destination_map.523///524/// In the process of copying over layout info, we may need to import525/// decls from the \ref source_map. This function will use the supplied526/// \ref importer to import the necessary decls into \ref dest_ctx.527///528/// \param[in,out] dest_ctx Destination ASTContext into which we import529/// decls from the \ref source_map.530/// \param[out] destination_map A map from decls in \ref dest_ctx to an531/// integral offest, which will be copies532/// of the decl/offest pairs in \ref source_map533/// if successful.534/// \param[in] source_map A map from decls to integral offests. These will535/// be copied into \ref destination_map.536/// \param[in,out] importer Used to import decls into \ref dest_ctx.537///538/// \returns On success, will return 'true' and the offsets in \ref539/// destination_map540/// are usable copies of \ref source_map.541template <class D, class O>542static bool ImportOffsetMap(clang::ASTContext *dest_ctx,543llvm::DenseMap<const D *, O> &destination_map,544llvm::DenseMap<const D *, O> &source_map,545ClangASTImporter &importer) {546// When importing fields into a new record, clang has a hard requirement that547// fields be imported in field offset order. Since they are stored in a548// DenseMap with a pointer as the key type, this means we cannot simply549// iterate over the map, as the order will be non-deterministic. Instead we550// have to sort by the offset and then insert in sorted order.551typedef llvm::DenseMap<const D *, O> MapType;552typedef typename MapType::value_type PairType;553std::vector<PairType> sorted_items;554sorted_items.reserve(source_map.size());555sorted_items.assign(source_map.begin(), source_map.end());556llvm::sort(sorted_items, llvm::less_second());557558for (const auto &item : sorted_items) {559DeclFromUser<D> user_decl(const_cast<D *>(item.first));560DeclFromParser<D> parser_decl(user_decl.Import(dest_ctx, importer));561if (parser_decl.IsInvalid())562return false;563destination_map.insert(564std::pair<const D *, O>(parser_decl.decl, item.second));565}566567return true;568}569570/// Given a CXXRecordDecl, will calculate and populate \ref base_offsets571/// with the integral offsets of any of its (possibly virtual) base classes.572///573/// \param[in] record_layout ASTRecordLayout of \ref record.574/// \param[in] record The record that we're calculating the base layouts of.575/// \param[out] base_offsets Map of base-class decl to integral offset which576/// this function will fill in.577///578/// \returns On success, will return 'true' and the offsets in \ref base_offsets579/// are usable.580template <bool IsVirtual>581bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,582DeclFromUser<const CXXRecordDecl> &record,583llvm::DenseMap<const clang::CXXRecordDecl *,584clang::CharUnits> &base_offsets) {585for (CXXRecordDecl::base_class_const_iterator586bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),587be = (IsVirtual ? record->vbases_end() : record->bases_end());588bi != be; ++bi) {589if (!IsVirtual && bi->isVirtual())590continue;591592const clang::Type *origin_base_type = bi->getType().getTypePtr();593const clang::RecordType *origin_base_record_type =594origin_base_type->getAs<RecordType>();595596if (!origin_base_record_type)597return false;598599DeclFromUser<RecordDecl> origin_base_record(600origin_base_record_type->getDecl());601602if (origin_base_record.IsInvalid())603return false;604605DeclFromUser<CXXRecordDecl> origin_base_cxx_record(606DynCast<CXXRecordDecl>(origin_base_record));607608if (origin_base_cxx_record.IsInvalid())609return false;610611CharUnits base_offset;612613if (IsVirtual)614base_offset =615record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);616else617base_offset =618record_layout.getBaseClassOffset(origin_base_cxx_record.decl);619620base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(621origin_base_cxx_record.decl, base_offset));622}623624return true;625}626627bool ClangASTImporter::importRecordLayoutFromOrigin(628const RecordDecl *record, uint64_t &size, uint64_t &alignment,629llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,630llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>631&base_offsets,632llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>633&vbase_offsets) {634635Log *log = GetLog(LLDBLog::Expressions);636637clang::ASTContext &dest_ctx = record->getASTContext();638LLDB_LOG(log,639"LayoutRecordType on (ASTContext*){0:x} '{1}' for (RecordDecl*)"640"{2:x} [name = '{3}']",641&dest_ctx,642TypeSystemClang::GetASTContext(&dest_ctx)->getDisplayName(), record,643record->getName());644645DeclFromParser<const RecordDecl> parser_record(record);646DeclFromUser<const RecordDecl> origin_record(parser_record.GetOrigin(*this));647648if (origin_record.IsInvalid())649return false;650651std::remove_reference_t<decltype(field_offsets)> origin_field_offsets;652std::remove_reference_t<decltype(base_offsets)> origin_base_offsets;653std::remove_reference_t<decltype(vbase_offsets)> origin_virtual_base_offsets;654655TypeSystemClang::GetCompleteDecl(656&origin_record->getASTContext(),657const_cast<RecordDecl *>(origin_record.decl));658659clang::RecordDecl *definition = origin_record.decl->getDefinition();660if (!definition || !definition->isCompleteDefinition())661return false;662663const ASTRecordLayout &record_layout(664origin_record->getASTContext().getASTRecordLayout(origin_record.decl));665666int field_idx = 0, field_count = record_layout.getFieldCount();667668for (RecordDecl::field_iterator fi = origin_record->field_begin(),669fe = origin_record->field_end();670fi != fe; ++fi) {671if (field_idx >= field_count)672return false; // Layout didn't go well. Bail out.673674uint64_t field_offset = record_layout.getFieldOffset(field_idx);675676origin_field_offsets.insert(677std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));678679field_idx++;680}681682DeclFromUser<const CXXRecordDecl> origin_cxx_record(683DynCast<const CXXRecordDecl>(origin_record));684685if (origin_cxx_record.IsValid()) {686if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,687origin_base_offsets) ||688!ExtractBaseOffsets<true>(record_layout, origin_cxx_record,689origin_virtual_base_offsets))690return false;691}692693if (!ImportOffsetMap(&dest_ctx, field_offsets, origin_field_offsets, *this) ||694!ImportOffsetMap(&dest_ctx, base_offsets, origin_base_offsets, *this) ||695!ImportOffsetMap(&dest_ctx, vbase_offsets, origin_virtual_base_offsets,696*this))697return false;698699size = record_layout.getSize().getQuantity() * dest_ctx.getCharWidth();700alignment =701record_layout.getAlignment().getQuantity() * dest_ctx.getCharWidth();702703if (log) {704LLDB_LOG(log, "LRT returned:");705LLDB_LOG(log, "LRT Original = (RecordDecl*){0:x}",706static_cast<const void *>(origin_record.decl));707LLDB_LOG(log, "LRT Size = {0}", size);708LLDB_LOG(log, "LRT Alignment = {0}", alignment);709LLDB_LOG(log, "LRT Fields:");710for (RecordDecl::field_iterator fi = record->field_begin(),711fe = record->field_end();712fi != fe; ++fi) {713LLDB_LOG(714log,715"LRT (FieldDecl*){0:x}, Name = '{1}', Type = '{2}', Offset = "716"{3} bits",717*fi, fi->getName(), fi->getType().getAsString(), field_offsets[*fi]);718}719DeclFromParser<const CXXRecordDecl> parser_cxx_record =720DynCast<const CXXRecordDecl>(parser_record);721if (parser_cxx_record.IsValid()) {722LLDB_LOG(log, "LRT Bases:");723for (CXXRecordDecl::base_class_const_iterator724bi = parser_cxx_record->bases_begin(),725be = parser_cxx_record->bases_end();726bi != be; ++bi) {727bool is_virtual = bi->isVirtual();728729QualType base_type = bi->getType();730const RecordType *base_record_type = base_type->getAs<RecordType>();731DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());732DeclFromParser<CXXRecordDecl> base_cxx_record =733DynCast<CXXRecordDecl>(base_record);734735LLDB_LOG(log,736"LRT {0}(CXXRecordDecl*){1:x}, Name = '{2}', Offset = "737"{3} chars",738(is_virtual ? "Virtual " : ""), base_cxx_record.decl,739base_cxx_record.decl->getName(),740(is_virtual741? vbase_offsets[base_cxx_record.decl].getQuantity()742: base_offsets[base_cxx_record.decl].getQuantity()));743}744} else {745LLDB_LOG(log, "LRD Not a CXXRecord, so no bases");746}747}748749return true;750}751752bool ClangASTImporter::LayoutRecordType(753const clang::RecordDecl *record_decl, uint64_t &bit_size,754uint64_t &alignment,755llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,756llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>757&base_offsets,758llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>759&vbase_offsets) {760RecordDeclToLayoutMap::iterator pos =761m_record_decl_to_layout_map.find(record_decl);762base_offsets.clear();763vbase_offsets.clear();764if (pos != m_record_decl_to_layout_map.end()) {765bit_size = pos->second.bit_size;766alignment = pos->second.alignment;767field_offsets.swap(pos->second.field_offsets);768base_offsets.swap(pos->second.base_offsets);769vbase_offsets.swap(pos->second.vbase_offsets);770m_record_decl_to_layout_map.erase(pos);771return true;772}773774// It's possible that we calculated the layout in a different775// ClangASTImporter instance. Try to import such layout if776// our decl has an origin.777if (auto origin = GetDeclOrigin(record_decl); origin.Valid())778if (importRecordLayoutFromOrigin(record_decl, bit_size, alignment,779field_offsets, base_offsets,780vbase_offsets))781return true;782783bit_size = 0;784alignment = 0;785field_offsets.clear();786787return false;788}789790void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,791const LayoutInfo &layout) {792m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));793}794795bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {796DeclOrigin decl_origin = GetDeclOrigin(decl);797798if (!decl_origin.Valid())799return false;800801if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))802return false;803804ImporterDelegateSP delegate_sp(805GetDelegate(&decl->getASTContext(), decl_origin.ctx));806807ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,808&decl->getASTContext());809if (delegate_sp)810delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);811812return true;813}814815bool ClangASTImporter::CompleteTagDeclWithOrigin(clang::TagDecl *decl,816clang::TagDecl *origin_decl) {817clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();818819if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl))820return false;821822ImporterDelegateSP delegate_sp(823GetDelegate(&decl->getASTContext(), origin_ast_ctx));824825if (delegate_sp)826delegate_sp->ImportDefinitionTo(decl, origin_decl);827828ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());829830context_md->setOrigin(decl, DeclOrigin(origin_ast_ctx, origin_decl));831return true;832}833834bool ClangASTImporter::CompleteObjCInterfaceDecl(835clang::ObjCInterfaceDecl *interface_decl) {836DeclOrigin decl_origin = GetDeclOrigin(interface_decl);837838if (!decl_origin.Valid())839return false;840841if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))842return false;843844ImporterDelegateSP delegate_sp(845GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));846847if (delegate_sp)848delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);849850if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())851RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));852853return true;854}855856bool ClangASTImporter::CompleteAndFetchChildren(clang::QualType type) {857if (!RequireCompleteType(type))858return false;859860Log *log = GetLog(LLDBLog::Expressions);861862if (const TagType *tag_type = type->getAs<TagType>()) {863TagDecl *tag_decl = tag_type->getDecl();864865DeclOrigin decl_origin = GetDeclOrigin(tag_decl);866867if (!decl_origin.Valid())868return false;869870ImporterDelegateSP delegate_sp(871GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));872873ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,874&tag_decl->getASTContext());875876TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);877878for (Decl *origin_child_decl : origin_tag_decl->decls()) {879llvm::Expected<Decl *> imported_or_err =880delegate_sp->Import(origin_child_decl);881if (!imported_or_err) {882LLDB_LOG_ERROR(log, imported_or_err.takeError(),883"Couldn't import decl: {0}");884return false;885}886}887888if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))889record_decl->setHasLoadedFieldsFromExternalStorage(true);890891return true;892}893894if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {895if (ObjCInterfaceDecl *objc_interface_decl =896objc_object_type->getInterface()) {897DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);898899if (!decl_origin.Valid())900return false;901902ImporterDelegateSP delegate_sp(903GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));904905ObjCInterfaceDecl *origin_interface_decl =906llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);907908for (Decl *origin_child_decl : origin_interface_decl->decls()) {909llvm::Expected<Decl *> imported_or_err =910delegate_sp->Import(origin_child_decl);911if (!imported_or_err) {912LLDB_LOG_ERROR(log, imported_or_err.takeError(),913"Couldn't import decl: {0}");914return false;915}916}917918return true;919}920return false;921}922923return true;924}925926bool ClangASTImporter::RequireCompleteType(clang::QualType type) {927if (type.isNull())928return false;929930if (const TagType *tag_type = type->getAs<TagType>()) {931TagDecl *tag_decl = tag_type->getDecl();932933if (tag_decl->getDefinition() || tag_decl->isBeingDefined())934return true;935936return CompleteTagDecl(tag_decl);937}938if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {939if (ObjCInterfaceDecl *objc_interface_decl =940objc_object_type->getInterface())941return CompleteObjCInterfaceDecl(objc_interface_decl);942return false;943}944if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())945return RequireCompleteType(array_type->getElementType());946if (const AtomicType *atomic_type = type->getAs<AtomicType>())947return RequireCompleteType(atomic_type->getPointeeType());948949return true;950}951952ClangASTMetadata *ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {953DeclOrigin decl_origin = GetDeclOrigin(decl);954955if (decl_origin.Valid()) {956TypeSystemClang *ast = TypeSystemClang::GetASTContext(decl_origin.ctx);957return ast->GetMetadata(decl_origin.decl);958}959TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext());960return ast->GetMetadata(decl);961}962963ClangASTImporter::DeclOrigin964ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {965ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());966967return context_md->getOrigin(decl);968}969970void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,971clang::Decl *original_decl) {972ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());973context_md->setOrigin(974decl, DeclOrigin(&original_decl->getASTContext(), original_decl));975}976977void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,978NamespaceMapSP &namespace_map) {979ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());980981context_md->m_namespace_maps[decl] = namespace_map;982}983984ClangASTImporter::NamespaceMapSP985ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {986ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());987988NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;989990NamespaceMetaMap::iterator iter = namespace_maps.find(decl);991992if (iter != namespace_maps.end())993return iter->second;994return NamespaceMapSP();995}996997void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {998assert(decl);999ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());10001001const DeclContext *parent_context = decl->getDeclContext();1002const NamespaceDecl *parent_namespace =1003dyn_cast<NamespaceDecl>(parent_context);1004NamespaceMapSP parent_map;10051006if (parent_namespace)1007parent_map = GetNamespaceMap(parent_namespace);10081009NamespaceMapSP new_map;10101011new_map = std::make_shared<NamespaceMap>();10121013if (context_md->m_map_completer) {1014std::string namespace_string = decl->getDeclName().getAsString();10151016context_md->m_map_completer->CompleteNamespaceMap(1017new_map, ConstString(namespace_string.c_str()), parent_map);1018}10191020context_md->m_namespace_maps[decl] = new_map;1021}10221023void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {1024Log *log = GetLog(LLDBLog::Expressions);10251026LLDB_LOG(log,1027" [ClangASTImporter] Forgetting destination (ASTContext*){0:x}",1028dst_ast);10291030m_metadata_map.erase(dst_ast);1031}10321033void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,1034clang::ASTContext *src_ast) {1035ASTContextMetadataSP md = MaybeGetContextMetadata(dst_ast);10361037Log *log = GetLog(LLDBLog::Expressions);10381039LLDB_LOG(log,1040" [ClangASTImporter] Forgetting source->dest "1041"(ASTContext*){0:x}->(ASTContext*){1:x}",1042src_ast, dst_ast);10431044if (!md)1045return;10461047md->m_delegates.erase(src_ast);1048md->removeOriginsWithContext(src_ast);1049}10501051ClangASTImporter::MapCompleter::~MapCompleter() = default;10521053llvm::Expected<Decl *>1054ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl *From) {1055if (m_std_handler) {1056std::optional<Decl *> D = m_std_handler->Import(From);1057if (D) {1058// Make sure we don't use this decl later to map it back to it's original1059// decl. The decl the CxxModuleHandler created has nothing to do with1060// the one from debug info, and linking those two would just cause the1061// ASTImporter to try 'updating' the module decl with the minimal one from1062// the debug info.1063m_decls_to_ignore.insert(*D);1064return *D;1065}1066}10671068// Check which ASTContext this declaration originally came from.1069DeclOrigin origin = m_main.GetDeclOrigin(From);10701071// Prevent infinite recursion when the origin tracking contains a cycle.1072assert(origin.decl != From && "Origin points to itself?");10731074// If it originally came from the target ASTContext then we can just1075// pretend that the original is the one we imported. This can happen for1076// example when inspecting a persistent declaration from the scratch1077// ASTContext (which will provide the declaration when parsing the1078// expression and then we later try to copy the declaration back to the1079// scratch ASTContext to store the result).1080// Without this check we would ask the ASTImporter to import a declaration1081// into the same ASTContext where it came from (which doesn't make a lot of1082// sense).1083if (origin.Valid() && origin.ctx == &getToContext()) {1084RegisterImportedDecl(From, origin.decl);1085return origin.decl;1086}10871088// This declaration came originally from another ASTContext. Instead of1089// copying our potentially incomplete 'From' Decl we instead go to the1090// original ASTContext and copy the original to the target. This is not1091// only faster than first completing our current decl and then copying it1092// to the target, but it also prevents that indirectly copying the same1093// declaration to the same target requires the ASTImporter to merge all1094// the different decls that appear to come from different ASTContexts (even1095// though all these different source ASTContexts just got a copy from1096// one source AST).1097if (origin.Valid()) {1098auto R = m_main.CopyDecl(&getToContext(), origin.decl);1099if (R) {1100RegisterImportedDecl(From, R);1101return R;1102}1103}11041105// If we have a forcefully completed type, try to find an actual definition1106// for it in other modules.1107const ClangASTMetadata *md = m_main.GetDeclMetadata(From);1108auto *td = dyn_cast<TagDecl>(From);1109if (td && md && md->IsForcefullyCompleted()) {1110Log *log = GetLog(LLDBLog::Expressions);1111LLDB_LOG(log,1112"[ClangASTImporter] Searching for a complete definition of {0} in "1113"other modules",1114td->getName());1115Expected<DeclContext *> dc_or_err = ImportContext(td->getDeclContext());1116if (!dc_or_err)1117return dc_or_err.takeError();1118Expected<DeclarationName> dn_or_err = Import(td->getDeclName());1119if (!dn_or_err)1120return dn_or_err.takeError();1121DeclContext *dc = *dc_or_err;1122DeclContext::lookup_result lr = dc->lookup(*dn_or_err);1123for (clang::Decl *candidate : lr) {1124if (candidate->getKind() == From->getKind()) {1125RegisterImportedDecl(From, candidate);1126m_decls_to_ignore.insert(candidate);1127return candidate;1128}1129}1130LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");1131}11321133return ASTImporter::ImportImpl(From);1134}11351136void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(1137clang::Decl *to, clang::Decl *from) {1138// We might have a forward declaration from a shared library that we1139// gave external lexical storage so that Clang asks us about the full1140// definition when it needs it. In this case the ASTImporter isn't aware1141// that the forward decl from the shared library is the actual import1142// target but would create a second declaration that would then be defined.1143// We want that 'to' is actually complete after this function so let's1144// tell the ASTImporter that 'to' was imported from 'from'.1145MapImported(from, to);11461147Log *log = GetLog(LLDBLog::Expressions);11481149if (llvm::Error err = ImportDefinition(from)) {1150LLDB_LOG_ERROR(log, std::move(err),1151"[ClangASTImporter] Error during importing definition: {0}");1152return;1153}11541155if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {1156if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {1157to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());11581159if (Log *log_ast = GetLog(LLDBLog::AST)) {1160std::string name_string;1161if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {1162llvm::raw_string_ostream name_stream(name_string);1163from_named_decl->printName(name_stream);1164name_stream.flush();1165}1166LLDB_LOG(log_ast,1167"==== [ClangASTImporter][TUDecl: {0:x}] Imported "1168"({1}Decl*){2:x}, named {3} (from "1169"(Decl*){4:x})",1170static_cast<void *>(to->getTranslationUnitDecl()),1171from->getDeclKindName(), static_cast<void *>(to), name_string,1172static_cast<void *>(from));11731174// Log the AST of the TU.1175std::string ast_string;1176llvm::raw_string_ostream ast_stream(ast_string);1177to->getTranslationUnitDecl()->dump(ast_stream);1178LLDB_LOG(log_ast, "{0}", ast_string);1179}1180}1181}11821183// If we're dealing with an Objective-C class, ensure that the inheritance1184// has been set up correctly. The ASTImporter may not do this correctly if1185// the class was originally sourced from symbols.11861187if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {1188ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();11891190if (to_superclass)1191return; // we're not going to override it if it's set11921193ObjCInterfaceDecl *from_objc_interface = dyn_cast<ObjCInterfaceDecl>(from);11941195if (!from_objc_interface)1196return;11971198ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();11991200if (!from_superclass)1201return;12021203llvm::Expected<Decl *> imported_from_superclass_decl =1204Import(from_superclass);12051206if (!imported_from_superclass_decl) {1207LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),1208"Couldn't import decl: {0}");1209return;1210}12111212ObjCInterfaceDecl *imported_from_superclass =1213dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);12141215if (!imported_from_superclass)1216return;12171218if (!to_objc_interface->hasDefinition())1219to_objc_interface->startDefinition();12201221to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(1222m_source_ctx->getObjCInterfaceType(imported_from_superclass)));1223}1224}12251226/// Takes a CXXMethodDecl and completes the return type if necessary. This1227/// is currently only necessary for virtual functions with covariant return1228/// types where Clang's CodeGen expects that the underlying records are already1229/// completed.1230static void MaybeCompleteReturnType(ClangASTImporter &importer,1231CXXMethodDecl *to_method) {1232if (!to_method->isVirtual())1233return;1234QualType return_type = to_method->getReturnType();1235if (!return_type->isPointerType() && !return_type->isReferenceType())1236return;12371238clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl();1239if (!rd)1240return;1241if (rd->getDefinition())1242return;12431244importer.CompleteTagDecl(rd);1245}12461247/// Recreate a module with its parents in \p to_source and return its id.1248static OptionalClangModuleID1249RemapModule(OptionalClangModuleID from_id,1250ClangExternalASTSourceCallbacks &from_source,1251ClangExternalASTSourceCallbacks &to_source) {1252if (!from_id.HasValue())1253return {};1254clang::Module *module = from_source.getModule(from_id.GetValue());1255OptionalClangModuleID parent = RemapModule(1256from_source.GetIDForModule(module->Parent), from_source, to_source);1257TypeSystemClang &to_ts = to_source.GetTypeSystem();1258return to_ts.GetOrCreateClangModule(module->Name, parent, module->IsFramework,1259module->IsExplicit);1260}12611262void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from,1263clang::Decl *to) {1264Log *log = GetLog(LLDBLog::Expressions);12651266// Some decls shouldn't be tracked here because they were not created by1267// copying 'from' to 'to'. Just exit early for those.1268if (m_decls_to_ignore.count(to))1269return;12701271// Transfer module ownership information.1272auto *from_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(1273getFromContext().getExternalSource());1274// Can also be a ClangASTSourceProxy.1275auto *to_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(1276getToContext().getExternalSource());1277if (from_source && to_source) {1278OptionalClangModuleID from_id(from->getOwningModuleID());1279OptionalClangModuleID to_id =1280RemapModule(from_id, *from_source, *to_source);1281TypeSystemClang &to_ts = to_source->GetTypeSystem();1282to_ts.SetOwningModule(to, to_id);1283}12841285lldb::user_id_t user_id = LLDB_INVALID_UID;1286ClangASTMetadata *metadata = m_main.GetDeclMetadata(from);1287if (metadata)1288user_id = metadata->GetUserID();12891290if (log) {1291if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {1292std::string name_string;1293llvm::raw_string_ostream name_stream(name_string);1294from_named_decl->printName(name_stream);1295name_stream.flush();12961297LLDB_LOG(1298log,1299" [ClangASTImporter] Imported ({0}Decl*){1:x}, named {2} (from "1300"(Decl*){3:x}), metadata {4}",1301from->getDeclKindName(), to, name_string, from, user_id);1302} else {1303LLDB_LOG(log,1304" [ClangASTImporter] Imported ({0}Decl*){1:x} (from "1305"(Decl*){2:x}), metadata {3}",1306from->getDeclKindName(), to, from, user_id);1307}1308}13091310ASTContextMetadataSP to_context_md =1311m_main.GetContextMetadata(&to->getASTContext());1312ASTContextMetadataSP from_context_md =1313m_main.MaybeGetContextMetadata(m_source_ctx);13141315if (from_context_md) {1316DeclOrigin origin = from_context_md->getOrigin(from);13171318if (origin.Valid()) {1319if (origin.ctx != &to->getASTContext()) {1320if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)1321to_context_md->setOrigin(to, origin);13221323LLDB_LOG(log,1324" [ClangASTImporter] Propagated origin "1325"(Decl*){0:x}/(ASTContext*){1:x} from (ASTContext*){2:x} to "1326"(ASTContext*){3:x}",1327origin.decl, origin.ctx, &from->getASTContext(),1328&to->getASTContext());1329}1330} else {1331if (m_new_decl_listener)1332m_new_decl_listener->NewDeclImported(from, to);13331334if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)1335to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));13361337LLDB_LOG(log,1338" [ClangASTImporter] Decl has no origin information in "1339"(ASTContext*){0:x}",1340&from->getASTContext());1341}13421343if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) {1344auto *from_namespace = cast<clang::NamespaceDecl>(from);13451346NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;13471348NamespaceMetaMap::iterator namespace_map_iter =1349namespace_maps.find(from_namespace);13501351if (namespace_map_iter != namespace_maps.end())1352to_context_md->m_namespace_maps[to_namespace] =1353namespace_map_iter->second;1354}1355} else {1356to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));13571358LLDB_LOG(log,1359" [ClangASTImporter] Sourced origin "1360"(Decl*){0:x}/(ASTContext*){1:x} into (ASTContext*){2:x}",1361from, m_source_ctx, &to->getASTContext());1362}13631364if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) {1365to_tag_decl->setHasExternalLexicalStorage();1366to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();1367auto from_tag_decl = cast<TagDecl>(from);13681369LLDB_LOG(1370log,1371" [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",1372(to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),1373(to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),1374(from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),1375(to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));1376}13771378if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) {1379m_main.BuildNamespaceMap(to_namespace_decl);1380to_namespace_decl->setHasExternalVisibleStorage();1381}13821383if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) {1384to_container_decl->setHasExternalLexicalStorage();1385to_container_decl->setHasExternalVisibleStorage();13861387if (log) {1388if (ObjCInterfaceDecl *to_interface_decl =1389llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {1390LLDB_LOG(1391log,1392" [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "1393"{0}{1}{2}",1394(to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),1395(to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),1396(to_interface_decl->hasDefinition() ? " HasDefinition" : ""));1397} else {1398LLDB_LOG(1399log, " [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",1400((Decl *)to_container_decl)->getDeclKindName(),1401(to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),1402(to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));1403}1404}1405}14061407if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to))1408MaybeCompleteReturnType(m_main, to_method);1409}14101411clang::Decl *1412ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl *To) {1413return m_main.GetDeclOrigin(To).decl;1414}141514161417