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 when it 37 // 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 by passing false to 145 // 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 any 235 // 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 somewhere 301 // 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 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 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 (m_ast_context->getLangOpts().ObjC) 775 if (name == id_name || name == Class_name) 776 return true; 777 778 StringRef name_string_ref = name.GetStringRef(); 779 780 // The ClangASTSource is not responsible for finding $-names. 781 if (name_string_ref.empty() || 782 (ignore_all_dollar_names && name_string_ref.startswith("$")) || 783 name_string_ref.startswith("_$")) 784 return true; 785 786 return false; 787 } 788 789 void ClangASTSource::FindExternalVisibleDecls( 790 NameSearchContext &context, lldb::ModuleSP module_sp, 791 CompilerDeclContext &namespace_decl, unsigned int current_id) { 792 assert(m_ast_context); 793 794 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 795 796 SymbolContextList sc_list; 797 798 const ConstString name(context.m_decl_name.getAsString().c_str()); 799 if (IgnoreName(name, true)) 800 return; 801 802 if (module_sp && namespace_decl) { 803 CompilerDeclContext found_namespace_decl; 804 805 SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor(); 806 807 if (symbol_vendor) { 808 SymbolContext null_sc; 809 810 found_namespace_decl = 811 symbol_vendor->FindNamespace(null_sc, name, &namespace_decl); 812 813 if (found_namespace_decl) { 814 context.m_namespace_map->push_back( 815 std::pair<lldb::ModuleSP, CompilerDeclContext>( 816 module_sp, found_namespace_decl)); 817 818 if (log) 819 log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s", 820 current_id, name.GetCString(), 821 module_sp->GetFileSpec().GetFilename().GetCString()); 822 } 823 } 824 } else if (!HasMerger()) { 825 const ModuleList &target_images = m_target->GetImages(); 826 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex()); 827 828 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { 829 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); 830 831 if (!image) 832 continue; 833 834 CompilerDeclContext found_namespace_decl; 835 836 SymbolVendor *symbol_vendor = image->GetSymbolVendor(); 837 838 if (!symbol_vendor) 839 continue; 840 841 SymbolContext null_sc; 842 843 found_namespace_decl = 844 symbol_vendor->FindNamespace(null_sc, name, &namespace_decl); 845 846 if (found_namespace_decl) { 847 context.m_namespace_map->push_back( 848 std::pair<lldb::ModuleSP, CompilerDeclContext>( 849 image, found_namespace_decl)); 850 851 if (log) 852 log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s", 853 current_id, name.GetCString(), 854 image->GetFileSpec().GetFilename().GetCString()); 855 } 856 } 857 } 858 859 do { 860 if (context.m_found.type) 861 break; 862 863 TypeList types; 864 SymbolContext null_sc; 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(null_sc, name, &namespace_decl, 1, types); 869 else { 870 SymbolContext sc; 871 sc.module_sp = module_sp; 872 m_target->GetImages().FindTypes(sc, name, exact_match, 1, 873 searched_symbol_files, types); 874 } 875 876 if (size_t num_types = types.GetSize()) { 877 for (size_t ti = 0; ti < num_types; ++ti) { 878 lldb::TypeSP type_sp = types.GetTypeAtIndex(ti); 879 880 if (log) { 881 const char *name_string = type_sp->GetName().GetCString(); 882 883 log->Printf(" CAS::FEVD[%u] Matching type found for \"%s\": %s", 884 current_id, name.GetCString(), 885 (name_string ? name_string : "<anonymous>")); 886 } 887 888 CompilerType full_type = type_sp->GetFullCompilerType(); 889 890 CompilerType copied_clang_type(GuardedCopyType(full_type)); 891 892 if (!copied_clang_type) { 893 if (log) 894 log->Printf(" CAS::FEVD[%u] - Couldn't export a type", current_id); 895 896 continue; 897 } 898 899 context.AddTypeDecl(copied_clang_type); 900 901 context.m_found.type = true; 902 break; 903 } 904 } 905 906 if (!context.m_found.type) { 907 // Try the modules next. 908 909 do { 910 if (ClangModulesDeclVendor *modules_decl_vendor = 911 m_target->GetClangModulesDeclVendor()) { 912 bool append = false; 913 uint32_t max_matches = 1; 914 std::vector<clang::NamedDecl *> decls; 915 916 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls)) 917 break; 918 919 if (log) { 920 log->Printf(" CAS::FEVD[%u] Matching entity found for \"%s\" in " 921 "the modules", 922 current_id, name.GetCString()); 923 } 924 925 clang::NamedDecl *const decl_from_modules = decls[0]; 926 927 if (llvm::isa<clang::TypeDecl>(decl_from_modules) || 928 llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) || 929 llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) { 930 clang::Decl *copied_decl = CopyDecl(decl_from_modules); 931 clang::NamedDecl *copied_named_decl = 932 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr; 933 934 if (!copied_named_decl) { 935 if (log) 936 log->Printf( 937 " CAS::FEVD[%u] - Couldn't export a type from the modules", 938 current_id); 939 940 break; 941 } 942 943 context.AddNamedDecl(copied_named_decl); 944 945 context.m_found.type = true; 946 } 947 } 948 } while (0); 949 } 950 951 if (!context.m_found.type) { 952 do { 953 // Couldn't find any types elsewhere. Try the Objective-C runtime if 954 // one exists. 955 956 lldb::ProcessSP process(m_target->GetProcessSP()); 957 958 if (!process) 959 break; 960 961 ObjCLanguageRuntime *language_runtime( 962 process->GetObjCLanguageRuntime()); 963 964 if (!language_runtime) 965 break; 966 967 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 968 969 if (!decl_vendor) 970 break; 971 972 bool append = false; 973 uint32_t max_matches = 1; 974 std::vector<clang::NamedDecl *> decls; 975 976 if (!decl_vendor->FindDecls(name, append, max_matches, decls)) 977 break; 978 979 if (log) { 980 log->Printf( 981 " CAS::FEVD[%u] Matching type found for \"%s\" in the runtime", 982 current_id, name.GetCString()); 983 } 984 985 clang::Decl *copied_decl = CopyDecl(decls[0]); 986 clang::NamedDecl *copied_named_decl = 987 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr; 988 989 if (!copied_named_decl) { 990 if (log) 991 log->Printf( 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 (0); 1000 } 1001 1002 } while (0); 1003 } 1004 1005 template <class D> class TaggedASTDecl { 1006 public: 1007 TaggedASTDecl() : decl(NULL) {} 1008 TaggedASTDecl(D *_decl) : decl(_decl) {} 1009 bool IsValid() const { return (decl != NULL); } 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, NULL); 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 log->Printf(" 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 = NULL; 1173 ASTContext *original_ctx = NULL; 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 (0); 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 if (log) 1211 log->Printf("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 (0); 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 log->Printf(" 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 if (log) 1366 log->Printf("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 (0); 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 (0); 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(process->GetObjCLanguageRuntime()); 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 if (!decl_vendor->FindDecls(interface_name, append, max_matches, decls)) 1429 break; 1430 1431 ObjCInterfaceDecl *runtime_interface_decl = 1432 dyn_cast<ObjCInterfaceDecl>(decls[0]); 1433 1434 if (!runtime_interface_decl) 1435 break; 1436 1437 FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl, 1438 "in runtime"); 1439 } while (0); 1440 } 1441 1442 static bool FindObjCPropertyAndIvarDeclsWithOrigin( 1443 unsigned int current_id, NameSearchContext &context, ClangASTSource &source, 1444 DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) { 1445 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1446 1447 if (origin_iface_decl.IsInvalid()) 1448 return false; 1449 1450 std::string name_str = context.m_decl_name.getAsString(); 1451 StringRef name(name_str); 1452 IdentifierInfo &name_identifier( 1453 origin_iface_decl->getASTContext().Idents.get(name)); 1454 1455 DeclFromUser<ObjCPropertyDecl> origin_property_decl( 1456 origin_iface_decl->FindPropertyDeclaration( 1457 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance)); 1458 1459 bool found = false; 1460 1461 if (origin_property_decl.IsValid()) { 1462 DeclFromParser<ObjCPropertyDecl> parser_property_decl( 1463 origin_property_decl.Import(source)); 1464 if (parser_property_decl.IsValid()) { 1465 if (log) { 1466 ASTDumper dumper((Decl *)parser_property_decl.decl); 1467 log->Printf(" CAS::FOPD[%d] found %s", current_id, 1468 dumper.GetCString()); 1469 } 1470 1471 context.AddNamedDecl(parser_property_decl.decl); 1472 found = true; 1473 } 1474 } 1475 1476 DeclFromUser<ObjCIvarDecl> origin_ivar_decl( 1477 origin_iface_decl->getIvarDecl(&name_identifier)); 1478 1479 if (origin_ivar_decl.IsValid()) { 1480 DeclFromParser<ObjCIvarDecl> parser_ivar_decl( 1481 origin_ivar_decl.Import(source)); 1482 if (parser_ivar_decl.IsValid()) { 1483 if (log) { 1484 ASTDumper dumper((Decl *)parser_ivar_decl.decl); 1485 log->Printf(" CAS::FOPD[%d] found %s", current_id, 1486 dumper.GetCString()); 1487 } 1488 1489 context.AddNamedDecl(parser_ivar_decl.decl); 1490 found = true; 1491 } 1492 } 1493 1494 return found; 1495 } 1496 1497 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) { 1498 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1499 1500 static unsigned int invocation_id = 0; 1501 unsigned int current_id = invocation_id++; 1502 1503 DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl( 1504 cast<ObjCInterfaceDecl>(context.m_decl_context)); 1505 DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl( 1506 parser_iface_decl.GetOrigin(*this)); 1507 1508 ConstString class_name(parser_iface_decl->getNameAsString().c_str()); 1509 1510 if (log) 1511 log->Printf("ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on " 1512 "(ASTContext*)%p for '%s.%s'", 1513 current_id, static_cast<void *>(m_ast_context), 1514 parser_iface_decl->getNameAsString().c_str(), 1515 context.m_decl_name.getAsString().c_str()); 1516 1517 if (FindObjCPropertyAndIvarDeclsWithOrigin( 1518 current_id, context, *this, origin_iface_decl)) 1519 return; 1520 1521 if (log) 1522 log->Printf("CAS::FOPD[%d] couldn't find the property on origin " 1523 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching " 1524 "elsewhere...", 1525 current_id, static_cast<const void *>(origin_iface_decl.decl), 1526 static_cast<void *>(&origin_iface_decl->getASTContext())); 1527 1528 SymbolContext null_sc; 1529 TypeList type_list; 1530 1531 do { 1532 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( 1533 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl)); 1534 1535 if (!complete_interface_decl) 1536 break; 1537 1538 // We found the complete interface. The runtime never needs to be queried 1539 // in this scenario. 1540 1541 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl( 1542 complete_interface_decl); 1543 1544 if (complete_iface_decl.decl == origin_iface_decl.decl) 1545 break; // already checked this one 1546 1547 if (log) 1548 log->Printf("CAS::FOPD[%d] trying origin " 1549 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1550 current_id, 1551 static_cast<const void *>(complete_iface_decl.decl), 1552 static_cast<void *>(&complete_iface_decl->getASTContext())); 1553 1554 FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, 1555 complete_iface_decl); 1556 1557 return; 1558 } while (0); 1559 1560 do { 1561 // Check the modules only if the debug information didn't have a complete 1562 // interface. 1563 1564 ClangModulesDeclVendor *modules_decl_vendor = 1565 m_target->GetClangModulesDeclVendor(); 1566 1567 if (!modules_decl_vendor) 1568 break; 1569 1570 bool append = false; 1571 uint32_t max_matches = 1; 1572 std::vector<clang::NamedDecl *> decls; 1573 1574 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls)) 1575 break; 1576 1577 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules( 1578 dyn_cast<ObjCInterfaceDecl>(decls[0])); 1579 1580 if (!interface_decl_from_modules.IsValid()) 1581 break; 1582 1583 if (log) 1584 log->Printf( 1585 "CAS::FOPD[%d] trying module " 1586 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1587 current_id, 1588 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 (0); 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(process->GetObjCLanguageRuntime()); 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 if (!decl_vendor->FindDecls(class_name, append, max_matches, decls)) 1620 break; 1621 1622 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime( 1623 dyn_cast<ObjCInterfaceDecl>(decls[0])); 1624 1625 if (!interface_decl_from_runtime.IsValid()) 1626 break; 1627 1628 if (log) 1629 log->Printf( 1630 "CAS::FOPD[%d] trying runtime " 1631 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1632 current_id, 1633 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 (0); 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 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 2055 // seems to be generating bad types on occasion. 2056 return CompilerType(); 2057 2058 return CompilerType(m_ast_context, copied_qual_type); 2059 } 2060 2061 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) { 2062 assert(type && "Type for variable must be valid!"); 2063 2064 if (!type.IsValid()) 2065 return NULL; 2066 2067 ClangASTContext *lldb_ast = 2068 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); 2069 if (!lldb_ast) 2070 return NULL; 2071 2072 IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo(); 2073 2074 clang::ASTContext *ast = lldb_ast->getASTContext(); 2075 2076 clang::NamedDecl *Decl = VarDecl::Create( 2077 *ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(), 2078 SourceLocation(), ii, ClangUtil::GetQualType(type), 0, SC_Static); 2079 m_decls.push_back(Decl); 2080 2081 return Decl; 2082 } 2083 2084 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type, 2085 bool extern_c) { 2086 assert(type && "Type for variable must be valid!"); 2087 2088 if (!type.IsValid()) 2089 return NULL; 2090 2091 if (m_function_types.count(type)) 2092 return NULL; 2093 2094 ClangASTContext *lldb_ast = 2095 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); 2096 if (!lldb_ast) 2097 return NULL; 2098 2099 m_function_types.insert(type); 2100 2101 QualType qual_type(ClangUtil::GetQualType(type)); 2102 2103 clang::ASTContext *ast = lldb_ast->getASTContext(); 2104 2105 const bool isInlineSpecified = false; 2106 const bool hasWrittenPrototype = true; 2107 const bool isConstexprSpecified = false; 2108 2109 clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context); 2110 2111 if (extern_c) { 2112 context = LinkageSpecDecl::Create( 2113 *ast, context, SourceLocation(), SourceLocation(), 2114 clang::LinkageSpecDecl::LanguageIDs::lang_c, false); 2115 } 2116 2117 // Pass the identifier info for functions the decl_name is needed for 2118 // operators 2119 clang::DeclarationName decl_name = 2120 m_decl_name.getNameKind() == DeclarationName::Identifier 2121 ? m_decl_name.getAsIdentifierInfo() 2122 : m_decl_name; 2123 2124 clang::FunctionDecl *func_decl = FunctionDecl::Create( 2125 *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type, 2126 NULL, SC_Extern, isInlineSpecified, hasWrittenPrototype, 2127 isConstexprSpecified); 2128 2129 // We have to do more than just synthesize the FunctionDecl. We have to 2130 // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do 2131 // this, we raid the function's FunctionProtoType for types. 2132 2133 const FunctionProtoType *func_proto_type = 2134 qual_type.getTypePtr()->getAs<FunctionProtoType>(); 2135 2136 if (func_proto_type) { 2137 unsigned NumArgs = func_proto_type->getNumParams(); 2138 unsigned ArgIndex; 2139 2140 SmallVector<ParmVarDecl *, 5> parm_var_decls; 2141 2142 for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) { 2143 QualType arg_qual_type(func_proto_type->getParamType(ArgIndex)); 2144 2145 parm_var_decls.push_back(ParmVarDecl::Create( 2146 *ast, const_cast<DeclContext *>(context), SourceLocation(), 2147 SourceLocation(), NULL, arg_qual_type, NULL, SC_Static, NULL)); 2148 } 2149 2150 func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls)); 2151 } else { 2152 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 2153 2154 if (log) 2155 log->Printf("Function type wasn't a FunctionProtoType"); 2156 } 2157 2158 // If this is an operator (e.g. operator new or operator==), only insert the 2159 // declaration we inferred from the symbol if we can provide the correct 2160 // number of arguments. We shouldn't really inject random decl(s) for 2161 // functions that are analyzed semantically in a special way, otherwise we 2162 // will crash in clang. 2163 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; 2164 if (func_proto_type && 2165 ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) { 2166 if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount( 2167 false, op_kind, func_proto_type->getNumParams())) 2168 return NULL; 2169 } 2170 m_decls.push_back(func_decl); 2171 2172 return func_decl; 2173 } 2174 2175 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() { 2176 FunctionProtoType::ExtProtoInfo proto_info; 2177 2178 proto_info.Variadic = true; 2179 2180 QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType( 2181 m_ast_source.m_ast_context->UnknownAnyTy, // result 2182 ArrayRef<QualType>(), // argument types 2183 proto_info)); 2184 2185 return AddFunDecl( 2186 CompilerType(m_ast_source.m_ast_context, generic_function_type), true); 2187 } 2188 2189 clang::NamedDecl * 2190 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) { 2191 if (ClangUtil::IsClangType(clang_type)) { 2192 QualType qual_type = ClangUtil::GetQualType(clang_type); 2193 2194 if (const TypedefType *typedef_type = 2195 llvm::dyn_cast<TypedefType>(qual_type)) { 2196 TypedefNameDecl *typedef_name_decl = typedef_type->getDecl(); 2197 2198 m_decls.push_back(typedef_name_decl); 2199 2200 return (NamedDecl *)typedef_name_decl; 2201 } else if (const TagType *tag_type = qual_type->getAs<TagType>()) { 2202 TagDecl *tag_decl = tag_type->getDecl(); 2203 2204 m_decls.push_back(tag_decl); 2205 2206 return tag_decl; 2207 } else if (const ObjCObjectType *objc_object_type = 2208 qual_type->getAs<ObjCObjectType>()) { 2209 ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface(); 2210 2211 m_decls.push_back((NamedDecl *)interface_decl); 2212 2213 return (NamedDecl *)interface_decl; 2214 } 2215 } 2216 return NULL; 2217 } 2218 2219 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) { 2220 for (clang::NamedDecl *decl : result) 2221 m_decls.push_back(decl); 2222 } 2223 2224 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) { 2225 m_decls.push_back(decl); 2226 } 2227