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