1 //===-- ClangASTImporter.cpp ----------------------------------------------===// 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 #include "lldb/Core/Module.h" 10 #include "lldb/Utility/LLDBAssert.h" 11 #include "lldb/Utility/Log.h" 12 #include "clang/AST/Decl.h" 13 #include "clang/AST/DeclCXX.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/Sema/Lookup.h" 16 #include "clang/Sema/Sema.h" 17 #include "llvm/Support/raw_ostream.h" 18 19 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h" 20 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" 21 #include "Plugins/ExpressionParser/Clang/ClangUtil.h" 22 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 23 24 #include <memory> 25 26 using namespace lldb_private; 27 using namespace clang; 28 29 CompilerType ClangASTImporter::CopyType(TypeSystemClang &dst_ast, 30 const CompilerType &src_type) { 31 clang::ASTContext &dst_clang_ast = dst_ast.getASTContext(); 32 33 TypeSystemClang *src_ast = 34 llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem()); 35 if (!src_ast) 36 return CompilerType(); 37 38 clang::ASTContext &src_clang_ast = src_ast->getASTContext(); 39 40 clang::QualType src_qual_type = ClangUtil::GetQualType(src_type); 41 42 ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast)); 43 if (!delegate_sp) 44 return CompilerType(); 45 46 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast); 47 48 llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type); 49 if (!ret_or_error) { 50 Log *log = 51 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 52 LLDB_LOG_ERROR(log, ret_or_error.takeError(), 53 "Couldn't import type: {0}"); 54 return CompilerType(); 55 } 56 57 lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr(); 58 59 if (dst_clang_type) 60 return CompilerType(&dst_ast, dst_clang_type); 61 return CompilerType(); 62 } 63 64 clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast, 65 clang::Decl *decl) { 66 ImporterDelegateSP delegate_sp; 67 68 clang::ASTContext *src_ast = &decl->getASTContext(); 69 delegate_sp = GetDelegate(dst_ast, src_ast); 70 71 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast); 72 73 if (!delegate_sp) 74 return nullptr; 75 76 llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl); 77 if (!result) { 78 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 79 LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}"); 80 if (log) { 81 lldb::user_id_t user_id = LLDB_INVALID_UID; 82 ClangASTMetadata *metadata = GetDeclMetadata(decl); 83 if (metadata) 84 user_id = metadata->GetUserID(); 85 86 if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl)) 87 LLDB_LOG(log, 88 " [ClangASTImporter] WARNING: Failed to import a {0} " 89 "'{1}', metadata {2}", 90 decl->getDeclKindName(), named_decl->getNameAsString(), 91 user_id); 92 else 93 LLDB_LOG(log, 94 " [ClangASTImporter] WARNING: Failed to import a {0}, " 95 "metadata {1}", 96 decl->getDeclKindName(), user_id); 97 } 98 return nullptr; 99 } 100 101 return *result; 102 } 103 104 class DeclContextOverride { 105 private: 106 struct Backup { 107 clang::DeclContext *decl_context; 108 clang::DeclContext *lexical_decl_context; 109 }; 110 111 llvm::DenseMap<clang::Decl *, Backup> m_backups; 112 113 void OverrideOne(clang::Decl *decl) { 114 if (m_backups.find(decl) != m_backups.end()) { 115 return; 116 } 117 118 m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()}; 119 120 decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl()); 121 decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl()); 122 } 123 124 bool ChainPassesThrough( 125 clang::Decl *decl, clang::DeclContext *base, 126 clang::DeclContext *(clang::Decl::*contextFromDecl)(), 127 clang::DeclContext *(clang::DeclContext::*contextFromContext)()) { 128 for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx; 129 decl_ctx = (decl_ctx->*contextFromContext)()) { 130 if (decl_ctx == base) { 131 return true; 132 } 133 } 134 135 return false; 136 } 137 138 clang::Decl *GetEscapedChild(clang::Decl *decl, 139 clang::DeclContext *base = nullptr) { 140 if (base) { 141 // decl's DeclContext chains must pass through base. 142 143 if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext, 144 &clang::DeclContext::getParent) || 145 !ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext, 146 &clang::DeclContext::getLexicalParent)) { 147 return decl; 148 } 149 } else { 150 base = clang::dyn_cast<clang::DeclContext>(decl); 151 152 if (!base) { 153 return nullptr; 154 } 155 } 156 157 if (clang::DeclContext *context = 158 clang::dyn_cast<clang::DeclContext>(decl)) { 159 for (clang::Decl *decl : context->decls()) { 160 if (clang::Decl *escaped_child = GetEscapedChild(decl)) { 161 return escaped_child; 162 } 163 } 164 } 165 166 return nullptr; 167 } 168 169 void Override(clang::Decl *decl) { 170 if (clang::Decl *escaped_child = GetEscapedChild(decl)) { 171 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 172 173 LLDB_LOG(log, 174 " [ClangASTImporter] DeclContextOverride couldn't " 175 "override ({0}Decl*){1} - its child ({2}Decl*){3} escapes", 176 decl->getDeclKindName(), decl, escaped_child->getDeclKindName(), 177 escaped_child); 178 lldbassert(0 && "Couldn't override!"); 179 } 180 181 OverrideOne(decl); 182 } 183 184 public: 185 DeclContextOverride() {} 186 187 void OverrideAllDeclsFromContainingFunction(clang::Decl *decl) { 188 for (DeclContext *decl_context = decl->getLexicalDeclContext(); 189 decl_context; decl_context = decl_context->getLexicalParent()) { 190 DeclContext *redecl_context = decl_context->getRedeclContext(); 191 192 if (llvm::isa<FunctionDecl>(redecl_context) && 193 llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())) { 194 for (clang::Decl *child_decl : decl_context->decls()) { 195 Override(child_decl); 196 } 197 } 198 } 199 } 200 201 ~DeclContextOverride() { 202 for (const std::pair<clang::Decl *, Backup> &backup : m_backups) { 203 backup.first->setDeclContext(backup.second.decl_context); 204 backup.first->setLexicalDeclContext(backup.second.lexical_decl_context); 205 } 206 } 207 }; 208 209 namespace { 210 /// Completes all imported TagDecls at the end of the scope. 211 /// 212 /// While in a CompleteTagDeclsScope, every decl that could be completed will 213 /// be completed at the end of the scope (including all Decls that are 214 /// imported while completing the original Decls). 215 class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener { 216 ClangASTImporter::ImporterDelegateSP m_delegate; 217 llvm::SmallVector<NamedDecl *, 32> m_decls_to_complete; 218 llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed; 219 clang::ASTContext *m_dst_ctx; 220 clang::ASTContext *m_src_ctx; 221 ClangASTImporter &importer; 222 223 public: 224 /// Constructs a CompleteTagDeclsScope. 225 /// \param importer The ClangASTImporter that we should observe. 226 /// \param dst_ctx The ASTContext to which Decls are imported. 227 /// \param src_ctx The ASTContext from which Decls are imported. 228 explicit CompleteTagDeclsScope(ClangASTImporter &importer, 229 clang::ASTContext *dst_ctx, 230 clang::ASTContext *src_ctx) 231 : m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx), 232 m_src_ctx(src_ctx), importer(importer) { 233 m_delegate->SetImportListener(this); 234 } 235 236 virtual ~CompleteTagDeclsScope() { 237 ClangASTImporter::ASTContextMetadataSP to_context_md = 238 importer.GetContextMetadata(m_dst_ctx); 239 240 // Complete all decls we collected until now. 241 while (!m_decls_to_complete.empty()) { 242 NamedDecl *decl = m_decls_to_complete.pop_back_val(); 243 m_decls_already_completed.insert(decl); 244 245 // We should only complete decls coming from the source context. 246 assert(to_context_md->m_origins[decl].ctx == m_src_ctx); 247 248 Decl *original_decl = to_context_md->m_origins[decl].decl; 249 250 // Complete the decl now. 251 TypeSystemClang::GetCompleteDecl(m_src_ctx, original_decl); 252 if (auto *tag_decl = dyn_cast<TagDecl>(decl)) { 253 if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) { 254 if (original_tag_decl->isCompleteDefinition()) { 255 m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl); 256 tag_decl->setCompleteDefinition(true); 257 } 258 } 259 260 tag_decl->setHasExternalLexicalStorage(false); 261 tag_decl->setHasExternalVisibleStorage(false); 262 } else if (auto *container_decl = dyn_cast<ObjCContainerDecl>(decl)) { 263 container_decl->setHasExternalLexicalStorage(false); 264 container_decl->setHasExternalVisibleStorage(false); 265 } 266 267 to_context_md->m_origins.erase(decl); 268 } 269 270 // Stop listening to imported decls. We do this after clearing the 271 // Decls we needed to import to catch all Decls they might have pulled in. 272 m_delegate->RemoveImportListener(); 273 } 274 275 void NewDeclImported(clang::Decl *from, clang::Decl *to) override { 276 // Filter out decls that we can't complete later. 277 if (!isa<TagDecl>(to) && !isa<ObjCInterfaceDecl>(to)) 278 return; 279 RecordDecl *from_record_decl = dyn_cast<RecordDecl>(from); 280 // We don't need to complete injected class name decls. 281 if (from_record_decl && from_record_decl->isInjectedClassName()) 282 return; 283 284 NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to); 285 // Check if we already completed this type. 286 if (m_decls_already_completed.count(to_named_decl) != 0) 287 return; 288 m_decls_to_complete.push_back(to_named_decl); 289 } 290 }; 291 } // namespace 292 293 CompilerType ClangASTImporter::DeportType(TypeSystemClang &dst, 294 const CompilerType &src_type) { 295 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 296 297 TypeSystemClang *src_ctxt = 298 llvm::cast<TypeSystemClang>(src_type.GetTypeSystem()); 299 300 LLDB_LOG(log, 301 " [ClangASTImporter] DeportType called on ({0}Type*){1} " 302 "from (ASTContext*){2} to (ASTContext*){3}", 303 src_type.GetTypeName(), src_type.GetOpaqueQualType(), 304 &src_ctxt->getASTContext(), &dst.getASTContext()); 305 306 DeclContextOverride decl_context_override; 307 308 if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>()) 309 decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl()); 310 311 CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(), 312 &src_ctxt->getASTContext()); 313 return CopyType(dst, src_type); 314 } 315 316 clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx, 317 clang::Decl *decl) { 318 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 319 320 clang::ASTContext *src_ctx = &decl->getASTContext(); 321 LLDB_LOG(log, 322 " [ClangASTImporter] DeportDecl called on ({0}Decl*){1} from " 323 "(ASTContext*){2} to (ASTContext*){3}", 324 decl->getDeclKindName(), decl, src_ctx, dst_ctx); 325 326 DeclContextOverride decl_context_override; 327 328 decl_context_override.OverrideAllDeclsFromContainingFunction(decl); 329 330 clang::Decl *result; 331 { 332 CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx); 333 result = CopyDecl(dst_ctx, decl); 334 } 335 336 if (!result) 337 return nullptr; 338 339 LLDB_LOG(log, 340 " [ClangASTImporter] DeportDecl deported ({0}Decl*){1} to " 341 "({2}Decl*){3}", 342 decl->getDeclKindName(), decl, result->getDeclKindName(), result); 343 344 return result; 345 } 346 347 bool ClangASTImporter::CanImport(const CompilerType &type) { 348 if (!ClangUtil::IsClangType(type)) 349 return false; 350 351 // TODO: remove external completion BOOL 352 // CompleteAndFetchChildren should get the Decl out and check for the 353 354 clang::QualType qual_type( 355 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type))); 356 357 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 358 switch (type_class) { 359 case clang::Type::Record: { 360 const clang::CXXRecordDecl *cxx_record_decl = 361 qual_type->getAsCXXRecordDecl(); 362 if (cxx_record_decl) { 363 if (GetDeclOrigin(cxx_record_decl).Valid()) 364 return true; 365 } 366 } break; 367 368 case clang::Type::Enum: { 369 clang::EnumDecl *enum_decl = 370 llvm::cast<clang::EnumType>(qual_type)->getDecl(); 371 if (enum_decl) { 372 if (GetDeclOrigin(enum_decl).Valid()) 373 return true; 374 } 375 } break; 376 377 case clang::Type::ObjCObject: 378 case clang::Type::ObjCInterface: { 379 const clang::ObjCObjectType *objc_class_type = 380 llvm::dyn_cast<clang::ObjCObjectType>(qual_type); 381 if (objc_class_type) { 382 clang::ObjCInterfaceDecl *class_interface_decl = 383 objc_class_type->getInterface(); 384 // We currently can't complete objective C types through the newly added 385 // ASTContext because it only supports TagDecl objects right now... 386 if (class_interface_decl) { 387 if (GetDeclOrigin(class_interface_decl).Valid()) 388 return true; 389 } 390 } 391 } break; 392 393 case clang::Type::Typedef: 394 return CanImport(CompilerType(type.GetTypeSystem(), 395 llvm::cast<clang::TypedefType>(qual_type) 396 ->getDecl() 397 ->getUnderlyingType() 398 .getAsOpaquePtr())); 399 400 case clang::Type::Auto: 401 return CanImport(CompilerType(type.GetTypeSystem(), 402 llvm::cast<clang::AutoType>(qual_type) 403 ->getDeducedType() 404 .getAsOpaquePtr())); 405 406 case clang::Type::Elaborated: 407 return CanImport(CompilerType(type.GetTypeSystem(), 408 llvm::cast<clang::ElaboratedType>(qual_type) 409 ->getNamedType() 410 .getAsOpaquePtr())); 411 412 case clang::Type::Paren: 413 return CanImport(CompilerType( 414 type.GetTypeSystem(), 415 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr())); 416 417 default: 418 break; 419 } 420 421 return false; 422 } 423 424 bool ClangASTImporter::Import(const CompilerType &type) { 425 if (!ClangUtil::IsClangType(type)) 426 return false; 427 // TODO: remove external completion BOOL 428 // CompleteAndFetchChildren should get the Decl out and check for the 429 430 clang::QualType qual_type( 431 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type))); 432 433 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 434 switch (type_class) { 435 case clang::Type::Record: { 436 const clang::CXXRecordDecl *cxx_record_decl = 437 qual_type->getAsCXXRecordDecl(); 438 if (cxx_record_decl) { 439 if (GetDeclOrigin(cxx_record_decl).Valid()) 440 return CompleteAndFetchChildren(qual_type); 441 } 442 } break; 443 444 case clang::Type::Enum: { 445 clang::EnumDecl *enum_decl = 446 llvm::cast<clang::EnumType>(qual_type)->getDecl(); 447 if (enum_decl) { 448 if (GetDeclOrigin(enum_decl).Valid()) 449 return CompleteAndFetchChildren(qual_type); 450 } 451 } break; 452 453 case clang::Type::ObjCObject: 454 case clang::Type::ObjCInterface: { 455 const clang::ObjCObjectType *objc_class_type = 456 llvm::dyn_cast<clang::ObjCObjectType>(qual_type); 457 if (objc_class_type) { 458 clang::ObjCInterfaceDecl *class_interface_decl = 459 objc_class_type->getInterface(); 460 // We currently can't complete objective C types through the newly added 461 // ASTContext because it only supports TagDecl objects right now... 462 if (class_interface_decl) { 463 if (GetDeclOrigin(class_interface_decl).Valid()) 464 return CompleteAndFetchChildren(qual_type); 465 } 466 } 467 } break; 468 469 case clang::Type::Typedef: 470 return Import(CompilerType(type.GetTypeSystem(), 471 llvm::cast<clang::TypedefType>(qual_type) 472 ->getDecl() 473 ->getUnderlyingType() 474 .getAsOpaquePtr())); 475 476 case clang::Type::Auto: 477 return Import(CompilerType(type.GetTypeSystem(), 478 llvm::cast<clang::AutoType>(qual_type) 479 ->getDeducedType() 480 .getAsOpaquePtr())); 481 482 case clang::Type::Elaborated: 483 return Import(CompilerType(type.GetTypeSystem(), 484 llvm::cast<clang::ElaboratedType>(qual_type) 485 ->getNamedType() 486 .getAsOpaquePtr())); 487 488 case clang::Type::Paren: 489 return Import(CompilerType( 490 type.GetTypeSystem(), 491 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr())); 492 493 default: 494 break; 495 } 496 return false; 497 } 498 499 bool ClangASTImporter::CompleteType(const CompilerType &compiler_type) { 500 if (!CanImport(compiler_type)) 501 return false; 502 503 if (Import(compiler_type)) { 504 TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type); 505 return true; 506 } 507 508 TypeSystemClang::SetHasExternalStorage(compiler_type.GetOpaqueQualType(), 509 false); 510 return false; 511 } 512 513 bool ClangASTImporter::LayoutRecordType( 514 const clang::RecordDecl *record_decl, uint64_t &bit_size, 515 uint64_t &alignment, 516 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets, 517 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> 518 &base_offsets, 519 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> 520 &vbase_offsets) { 521 RecordDeclToLayoutMap::iterator pos = 522 m_record_decl_to_layout_map.find(record_decl); 523 bool success = false; 524 base_offsets.clear(); 525 vbase_offsets.clear(); 526 if (pos != m_record_decl_to_layout_map.end()) { 527 bit_size = pos->second.bit_size; 528 alignment = pos->second.alignment; 529 field_offsets.swap(pos->second.field_offsets); 530 base_offsets.swap(pos->second.base_offsets); 531 vbase_offsets.swap(pos->second.vbase_offsets); 532 m_record_decl_to_layout_map.erase(pos); 533 success = true; 534 } else { 535 bit_size = 0; 536 alignment = 0; 537 field_offsets.clear(); 538 } 539 return success; 540 } 541 542 void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl, 543 const LayoutInfo &layout) { 544 m_record_decl_to_layout_map.insert(std::make_pair(decl, layout)); 545 } 546 547 bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) { 548 DeclOrigin decl_origin = GetDeclOrigin(decl); 549 550 if (!decl_origin.Valid()) 551 return false; 552 553 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl)) 554 return false; 555 556 ImporterDelegateSP delegate_sp( 557 GetDelegate(&decl->getASTContext(), decl_origin.ctx)); 558 559 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, 560 &decl->getASTContext()); 561 if (delegate_sp) 562 delegate_sp->ImportDefinitionTo(decl, decl_origin.decl); 563 564 return true; 565 } 566 567 bool ClangASTImporter::CompleteTagDeclWithOrigin(clang::TagDecl *decl, 568 clang::TagDecl *origin_decl) { 569 clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext(); 570 571 if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl)) 572 return false; 573 574 ImporterDelegateSP delegate_sp( 575 GetDelegate(&decl->getASTContext(), origin_ast_ctx)); 576 577 if (delegate_sp) 578 delegate_sp->ImportDefinitionTo(decl, origin_decl); 579 580 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); 581 582 OriginMap &origins = context_md->m_origins; 583 584 origins[decl] = DeclOrigin(origin_ast_ctx, origin_decl); 585 586 return true; 587 } 588 589 bool ClangASTImporter::CompleteObjCInterfaceDecl( 590 clang::ObjCInterfaceDecl *interface_decl) { 591 DeclOrigin decl_origin = GetDeclOrigin(interface_decl); 592 593 if (!decl_origin.Valid()) 594 return false; 595 596 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl)) 597 return false; 598 599 ImporterDelegateSP delegate_sp( 600 GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx)); 601 602 if (delegate_sp) 603 delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl); 604 605 if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass()) 606 RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0)); 607 608 return true; 609 } 610 611 bool ClangASTImporter::CompleteAndFetchChildren(clang::QualType type) { 612 if (!RequireCompleteType(type)) 613 return false; 614 615 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 616 617 if (const TagType *tag_type = type->getAs<TagType>()) { 618 TagDecl *tag_decl = tag_type->getDecl(); 619 620 DeclOrigin decl_origin = GetDeclOrigin(tag_decl); 621 622 if (!decl_origin.Valid()) 623 return false; 624 625 ImporterDelegateSP delegate_sp( 626 GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx)); 627 628 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, 629 &tag_decl->getASTContext()); 630 631 TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl); 632 633 for (Decl *origin_child_decl : origin_tag_decl->decls()) { 634 llvm::Expected<Decl *> imported_or_err = 635 delegate_sp->Import(origin_child_decl); 636 if (!imported_or_err) { 637 LLDB_LOG_ERROR(log, imported_or_err.takeError(), 638 "Couldn't import decl: {0}"); 639 return false; 640 } 641 } 642 643 if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl)) 644 record_decl->setHasLoadedFieldsFromExternalStorage(true); 645 646 return true; 647 } 648 649 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) { 650 if (ObjCInterfaceDecl *objc_interface_decl = 651 objc_object_type->getInterface()) { 652 DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl); 653 654 if (!decl_origin.Valid()) 655 return false; 656 657 ImporterDelegateSP delegate_sp( 658 GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx)); 659 660 ObjCInterfaceDecl *origin_interface_decl = 661 llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl); 662 663 for (Decl *origin_child_decl : origin_interface_decl->decls()) { 664 llvm::Expected<Decl *> imported_or_err = 665 delegate_sp->Import(origin_child_decl); 666 if (!imported_or_err) { 667 LLDB_LOG_ERROR(log, imported_or_err.takeError(), 668 "Couldn't import decl: {0}"); 669 return false; 670 } 671 } 672 673 return true; 674 } 675 return false; 676 } 677 678 return true; 679 } 680 681 bool ClangASTImporter::RequireCompleteType(clang::QualType type) { 682 if (type.isNull()) 683 return false; 684 685 if (const TagType *tag_type = type->getAs<TagType>()) { 686 TagDecl *tag_decl = tag_type->getDecl(); 687 688 if (tag_decl->getDefinition() || tag_decl->isBeingDefined()) 689 return true; 690 691 return CompleteTagDecl(tag_decl); 692 } 693 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) { 694 if (ObjCInterfaceDecl *objc_interface_decl = 695 objc_object_type->getInterface()) 696 return CompleteObjCInterfaceDecl(objc_interface_decl); 697 return false; 698 } 699 if (const ArrayType *array_type = type->getAsArrayTypeUnsafe()) 700 return RequireCompleteType(array_type->getElementType()); 701 if (const AtomicType *atomic_type = type->getAs<AtomicType>()) 702 return RequireCompleteType(atomic_type->getPointeeType()); 703 704 return true; 705 } 706 707 ClangASTMetadata *ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) { 708 DeclOrigin decl_origin = GetDeclOrigin(decl); 709 710 if (decl_origin.Valid()) { 711 TypeSystemClang *ast = TypeSystemClang::GetASTContext(decl_origin.ctx); 712 return ast->GetMetadata(decl_origin.decl); 713 } 714 TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext()); 715 return ast->GetMetadata(decl); 716 } 717 718 ClangASTImporter::DeclOrigin 719 ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) { 720 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); 721 722 OriginMap &origins = context_md->m_origins; 723 724 OriginMap::iterator iter = origins.find(decl); 725 726 if (iter != origins.end()) 727 return iter->second; 728 return DeclOrigin(); 729 } 730 731 void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl, 732 clang::Decl *original_decl) { 733 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); 734 735 OriginMap &origins = context_md->m_origins; 736 737 OriginMap::iterator iter = origins.find(decl); 738 739 if (iter != origins.end()) { 740 iter->second.decl = original_decl; 741 iter->second.ctx = &original_decl->getASTContext(); 742 return; 743 } 744 origins[decl] = DeclOrigin(&original_decl->getASTContext(), original_decl); 745 } 746 747 void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl, 748 NamespaceMapSP &namespace_map) { 749 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); 750 751 context_md->m_namespace_maps[decl] = namespace_map; 752 } 753 754 ClangASTImporter::NamespaceMapSP 755 ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) { 756 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); 757 758 NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps; 759 760 NamespaceMetaMap::iterator iter = namespace_maps.find(decl); 761 762 if (iter != namespace_maps.end()) 763 return iter->second; 764 return NamespaceMapSP(); 765 } 766 767 void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) { 768 assert(decl); 769 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext()); 770 771 const DeclContext *parent_context = decl->getDeclContext(); 772 const NamespaceDecl *parent_namespace = 773 dyn_cast<NamespaceDecl>(parent_context); 774 NamespaceMapSP parent_map; 775 776 if (parent_namespace) 777 parent_map = GetNamespaceMap(parent_namespace); 778 779 NamespaceMapSP new_map; 780 781 new_map = std::make_shared<NamespaceMap>(); 782 783 if (context_md->m_map_completer) { 784 std::string namespace_string = decl->getDeclName().getAsString(); 785 786 context_md->m_map_completer->CompleteNamespaceMap( 787 new_map, ConstString(namespace_string.c_str()), parent_map); 788 } 789 790 context_md->m_namespace_maps[decl] = new_map; 791 } 792 793 void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) { 794 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 795 796 LLDB_LOG(log, 797 " [ClangASTImporter] Forgetting destination (ASTContext*){0}", 798 dst_ast); 799 800 m_metadata_map.erase(dst_ast); 801 } 802 803 void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast, 804 clang::ASTContext *src_ast) { 805 ASTContextMetadataSP md = MaybeGetContextMetadata(dst_ast); 806 807 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 808 809 LLDB_LOG(log, 810 " [ClangASTImporter] Forgetting source->dest " 811 "(ASTContext*){0}->(ASTContext*){1}", 812 src_ast, dst_ast); 813 814 if (!md) 815 return; 816 817 md->m_delegates.erase(src_ast); 818 819 for (OriginMap::iterator iter = md->m_origins.begin(); 820 iter != md->m_origins.end();) { 821 if (iter->second.ctx == src_ast) 822 md->m_origins.erase(iter++); 823 else 824 ++iter; 825 } 826 } 827 828 ClangASTImporter::MapCompleter::~MapCompleter() { return; } 829 830 llvm::Expected<Decl *> 831 ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl *From) { 832 if (m_std_handler) { 833 llvm::Optional<Decl *> D = m_std_handler->Import(From); 834 if (D) { 835 // Make sure we don't use this decl later to map it back to it's original 836 // decl. The decl the CxxModuleHandler created has nothing to do with 837 // the one from debug info, and linking those two would just cause the 838 // ASTImporter to try 'updating' the module decl with the minimal one from 839 // the debug info. 840 m_decls_to_ignore.insert(*D); 841 return *D; 842 } 843 } 844 845 // Check which ASTContext this declaration originally came from. 846 DeclOrigin origin = m_master.GetDeclOrigin(From); 847 // If it originally came from the target ASTContext then we can just 848 // pretend that the original is the one we imported. This can happen for 849 // example when inspecting a persistent declaration from the scratch 850 // ASTContext (which will provide the declaration when parsing the 851 // expression and then we later try to copy the declaration back to the 852 // scratch ASTContext to store the result). 853 // Without this check we would ask the ASTImporter to import a declaration 854 // into the same ASTContext where it came from (which doesn't make a lot of 855 // sense). 856 if (origin.Valid() && origin.ctx == &getToContext()) { 857 RegisterImportedDecl(From, origin.decl); 858 return origin.decl; 859 } 860 861 // This declaration came originally from another ASTContext. Instead of 862 // copying our potentially incomplete 'From' Decl we instead go to the 863 // original ASTContext and copy the original to the target. This is not 864 // only faster than first completing our current decl and then copying it 865 // to the target, but it also prevents that indirectly copying the same 866 // declaration to the same target requires the ASTImporter to merge all 867 // the different decls that appear to come from different ASTContexts (even 868 // though all these different source ASTContexts just got a copy from 869 // one source AST). 870 if (origin.Valid()) { 871 auto R = m_master.CopyDecl(&getToContext(), origin.decl); 872 if (R) { 873 RegisterImportedDecl(From, R); 874 return R; 875 } 876 } 877 878 return ASTImporter::ImportImpl(From); 879 } 880 881 void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo( 882 clang::Decl *to, clang::Decl *from) { 883 // We might have a forward declaration from a shared library that we 884 // gave external lexical storage so that Clang asks us about the full 885 // definition when it needs it. In this case the ASTImporter isn't aware 886 // that the forward decl from the shared library is the actual import 887 // target but would create a second declaration that would then be defined. 888 // We want that 'to' is actually complete after this function so let's 889 // tell the ASTImporter that 'to' was imported from 'from'. 890 MapImported(from, to); 891 ASTImporter::Imported(from, to); 892 893 /* 894 if (to_objc_interface) 895 to_objc_interface->startDefinition(); 896 897 CXXRecordDecl *to_cxx_record = dyn_cast<CXXRecordDecl>(to); 898 899 if (to_cxx_record) 900 to_cxx_record->startDefinition(); 901 */ 902 903 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 904 905 if (llvm::Error err = ImportDefinition(from)) { 906 LLDB_LOG_ERROR(log, std::move(err), 907 "[ClangASTImporter] Error during importing definition: {0}"); 908 return; 909 } 910 911 if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) { 912 if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) { 913 to_tag->setCompleteDefinition(from_tag->isCompleteDefinition()); 914 915 if (Log *log_ast = 916 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_AST)) { 917 std::string name_string; 918 if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) { 919 llvm::raw_string_ostream name_stream(name_string); 920 from_named_decl->printName(name_stream); 921 name_stream.flush(); 922 } 923 LLDB_LOG(log_ast, "==== [ClangASTImporter][TUDecl: {0}] Imported " 924 "({1}Decl*){2}, named {3} (from " 925 "(Decl*){4})", 926 static_cast<void *>(to->getTranslationUnitDecl()), 927 from->getDeclKindName(), static_cast<void *>(to), name_string, 928 static_cast<void *>(from)); 929 930 // Log the AST of the TU. 931 std::string ast_string; 932 llvm::raw_string_ostream ast_stream(ast_string); 933 to->getTranslationUnitDecl()->dump(ast_stream); 934 LLDB_LOG(log_ast, "{0}", ast_string); 935 } 936 } 937 } 938 939 // If we're dealing with an Objective-C class, ensure that the inheritance 940 // has been set up correctly. The ASTImporter may not do this correctly if 941 // the class was originally sourced from symbols. 942 943 if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) { 944 do { 945 ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass(); 946 947 if (to_superclass) 948 break; // we're not going to override it if it's set 949 950 ObjCInterfaceDecl *from_objc_interface = 951 dyn_cast<ObjCInterfaceDecl>(from); 952 953 if (!from_objc_interface) 954 break; 955 956 ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass(); 957 958 if (!from_superclass) 959 break; 960 961 llvm::Expected<Decl *> imported_from_superclass_decl = 962 Import(from_superclass); 963 964 if (!imported_from_superclass_decl) { 965 LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(), 966 "Couldn't import decl: {0}"); 967 break; 968 } 969 970 ObjCInterfaceDecl *imported_from_superclass = 971 dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl); 972 973 if (!imported_from_superclass) 974 break; 975 976 if (!to_objc_interface->hasDefinition()) 977 to_objc_interface->startDefinition(); 978 979 to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo( 980 m_source_ctx->getObjCInterfaceType(imported_from_superclass))); 981 } while (false); 982 } 983 } 984 985 /// Takes a CXXMethodDecl and completes the return type if necessary. This 986 /// is currently only necessary for virtual functions with covariant return 987 /// types where Clang's CodeGen expects that the underlying records are already 988 /// completed. 989 static void MaybeCompleteReturnType(ClangASTImporter &importer, 990 CXXMethodDecl *to_method) { 991 if (!to_method->isVirtual()) 992 return; 993 QualType return_type = to_method->getReturnType(); 994 if (!return_type->isPointerType() && !return_type->isReferenceType()) 995 return; 996 997 clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl(); 998 if (!rd) 999 return; 1000 if (rd->getDefinition()) 1001 return; 1002 1003 importer.CompleteTagDecl(rd); 1004 } 1005 1006 void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from, 1007 clang::Decl *to) { 1008 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1009 1010 // Some decls shouldn't be tracked here because they were not created by 1011 // copying 'from' to 'to'. Just exit early for those. 1012 if (m_decls_to_ignore.find(to) != m_decls_to_ignore.end()) 1013 return clang::ASTImporter::Imported(from, to); 1014 1015 lldb::user_id_t user_id = LLDB_INVALID_UID; 1016 ClangASTMetadata *metadata = m_master.GetDeclMetadata(from); 1017 if (metadata) 1018 user_id = metadata->GetUserID(); 1019 1020 if (log) { 1021 if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) { 1022 std::string name_string; 1023 llvm::raw_string_ostream name_stream(name_string); 1024 from_named_decl->printName(name_stream); 1025 name_stream.flush(); 1026 1027 LLDB_LOG(log, 1028 " [ClangASTImporter] Imported ({0}Decl*){1}, named {2} (from " 1029 "(Decl*){3}), metadata {4}", 1030 from->getDeclKindName(), to, name_string, from, user_id); 1031 } else { 1032 LLDB_LOG(log, 1033 " [ClangASTImporter] Imported ({0}Decl*){1} (from " 1034 "(Decl*){2}), metadata {3}", 1035 from->getDeclKindName(), to, from, user_id); 1036 } 1037 } 1038 1039 ASTContextMetadataSP to_context_md = 1040 m_master.GetContextMetadata(&to->getASTContext()); 1041 ASTContextMetadataSP from_context_md = 1042 m_master.MaybeGetContextMetadata(m_source_ctx); 1043 1044 if (from_context_md) { 1045 OriginMap &origins = from_context_md->m_origins; 1046 1047 OriginMap::iterator origin_iter = origins.find(from); 1048 1049 if (origin_iter != origins.end()) { 1050 if (to_context_md->m_origins.find(to) == to_context_md->m_origins.end() || 1051 user_id != LLDB_INVALID_UID) { 1052 if (origin_iter->second.ctx != &to->getASTContext()) 1053 to_context_md->m_origins[to] = origin_iter->second; 1054 } 1055 1056 ImporterDelegateSP direct_completer = 1057 m_master.GetDelegate(&to->getASTContext(), origin_iter->second.ctx); 1058 1059 if (direct_completer.get() != this) 1060 direct_completer->ASTImporter::Imported(origin_iter->second.decl, to); 1061 1062 LLDB_LOG(log, 1063 " [ClangASTImporter] Propagated origin " 1064 "(Decl*){0}/(ASTContext*){1} from (ASTContext*){2} to " 1065 "(ASTContext*){3}", 1066 origin_iter->second.decl, origin_iter->second.ctx, 1067 &from->getASTContext(), &to->getASTContext()); 1068 } else { 1069 if (m_new_decl_listener) 1070 m_new_decl_listener->NewDeclImported(from, to); 1071 1072 if (to_context_md->m_origins.find(to) == to_context_md->m_origins.end() || 1073 user_id != LLDB_INVALID_UID) { 1074 to_context_md->m_origins[to] = DeclOrigin(m_source_ctx, from); 1075 } 1076 1077 LLDB_LOG(log, 1078 " [ClangASTImporter] Decl has no origin information in " 1079 "(ASTContext*){0}", 1080 &from->getASTContext()); 1081 } 1082 1083 if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) { 1084 auto *from_namespace = cast<clang::NamespaceDecl>(from); 1085 1086 NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps; 1087 1088 NamespaceMetaMap::iterator namespace_map_iter = 1089 namespace_maps.find(from_namespace); 1090 1091 if (namespace_map_iter != namespace_maps.end()) 1092 to_context_md->m_namespace_maps[to_namespace] = 1093 namespace_map_iter->second; 1094 } 1095 } else { 1096 to_context_md->m_origins[to] = DeclOrigin(m_source_ctx, from); 1097 1098 LLDB_LOG(log, 1099 " [ClangASTImporter] Sourced origin " 1100 "(Decl*){0}/(ASTContext*){1} into (ASTContext*){2}", 1101 from, m_source_ctx, &to->getASTContext()); 1102 } 1103 1104 if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) { 1105 to_tag_decl->setHasExternalLexicalStorage(); 1106 to_tag_decl->getPrimaryContext()->setMustBuildLookupTable(); 1107 auto from_tag_decl = cast<TagDecl>(from); 1108 1109 LLDB_LOG( 1110 log, 1111 " [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]", 1112 (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""), 1113 (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""), 1114 (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"), 1115 (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete")); 1116 } 1117 1118 if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) { 1119 m_master.BuildNamespaceMap(to_namespace_decl); 1120 to_namespace_decl->setHasExternalVisibleStorage(); 1121 } 1122 1123 if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) { 1124 to_container_decl->setHasExternalLexicalStorage(); 1125 to_container_decl->setHasExternalVisibleStorage(); 1126 1127 if (log) { 1128 if (ObjCInterfaceDecl *to_interface_decl = 1129 llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) { 1130 LLDB_LOG( 1131 log, 1132 " [ClangASTImporter] To is an ObjCInterfaceDecl - attributes " 1133 "{0}{1}{2}", 1134 (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""), 1135 (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""), 1136 (to_interface_decl->hasDefinition() ? " HasDefinition" : "")); 1137 } else { 1138 LLDB_LOG( 1139 log, " [ClangASTImporter] To is an {0}Decl - attributes {1}{2}", 1140 ((Decl *)to_container_decl)->getDeclKindName(), 1141 (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""), 1142 (to_container_decl->hasExternalVisibleStorage() ? " Visible" : "")); 1143 } 1144 } 1145 } 1146 1147 if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to)) 1148 MaybeCompleteReturnType(m_master, to_method); 1149 } 1150 1151 clang::Decl * 1152 ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl *To) { 1153 return m_master.GetDeclOrigin(To).decl; 1154 } 1155