1 //===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===// 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 "ClangASTSource.h" 10 11 #include "ASTDumper.h" 12 #include "ClangDeclVendor.h" 13 #include "ClangModulesDeclVendor.h" 14 15 #include "lldb/Core/Module.h" 16 #include "lldb/Core/ModuleList.h" 17 #include "lldb/Symbol/ClangASTContext.h" 18 #include "lldb/Symbol/ClangUtil.h" 19 #include "lldb/Symbol/CompilerDeclContext.h" 20 #include "lldb/Symbol/Function.h" 21 #include "lldb/Symbol/SymbolFile.h" 22 #include "lldb/Symbol/TaggedASTType.h" 23 #include "lldb/Target/Target.h" 24 #include "lldb/Utility/Log.h" 25 #include "clang/AST/ASTContext.h" 26 #include "clang/AST/RecordLayout.h" 27 28 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" 29 30 #include <memory> 31 #include <vector> 32 33 using namespace clang; 34 using namespace lldb_private; 35 36 // Scoped class that will remove an active lexical decl from the set when it 37 // goes out of scope. 38 namespace { 39 class ScopedLexicalDeclEraser { 40 public: 41 ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls, 42 const clang::Decl *decl) 43 : m_active_lexical_decls(decls), m_decl(decl) {} 44 45 ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); } 46 47 private: 48 std::set<const clang::Decl *> &m_active_lexical_decls; 49 const clang::Decl *m_decl; 50 }; 51 } 52 53 ClangASTSource::ClangASTSource(const lldb::TargetSP &target) 54 : m_import_in_progress(false), m_lookups_enabled(false), m_target(target), 55 m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() { 56 if (!target->GetUseModernTypeLookup()) { 57 m_ast_importer_sp = m_target->GetClangASTImporter(); 58 } 59 } 60 61 void ClangASTSource::InstallASTContext(clang::ASTContext &ast_context, 62 clang::FileManager &file_manager, 63 bool is_shared_context) { 64 m_ast_context = &ast_context; 65 m_file_manager = &file_manager; 66 if (m_target->GetUseModernTypeLookup()) { 67 // Configure the ExternalASTMerger. The merger needs to be able to import 68 // types from any source that we would do lookups in, which includes the 69 // persistent AST context as well as the modules and Objective-C runtime 70 // AST contexts. 71 72 lldbassert(!m_merger_up); 73 clang::ExternalASTMerger::ImporterTarget target = {ast_context, 74 file_manager}; 75 std::vector<clang::ExternalASTMerger::ImporterSource> sources; 76 for (lldb::ModuleSP module_sp : m_target->GetImages().Modules()) { 77 auto type_system_or_err = 78 module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeC); 79 if (auto err = type_system_or_err.takeError()) { 80 LLDB_LOG_ERROR( 81 lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS), 82 std::move(err), "Failed to get ClangASTContext"); 83 } else if (auto *module_ast_ctx = llvm::cast_or_null<ClangASTContext>( 84 &type_system_or_err.get())) { 85 lldbassert(module_ast_ctx->getASTContext()); 86 lldbassert(module_ast_ctx->getFileManager()); 87 sources.push_back({*module_ast_ctx->getASTContext(), 88 *module_ast_ctx->getFileManager(), 89 module_ast_ctx->GetOriginMap()}); 90 } 91 } 92 93 do { 94 lldb::ProcessSP process(m_target->GetProcessSP()); 95 96 if (!process) 97 break; 98 99 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 100 101 if (!language_runtime) 102 break; 103 104 if (auto *runtime_decl_vendor = llvm::dyn_cast_or_null<ClangDeclVendor>( 105 language_runtime->GetDeclVendor())) { 106 sources.push_back(runtime_decl_vendor->GetImporterSource()); 107 } 108 } while (false); 109 110 do { 111 auto *modules_decl_vendor = llvm::cast<ClangModulesDeclVendor>( 112 m_target->GetClangModulesDeclVendor()); 113 114 if (!modules_decl_vendor) 115 break; 116 117 sources.push_back(modules_decl_vendor->GetImporterSource()); 118 } while (false); 119 120 if (!is_shared_context) { 121 // Update the scratch AST context's merger to reflect any new sources we 122 // might have come across since the last time an expression was parsed. 123 124 auto scratch_ast_context = static_cast<ClangASTContextForExpressions*>( 125 m_target->GetScratchClangASTContext()); 126 127 scratch_ast_context->GetMergerUnchecked().AddSources(sources); 128 129 sources.push_back({*scratch_ast_context->getASTContext(), 130 *scratch_ast_context->getFileManager(), 131 scratch_ast_context->GetOriginMap()}); 132 } 133 while (false) 134 ; 135 136 m_merger_up = 137 std::make_unique<clang::ExternalASTMerger>(target, sources); 138 } else { 139 m_ast_importer_sp->InstallMapCompleter(&ast_context, *this); 140 } 141 } 142 143 ClangASTSource::~ClangASTSource() { 144 if (m_ast_importer_sp) 145 m_ast_importer_sp->ForgetDestination(m_ast_context); 146 147 // We are in the process of destruction, don't create clang ast context on 148 // demand by passing false to 149 // Target::GetScratchClangASTContext(create_on_demand). 150 ClangASTContext *scratch_clang_ast_context = 151 m_target->GetScratchClangASTContext(false); 152 153 if (!scratch_clang_ast_context) 154 return; 155 156 clang::ASTContext *scratch_ast_context = 157 scratch_clang_ast_context->getASTContext(); 158 159 if (!scratch_ast_context) 160 return; 161 162 if (m_ast_context != scratch_ast_context && m_ast_importer_sp) 163 m_ast_importer_sp->ForgetSource(scratch_ast_context, m_ast_context); 164 } 165 166 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) { 167 if (!m_ast_context) 168 return; 169 170 m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage(); 171 m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage(); 172 } 173 174 // The core lookup interface. 175 bool ClangASTSource::FindExternalVisibleDeclsByName( 176 const DeclContext *decl_ctx, DeclarationName clang_decl_name) { 177 if (!m_ast_context) { 178 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 179 return false; 180 } 181 182 if (GetImportInProgress()) { 183 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 184 return false; 185 } 186 187 std::string decl_name(clang_decl_name.getAsString()); 188 189 // if (m_decl_map.DoingASTImport ()) 190 // return DeclContext::lookup_result(); 191 // 192 switch (clang_decl_name.getNameKind()) { 193 // Normal identifiers. 194 case DeclarationName::Identifier: { 195 clang::IdentifierInfo *identifier_info = 196 clang_decl_name.getAsIdentifierInfo(); 197 198 if (!identifier_info || identifier_info->getBuiltinID() != 0) { 199 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 200 return false; 201 } 202 } break; 203 204 // Operator names. 205 case DeclarationName::CXXOperatorName: 206 case DeclarationName::CXXLiteralOperatorName: 207 break; 208 209 // Using directives found in this context. 210 // Tell Sema we didn't find any or we'll end up getting asked a *lot*. 211 case DeclarationName::CXXUsingDirective: 212 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 213 return false; 214 215 case DeclarationName::ObjCZeroArgSelector: 216 case DeclarationName::ObjCOneArgSelector: 217 case DeclarationName::ObjCMultiArgSelector: { 218 llvm::SmallVector<NamedDecl *, 1> method_decls; 219 220 NameSearchContext method_search_context(*this, method_decls, 221 clang_decl_name, decl_ctx); 222 223 FindObjCMethodDecls(method_search_context); 224 225 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls); 226 return (method_decls.size() > 0); 227 } 228 // These aren't possible in the global context. 229 case DeclarationName::CXXConstructorName: 230 case DeclarationName::CXXDestructorName: 231 case DeclarationName::CXXConversionFunctionName: 232 case DeclarationName::CXXDeductionGuideName: 233 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 234 return false; 235 } 236 237 if (!GetLookupsEnabled()) { 238 // Wait until we see a '$' at the start of a name before we start doing any 239 // lookups so we can avoid lookup up all of the builtin types. 240 if (!decl_name.empty() && decl_name[0] == '$') { 241 SetLookupsEnabled(true); 242 } else { 243 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 244 return false; 245 } 246 } 247 248 ConstString const_decl_name(decl_name.c_str()); 249 250 const char *uniqued_const_decl_name = const_decl_name.GetCString(); 251 if (m_active_lookups.find(uniqued_const_decl_name) != 252 m_active_lookups.end()) { 253 // We are currently looking up this name... 254 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 255 return false; 256 } 257 m_active_lookups.insert(uniqued_const_decl_name); 258 // static uint32_t g_depth = 0; 259 // ++g_depth; 260 // printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth, 261 // uniqued_const_decl_name); 262 llvm::SmallVector<NamedDecl *, 4> name_decls; 263 NameSearchContext name_search_context(*this, name_decls, clang_decl_name, 264 decl_ctx); 265 FindExternalVisibleDecls(name_search_context); 266 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls); 267 // --g_depth; 268 m_active_lookups.erase(uniqued_const_decl_name); 269 return (name_decls.size() != 0); 270 } 271 272 void ClangASTSource::CompleteType(TagDecl *tag_decl) { 273 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 274 275 static unsigned int invocation_id = 0; 276 unsigned int current_id = invocation_id++; 277 278 if (log) { 279 LLDB_LOGF(log, 280 " CompleteTagDecl[%u] on (ASTContext*)%p Completing " 281 "(TagDecl*)%p named %s", 282 current_id, static_cast<void *>(m_ast_context), 283 static_cast<void *>(tag_decl), tag_decl->getName().str().c_str()); 284 285 LLDB_LOGF(log, " CTD[%u] Before:", current_id); 286 ASTDumper dumper((Decl *)tag_decl); 287 dumper.ToLog(log, " [CTD] "); 288 } 289 290 auto iter = m_active_lexical_decls.find(tag_decl); 291 if (iter != m_active_lexical_decls.end()) 292 return; 293 m_active_lexical_decls.insert(tag_decl); 294 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl); 295 296 if (!m_ast_importer_sp) { 297 if (HasMerger()) { 298 GetMergerUnchecked().CompleteType(tag_decl); 299 } 300 return; 301 } 302 303 if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) { 304 // We couldn't complete the type. Maybe there's a definition somewhere 305 // else that can be completed. 306 307 LLDB_LOGF(log, 308 " CTD[%u] Type could not be completed in the module in " 309 "which it was first found.", 310 current_id); 311 312 bool found = false; 313 314 DeclContext *decl_ctx = tag_decl->getDeclContext(); 315 316 if (const NamespaceDecl *namespace_context = 317 dyn_cast<NamespaceDecl>(decl_ctx)) { 318 ClangASTImporter::NamespaceMapSP namespace_map = 319 m_ast_importer_sp->GetNamespaceMap(namespace_context); 320 321 if (log && log->GetVerbose()) 322 LLDB_LOGF(log, " CTD[%u] Inspecting namespace map %p (%d entries)", 323 current_id, static_cast<void *>(namespace_map.get()), 324 static_cast<int>(namespace_map->size())); 325 326 if (!namespace_map) 327 return; 328 329 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), 330 e = namespace_map->end(); 331 i != e && !found; ++i) { 332 LLDB_LOGF(log, " CTD[%u] Searching namespace %s in module %s", 333 current_id, i->second.GetName().AsCString(), 334 i->first->GetFileSpec().GetFilename().GetCString()); 335 336 TypeList types; 337 338 ConstString name(tag_decl->getName().str().c_str()); 339 340 i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types); 341 342 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) { 343 lldb::TypeSP type = types.GetTypeAtIndex(ti); 344 345 if (!type) 346 continue; 347 348 CompilerType clang_type(type->GetFullCompilerType()); 349 350 if (!ClangUtil::IsClangType(clang_type)) 351 continue; 352 353 const TagType *tag_type = 354 ClangUtil::GetQualType(clang_type)->getAs<TagType>(); 355 356 if (!tag_type) 357 continue; 358 359 TagDecl *candidate_tag_decl = 360 const_cast<TagDecl *>(tag_type->getDecl()); 361 362 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, 363 candidate_tag_decl)) 364 found = true; 365 } 366 } 367 } else { 368 TypeList types; 369 370 ConstString name(tag_decl->getName().str().c_str()); 371 CompilerDeclContext namespace_decl; 372 373 const ModuleList &module_list = m_target->GetImages(); 374 375 bool exact_match = false; 376 llvm::DenseSet<SymbolFile *> searched_symbol_files; 377 module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX, 378 searched_symbol_files, types); 379 380 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) { 381 lldb::TypeSP type = types.GetTypeAtIndex(ti); 382 383 if (!type) 384 continue; 385 386 CompilerType clang_type(type->GetFullCompilerType()); 387 388 if (!ClangUtil::IsClangType(clang_type)) 389 continue; 390 391 const TagType *tag_type = 392 ClangUtil::GetQualType(clang_type)->getAs<TagType>(); 393 394 if (!tag_type) 395 continue; 396 397 TagDecl *candidate_tag_decl = 398 const_cast<TagDecl *>(tag_type->getDecl()); 399 400 // We have found a type by basename and we need to make sure the decl 401 // contexts are the same before we can try to complete this type with 402 // another 403 if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl)) 404 continue; 405 406 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, 407 candidate_tag_decl)) 408 found = true; 409 } 410 } 411 } 412 413 if (log) { 414 LLDB_LOGF(log, " [CTD] After:"); 415 ASTDumper dumper((Decl *)tag_decl); 416 dumper.ToLog(log, " [CTD] "); 417 } 418 } 419 420 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) { 421 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 422 423 if (log) { 424 LLDB_LOGF(log, 425 " [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing " 426 "an ObjCInterfaceDecl named %s", 427 static_cast<void *>(m_ast_context), 428 interface_decl->getName().str().c_str()); 429 LLDB_LOGF(log, " [COID] Before:"); 430 ASTDumper dumper((Decl *)interface_decl); 431 dumper.ToLog(log, " [COID] "); 432 } 433 434 if (!m_ast_importer_sp) { 435 if (HasMerger()) { 436 ObjCInterfaceDecl *complete_iface_decl = 437 GetCompleteObjCInterface(interface_decl); 438 439 if (complete_iface_decl && (complete_iface_decl != interface_decl)) { 440 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()}); 441 } 442 443 GetMergerUnchecked().CompleteType(interface_decl); 444 } else { 445 lldbassert(0 && "No mechanism for completing a type!"); 446 } 447 return; 448 } 449 450 Decl *original_decl = nullptr; 451 ASTContext *original_ctx = nullptr; 452 453 if (m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl, 454 &original_ctx)) { 455 if (ObjCInterfaceDecl *original_iface_decl = 456 dyn_cast<ObjCInterfaceDecl>(original_decl)) { 457 ObjCInterfaceDecl *complete_iface_decl = 458 GetCompleteObjCInterface(original_iface_decl); 459 460 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) { 461 m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl); 462 } 463 } 464 } 465 466 m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl); 467 468 if (interface_decl->getSuperClass() && 469 interface_decl->getSuperClass() != interface_decl) 470 CompleteType(interface_decl->getSuperClass()); 471 472 if (log) { 473 LLDB_LOGF(log, " [COID] After:"); 474 ASTDumper dumper((Decl *)interface_decl); 475 dumper.ToLog(log, " [COID] "); 476 } 477 } 478 479 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface( 480 const clang::ObjCInterfaceDecl *interface_decl) { 481 lldb::ProcessSP process(m_target->GetProcessSP()); 482 483 if (!process) 484 return nullptr; 485 486 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 487 488 if (!language_runtime) 489 return nullptr; 490 491 ConstString class_name(interface_decl->getNameAsString().c_str()); 492 493 lldb::TypeSP complete_type_sp( 494 language_runtime->LookupInCompleteClassCache(class_name)); 495 496 if (!complete_type_sp) 497 return nullptr; 498 499 TypeFromUser complete_type = 500 TypeFromUser(complete_type_sp->GetFullCompilerType()); 501 lldb::opaque_compiler_type_t complete_opaque_type = 502 complete_type.GetOpaqueQualType(); 503 504 if (!complete_opaque_type) 505 return nullptr; 506 507 const clang::Type *complete_clang_type = 508 QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr(); 509 const ObjCInterfaceType *complete_interface_type = 510 dyn_cast<ObjCInterfaceType>(complete_clang_type); 511 512 if (!complete_interface_type) 513 return nullptr; 514 515 ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl()); 516 517 return complete_iface_decl; 518 } 519 520 void ClangASTSource::FindExternalLexicalDecls( 521 const DeclContext *decl_context, 522 llvm::function_ref<bool(Decl::Kind)> predicate, 523 llvm::SmallVectorImpl<Decl *> &decls) { 524 525 if (HasMerger()) { 526 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(decl_context)) { 527 ObjCInterfaceDecl *complete_iface_decl = 528 GetCompleteObjCInterface(interface_decl); 529 530 if (complete_iface_decl && (complete_iface_decl != interface_decl)) { 531 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()}); 532 } 533 } 534 return GetMergerUnchecked().FindExternalLexicalDecls(decl_context, 535 predicate, 536 decls); 537 } else if (!m_ast_importer_sp) 538 return; 539 540 ClangASTMetrics::RegisterLexicalQuery(); 541 542 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 543 544 const Decl *context_decl = dyn_cast<Decl>(decl_context); 545 546 if (!context_decl) 547 return; 548 549 auto iter = m_active_lexical_decls.find(context_decl); 550 if (iter != m_active_lexical_decls.end()) 551 return; 552 m_active_lexical_decls.insert(context_decl); 553 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl); 554 555 static unsigned int invocation_id = 0; 556 unsigned int current_id = invocation_id++; 557 558 if (log) { 559 if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl)) 560 LLDB_LOGF( 561 log, 562 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p", 563 current_id, static_cast<void *>(m_ast_context), 564 context_named_decl->getNameAsString().c_str(), 565 context_decl->getDeclKindName(), 566 static_cast<const void *>(context_decl)); 567 else if (context_decl) 568 LLDB_LOGF( 569 log, "FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p", 570 current_id, static_cast<void *>(m_ast_context), 571 context_decl->getDeclKindName(), 572 static_cast<const void *>(context_decl)); 573 else 574 LLDB_LOGF( 575 log, 576 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context", 577 current_id, static_cast<const void *>(m_ast_context)); 578 } 579 580 Decl *original_decl = nullptr; 581 ASTContext *original_ctx = nullptr; 582 583 if (!m_ast_importer_sp->ResolveDeclOrigin(context_decl, &original_decl, 584 &original_ctx)) 585 return; 586 587 if (log) { 588 LLDB_LOGF( 589 log, " FELD[%u] Original decl (ASTContext*)%p (Decl*)%p:", current_id, 590 static_cast<void *>(original_ctx), static_cast<void *>(original_decl)); 591 ASTDumper(original_decl).ToLog(log, " "); 592 } 593 594 if (ObjCInterfaceDecl *original_iface_decl = 595 dyn_cast<ObjCInterfaceDecl>(original_decl)) { 596 ObjCInterfaceDecl *complete_iface_decl = 597 GetCompleteObjCInterface(original_iface_decl); 598 599 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) { 600 original_decl = complete_iface_decl; 601 original_ctx = &complete_iface_decl->getASTContext(); 602 603 m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl); 604 } 605 } 606 607 if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original_decl)) { 608 ExternalASTSource *external_source = original_ctx->getExternalSource(); 609 610 if (external_source) 611 external_source->CompleteType(original_tag_decl); 612 } 613 614 const DeclContext *original_decl_context = 615 dyn_cast<DeclContext>(original_decl); 616 617 if (!original_decl_context) 618 return; 619 620 // Indicates whether we skipped any Decls of the original DeclContext. 621 bool SkippedDecls = false; 622 for (TagDecl::decl_iterator iter = original_decl_context->decls_begin(); 623 iter != original_decl_context->decls_end(); ++iter) { 624 Decl *decl = *iter; 625 626 // The predicate function returns true if the passed declaration kind is 627 // the one we are looking for. 628 // See clang::ExternalASTSource::FindExternalLexicalDecls() 629 if (predicate(decl->getKind())) { 630 if (log) { 631 ASTDumper ast_dumper(decl); 632 if (const NamedDecl *context_named_decl = 633 dyn_cast<NamedDecl>(context_decl)) 634 LLDB_LOGF(log, " FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s", 635 current_id, context_named_decl->getDeclKindName(), 636 context_named_decl->getNameAsString().c_str(), 637 decl->getDeclKindName(), ast_dumper.GetCString()); 638 else 639 LLDB_LOGF(log, " FELD[%d] Adding lexical %sDecl %s", current_id, 640 decl->getDeclKindName(), ast_dumper.GetCString()); 641 } 642 643 Decl *copied_decl = CopyDecl(decl); 644 645 if (!copied_decl) 646 continue; 647 648 if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) { 649 QualType copied_field_type = copied_field->getType(); 650 651 m_ast_importer_sp->RequireCompleteType(copied_field_type); 652 } 653 } else { 654 SkippedDecls = true; 655 } 656 } 657 658 // CopyDecl may build a lookup table which may set up ExternalLexicalStorage 659 // to false. However, since we skipped some of the external Decls we must 660 // set it back! 661 if (SkippedDecls) { 662 decl_context->setHasExternalLexicalStorage(true); 663 // This sets HasLazyExternalLexicalLookups to true. By setting this bit we 664 // ensure that the lookup table is rebuilt, which means the external source 665 // is consulted again when a clang::DeclContext::lookup is called. 666 const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable(); 667 } 668 669 return; 670 } 671 672 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) { 673 assert(m_ast_context); 674 675 ClangASTMetrics::RegisterVisibleQuery(); 676 677 const ConstString name(context.m_decl_name.getAsString().c_str()); 678 679 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 680 681 static unsigned int invocation_id = 0; 682 unsigned int current_id = invocation_id++; 683 684 if (log) { 685 if (!context.m_decl_context) 686 LLDB_LOGF(log, 687 "ClangASTSource::FindExternalVisibleDecls[%u] on " 688 "(ASTContext*)%p for '%s' in a NULL DeclContext", 689 current_id, static_cast<void *>(m_ast_context), 690 name.GetCString()); 691 else if (const NamedDecl *context_named_decl = 692 dyn_cast<NamedDecl>(context.m_decl_context)) 693 LLDB_LOGF(log, 694 "ClangASTSource::FindExternalVisibleDecls[%u] on " 695 "(ASTContext*)%p for '%s' in '%s'", 696 current_id, static_cast<void *>(m_ast_context), 697 name.GetCString(), 698 context_named_decl->getNameAsString().c_str()); 699 else 700 LLDB_LOGF(log, 701 "ClangASTSource::FindExternalVisibleDecls[%u] on " 702 "(ASTContext*)%p for '%s' in a '%s'", 703 current_id, static_cast<void *>(m_ast_context), 704 name.GetCString(), context.m_decl_context->getDeclKindName()); 705 } 706 707 if (HasMerger() && !isa<TranslationUnitDecl>(context.m_decl_context) 708 /* possibly handle NamespaceDecls here? */) { 709 if (auto *interface_decl = 710 dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) { 711 ObjCInterfaceDecl *complete_iface_decl = 712 GetCompleteObjCInterface(interface_decl); 713 714 if (complete_iface_decl && (complete_iface_decl != interface_decl)) { 715 GetMergerUnchecked().ForceRecordOrigin( 716 interface_decl, 717 {complete_iface_decl, &complete_iface_decl->getASTContext()}); 718 } 719 } 720 721 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context, 722 context.m_decl_name); 723 return; // otherwise we may need to fall back 724 } 725 726 context.m_namespace_map = std::make_shared<ClangASTImporter::NamespaceMap>(); 727 728 if (const NamespaceDecl *namespace_context = 729 dyn_cast<NamespaceDecl>(context.m_decl_context)) { 730 ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp ? 731 m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr; 732 733 if (log && log->GetVerbose()) 734 LLDB_LOGF(log, " CAS::FEVD[%u] Inspecting namespace map %p (%d entries)", 735 current_id, static_cast<void *>(namespace_map.get()), 736 static_cast<int>(namespace_map->size())); 737 738 if (!namespace_map) 739 return; 740 741 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), 742 e = namespace_map->end(); 743 i != e; ++i) { 744 LLDB_LOGF(log, " CAS::FEVD[%u] Searching namespace %s in module %s", 745 current_id, i->second.GetName().AsCString(), 746 i->first->GetFileSpec().GetFilename().GetCString()); 747 748 FindExternalVisibleDecls(context, i->first, i->second, current_id); 749 } 750 } else if (isa<ObjCInterfaceDecl>(context.m_decl_context) && !HasMerger()) { 751 FindObjCPropertyAndIvarDecls(context); 752 } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) { 753 // we shouldn't be getting FindExternalVisibleDecls calls for these 754 return; 755 } else { 756 CompilerDeclContext namespace_decl; 757 758 LLDB_LOGF(log, " CAS::FEVD[%u] Searching the root namespace", current_id); 759 760 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl, 761 current_id); 762 } 763 764 if (!context.m_namespace_map->empty()) { 765 if (log && log->GetVerbose()) 766 LLDB_LOGF(log, 767 " CAS::FEVD[%u] Registering namespace map %p (%d entries)", 768 current_id, static_cast<void *>(context.m_namespace_map.get()), 769 static_cast<int>(context.m_namespace_map->size())); 770 771 NamespaceDecl *clang_namespace_decl = 772 AddNamespace(context, context.m_namespace_map); 773 774 if (clang_namespace_decl) 775 clang_namespace_decl->setHasExternalVisibleStorage(); 776 } 777 } 778 779 clang::Sema *ClangASTSource::getSema() { 780 return ClangASTContext::GetASTContext(m_ast_context)->getSema(); 781 } 782 783 bool ClangASTSource::IgnoreName(const ConstString name, 784 bool ignore_all_dollar_names) { 785 static const ConstString id_name("id"); 786 static const ConstString Class_name("Class"); 787 788 if (m_ast_context->getLangOpts().ObjC) 789 if (name == id_name || name == Class_name) 790 return true; 791 792 StringRef name_string_ref = name.GetStringRef(); 793 794 // The ClangASTSource is not responsible for finding $-names. 795 return name_string_ref.empty() || 796 (ignore_all_dollar_names && name_string_ref.startswith("$")) || 797 name_string_ref.startswith("_$"); 798 } 799 800 void ClangASTSource::FindExternalVisibleDecls( 801 NameSearchContext &context, lldb::ModuleSP module_sp, 802 CompilerDeclContext &namespace_decl, unsigned int current_id) { 803 assert(m_ast_context); 804 805 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 806 807 SymbolContextList sc_list; 808 809 const ConstString name(context.m_decl_name.getAsString().c_str()); 810 if (IgnoreName(name, true)) 811 return; 812 813 if (module_sp && namespace_decl) { 814 CompilerDeclContext found_namespace_decl; 815 816 if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) { 817 found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl); 818 819 if (found_namespace_decl) { 820 context.m_namespace_map->push_back( 821 std::pair<lldb::ModuleSP, CompilerDeclContext>( 822 module_sp, found_namespace_decl)); 823 824 LLDB_LOGF(log, " CAS::FEVD[%u] Found namespace %s in module %s", 825 current_id, name.GetCString(), 826 module_sp->GetFileSpec().GetFilename().GetCString()); 827 } 828 } 829 } else if (!HasMerger()) { 830 const ModuleList &target_images = m_target->GetImages(); 831 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex()); 832 833 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { 834 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); 835 836 if (!image) 837 continue; 838 839 CompilerDeclContext found_namespace_decl; 840 841 SymbolFile *symbol_file = image->GetSymbolFile(); 842 843 if (!symbol_file) 844 continue; 845 846 found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl); 847 848 if (found_namespace_decl) { 849 context.m_namespace_map->push_back( 850 std::pair<lldb::ModuleSP, CompilerDeclContext>( 851 image, found_namespace_decl)); 852 853 LLDB_LOGF(log, " CAS::FEVD[%u] Found namespace %s in module %s", 854 current_id, name.GetCString(), 855 image->GetFileSpec().GetFilename().GetCString()); 856 } 857 } 858 } 859 860 do { 861 if (context.m_found.type) 862 break; 863 864 TypeList types; 865 const bool exact_match = true; 866 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; 867 if (module_sp && namespace_decl) 868 module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types); 869 else { 870 m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1, 871 searched_symbol_files, types); 872 } 873 874 if (size_t num_types = types.GetSize()) { 875 for (size_t ti = 0; ti < num_types; ++ti) { 876 lldb::TypeSP type_sp = types.GetTypeAtIndex(ti); 877 878 if (log) { 879 const char *name_string = type_sp->GetName().GetCString(); 880 881 LLDB_LOGF(log, " CAS::FEVD[%u] Matching type found for \"%s\": %s", 882 current_id, name.GetCString(), 883 (name_string ? name_string : "<anonymous>")); 884 } 885 886 CompilerType full_type = type_sp->GetFullCompilerType(); 887 888 CompilerType copied_clang_type(GuardedCopyType(full_type)); 889 890 if (!copied_clang_type) { 891 LLDB_LOGF(log, " CAS::FEVD[%u] - Couldn't export a type", 892 current_id); 893 894 continue; 895 } 896 897 context.AddTypeDecl(copied_clang_type); 898 899 context.m_found.type = true; 900 break; 901 } 902 } 903 904 if (!context.m_found.type) { 905 // Try the modules next. 906 907 do { 908 if (ClangModulesDeclVendor *modules_decl_vendor = 909 m_target->GetClangModulesDeclVendor()) { 910 bool append = false; 911 uint32_t max_matches = 1; 912 std::vector<clang::NamedDecl *> decls; 913 914 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls)) 915 break; 916 917 if (log) { 918 LLDB_LOGF(log, 919 " CAS::FEVD[%u] Matching entity found for \"%s\" in " 920 "the modules", 921 current_id, name.GetCString()); 922 } 923 924 clang::NamedDecl *const decl_from_modules = decls[0]; 925 926 if (llvm::isa<clang::TypeDecl>(decl_from_modules) || 927 llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) || 928 llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) { 929 clang::Decl *copied_decl = CopyDecl(decl_from_modules); 930 clang::NamedDecl *copied_named_decl = 931 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr; 932 933 if (!copied_named_decl) { 934 LLDB_LOGF( 935 log, 936 " CAS::FEVD[%u] - Couldn't export a type from the modules", 937 current_id); 938 939 break; 940 } 941 942 context.AddNamedDecl(copied_named_decl); 943 944 context.m_found.type = true; 945 } 946 } 947 } while (false); 948 } 949 950 if (!context.m_found.type) { 951 do { 952 // Couldn't find any types elsewhere. Try the Objective-C runtime if 953 // one exists. 954 955 lldb::ProcessSP process(m_target->GetProcessSP()); 956 957 if (!process) 958 break; 959 960 ObjCLanguageRuntime *language_runtime( 961 ObjCLanguageRuntime::Get(*process)); 962 963 if (!language_runtime) 964 break; 965 966 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 967 968 if (!decl_vendor) 969 break; 970 971 bool append = false; 972 uint32_t max_matches = 1; 973 std::vector<clang::NamedDecl *> decls; 974 975 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor); 976 if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls)) 977 break; 978 979 if (log) { 980 LLDB_LOGF( 981 log, 982 " CAS::FEVD[%u] Matching type found for \"%s\" in the runtime", 983 current_id, name.GetCString()); 984 } 985 986 clang::Decl *copied_decl = CopyDecl(decls[0]); 987 clang::NamedDecl *copied_named_decl = 988 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr; 989 990 if (!copied_named_decl) { 991 LLDB_LOGF(log, 992 " CAS::FEVD[%u] - Couldn't export a type from the runtime", 993 current_id); 994 995 break; 996 } 997 998 context.AddNamedDecl(copied_named_decl); 999 } while (false); 1000 } 1001 1002 } while (false); 1003 } 1004 1005 template <class D> class TaggedASTDecl { 1006 public: 1007 TaggedASTDecl() : decl(nullptr) {} 1008 TaggedASTDecl(D *_decl) : decl(_decl) {} 1009 bool IsValid() const { return (decl != nullptr); } 1010 bool IsInvalid() const { return !IsValid(); } 1011 D *operator->() const { return decl; } 1012 D *decl; 1013 }; 1014 1015 template <class D2, template <class D> class TD, class D1> 1016 TD<D2> DynCast(TD<D1> source) { 1017 return TD<D2>(dyn_cast<D2>(source.decl)); 1018 } 1019 1020 template <class D = Decl> class DeclFromParser; 1021 template <class D = Decl> class DeclFromUser; 1022 1023 template <class D> class DeclFromParser : public TaggedASTDecl<D> { 1024 public: 1025 DeclFromParser() : TaggedASTDecl<D>() {} 1026 DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {} 1027 1028 DeclFromUser<D> GetOrigin(ClangASTSource &source); 1029 }; 1030 1031 template <class D> class DeclFromUser : public TaggedASTDecl<D> { 1032 public: 1033 DeclFromUser() : TaggedASTDecl<D>() {} 1034 DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {} 1035 1036 DeclFromParser<D> Import(ClangASTSource &source); 1037 }; 1038 1039 template <class D> 1040 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) { 1041 DeclFromUser<> origin_decl; 1042 source.ResolveDeclOrigin(this->decl, &origin_decl.decl, nullptr); 1043 if (origin_decl.IsInvalid()) 1044 return DeclFromUser<D>(); 1045 return DeclFromUser<D>(dyn_cast<D>(origin_decl.decl)); 1046 } 1047 1048 template <class D> 1049 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) { 1050 DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl)); 1051 if (parser_generic_decl.IsInvalid()) 1052 return DeclFromParser<D>(); 1053 return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl)); 1054 } 1055 1056 bool ClangASTSource::FindObjCMethodDeclsWithOrigin( 1057 unsigned int current_id, NameSearchContext &context, 1058 ObjCInterfaceDecl *original_interface_decl, const char *log_info) { 1059 const DeclarationName &decl_name(context.m_decl_name); 1060 clang::ASTContext *original_ctx = &original_interface_decl->getASTContext(); 1061 1062 Selector original_selector; 1063 1064 if (decl_name.isObjCZeroArgSelector()) { 1065 IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString()); 1066 original_selector = original_ctx->Selectors.getSelector(0, &ident); 1067 } else if (decl_name.isObjCOneArgSelector()) { 1068 const std::string &decl_name_string = decl_name.getAsString(); 1069 std::string decl_name_string_without_colon(decl_name_string.c_str(), 1070 decl_name_string.length() - 1); 1071 IdentifierInfo *ident = 1072 &original_ctx->Idents.get(decl_name_string_without_colon); 1073 original_selector = original_ctx->Selectors.getSelector(1, &ident); 1074 } else { 1075 SmallVector<IdentifierInfo *, 4> idents; 1076 1077 clang::Selector sel = decl_name.getObjCSelector(); 1078 1079 unsigned num_args = sel.getNumArgs(); 1080 1081 for (unsigned i = 0; i != num_args; ++i) { 1082 idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i))); 1083 } 1084 1085 original_selector = 1086 original_ctx->Selectors.getSelector(num_args, idents.data()); 1087 } 1088 1089 DeclarationName original_decl_name(original_selector); 1090 1091 llvm::SmallVector<NamedDecl *, 1> methods; 1092 1093 ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl); 1094 1095 if (ObjCMethodDecl *instance_method_decl = 1096 original_interface_decl->lookupInstanceMethod(original_selector)) { 1097 methods.push_back(instance_method_decl); 1098 } else if (ObjCMethodDecl *class_method_decl = 1099 original_interface_decl->lookupClassMethod( 1100 original_selector)) { 1101 methods.push_back(class_method_decl); 1102 } 1103 1104 if (methods.empty()) { 1105 return false; 1106 } 1107 1108 for (NamedDecl *named_decl : methods) { 1109 if (!named_decl) 1110 continue; 1111 1112 ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl); 1113 1114 if (!result_method) 1115 continue; 1116 1117 Decl *copied_decl = CopyDecl(result_method); 1118 1119 if (!copied_decl) 1120 continue; 1121 1122 ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl); 1123 1124 if (!copied_method_decl) 1125 continue; 1126 1127 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1128 1129 if (log) { 1130 ASTDumper dumper((Decl *)copied_method_decl); 1131 LLDB_LOGF(log, " CAS::FOMD[%d] found (%s) %s", current_id, log_info, 1132 dumper.GetCString()); 1133 } 1134 1135 context.AddNamedDecl(copied_method_decl); 1136 } 1137 1138 return true; 1139 } 1140 1141 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) { 1142 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1143 1144 if (HasMerger()) { 1145 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) { 1146 ObjCInterfaceDecl *complete_iface_decl = 1147 GetCompleteObjCInterface(interface_decl); 1148 1149 if (complete_iface_decl && (complete_iface_decl != context.m_decl_context)) { 1150 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()}); 1151 } 1152 } 1153 1154 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context, 1155 context.m_decl_name); 1156 return; 1157 } 1158 1159 static unsigned int invocation_id = 0; 1160 unsigned int current_id = invocation_id++; 1161 1162 const DeclarationName &decl_name(context.m_decl_name); 1163 const DeclContext *decl_ctx(context.m_decl_context); 1164 1165 const ObjCInterfaceDecl *interface_decl = 1166 dyn_cast<ObjCInterfaceDecl>(decl_ctx); 1167 1168 if (!interface_decl) 1169 return; 1170 1171 do { 1172 Decl *original_decl = nullptr; 1173 ASTContext *original_ctx = nullptr; 1174 1175 m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl, 1176 &original_ctx); 1177 1178 if (!original_decl) 1179 break; 1180 1181 ObjCInterfaceDecl *original_interface_decl = 1182 dyn_cast<ObjCInterfaceDecl>(original_decl); 1183 1184 if (FindObjCMethodDeclsWithOrigin(current_id, context, 1185 original_interface_decl, "at origin")) 1186 return; // found it, no need to look any further 1187 } while (false); 1188 1189 StreamString ss; 1190 1191 if (decl_name.isObjCZeroArgSelector()) { 1192 ss.Printf("%s", decl_name.getAsString().c_str()); 1193 } else if (decl_name.isObjCOneArgSelector()) { 1194 ss.Printf("%s", decl_name.getAsString().c_str()); 1195 } else { 1196 clang::Selector sel = decl_name.getObjCSelector(); 1197 1198 for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) { 1199 llvm::StringRef r = sel.getNameForSlot(i); 1200 ss.Printf("%s:", r.str().c_str()); 1201 } 1202 } 1203 ss.Flush(); 1204 1205 if (ss.GetString().contains("$__lldb")) 1206 return; // we don't need any results 1207 1208 ConstString selector_name(ss.GetString()); 1209 1210 LLDB_LOGF(log, 1211 "ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p " 1212 "for selector [%s %s]", 1213 current_id, static_cast<void *>(m_ast_context), 1214 interface_decl->getNameAsString().c_str(), 1215 selector_name.AsCString()); 1216 SymbolContextList sc_list; 1217 1218 const bool include_symbols = false; 1219 const bool include_inlines = false; 1220 const bool append = false; 1221 1222 std::string interface_name = interface_decl->getNameAsString(); 1223 1224 do { 1225 StreamString ms; 1226 ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString()); 1227 ms.Flush(); 1228 ConstString instance_method_name(ms.GetString()); 1229 1230 m_target->GetImages().FindFunctions( 1231 instance_method_name, lldb::eFunctionNameTypeFull, include_symbols, 1232 include_inlines, append, sc_list); 1233 1234 if (sc_list.GetSize()) 1235 break; 1236 1237 ms.Clear(); 1238 ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString()); 1239 ms.Flush(); 1240 ConstString class_method_name(ms.GetString()); 1241 1242 m_target->GetImages().FindFunctions( 1243 class_method_name, lldb::eFunctionNameTypeFull, include_symbols, 1244 include_inlines, append, sc_list); 1245 1246 if (sc_list.GetSize()) 1247 break; 1248 1249 // Fall back and check for methods in categories. If we find methods this 1250 // way, we need to check that they're actually in categories on the desired 1251 // class. 1252 1253 SymbolContextList candidate_sc_list; 1254 1255 m_target->GetImages().FindFunctions( 1256 selector_name, lldb::eFunctionNameTypeSelector, include_symbols, 1257 include_inlines, append, candidate_sc_list); 1258 1259 for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) { 1260 SymbolContext candidate_sc; 1261 1262 if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc)) 1263 continue; 1264 1265 if (!candidate_sc.function) 1266 continue; 1267 1268 const char *candidate_name = candidate_sc.function->GetName().AsCString(); 1269 1270 const char *cursor = candidate_name; 1271 1272 if (*cursor != '+' && *cursor != '-') 1273 continue; 1274 1275 ++cursor; 1276 1277 if (*cursor != '[') 1278 continue; 1279 1280 ++cursor; 1281 1282 size_t interface_len = interface_name.length(); 1283 1284 if (strncmp(cursor, interface_name.c_str(), interface_len)) 1285 continue; 1286 1287 cursor += interface_len; 1288 1289 if (*cursor == ' ' || *cursor == '(') 1290 sc_list.Append(candidate_sc); 1291 } 1292 } while (false); 1293 1294 if (sc_list.GetSize()) { 1295 // We found a good function symbol. Use that. 1296 1297 for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) { 1298 SymbolContext sc; 1299 1300 if (!sc_list.GetContextAtIndex(i, sc)) 1301 continue; 1302 1303 if (!sc.function) 1304 continue; 1305 1306 CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext(); 1307 if (!function_decl_ctx) 1308 continue; 1309 1310 ObjCMethodDecl *method_decl = 1311 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx); 1312 1313 if (!method_decl) 1314 continue; 1315 1316 ObjCInterfaceDecl *found_interface_decl = 1317 method_decl->getClassInterface(); 1318 1319 if (!found_interface_decl) 1320 continue; 1321 1322 if (found_interface_decl->getName() == interface_decl->getName()) { 1323 Decl *copied_decl = CopyDecl(method_decl); 1324 1325 if (!copied_decl) 1326 continue; 1327 1328 ObjCMethodDecl *copied_method_decl = 1329 dyn_cast<ObjCMethodDecl>(copied_decl); 1330 1331 if (!copied_method_decl) 1332 continue; 1333 1334 if (log) { 1335 ASTDumper dumper((Decl *)copied_method_decl); 1336 LLDB_LOGF(log, " CAS::FOMD[%d] found (in symbols) %s", current_id, 1337 dumper.GetCString()); 1338 } 1339 1340 context.AddNamedDecl(copied_method_decl); 1341 } 1342 } 1343 1344 return; 1345 } 1346 1347 // Try the debug information. 1348 1349 do { 1350 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( 1351 const_cast<ObjCInterfaceDecl *>(interface_decl)); 1352 1353 if (!complete_interface_decl) 1354 break; 1355 1356 // We found the complete interface. The runtime never needs to be queried 1357 // in this scenario. 1358 1359 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl( 1360 complete_interface_decl); 1361 1362 if (complete_interface_decl == interface_decl) 1363 break; // already checked this one 1364 1365 LLDB_LOGF(log, 1366 "CAS::FOPD[%d] trying origin " 1367 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1368 current_id, static_cast<void *>(complete_interface_decl), 1369 static_cast<void *>(&complete_iface_decl->getASTContext())); 1370 1371 FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl, 1372 "in debug info"); 1373 1374 return; 1375 } while (false); 1376 1377 do { 1378 // Check the modules only if the debug information didn't have a complete 1379 // interface. 1380 1381 if (ClangModulesDeclVendor *modules_decl_vendor = 1382 m_target->GetClangModulesDeclVendor()) { 1383 ConstString interface_name(interface_decl->getNameAsString().c_str()); 1384 bool append = false; 1385 uint32_t max_matches = 1; 1386 std::vector<clang::NamedDecl *> decls; 1387 1388 if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches, 1389 decls)) 1390 break; 1391 1392 ObjCInterfaceDecl *interface_decl_from_modules = 1393 dyn_cast<ObjCInterfaceDecl>(decls[0]); 1394 1395 if (!interface_decl_from_modules) 1396 break; 1397 1398 if (FindObjCMethodDeclsWithOrigin( 1399 current_id, context, interface_decl_from_modules, "in modules")) 1400 return; 1401 } 1402 } while (false); 1403 1404 do { 1405 // Check the runtime only if the debug information didn't have a complete 1406 // interface and the modules don't get us anywhere. 1407 1408 lldb::ProcessSP process(m_target->GetProcessSP()); 1409 1410 if (!process) 1411 break; 1412 1413 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 1414 1415 if (!language_runtime) 1416 break; 1417 1418 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 1419 1420 if (!decl_vendor) 1421 break; 1422 1423 ConstString interface_name(interface_decl->getNameAsString().c_str()); 1424 bool append = false; 1425 uint32_t max_matches = 1; 1426 std::vector<clang::NamedDecl *> decls; 1427 1428 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor); 1429 if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches, 1430 decls)) 1431 break; 1432 1433 ObjCInterfaceDecl *runtime_interface_decl = 1434 dyn_cast<ObjCInterfaceDecl>(decls[0]); 1435 1436 if (!runtime_interface_decl) 1437 break; 1438 1439 FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl, 1440 "in runtime"); 1441 } while (false); 1442 } 1443 1444 static bool FindObjCPropertyAndIvarDeclsWithOrigin( 1445 unsigned int current_id, NameSearchContext &context, ClangASTSource &source, 1446 DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) { 1447 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1448 1449 if (origin_iface_decl.IsInvalid()) 1450 return false; 1451 1452 std::string name_str = context.m_decl_name.getAsString(); 1453 StringRef name(name_str); 1454 IdentifierInfo &name_identifier( 1455 origin_iface_decl->getASTContext().Idents.get(name)); 1456 1457 DeclFromUser<ObjCPropertyDecl> origin_property_decl( 1458 origin_iface_decl->FindPropertyDeclaration( 1459 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance)); 1460 1461 bool found = false; 1462 1463 if (origin_property_decl.IsValid()) { 1464 DeclFromParser<ObjCPropertyDecl> parser_property_decl( 1465 origin_property_decl.Import(source)); 1466 if (parser_property_decl.IsValid()) { 1467 if (log) { 1468 ASTDumper dumper((Decl *)parser_property_decl.decl); 1469 LLDB_LOGF(log, " CAS::FOPD[%d] found %s", current_id, 1470 dumper.GetCString()); 1471 } 1472 1473 context.AddNamedDecl(parser_property_decl.decl); 1474 found = true; 1475 } 1476 } 1477 1478 DeclFromUser<ObjCIvarDecl> origin_ivar_decl( 1479 origin_iface_decl->getIvarDecl(&name_identifier)); 1480 1481 if (origin_ivar_decl.IsValid()) { 1482 DeclFromParser<ObjCIvarDecl> parser_ivar_decl( 1483 origin_ivar_decl.Import(source)); 1484 if (parser_ivar_decl.IsValid()) { 1485 if (log) { 1486 ASTDumper dumper((Decl *)parser_ivar_decl.decl); 1487 LLDB_LOGF(log, " CAS::FOPD[%d] found %s", current_id, 1488 dumper.GetCString()); 1489 } 1490 1491 context.AddNamedDecl(parser_ivar_decl.decl); 1492 found = true; 1493 } 1494 } 1495 1496 return found; 1497 } 1498 1499 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) { 1500 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1501 1502 static unsigned int invocation_id = 0; 1503 unsigned int current_id = invocation_id++; 1504 1505 DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl( 1506 cast<ObjCInterfaceDecl>(context.m_decl_context)); 1507 DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl( 1508 parser_iface_decl.GetOrigin(*this)); 1509 1510 ConstString class_name(parser_iface_decl->getNameAsString().c_str()); 1511 1512 LLDB_LOGF(log, 1513 "ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on " 1514 "(ASTContext*)%p for '%s.%s'", 1515 current_id, static_cast<void *>(m_ast_context), 1516 parser_iface_decl->getNameAsString().c_str(), 1517 context.m_decl_name.getAsString().c_str()); 1518 1519 if (FindObjCPropertyAndIvarDeclsWithOrigin( 1520 current_id, context, *this, origin_iface_decl)) 1521 return; 1522 1523 LLDB_LOGF(log, 1524 "CAS::FOPD[%d] couldn't find the property on origin " 1525 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching " 1526 "elsewhere...", 1527 current_id, static_cast<const void *>(origin_iface_decl.decl), 1528 static_cast<void *>(&origin_iface_decl->getASTContext())); 1529 1530 SymbolContext null_sc; 1531 TypeList type_list; 1532 1533 do { 1534 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( 1535 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl)); 1536 1537 if (!complete_interface_decl) 1538 break; 1539 1540 // We found the complete interface. The runtime never needs to be queried 1541 // in this scenario. 1542 1543 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl( 1544 complete_interface_decl); 1545 1546 if (complete_iface_decl.decl == origin_iface_decl.decl) 1547 break; // already checked this one 1548 1549 LLDB_LOGF(log, 1550 "CAS::FOPD[%d] trying origin " 1551 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1552 current_id, static_cast<const void *>(complete_iface_decl.decl), 1553 static_cast<void *>(&complete_iface_decl->getASTContext())); 1554 1555 FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, 1556 complete_iface_decl); 1557 1558 return; 1559 } while (false); 1560 1561 do { 1562 // Check the modules only if the debug information didn't have a complete 1563 // interface. 1564 1565 ClangModulesDeclVendor *modules_decl_vendor = 1566 m_target->GetClangModulesDeclVendor(); 1567 1568 if (!modules_decl_vendor) 1569 break; 1570 1571 bool append = false; 1572 uint32_t max_matches = 1; 1573 std::vector<clang::NamedDecl *> decls; 1574 1575 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls)) 1576 break; 1577 1578 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules( 1579 dyn_cast<ObjCInterfaceDecl>(decls[0])); 1580 1581 if (!interface_decl_from_modules.IsValid()) 1582 break; 1583 1584 LLDB_LOGF( 1585 log, 1586 "CAS::FOPD[%d] trying module " 1587 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1588 current_id, static_cast<const void *>(interface_decl_from_modules.decl), 1589 static_cast<void *>(&interface_decl_from_modules->getASTContext())); 1590 1591 if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, 1592 interface_decl_from_modules)) 1593 return; 1594 } while (false); 1595 1596 do { 1597 // Check the runtime only if the debug information didn't have a complete 1598 // interface and nothing was in the modules. 1599 1600 lldb::ProcessSP process(m_target->GetProcessSP()); 1601 1602 if (!process) 1603 return; 1604 1605 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 1606 1607 if (!language_runtime) 1608 return; 1609 1610 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 1611 1612 if (!decl_vendor) 1613 break; 1614 1615 bool append = false; 1616 uint32_t max_matches = 1; 1617 std::vector<clang::NamedDecl *> decls; 1618 1619 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor); 1620 if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls)) 1621 break; 1622 1623 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime( 1624 dyn_cast<ObjCInterfaceDecl>(decls[0])); 1625 1626 if (!interface_decl_from_runtime.IsValid()) 1627 break; 1628 1629 LLDB_LOGF( 1630 log, 1631 "CAS::FOPD[%d] trying runtime " 1632 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1633 current_id, static_cast<const void *>(interface_decl_from_runtime.decl), 1634 static_cast<void *>(&interface_decl_from_runtime->getASTContext())); 1635 1636 if (FindObjCPropertyAndIvarDeclsWithOrigin( 1637 current_id, context, *this, interface_decl_from_runtime)) 1638 return; 1639 } while (false); 1640 } 1641 1642 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap; 1643 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap; 1644 1645 template <class D, class O> 1646 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map, 1647 llvm::DenseMap<const D *, O> &source_map, 1648 ClangASTSource &source) { 1649 // When importing fields into a new record, clang has a hard requirement that 1650 // fields be imported in field offset order. Since they are stored in a 1651 // DenseMap with a pointer as the key type, this means we cannot simply 1652 // iterate over the map, as the order will be non-deterministic. Instead we 1653 // have to sort by the offset and then insert in sorted order. 1654 typedef llvm::DenseMap<const D *, O> MapType; 1655 typedef typename MapType::value_type PairType; 1656 std::vector<PairType> sorted_items; 1657 sorted_items.reserve(source_map.size()); 1658 sorted_items.assign(source_map.begin(), source_map.end()); 1659 llvm::sort(sorted_items.begin(), sorted_items.end(), 1660 [](const PairType &lhs, const PairType &rhs) { 1661 return lhs.second < rhs.second; 1662 }); 1663 1664 for (const auto &item : sorted_items) { 1665 DeclFromUser<D> user_decl(const_cast<D *>(item.first)); 1666 DeclFromParser<D> parser_decl(user_decl.Import(source)); 1667 if (parser_decl.IsInvalid()) 1668 return false; 1669 destination_map.insert( 1670 std::pair<const D *, O>(parser_decl.decl, item.second)); 1671 } 1672 1673 return true; 1674 } 1675 1676 template <bool IsVirtual> 1677 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout, 1678 DeclFromUser<const CXXRecordDecl> &record, 1679 BaseOffsetMap &base_offsets) { 1680 for (CXXRecordDecl::base_class_const_iterator 1681 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()), 1682 be = (IsVirtual ? record->vbases_end() : record->bases_end()); 1683 bi != be; ++bi) { 1684 if (!IsVirtual && bi->isVirtual()) 1685 continue; 1686 1687 const clang::Type *origin_base_type = bi->getType().getTypePtr(); 1688 const clang::RecordType *origin_base_record_type = 1689 origin_base_type->getAs<RecordType>(); 1690 1691 if (!origin_base_record_type) 1692 return false; 1693 1694 DeclFromUser<RecordDecl> origin_base_record( 1695 origin_base_record_type->getDecl()); 1696 1697 if (origin_base_record.IsInvalid()) 1698 return false; 1699 1700 DeclFromUser<CXXRecordDecl> origin_base_cxx_record( 1701 DynCast<CXXRecordDecl>(origin_base_record)); 1702 1703 if (origin_base_cxx_record.IsInvalid()) 1704 return false; 1705 1706 CharUnits base_offset; 1707 1708 if (IsVirtual) 1709 base_offset = 1710 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl); 1711 else 1712 base_offset = 1713 record_layout.getBaseClassOffset(origin_base_cxx_record.decl); 1714 1715 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>( 1716 origin_base_cxx_record.decl, base_offset)); 1717 } 1718 1719 return true; 1720 } 1721 1722 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size, 1723 uint64_t &alignment, 1724 FieldOffsetMap &field_offsets, 1725 BaseOffsetMap &base_offsets, 1726 BaseOffsetMap &virtual_base_offsets) { 1727 ClangASTMetrics::RegisterRecordLayout(); 1728 1729 static unsigned int invocation_id = 0; 1730 unsigned int current_id = invocation_id++; 1731 1732 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1733 1734 LLDB_LOGF(log, 1735 "LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p " 1736 "[name = '%s']", 1737 current_id, static_cast<void *>(m_ast_context), 1738 static_cast<const void *>(record), 1739 record->getNameAsString().c_str()); 1740 1741 DeclFromParser<const RecordDecl> parser_record(record); 1742 DeclFromUser<const RecordDecl> origin_record( 1743 parser_record.GetOrigin(*this)); 1744 1745 if (origin_record.IsInvalid()) 1746 return false; 1747 1748 FieldOffsetMap origin_field_offsets; 1749 BaseOffsetMap origin_base_offsets; 1750 BaseOffsetMap origin_virtual_base_offsets; 1751 1752 ClangASTContext::GetCompleteDecl( 1753 &origin_record->getASTContext(), 1754 const_cast<RecordDecl *>(origin_record.decl)); 1755 1756 clang::RecordDecl *definition = origin_record.decl->getDefinition(); 1757 if (!definition || !definition->isCompleteDefinition()) 1758 return false; 1759 1760 const ASTRecordLayout &record_layout( 1761 origin_record->getASTContext().getASTRecordLayout(origin_record.decl)); 1762 1763 int field_idx = 0, field_count = record_layout.getFieldCount(); 1764 1765 for (RecordDecl::field_iterator fi = origin_record->field_begin(), 1766 fe = origin_record->field_end(); 1767 fi != fe; ++fi) { 1768 if (field_idx >= field_count) 1769 return false; // Layout didn't go well. Bail out. 1770 1771 uint64_t field_offset = record_layout.getFieldOffset(field_idx); 1772 1773 origin_field_offsets.insert( 1774 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset)); 1775 1776 field_idx++; 1777 } 1778 1779 lldbassert(&record->getASTContext() == m_ast_context); 1780 1781 DeclFromUser<const CXXRecordDecl> origin_cxx_record( 1782 DynCast<const CXXRecordDecl>(origin_record)); 1783 1784 if (origin_cxx_record.IsValid()) { 1785 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record, 1786 origin_base_offsets) || 1787 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record, 1788 origin_virtual_base_offsets)) 1789 return false; 1790 } 1791 1792 if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) || 1793 !ImportOffsetMap(base_offsets, origin_base_offsets, *this) || 1794 !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets, 1795 *this)) 1796 return false; 1797 1798 size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth(); 1799 alignment = record_layout.getAlignment().getQuantity() * 1800 m_ast_context->getCharWidth(); 1801 1802 if (log) { 1803 LLDB_LOGF(log, "LRT[%u] returned:", current_id); 1804 LLDB_LOGF(log, "LRT[%u] Original = (RecordDecl*)%p", current_id, 1805 static_cast<const void *>(origin_record.decl)); 1806 LLDB_LOGF(log, "LRT[%u] Size = %" PRId64, current_id, size); 1807 LLDB_LOGF(log, "LRT[%u] Alignment = %" PRId64, current_id, alignment); 1808 LLDB_LOGF(log, "LRT[%u] Fields:", current_id); 1809 for (RecordDecl::field_iterator fi = record->field_begin(), 1810 fe = record->field_end(); 1811 fi != fe; ++fi) { 1812 LLDB_LOGF(log, 1813 "LRT[%u] (FieldDecl*)%p, Name = '%s', Offset = %" PRId64 1814 " bits", 1815 current_id, static_cast<void *>(*fi), 1816 fi->getNameAsString().c_str(), field_offsets[*fi]); 1817 } 1818 DeclFromParser<const CXXRecordDecl> parser_cxx_record = 1819 DynCast<const CXXRecordDecl>(parser_record); 1820 if (parser_cxx_record.IsValid()) { 1821 LLDB_LOGF(log, "LRT[%u] Bases:", current_id); 1822 for (CXXRecordDecl::base_class_const_iterator 1823 bi = parser_cxx_record->bases_begin(), 1824 be = parser_cxx_record->bases_end(); 1825 bi != be; ++bi) { 1826 bool is_virtual = bi->isVirtual(); 1827 1828 QualType base_type = bi->getType(); 1829 const RecordType *base_record_type = base_type->getAs<RecordType>(); 1830 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl()); 1831 DeclFromParser<CXXRecordDecl> base_cxx_record = 1832 DynCast<CXXRecordDecl>(base_record); 1833 1834 LLDB_LOGF( 1835 log, 1836 "LRT[%u] %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64 1837 " chars", 1838 current_id, (is_virtual ? "Virtual " : ""), 1839 static_cast<void *>(base_cxx_record.decl), 1840 base_cxx_record.decl->getNameAsString().c_str(), 1841 (is_virtual 1842 ? virtual_base_offsets[base_cxx_record.decl].getQuantity() 1843 : base_offsets[base_cxx_record.decl].getQuantity())); 1844 } 1845 } else { 1846 LLDB_LOGF(log, "LRD[%u] Not a CXXRecord, so no bases", current_id); 1847 } 1848 } 1849 1850 return true; 1851 } 1852 1853 void ClangASTSource::CompleteNamespaceMap( 1854 ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name, 1855 ClangASTImporter::NamespaceMapSP &parent_map) const { 1856 static unsigned int invocation_id = 0; 1857 unsigned int current_id = invocation_id++; 1858 1859 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1860 1861 if (log) { 1862 if (parent_map && parent_map->size()) 1863 LLDB_LOGF(log, 1864 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for " 1865 "namespace %s in namespace %s", 1866 current_id, static_cast<void *>(m_ast_context), 1867 name.GetCString(), 1868 parent_map->begin()->second.GetName().AsCString()); 1869 else 1870 LLDB_LOGF(log, 1871 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for " 1872 "namespace %s", 1873 current_id, static_cast<void *>(m_ast_context), 1874 name.GetCString()); 1875 } 1876 1877 if (parent_map) { 1878 for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(), 1879 e = parent_map->end(); 1880 i != e; ++i) { 1881 CompilerDeclContext found_namespace_decl; 1882 1883 lldb::ModuleSP module_sp = i->first; 1884 CompilerDeclContext module_parent_namespace_decl = i->second; 1885 1886 SymbolFile *symbol_file = module_sp->GetSymbolFile(); 1887 1888 if (!symbol_file) 1889 continue; 1890 1891 found_namespace_decl = 1892 symbol_file->FindNamespace(name, &module_parent_namespace_decl); 1893 1894 if (!found_namespace_decl) 1895 continue; 1896 1897 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>( 1898 module_sp, found_namespace_decl)); 1899 1900 LLDB_LOGF(log, " CMN[%u] Found namespace %s in module %s", current_id, 1901 name.GetCString(), 1902 module_sp->GetFileSpec().GetFilename().GetCString()); 1903 } 1904 } else { 1905 const ModuleList &target_images = m_target->GetImages(); 1906 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex()); 1907 1908 CompilerDeclContext null_namespace_decl; 1909 1910 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { 1911 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); 1912 1913 if (!image) 1914 continue; 1915 1916 CompilerDeclContext found_namespace_decl; 1917 1918 SymbolFile *symbol_file = image->GetSymbolFile(); 1919 1920 if (!symbol_file) 1921 continue; 1922 1923 found_namespace_decl = 1924 symbol_file->FindNamespace(name, &null_namespace_decl); 1925 1926 if (!found_namespace_decl) 1927 continue; 1928 1929 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>( 1930 image, found_namespace_decl)); 1931 1932 LLDB_LOGF(log, " CMN[%u] Found namespace %s in module %s", current_id, 1933 name.GetCString(), 1934 image->GetFileSpec().GetFilename().GetCString()); 1935 } 1936 } 1937 } 1938 1939 NamespaceDecl *ClangASTSource::AddNamespace( 1940 NameSearchContext &context, 1941 ClangASTImporter::NamespaceMapSP &namespace_decls) { 1942 if (!namespace_decls) 1943 return nullptr; 1944 1945 const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second; 1946 1947 clang::ASTContext *src_ast = 1948 ClangASTContext::DeclContextGetClangASTContext(namespace_decl); 1949 if (!src_ast) 1950 return nullptr; 1951 clang::NamespaceDecl *src_namespace_decl = 1952 ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl); 1953 1954 if (!src_namespace_decl) 1955 return nullptr; 1956 1957 Decl *copied_decl = CopyDecl(src_namespace_decl); 1958 1959 if (!copied_decl) 1960 return nullptr; 1961 1962 NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl); 1963 1964 if (!copied_namespace_decl) 1965 return nullptr; 1966 1967 context.m_decls.push_back(copied_namespace_decl); 1968 1969 m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl, 1970 namespace_decls); 1971 1972 return dyn_cast<NamespaceDecl>(copied_decl); 1973 } 1974 1975 clang::QualType ClangASTSource::CopyTypeWithMerger( 1976 clang::ASTContext &from_context, 1977 clang::ExternalASTMerger &merger, 1978 clang::QualType type) { 1979 if (!merger.HasImporterForOrigin(from_context)) { 1980 lldbassert(0 && "Couldn't find the importer for a source context!"); 1981 return QualType(); 1982 } 1983 1984 if (llvm::Expected<QualType> type_or_error = 1985 merger.ImporterForOrigin(from_context).Import(type)) { 1986 return *type_or_error; 1987 } else { 1988 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 1989 LLDB_LOG_ERROR(log, type_or_error.takeError(), "Couldn't import type: {0}"); 1990 return QualType(); 1991 } 1992 } 1993 1994 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) { 1995 clang::ASTContext &from_context = src_decl->getASTContext(); 1996 if (m_ast_importer_sp) { 1997 return m_ast_importer_sp->CopyDecl(m_ast_context, &from_context, src_decl); 1998 } else if (m_merger_up) { 1999 if (!m_merger_up->HasImporterForOrigin(from_context)) { 2000 lldbassert(0 && "Couldn't find the importer for a source context!"); 2001 return nullptr; 2002 } 2003 2004 if (llvm::Expected<Decl *> decl_or_error = 2005 m_merger_up->ImporterForOrigin(from_context).Import(src_decl)) { 2006 return *decl_or_error; 2007 } else { 2008 Log *log = 2009 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 2010 LLDB_LOG_ERROR(log, decl_or_error.takeError(), 2011 "Couldn't import decl: {0}"); 2012 return nullptr; 2013 } 2014 } else { 2015 lldbassert(0 && "No mechanism for copying a decl!"); 2016 return nullptr; 2017 } 2018 } 2019 2020 bool ClangASTSource::ResolveDeclOrigin(const clang::Decl *decl, 2021 clang::Decl **original_decl, 2022 clang::ASTContext **original_ctx) { 2023 if (m_ast_importer_sp) { 2024 return m_ast_importer_sp->ResolveDeclOrigin(decl, original_decl, 2025 original_ctx); 2026 } else if (m_merger_up) { 2027 return false; // Implement this correctly in ExternalASTMerger 2028 } else { 2029 // this can happen early enough that no ExternalASTSource is installed. 2030 return false; 2031 } 2032 } 2033 2034 clang::ExternalASTMerger &ClangASTSource::GetMergerUnchecked() { 2035 lldbassert(m_merger_up != nullptr); 2036 return *m_merger_up; 2037 } 2038 2039 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) { 2040 ClangASTContext *src_ast = 2041 llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem()); 2042 if (src_ast == nullptr) 2043 return CompilerType(); 2044 2045 ClangASTMetrics::RegisterLLDBImport(); 2046 2047 SetImportInProgress(true); 2048 2049 QualType copied_qual_type; 2050 2051 if (m_ast_importer_sp) { 2052 copied_qual_type = 2053 m_ast_importer_sp->CopyType(m_ast_context, src_ast->getASTContext(), 2054 ClangUtil::GetQualType(src_type)); 2055 } else if (m_merger_up) { 2056 copied_qual_type = 2057 CopyTypeWithMerger(*src_ast->getASTContext(), *m_merger_up, 2058 ClangUtil::GetQualType(src_type)); 2059 } else { 2060 lldbassert(0 && "No mechanism for copying a type!"); 2061 return CompilerType(); 2062 } 2063 2064 SetImportInProgress(false); 2065 2066 if (copied_qual_type.getAsOpaquePtr() && 2067 copied_qual_type->getCanonicalTypeInternal().isNull()) 2068 // this shouldn't happen, but we're hardening because the AST importer 2069 // seems to be generating bad types on occasion. 2070 return CompilerType(); 2071 2072 return CompilerType(ClangASTContext::GetASTContext(m_ast_context), 2073 copied_qual_type.getAsOpaquePtr()); 2074 } 2075 2076 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) { 2077 assert(type && "Type for variable must be valid!"); 2078 2079 if (!type.IsValid()) 2080 return nullptr; 2081 2082 ClangASTContext *lldb_ast = 2083 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); 2084 if (!lldb_ast) 2085 return nullptr; 2086 2087 IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo(); 2088 2089 clang::ASTContext *ast = lldb_ast->getASTContext(); 2090 2091 clang::NamedDecl *Decl = VarDecl::Create( 2092 *ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(), 2093 SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static); 2094 m_decls.push_back(Decl); 2095 2096 return Decl; 2097 } 2098 2099 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type, 2100 bool extern_c) { 2101 assert(type && "Type for variable must be valid!"); 2102 2103 if (!type.IsValid()) 2104 return nullptr; 2105 2106 if (m_function_types.count(type)) 2107 return nullptr; 2108 2109 ClangASTContext *lldb_ast = 2110 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); 2111 if (!lldb_ast) 2112 return nullptr; 2113 2114 m_function_types.insert(type); 2115 2116 QualType qual_type(ClangUtil::GetQualType(type)); 2117 2118 clang::ASTContext *ast = lldb_ast->getASTContext(); 2119 2120 const bool isInlineSpecified = false; 2121 const bool hasWrittenPrototype = true; 2122 const bool isConstexprSpecified = false; 2123 2124 clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context); 2125 2126 if (extern_c) { 2127 context = LinkageSpecDecl::Create( 2128 *ast, context, SourceLocation(), SourceLocation(), 2129 clang::LinkageSpecDecl::LanguageIDs::lang_c, false); 2130 } 2131 2132 // Pass the identifier info for functions the decl_name is needed for 2133 // operators 2134 clang::DeclarationName decl_name = 2135 m_decl_name.getNameKind() == DeclarationName::Identifier 2136 ? m_decl_name.getAsIdentifierInfo() 2137 : m_decl_name; 2138 2139 clang::FunctionDecl *func_decl = FunctionDecl::Create( 2140 *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type, 2141 nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype, 2142 isConstexprSpecified ? CSK_constexpr : CSK_unspecified); 2143 2144 // We have to do more than just synthesize the FunctionDecl. We have to 2145 // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do 2146 // this, we raid the function's FunctionProtoType for types. 2147 2148 const FunctionProtoType *func_proto_type = 2149 qual_type.getTypePtr()->getAs<FunctionProtoType>(); 2150 2151 if (func_proto_type) { 2152 unsigned NumArgs = func_proto_type->getNumParams(); 2153 unsigned ArgIndex; 2154 2155 SmallVector<ParmVarDecl *, 5> parm_var_decls; 2156 2157 for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) { 2158 QualType arg_qual_type(func_proto_type->getParamType(ArgIndex)); 2159 2160 parm_var_decls.push_back( 2161 ParmVarDecl::Create(*ast, const_cast<DeclContext *>(context), 2162 SourceLocation(), SourceLocation(), nullptr, 2163 arg_qual_type, nullptr, SC_Static, nullptr)); 2164 } 2165 2166 func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls)); 2167 } else { 2168 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 2169 2170 LLDB_LOGF(log, "Function type wasn't a FunctionProtoType"); 2171 } 2172 2173 // If this is an operator (e.g. operator new or operator==), only insert the 2174 // declaration we inferred from the symbol if we can provide the correct 2175 // number of arguments. We shouldn't really inject random decl(s) for 2176 // functions that are analyzed semantically in a special way, otherwise we 2177 // will crash in clang. 2178 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; 2179 if (func_proto_type && 2180 ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) { 2181 if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount( 2182 false, op_kind, func_proto_type->getNumParams())) 2183 return nullptr; 2184 } 2185 m_decls.push_back(func_decl); 2186 2187 return func_decl; 2188 } 2189 2190 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() { 2191 FunctionProtoType::ExtProtoInfo proto_info; 2192 2193 proto_info.Variadic = true; 2194 2195 QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType( 2196 m_ast_source.m_ast_context->UnknownAnyTy, // result 2197 ArrayRef<QualType>(), // argument types 2198 proto_info)); 2199 2200 return AddFunDecl( 2201 CompilerType(ClangASTContext::GetASTContext(m_ast_source.m_ast_context), 2202 generic_function_type.getAsOpaquePtr()), 2203 true); 2204 } 2205 2206 clang::NamedDecl * 2207 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) { 2208 if (ClangUtil::IsClangType(clang_type)) { 2209 QualType qual_type = ClangUtil::GetQualType(clang_type); 2210 2211 if (const TypedefType *typedef_type = 2212 llvm::dyn_cast<TypedefType>(qual_type)) { 2213 TypedefNameDecl *typedef_name_decl = typedef_type->getDecl(); 2214 2215 m_decls.push_back(typedef_name_decl); 2216 2217 return (NamedDecl *)typedef_name_decl; 2218 } else if (const TagType *tag_type = qual_type->getAs<TagType>()) { 2219 TagDecl *tag_decl = tag_type->getDecl(); 2220 2221 m_decls.push_back(tag_decl); 2222 2223 return tag_decl; 2224 } else if (const ObjCObjectType *objc_object_type = 2225 qual_type->getAs<ObjCObjectType>()) { 2226 ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface(); 2227 2228 m_decls.push_back((NamedDecl *)interface_decl); 2229 2230 return (NamedDecl *)interface_decl; 2231 } 2232 } 2233 return nullptr; 2234 } 2235 2236 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) { 2237 for (clang::NamedDecl *decl : result) 2238 m_decls.push_back(decl); 2239 } 2240 2241 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) { 2242 m_decls.push_back(decl); 2243 } 2244