1 //===-- ClangExpressionDeclMap.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ClangExpressionDeclMap.h"
12 #include "ASTDumper.h"
13 #include "ClangASTSource.h"
14 #include "ClangModulesDeclVendor.h"
15 #include "ClangPersistentVariables.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/Decl.h"
21 #include "lldb/lldb-private.h"
22 #include "lldb/Core/Address.h"
23 #include "lldb/Core/Error.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/RegisterValue.h"
28 #include "lldb/Core/ValueObjectConstResult.h"
29 #include "lldb/Core/ValueObjectVariable.h"
30 #include "lldb/Expression/Materializer.h"
31 #include "lldb/Host/Endian.h"
32 #include "lldb/Symbol/ClangASTContext.h"
33 #include "lldb/Symbol/CompilerDecl.h"
34 #include "lldb/Symbol/CompilerDeclContext.h"
35 #include "lldb/Symbol/CompileUnit.h"
36 #include "lldb/Symbol/Function.h"
37 #include "lldb/Symbol/ObjectFile.h"
38 #include "lldb/Symbol/SymbolContext.h"
39 #include "lldb/Symbol/SymbolFile.h"
40 #include "lldb/Symbol/SymbolVendor.h"
41 #include "lldb/Symbol/Type.h"
42 #include "lldb/Symbol/TypeList.h"
43 #include "lldb/Symbol/Variable.h"
44 #include "lldb/Symbol/VariableList.h"
45 #include "lldb/Target/CPPLanguageRuntime.h"
46 #include "lldb/Target/ExecutionContext.h"
47 #include "lldb/Target/ObjCLanguageRuntime.h"
48 #include "lldb/Target/Process.h"
49 #include "lldb/Target/RegisterContext.h"
50 #include "lldb/Target/StackFrame.h"
51 #include "lldb/Target/Target.h"
52 #include "lldb/Target/Thread.h"
54 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
57 using namespace lldb_private;
58 using namespace clang;
62 const char *g_lldb_local_vars_namespace_cstr = "$__lldb_local_vars";
63 } // anonymous namespace
65 ClangExpressionDeclMap::ClangExpressionDeclMap (bool keep_result_in_memory,
66 Materializer::PersistentVariableDelegate *result_delegate,
67 ExecutionContext &exe_ctx) :
68 ClangASTSource (exe_ctx.GetTargetSP()),
71 m_keep_result_in_memory (keep_result_in_memory),
72 m_result_delegate (result_delegate),
79 ClangExpressionDeclMap::~ClangExpressionDeclMap()
81 // Note: The model is now that the parser's AST context and all associated
82 // data does not vanish until the expression has been executed. This means
83 // that valuable lookup data (like namespaces) doesn't vanish, but
90 ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx,
91 Materializer *materializer)
93 ClangASTMetrics::ClearLocalCounters();
96 m_parser_vars->m_exe_ctx = exe_ctx;
98 Target *target = exe_ctx.GetTargetPtr();
99 if (exe_ctx.GetFramePtr())
100 m_parser_vars->m_sym_ctx = exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
101 else if (exe_ctx.GetThreadPtr() && exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0))
102 m_parser_vars->m_sym_ctx = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(lldb::eSymbolContextEverything);
103 else if (exe_ctx.GetProcessPtr())
105 m_parser_vars->m_sym_ctx.Clear(true);
106 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
110 m_parser_vars->m_sym_ctx.Clear(true);
111 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
116 m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>(target->GetPersistentExpressionStateForLanguage(eLanguageTypeC));
118 if (!target->GetScratchClangASTContext())
122 m_parser_vars->m_target_info = GetTargetInfo();
123 m_parser_vars->m_materializer = materializer;
129 ClangExpressionDeclMap::InstallCodeGenerator (clang::ASTConsumer *code_gen)
131 assert(m_parser_vars);
132 m_parser_vars->m_code_gen = code_gen;
136 ClangExpressionDeclMap::DidParse()
138 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
141 ClangASTMetrics::DumpCounters(log);
143 if (m_parser_vars.get())
145 for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
146 entity_index < num_entities;
149 ExpressionVariableSP var_sp(m_found_entities.GetVariableAtIndex(entity_index));
151 llvm::cast<ClangExpressionVariable>(var_sp.get())->DisableParserVars(GetParserID());
154 for (size_t pvar_index = 0, num_pvars = m_parser_vars->m_persistent_vars->GetSize();
155 pvar_index < num_pvars;
158 ExpressionVariableSP pvar_sp(m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
159 if (ClangExpressionVariable *clang_var = llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get()))
160 clang_var->DisableParserVars(GetParserID());
167 // Interface for IRForTarget
169 ClangExpressionDeclMap::TargetInfo
170 ClangExpressionDeclMap::GetTargetInfo()
172 assert (m_parser_vars.get());
176 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
178 Process *process = exe_ctx.GetProcessPtr();
181 ret.byte_order = process->GetByteOrder();
182 ret.address_byte_size = process->GetAddressByteSize();
186 Target *target = exe_ctx.GetTargetPtr();
189 ret.byte_order = target->GetArchitecture().GetByteOrder();
190 ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
198 ClangExpressionDeclMap::AddPersistentVariable
200 const NamedDecl *decl,
201 const ConstString &name,
202 TypeFromParser parser_type,
207 assert (m_parser_vars.get());
209 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(parser_type.GetTypeSystem());
213 if (m_parser_vars->m_materializer && is_result)
217 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
218 Target *target = exe_ctx.GetTargetPtr();
219 if (target == nullptr)
222 ClangASTContext *context(target->GetScratchClangASTContext());
224 TypeFromUser user_type(m_ast_importer_sp->DeportType(context->getASTContext(),
225 ast->getASTContext(),
226 parser_type.GetOpaqueQualType()),
229 uint32_t offset = m_parser_vars->m_materializer->AddResultVariable(user_type,
231 m_keep_result_in_memory,
235 ClangExpressionVariable *var = new ClangExpressionVariable(exe_ctx.GetBestExecutionContextScope(),
238 m_parser_vars->m_target_info.byte_order,
239 m_parser_vars->m_target_info.address_byte_size);
241 m_found_entities.AddNewlyConstructedVariable(var);
243 var->EnableParserVars(GetParserID());
245 ClangExpressionVariable::ParserVars *parser_vars = var->GetParserVars(GetParserID());
247 parser_vars->m_named_decl = decl;
248 parser_vars->m_parser_type = parser_type;
250 var->EnableJITVars(GetParserID());
252 ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID());
254 jit_vars->m_offset = offset;
259 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
260 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
261 Target *target = exe_ctx.GetTargetPtr();
265 ClangASTContext *context(target->GetScratchClangASTContext());
267 TypeFromUser user_type(m_ast_importer_sp->DeportType(context->getASTContext(),
268 ast->getASTContext(),
269 parser_type.GetOpaqueQualType()),
272 if (!user_type.GetOpaqueQualType())
275 log->Printf("Persistent variable's type wasn't copied successfully");
279 if (!m_parser_vars->m_target_info.IsValid())
282 ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>(m_parser_vars->m_persistent_vars->CreatePersistentVariable (exe_ctx.GetBestExecutionContextScope (),
285 m_parser_vars->m_target_info.byte_order,
286 m_parser_vars->m_target_info.address_byte_size).get());
291 var->m_frozen_sp->SetHasCompleteType();
294 var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
296 var->m_flags |= ClangExpressionVariable::EVKeepInTarget; // explicitly-declared persistent variables should persist
300 var->m_flags |= ClangExpressionVariable::EVIsProgramReference;
304 var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
305 var->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
308 if (m_keep_result_in_memory)
310 var->m_flags |= ClangExpressionVariable::EVKeepInTarget;
314 log->Printf("Created persistent variable with flags 0x%hx", var->m_flags);
316 var->EnableParserVars(GetParserID());
318 ClangExpressionVariable::ParserVars *parser_vars = var->GetParserVars(GetParserID());
320 parser_vars->m_named_decl = decl;
321 parser_vars->m_parser_type = parser_type;
327 ClangExpressionDeclMap::AddValueToStruct
329 const NamedDecl *decl,
330 const ConstString &name,
333 lldb::offset_t alignment
336 assert (m_struct_vars.get());
337 assert (m_parser_vars.get());
339 bool is_persistent_variable = false;
341 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
343 m_struct_vars->m_struct_laid_out = false;
345 if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl, GetParserID()))
348 ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList(m_found_entities, decl, GetParserID()));
352 var = ClangExpressionVariable::FindVariableInList(*m_parser_vars->m_persistent_vars, decl, GetParserID());
353 is_persistent_variable = true;
360 log->Printf("Adding value for (NamedDecl*)%p [%s - %s] to the structure",
361 static_cast<const void*>(decl), name.GetCString(),
362 var->GetName().GetCString());
364 // We know entity->m_parser_vars is valid because we used a parser variable
367 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID());
369 parser_vars->m_llvm_value = value;
371 if (ClangExpressionVariable::JITVars *jit_vars = llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID()))
373 // We already laid this out; do not touch
376 log->Printf("Already placed at 0x%llx", (unsigned long long)jit_vars->m_offset);
379 llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID());
381 ClangExpressionVariable::JITVars *jit_vars = llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID());
383 jit_vars->m_alignment = alignment;
384 jit_vars->m_size = size;
386 m_struct_members.AddVariable(var->shared_from_this());
388 if (m_parser_vars->m_materializer)
394 if (is_persistent_variable)
396 ExpressionVariableSP var_sp(var->shared_from_this());
397 offset = m_parser_vars->m_materializer->AddPersistentVariable(var_sp, nullptr, err);
401 if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym)
402 offset = m_parser_vars->m_materializer->AddSymbol(*sym, err);
403 else if (const RegisterInfo *reg_info = var->GetRegisterInfo())
404 offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err);
405 else if (parser_vars->m_lldb_var)
406 offset = m_parser_vars->m_materializer->AddVariable(parser_vars->m_lldb_var, err);
413 log->Printf("Placed at 0x%llx", (unsigned long long)offset);
415 jit_vars->m_offset = offset; // TODO DoStructLayout() should not change this.
422 ClangExpressionDeclMap::DoStructLayout ()
424 assert (m_struct_vars.get());
426 if (m_struct_vars->m_struct_laid_out)
429 if (!m_parser_vars->m_materializer)
432 m_struct_vars->m_struct_alignment = m_parser_vars->m_materializer->GetStructAlignment();
433 m_struct_vars->m_struct_size = m_parser_vars->m_materializer->GetStructByteSize();
434 m_struct_vars->m_struct_laid_out = true;
438 bool ClangExpressionDeclMap::GetStructInfo
440 uint32_t &num_elements,
442 lldb::offset_t &alignment
445 assert (m_struct_vars.get());
447 if (!m_struct_vars->m_struct_laid_out)
450 num_elements = m_struct_members.GetSize();
451 size = m_struct_vars->m_struct_size;
452 alignment = m_struct_vars->m_struct_alignment;
458 ClangExpressionDeclMap::GetStructElement
460 const NamedDecl *&decl,
462 lldb::offset_t &offset,
467 assert (m_struct_vars.get());
469 if (!m_struct_vars->m_struct_laid_out)
472 if (index >= m_struct_members.GetSize())
475 ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
480 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(member_sp.get())->GetParserVars(GetParserID());
481 ClangExpressionVariable::JITVars *jit_vars = llvm::cast<ClangExpressionVariable>(member_sp.get())->GetJITVars(GetParserID());
485 !member_sp->GetValueObject())
488 decl = parser_vars->m_named_decl;
489 value = parser_vars->m_llvm_value;
490 offset = jit_vars->m_offset;
491 name = member_sp->GetName();
497 ClangExpressionDeclMap::GetFunctionInfo
499 const NamedDecl *decl,
503 ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList(m_found_entities, decl, GetParserID()));
508 // We know m_parser_vars is valid since we searched for the variable by
511 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
513 ptr = parser_vars->m_lldb_value.GetScalar().ULongLong();
519 ClangExpressionDeclMap::GetSymbolAddress (Target &target,
521 const ConstString &name,
522 lldb::SymbolType symbol_type,
523 lldb_private::Module *module)
525 SymbolContextList sc_list;
528 module->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
530 target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list);
532 const uint32_t num_matches = sc_list.GetSize();
533 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
535 for (uint32_t i=0; i<num_matches && (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS); i++)
537 SymbolContext sym_ctx;
538 sc_list.GetContextAtIndex(i, sym_ctx);
540 const Address sym_address = sym_ctx.symbol->GetAddress();
542 if (!sym_address.IsValid())
545 switch (sym_ctx.symbol->GetType())
547 case eSymbolTypeCode:
548 case eSymbolTypeTrampoline:
549 symbol_load_addr = sym_address.GetCallableLoadAddress (&target);
552 case eSymbolTypeResolver:
553 symbol_load_addr = sym_address.GetCallableLoadAddress (&target, true);
556 case eSymbolTypeReExported:
558 ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName();
561 ModuleSP reexport_module_sp;
562 ModuleSpec reexport_module_spec;
563 reexport_module_spec.GetPlatformFileSpec() = sym_ctx.symbol->GetReExportedSymbolSharedLibrary();
564 if (reexport_module_spec.GetPlatformFileSpec())
566 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
567 if (!reexport_module_sp)
569 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
570 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
573 symbol_load_addr = GetSymbolAddress(target, process, sym_ctx.symbol->GetReExportedSymbolName(), symbol_type, reexport_module_sp.get());
578 case eSymbolTypeData:
579 case eSymbolTypeRuntime:
580 case eSymbolTypeVariable:
581 case eSymbolTypeLocal:
582 case eSymbolTypeParam:
583 case eSymbolTypeInvalid:
584 case eSymbolTypeAbsolute:
585 case eSymbolTypeException:
586 case eSymbolTypeSourceFile:
587 case eSymbolTypeHeaderFile:
588 case eSymbolTypeObjectFile:
589 case eSymbolTypeCommonBlock:
590 case eSymbolTypeBlock:
591 case eSymbolTypeVariableType:
592 case eSymbolTypeLineEntry:
593 case eSymbolTypeLineHeader:
594 case eSymbolTypeScopeBegin:
595 case eSymbolTypeScopeEnd:
596 case eSymbolTypeAdditional:
597 case eSymbolTypeCompiler:
598 case eSymbolTypeInstrumentation:
599 case eSymbolTypeUndefined:
600 case eSymbolTypeObjCClass:
601 case eSymbolTypeObjCMetaClass:
602 case eSymbolTypeObjCIVar:
603 symbol_load_addr = sym_address.GetLoadAddress (&target);
608 if (symbol_load_addr == LLDB_INVALID_ADDRESS && process)
610 ObjCLanguageRuntime *runtime = process->GetObjCLanguageRuntime();
614 symbol_load_addr = runtime->LookupRuntimeSymbol(name);
618 return symbol_load_addr;
622 ClangExpressionDeclMap::GetSymbolAddress (const ConstString &name, lldb::SymbolType symbol_type)
624 assert (m_parser_vars.get());
626 if (!m_parser_vars->m_exe_ctx.GetTargetPtr())
629 return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(), m_parser_vars->m_exe_ctx.GetProcessPtr(), name, symbol_type);
633 ClangExpressionDeclMap::FindGlobalDataSymbol (Target &target,
634 const ConstString &name,
635 lldb_private::Module *module)
637 SymbolContextList sc_list;
640 module->FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
642 target.GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
644 const uint32_t matches = sc_list.GetSize();
645 for (uint32_t i=0; i<matches; ++i)
647 SymbolContext sym_ctx;
648 sc_list.GetContextAtIndex(i, sym_ctx);
651 const Symbol *symbol = sym_ctx.symbol;
652 const Address sym_address = symbol->GetAddress();
654 if (sym_address.IsValid())
656 switch (symbol->GetType())
658 case eSymbolTypeData:
659 case eSymbolTypeRuntime:
660 case eSymbolTypeAbsolute:
661 case eSymbolTypeObjCClass:
662 case eSymbolTypeObjCMetaClass:
663 case eSymbolTypeObjCIVar:
664 if (symbol->GetDemangledNameIsSynthesized())
666 // If the demangled name was synthesized, then don't use it
667 // for expressions. Only let the symbol match if the mangled
668 // named matches for these symbols.
669 if (symbol->GetMangled().GetMangledName() != name)
674 case eSymbolTypeReExported:
676 ConstString reexport_name = symbol->GetReExportedSymbolName();
679 ModuleSP reexport_module_sp;
680 ModuleSpec reexport_module_spec;
681 reexport_module_spec.GetPlatformFileSpec() = symbol->GetReExportedSymbolSharedLibrary();
682 if (reexport_module_spec.GetPlatformFileSpec())
684 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
685 if (!reexport_module_sp)
687 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
688 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
691 // Don't allow us to try and resolve a re-exported symbol if it is the same
692 // as the current symbol
693 if (name == symbol->GetReExportedSymbolName() && module == reexport_module_sp.get())
696 return FindGlobalDataSymbol(target, symbol->GetReExportedSymbolName(), reexport_module_sp.get());
701 case eSymbolTypeCode: // We already lookup functions elsewhere
702 case eSymbolTypeVariable:
703 case eSymbolTypeLocal:
704 case eSymbolTypeParam:
705 case eSymbolTypeTrampoline:
706 case eSymbolTypeInvalid:
707 case eSymbolTypeException:
708 case eSymbolTypeSourceFile:
709 case eSymbolTypeHeaderFile:
710 case eSymbolTypeObjectFile:
711 case eSymbolTypeCommonBlock:
712 case eSymbolTypeBlock:
713 case eSymbolTypeVariableType:
714 case eSymbolTypeLineEntry:
715 case eSymbolTypeLineHeader:
716 case eSymbolTypeScopeBegin:
717 case eSymbolTypeScopeEnd:
718 case eSymbolTypeAdditional:
719 case eSymbolTypeCompiler:
720 case eSymbolTypeInstrumentation:
721 case eSymbolTypeUndefined:
722 case eSymbolTypeResolver:
733 ClangExpressionDeclMap::FindGlobalVariable
737 const ConstString &name,
738 CompilerDeclContext *namespace_decl,
744 if (module && namespace_decl)
745 module->FindGlobalVariables (name, namespace_decl, true, -1, vars);
747 target.GetImages().FindGlobalVariables(name, true, -1, vars);
753 for (size_t i = 0; i < vars.GetSize(); ++i)
755 VariableSP var_sp = vars.GetVariableAtIndex(i);
757 if (ClangASTContext::AreTypesSame(*type, var_sp->GetType()->GetFullCompilerType ()))
763 return vars.GetVariableAtIndex(0);
771 ClangExpressionDeclMap::GetClangASTContext ()
773 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
774 if (frame == nullptr)
777 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
778 if (sym_ctx.block == nullptr)
781 CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
782 if (!frame_decl_context)
785 return llvm::dyn_cast_or_null<ClangASTContext>(frame_decl_context.GetTypeSystem());
788 // Interface for ClangASTSource
791 ClangExpressionDeclMap::FindExternalVisibleDecls (NameSearchContext &context)
793 assert (m_ast_context);
795 ClangASTMetrics::RegisterVisibleQuery();
797 const ConstString name(context.m_decl_name.getAsString().c_str());
799 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
801 if (GetImportInProgress())
803 if (log && log->GetVerbose())
804 log->Printf("Ignoring a query during an import");
808 static unsigned int invocation_id = 0;
809 unsigned int current_id = invocation_id++;
813 if (!context.m_decl_context)
814 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for '%s' in a NULL DeclContext", current_id, name.GetCString());
815 else if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context.m_decl_context))
816 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for '%s' in '%s'", current_id, name.GetCString(), context_named_decl->getNameAsString().c_str());
818 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for '%s' in a '%s'", current_id, name.GetCString(), context.m_decl_context->getDeclKindName());
821 if (const NamespaceDecl *namespace_context = dyn_cast<NamespaceDecl>(context.m_decl_context))
823 if (namespace_context->getName().str() == std::string(g_lldb_local_vars_namespace_cstr))
825 CompilerDeclContext compiler_decl_ctx(GetClangASTContext(), const_cast<void *>(static_cast<const void *>(context.m_decl_context)));
826 FindExternalVisibleDecls(context, lldb::ModuleSP(), compiler_decl_ctx, current_id);
830 ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp->GetNamespaceMap(namespace_context);
832 if (log && log->GetVerbose())
833 log->Printf(" CEDM::FEVD[%u] Inspecting (NamespaceMap*)%p (%d entries)",
834 current_id, static_cast<void*>(namespace_map.get()),
835 (int)namespace_map->size());
840 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), e = namespace_map->end();
845 log->Printf(" CEDM::FEVD[%u] Searching namespace %s in module %s",
847 i->second.GetName().AsCString(),
848 i->first->GetFileSpec().GetFilename().GetCString());
850 FindExternalVisibleDecls(context,
856 else if (isa<TranslationUnitDecl>(context.m_decl_context))
858 CompilerDeclContext namespace_decl;
861 log->Printf(" CEDM::FEVD[%u] Searching the root namespace", current_id);
863 FindExternalVisibleDecls(context,
869 if (!context.m_found.variable && !context.m_found.local_vars_nsp)
870 ClangASTSource::FindExternalVisibleDecls(context);
874 ClangExpressionDeclMap::FindExternalVisibleDecls (NameSearchContext &context,
875 lldb::ModuleSP module_sp,
876 CompilerDeclContext &namespace_decl,
877 unsigned int current_id)
879 assert (m_ast_context);
881 std::function<void (clang::FunctionDecl *)> MaybeRegisterFunctionBody =
882 [this](clang::FunctionDecl *copied_function_decl)
884 if (copied_function_decl->getBody() && m_parser_vars->m_code_gen)
886 DeclGroupRef decl_group_ref(copied_function_decl);
887 m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
892 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
894 SymbolContextList sc_list;
896 const ConstString name(context.m_decl_name.getAsString().c_str());
898 const char *name_unique_cstr = name.GetCString();
900 if (name_unique_cstr == NULL)
903 static ConstString id_name("id");
904 static ConstString Class_name("Class");
906 if (name == id_name || name == Class_name)
909 // Only look for functions by name out in our symbols if the function
910 // doesn't start with our phony prefix of '$'
911 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
912 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
913 SymbolContext sym_ctx;
914 if (frame != nullptr)
915 sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
917 // Try the persistent decls, which take precedence over all else.
925 ClangASTContext *scratch_clang_ast_context = target->GetScratchClangASTContext();
927 if (!scratch_clang_ast_context)
930 ASTContext *scratch_ast_context = scratch_clang_ast_context->getASTContext();
932 if (!scratch_ast_context)
935 NamedDecl *persistent_decl = m_parser_vars->m_persistent_vars->GetPersistentDecl(name);
937 if (!persistent_decl)
940 Decl *parser_persistent_decl = m_ast_importer_sp->CopyDecl(m_ast_context, scratch_ast_context, persistent_decl);
942 if (!parser_persistent_decl)
945 NamedDecl *parser_named_decl = dyn_cast<NamedDecl>(parser_persistent_decl);
947 if (!parser_named_decl)
950 if (clang::FunctionDecl *parser_function_decl = llvm::dyn_cast<clang::FunctionDecl>(parser_named_decl))
952 MaybeRegisterFunctionBody(parser_function_decl);
956 log->Printf(" CEDM::FEVD[%u] Found persistent decl %s", current_id, name.GetCString());
958 context.AddNamedDecl(parser_named_decl);
962 if (name_unique_cstr[0] == '$' && !namespace_decl)
964 static ConstString g_lldb_class_name ("$__lldb_class");
966 if (name == g_lldb_class_name)
968 // Clang is looking for the type of "this"
974 // Find the block that defines the function represented by "sym_ctx"
975 Block *function_block = sym_ctx.GetFunctionBlock();
980 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
982 if (!function_decl_ctx)
985 clang::CXXMethodDecl *method_decl = ClangASTContext::DeclContextGetAsCXXMethodDecl(function_decl_ctx);
989 clang::CXXRecordDecl *class_decl = method_decl->getParent();
991 QualType class_qual_type(class_decl->getTypeForDecl(), 0);
993 TypeFromUser class_user_type (class_qual_type.getAsOpaquePtr(),
994 ClangASTContext::GetASTContext(&class_decl->getASTContext()));
998 ASTDumper ast_dumper(class_qual_type);
999 log->Printf(" CEDM::FEVD[%u] Adding type for $__lldb_class: %s", current_id, ast_dumper.GetCString());
1002 AddThisType(context, class_user_type, current_id);
1004 if (method_decl->isInstance())
1006 // self is a pointer to the object
1008 QualType class_pointer_type = method_decl->getASTContext().getPointerType(class_qual_type);
1010 TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
1011 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1013 m_struct_vars->m_object_pointer_type = self_user_type;
1018 // This branch will get hit if we are executing code in the context of a function that
1019 // claims to have an object pointer (through DW_AT_object_pointer?) but is not formally a
1020 // method of the class. In that case, just look up the "this" variable in the current
1021 // scope and use its type.
1022 // FIXME: This code is formally correct, but clang doesn't currently emit DW_AT_object_pointer
1023 // for C++ so it hasn't actually been tested.
1025 VariableList *vars = frame->GetVariableList(false);
1027 lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
1030 this_var->IsInScope(frame) &&
1031 this_var->LocationIsValidForFrame (frame))
1033 Type *this_type = this_var->GetType();
1038 TypeFromUser pointee_type = this_type->GetForwardCompilerType ().GetPointeeType();
1040 if (pointee_type.IsValid())
1044 ASTDumper ast_dumper(pointee_type);
1045 log->Printf(" FEVD[%u] Adding type for $__lldb_class: %s", current_id, ast_dumper.GetCString());
1048 AddThisType(context, pointee_type, current_id);
1049 TypeFromUser this_user_type(this_type->GetFullCompilerType ());
1050 m_struct_vars->m_object_pointer_type = this_user_type;
1059 static ConstString g_lldb_objc_class_name ("$__lldb_objc_class");
1060 if (name == g_lldb_objc_class_name)
1062 // Clang is looking for the type of "*self"
1067 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
1069 // Find the block that defines the function represented by "sym_ctx"
1070 Block *function_block = sym_ctx.GetFunctionBlock();
1072 if (!function_block)
1075 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
1077 if (!function_decl_ctx)
1080 clang::ObjCMethodDecl *method_decl = ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1084 ObjCInterfaceDecl* self_interface = method_decl->getClassInterface();
1086 if (!self_interface)
1089 const clang::Type *interface_type = self_interface->getTypeForDecl();
1091 if (!interface_type)
1092 return; // This is unlikely, but we have seen crashes where this occurred
1094 TypeFromUser class_user_type(QualType(interface_type, 0).getAsOpaquePtr(),
1095 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1099 ASTDumper ast_dumper(interface_type);
1100 log->Printf(" FEVD[%u] Adding type for $__lldb_objc_class: %s", current_id, ast_dumper.GetCString());
1103 AddOneType(context, class_user_type, current_id);
1105 if (method_decl->isInstanceMethod())
1107 // self is a pointer to the object
1109 QualType class_pointer_type = method_decl->getASTContext().getObjCObjectPointerType(QualType(interface_type, 0));
1111 TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
1112 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1114 m_struct_vars->m_object_pointer_type = self_user_type;
1118 // self is a Class pointer
1119 QualType class_type = method_decl->getASTContext().getObjCClassType();
1121 TypeFromUser self_user_type(class_type.getAsOpaquePtr(),
1122 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1124 m_struct_vars->m_object_pointer_type = self_user_type;
1131 // This branch will get hit if we are executing code in the context of a function that
1132 // claims to have an object pointer (through DW_AT_object_pointer?) but is not formally a
1133 // method of the class. In that case, just look up the "self" variable in the current
1134 // scope and use its type.
1136 VariableList *vars = frame->GetVariableList(false);
1138 lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
1141 self_var->IsInScope(frame) &&
1142 self_var->LocationIsValidForFrame (frame))
1144 Type *self_type = self_var->GetType();
1149 CompilerType self_clang_type = self_type->GetFullCompilerType ();
1151 if (ClangASTContext::IsObjCClassType(self_clang_type))
1155 else if (ClangASTContext::IsObjCObjectPointerType(self_clang_type))
1157 self_clang_type = self_clang_type.GetPointeeType();
1159 if (!self_clang_type)
1164 ASTDumper ast_dumper(self_type->GetFullCompilerType ());
1165 log->Printf(" FEVD[%u] Adding type for $__lldb_objc_class: %s", current_id, ast_dumper.GetCString());
1168 TypeFromUser class_user_type (self_clang_type);
1170 AddOneType(context, class_user_type, current_id);
1172 TypeFromUser self_user_type(self_type->GetFullCompilerType ());
1174 m_struct_vars->m_object_pointer_type = self_user_type;
1183 if (name == ConstString(g_lldb_local_vars_namespace_cstr))
1185 CompilerDeclContext frame_decl_context = sym_ctx.block != nullptr ?
1186 sym_ctx.block->GetDeclContext() :
1187 CompilerDeclContext();
1189 if (frame_decl_context)
1191 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(frame_decl_context.GetTypeSystem());
1195 clang::NamespaceDecl *namespace_decl = ClangASTContext::GetUniqueNamespaceDeclaration(
1196 m_ast_context, name_unique_cstr, nullptr);
1199 context.AddNamedDecl(namespace_decl);
1200 clang::DeclContext *clang_decl_ctx = clang::Decl::castToDeclContext(namespace_decl);
1201 clang_decl_ctx->setHasExternalVisibleStorage(true);
1202 context.m_found.local_vars_nsp = true;
1210 // any other $__lldb names should be weeded out now
1211 if (!::strncmp(name_unique_cstr, "$__lldb", sizeof("$__lldb") - 1))
1214 ExpressionVariableSP pvar_sp(m_parser_vars->m_persistent_vars->GetVariable(name));
1218 AddOneVariable(context, pvar_sp, current_id);
1222 const char *reg_name(&name.GetCString()[1]);
1224 if (m_parser_vars->m_exe_ctx.GetRegisterContext())
1226 const RegisterInfo *reg_info(m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(reg_name));
1231 log->Printf(" CEDM::FEVD[%u] Found register %s", current_id, reg_info->name);
1233 AddOneRegister(context, reg_info, current_id);
1239 ValueObjectSP valobj;
1242 bool local_var_lookup = !namespace_decl ||
1243 (namespace_decl.GetName() == ConstString(g_lldb_local_vars_namespace_cstr));
1244 if (frame && local_var_lookup)
1246 CompilerDeclContext compiler_decl_context = sym_ctx.block != nullptr ? sym_ctx.block->GetDeclContext() : CompilerDeclContext();
1248 if (compiler_decl_context)
1250 // Make sure that the variables are parsed so that we have the declarations.
1251 VariableListSP vars = frame->GetInScopeVariableList(true);
1252 for (size_t i = 0; i < vars->GetSize(); i++)
1253 vars->GetVariableAtIndex(i)->GetDecl();
1255 // Search for declarations matching the name. Do not include imported decls
1256 // in the search if we are looking for decls in the artificial namespace
1257 // $__lldb_local_vars.
1258 std::vector<CompilerDecl> found_decls = compiler_decl_context.FindDeclByName(name, namespace_decl.IsValid());
1260 bool variable_found = false;
1261 for (CompilerDecl decl : found_decls)
1263 for (size_t vi = 0, ve = vars->GetSize(); vi != ve; ++vi)
1265 VariableSP candidate_var = vars->GetVariableAtIndex(vi);
1266 if (candidate_var->GetDecl() == decl)
1268 var = candidate_var;
1275 variable_found = true;
1276 valobj = ValueObjectVariable::Create(frame, var);
1277 AddOneVariable(context, var, valobj, current_id);
1278 context.m_found.variable = true;
1287 var = FindGlobalVariable (*target,
1295 valobj = ValueObjectVariable::Create(target, var);
1296 AddOneVariable(context, var, valobj, current_id);
1297 context.m_found.variable = true;
1302 std::vector<clang::NamedDecl *> decls_from_modules;
1306 if (ClangModulesDeclVendor *decl_vendor = target->GetClangModulesDeclVendor())
1308 decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules);
1312 if (!context.m_found.variable)
1314 const bool include_inlines = false;
1315 const bool append = false;
1317 if (namespace_decl && module_sp)
1319 const bool include_symbols = false;
1321 module_sp->FindFunctions(name,
1323 eFunctionNameTypeBase,
1329 else if (target && !namespace_decl)
1331 const bool include_symbols = true;
1333 // TODO Fix FindFunctions so that it doesn't return
1334 // instance methods for eFunctionNameTypeBase.
1336 target->GetImages().FindFunctions(name,
1337 eFunctionNameTypeFull,
1344 // If we found more than one function, see if we can use the
1345 // frame's decl context to remove functions that are shadowed
1346 // by other functions which match in type but are nearer in scope.
1348 // AddOneFunction will not add a function whose type has already been
1349 // added, so if there's another function in the list with a matching
1350 // type, check to see if their decl context is a parent of the current
1351 // frame's or was imported via a and using statement, and pick the
1352 // best match according to lookup rules.
1353 if (sc_list.GetSize() > 1)
1355 // Collect some info about our frame's context.
1356 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1357 SymbolContext frame_sym_ctx;
1358 if (frame != nullptr)
1359 frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
1360 CompilerDeclContext frame_decl_context = frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext() : CompilerDeclContext();
1362 // We can't do this without a compiler decl context for our frame.
1363 if (frame_decl_context)
1365 clang::DeclContext *frame_decl_ctx = (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1366 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(frame_decl_context.GetTypeSystem());
1368 // Structure to hold the info needed when comparing function
1373 CompilerType m_copied_type;
1374 uint32_t m_decl_lvl;
1375 SymbolContext m_sym_ctx;
1378 // First, symplify things by looping through the symbol contexts
1379 // to remove unwanted functions and separate out the functions we
1380 // want to compare and prune into a separate list.
1381 // Cache the info needed about the function declarations in a
1382 // vector for efficiency.
1383 SymbolContextList sc_sym_list;
1384 uint32_t num_indices = sc_list.GetSize();
1385 std::vector<FuncDeclInfo> fdi_cache;
1386 fdi_cache.reserve(num_indices);
1387 for (uint32_t index = 0; index < num_indices; ++index)
1390 SymbolContext sym_ctx;
1391 sc_list.GetContextAtIndex(index, sym_ctx);
1393 // We don't know enough about symbols to compare them,
1394 // but we should keep them in the list.
1395 Function *function = sym_ctx.function;
1398 sc_sym_list.Append(sym_ctx);
1401 // Filter out functions without declaration contexts, as well as
1402 // class/instance methods, since they'll be skipped in the
1403 // code that follows anyway.
1404 CompilerDeclContext func_decl_context = function->GetDeclContext();
1405 if (!func_decl_context || func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1407 // We can only prune functions for which we can copy the type.
1408 CompilerType func_clang_type = function->GetType()->GetFullCompilerType();
1409 CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1410 if (!copied_func_type)
1412 sc_sym_list.Append(sym_ctx);
1416 fdi.m_sym_ctx = sym_ctx;
1417 fdi.m_name = function->GetName();
1418 fdi.m_copied_type = copied_func_type;
1419 fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1420 if (fdi.m_copied_type && func_decl_context)
1422 // Call CountDeclLevels to get the number of parent scopes we
1423 // have to look through before we find the function declaration.
1424 // When comparing functions of the same type, the one with a
1425 // lower count will be closer to us in the lookup scope and
1426 // shadows the other.
1427 clang::DeclContext *func_decl_ctx = (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1428 fdi.m_decl_lvl = ast->CountDeclLevels(frame_decl_ctx,
1431 &fdi.m_copied_type);
1433 fdi_cache.emplace_back(fdi);
1436 // Loop through the functions in our cache looking for matching types,
1437 // then compare their scope levels to see which is closer.
1438 std::multimap<CompilerType, const FuncDeclInfo*> matches;
1439 for (const FuncDeclInfo &fdi : fdi_cache)
1441 const CompilerType t = fdi.m_copied_type;
1442 auto q = matches.find(t);
1443 if (q != matches.end())
1445 if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1446 // This function is closer; remove the old set.
1448 else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1449 // The functions in our set are closer - skip this one.
1452 matches.insert(std::make_pair(t, &fdi));
1455 // Loop through our matches and add their symbol contexts to our list.
1456 SymbolContextList sc_func_list;
1457 for (const auto &q : matches)
1458 sc_func_list.Append(q.second->m_sym_ctx);
1460 // Rejoin the lists with the functions in front.
1461 sc_list = sc_func_list;
1462 sc_list.Append(sc_sym_list);
1466 if (sc_list.GetSize())
1468 Symbol *extern_symbol = NULL;
1469 Symbol *non_extern_symbol = NULL;
1471 for (uint32_t index = 0, num_indices = sc_list.GetSize();
1472 index < num_indices;
1475 SymbolContext sym_ctx;
1476 sc_list.GetContextAtIndex(index, sym_ctx);
1478 if (sym_ctx.function)
1480 CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1485 // Filter out class/instance methods.
1486 if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1489 AddOneFunction(context, sym_ctx.function, NULL, current_id);
1490 context.m_found.function_with_type_info = true;
1491 context.m_found.function = true;
1493 else if (sym_ctx.symbol)
1495 if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target)
1497 sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1498 if (sym_ctx.symbol == NULL)
1502 if (sym_ctx.symbol->IsExternal())
1503 extern_symbol = sym_ctx.symbol;
1505 non_extern_symbol = sym_ctx.symbol;
1509 if (!context.m_found.function_with_type_info)
1511 for (clang::NamedDecl *decl : decls_from_modules)
1513 if (llvm::isa<clang::FunctionDecl>(decl))
1515 clang::NamedDecl *copied_decl = llvm::cast_or_null<FunctionDecl>(m_ast_importer_sp->CopyDecl(m_ast_context, &decl->getASTContext(), decl));
1518 context.AddNamedDecl(copied_decl);
1519 context.m_found.function_with_type_info = true;
1525 if (!context.m_found.function_with_type_info)
1529 AddOneFunction (context, NULL, extern_symbol, current_id);
1530 context.m_found.function = true;
1532 else if (non_extern_symbol)
1534 AddOneFunction (context, NULL, non_extern_symbol, current_id);
1535 context.m_found.function = true;
1540 if (!context.m_found.function_with_type_info)
1542 // Try the modules next.
1546 if (ClangModulesDeclVendor *modules_decl_vendor = m_target->GetClangModulesDeclVendor())
1548 bool append = false;
1549 uint32_t max_matches = 1;
1550 std::vector <clang::NamedDecl *> decls;
1552 if (!modules_decl_vendor->FindDecls(name,
1558 clang::NamedDecl *const decl_from_modules = decls[0];
1560 if (llvm::isa<clang::FunctionDecl>(decl_from_modules))
1564 log->Printf(" CAS::FEVD[%u] Matching function found for \"%s\" in the modules",
1569 clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(m_ast_context, &decl_from_modules->getASTContext(), decl_from_modules);
1570 clang::FunctionDecl *copied_function_decl = copied_decl ? dyn_cast<clang::FunctionDecl>(copied_decl) : nullptr;
1572 if (!copied_function_decl)
1575 log->Printf(" CAS::FEVD[%u] - Couldn't export a function declaration from the modules",
1581 MaybeRegisterFunctionBody(copied_function_decl);
1583 context.AddNamedDecl(copied_function_decl);
1585 context.m_found.function_with_type_info = true;
1586 context.m_found.function = true;
1588 else if (llvm::isa<clang::VarDecl>(decl_from_modules))
1592 log->Printf(" CAS::FEVD[%u] Matching variable found for \"%s\" in the modules",
1597 clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(m_ast_context, &decl_from_modules->getASTContext(), decl_from_modules);
1598 clang::VarDecl *copied_var_decl = copied_decl ? dyn_cast_or_null<clang::VarDecl>(copied_decl) : nullptr;
1600 if (!copied_var_decl)
1603 log->Printf(" CAS::FEVD[%u] - Couldn't export a variable declaration from the modules",
1609 context.AddNamedDecl(copied_var_decl);
1611 context.m_found.variable = true;
1617 if (target && !context.m_found.variable && !namespace_decl)
1619 // We couldn't find a non-symbol variable for this. Now we'll hunt for a generic
1620 // data symbol, and -- if it is found -- treat it as a variable.
1622 const Symbol *data_symbol = FindGlobalDataSymbol(*target, name);
1626 std::string warning("got name from symbols: ");
1627 warning.append(name.AsCString());
1628 const unsigned diag_id = m_ast_context->getDiagnostics().getCustomDiagID(clang::DiagnosticsEngine::Level::Warning, "%0");
1629 m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1630 AddOneGenericVariable(context, *data_symbol, current_id);
1631 context.m_found.variable = true;
1638 //static opaque_compiler_type_t
1639 //MaybePromoteToBlockPointerType
1641 // ASTContext *ast_context,
1642 // opaque_compiler_type_t candidate_type
1645 // if (!candidate_type)
1646 // return candidate_type;
1648 // QualType candidate_qual_type = QualType::getFromOpaquePtr(candidate_type);
1650 // const PointerType *candidate_pointer_type = dyn_cast<PointerType>(candidate_qual_type);
1652 // if (!candidate_pointer_type)
1653 // return candidate_type;
1655 // QualType pointee_qual_type = candidate_pointer_type->getPointeeType();
1657 // const RecordType *pointee_record_type = dyn_cast<RecordType>(pointee_qual_type);
1659 // if (!pointee_record_type)
1660 // return candidate_type;
1662 // RecordDecl *pointee_record_decl = pointee_record_type->getDecl();
1664 // if (!pointee_record_decl->isRecord())
1665 // return candidate_type;
1667 // if (!pointee_record_decl->getName().startswith(llvm::StringRef("__block_literal_")))
1668 // return candidate_type;
1670 // QualType generic_function_type = ast_context->getFunctionNoProtoType(ast_context->UnknownAnyTy);
1671 // QualType block_pointer_type = ast_context->getBlockPointerType(generic_function_type);
1673 // return block_pointer_type.getAsOpaquePtr();
1677 ClangExpressionDeclMap::GetVariableValue (VariableSP &var,
1678 lldb_private::Value &var_location,
1679 TypeFromUser *user_type,
1680 TypeFromParser *parser_type)
1682 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1684 Type *var_type = var->GetType();
1689 log->PutCString("Skipped a definition because it has no type");
1693 CompilerType var_clang_type = var_type->GetFullCompilerType ();
1695 if (!var_clang_type)
1698 log->PutCString("Skipped a definition because it has no Clang type");
1702 ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(var_type->GetForwardCompilerType().GetTypeSystem());
1707 log->PutCString("Skipped a definition because it has no Clang AST");
1712 ASTContext *ast = clang_ast->getASTContext();
1717 log->PutCString("There is no AST context for the current execution context");
1720 //var_clang_type = MaybePromoteToBlockPointerType (ast, var_clang_type);
1722 DWARFExpression &var_location_expr = var->LocationExpression();
1724 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1727 if (var->GetLocationIsConstantValueData())
1729 DataExtractor const_value_extractor;
1731 if (var_location_expr.GetExpressionData(const_value_extractor))
1733 var_location = Value(const_value_extractor.GetDataStart(), const_value_extractor.GetByteSize());
1734 var_location.SetValueType(Value::eValueTypeHostAddress);
1739 log->Printf("Error evaluating constant variable: %s", err.AsCString());
1744 CompilerType type_to_use = GuardedCopyType(var_clang_type);
1749 log->Printf("Couldn't copy a variable's type into the parser's AST context");
1755 *parser_type = TypeFromParser(type_to_use);
1757 if (var_location.GetContextType() == Value::eContextTypeInvalid)
1758 var_location.SetCompilerType(type_to_use);
1760 if (var_location.GetValueType() == Value::eValueTypeFileAddress)
1762 SymbolContext var_sc;
1763 var->CalculateSymbolContext(&var_sc);
1765 if (!var_sc.module_sp)
1768 Address so_addr(var_location.GetScalar().ULongLong(), var_sc.module_sp->GetSectionList());
1770 lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1772 if (load_addr != LLDB_INVALID_ADDRESS)
1774 var_location.GetScalar() = load_addr;
1775 var_location.SetValueType(Value::eValueTypeLoadAddress);
1780 *user_type = TypeFromUser(var_clang_type);
1786 ClangExpressionDeclMap::AddOneVariable (NameSearchContext &context, VariableSP var, ValueObjectSP valobj, unsigned int current_id)
1788 assert (m_parser_vars.get());
1790 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1796 if (!GetVariableValue (var, var_location, &ut, &pt))
1799 clang::QualType parser_opaque_type = QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1801 if (parser_opaque_type.isNull())
1804 if (const clang::Type *parser_type = parser_opaque_type.getTypePtr())
1806 if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1807 CompleteType(tag_type->getDecl());
1808 if (const ObjCObjectPointerType *objc_object_ptr_type = dyn_cast<ObjCObjectPointerType>(parser_type))
1809 CompleteType(objc_object_ptr_type->getInterfaceDecl());
1813 bool is_reference = pt.IsReferenceType();
1815 NamedDecl *var_decl = NULL;
1817 var_decl = context.AddVarDecl(pt);
1819 var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1821 std::string decl_name(context.m_decl_name.getAsString());
1822 ConstString entity_name(decl_name.c_str());
1823 ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1824 m_found_entities.AddNewlyConstructedVariable(entity);
1827 entity->EnableParserVars(GetParserID());
1828 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
1829 parser_vars->m_parser_type = pt;
1830 parser_vars->m_named_decl = var_decl;
1831 parser_vars->m_llvm_value = NULL;
1832 parser_vars->m_lldb_value = var_location;
1833 parser_vars->m_lldb_var = var;
1836 entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1840 ASTDumper orig_dumper(ut.GetOpaqueQualType());
1841 ASTDumper ast_dumper(var_decl);
1842 log->Printf(" CEDM::FEVD[%u] Found variable %s, returned %s (original %s)", current_id, decl_name.c_str(), ast_dumper.GetCString(), orig_dumper.GetCString());
1847 ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1848 ExpressionVariableSP &pvar_sp,
1849 unsigned int current_id)
1851 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1853 TypeFromUser user_type (llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1855 TypeFromParser parser_type (GuardedCopyType(user_type));
1857 if (!parser_type.GetOpaqueQualType())
1860 log->Printf(" CEDM::FEVD[%u] Couldn't import type for pvar %s", current_id, pvar_sp->GetName().GetCString());
1864 NamedDecl *var_decl = context.AddVarDecl(parser_type.GetLValueReferenceType());
1866 llvm::cast<ClangExpressionVariable>(pvar_sp.get())->EnableParserVars(GetParserID());
1867 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetParserVars(GetParserID());
1868 parser_vars->m_parser_type = parser_type;
1869 parser_vars->m_named_decl = var_decl;
1870 parser_vars->m_llvm_value = NULL;
1871 parser_vars->m_lldb_value.Clear();
1875 ASTDumper ast_dumper(var_decl);
1876 log->Printf(" CEDM::FEVD[%u] Added pvar %s, returned %s", current_id, pvar_sp->GetName().GetCString(), ast_dumper.GetCString());
1881 ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1882 const Symbol &symbol,
1883 unsigned int current_id)
1885 assert(m_parser_vars.get());
1887 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1889 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1894 ASTContext *scratch_ast_context = target->GetScratchClangASTContext()->getASTContext();
1896 TypeFromUser user_type (ClangASTContext::GetBasicType(scratch_ast_context, eBasicTypeVoid).GetPointerType().GetLValueReferenceType());
1897 TypeFromParser parser_type (ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid).GetPointerType().GetLValueReferenceType());
1898 NamedDecl *var_decl = context.AddVarDecl(parser_type);
1900 std::string decl_name(context.m_decl_name.getAsString());
1901 ConstString entity_name(decl_name.c_str());
1902 ClangExpressionVariable *entity(new ClangExpressionVariable(m_parser_vars->m_exe_ctx.GetBestExecutionContextScope (),
1905 m_parser_vars->m_target_info.byte_order,
1906 m_parser_vars->m_target_info.address_byte_size));
1907 m_found_entities.AddNewlyConstructedVariable(entity);
1909 entity->EnableParserVars(GetParserID());
1910 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
1912 const Address symbol_address = symbol.GetAddress();
1913 lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1915 //parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
1916 parser_vars->m_lldb_value.SetCompilerType(user_type);
1917 parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
1918 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
1920 parser_vars->m_parser_type = parser_type;
1921 parser_vars->m_named_decl = var_decl;
1922 parser_vars->m_llvm_value = NULL;
1923 parser_vars->m_lldb_sym = &symbol;
1927 ASTDumper ast_dumper(var_decl);
1929 log->Printf(" CEDM::FEVD[%u] Found variable %s, returned %s", current_id, decl_name.c_str(), ast_dumper.GetCString());
1934 ClangExpressionDeclMap::ResolveUnknownTypes()
1936 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1937 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1939 ClangASTContext *scratch_ast_context = target->GetScratchClangASTContext();
1941 for (size_t index = 0, num_entities = m_found_entities.GetSize();
1942 index < num_entities;
1945 ExpressionVariableSP entity = m_found_entities.GetVariableAtIndex(index);
1947 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(entity.get())->GetParserVars(GetParserID());
1949 if (entity->m_flags & ClangExpressionVariable::EVUnknownType)
1951 const NamedDecl *named_decl = parser_vars->m_named_decl;
1952 const VarDecl *var_decl = dyn_cast<VarDecl>(named_decl);
1957 log->Printf("Entity of unknown type does not have a VarDecl");
1963 ASTDumper ast_dumper(const_cast<VarDecl*>(var_decl));
1964 log->Printf("Variable of unknown type now has Decl %s", ast_dumper.GetCString());
1967 QualType var_type = var_decl->getType();
1968 TypeFromParser parser_type(var_type.getAsOpaquePtr(), ClangASTContext::GetASTContext(&var_decl->getASTContext()));
1970 lldb::opaque_compiler_type_t copied_type = m_ast_importer_sp->CopyType(scratch_ast_context->getASTContext(), &var_decl->getASTContext(), var_type.getAsOpaquePtr());
1975 log->Printf("ClangExpressionDeclMap::ResolveUnknownType - Couldn't import the type for a variable");
1977 return (bool) lldb::ExpressionVariableSP();
1980 TypeFromUser user_type(copied_type, scratch_ast_context);
1982 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
1983 parser_vars->m_lldb_value.SetCompilerType(user_type);
1984 parser_vars->m_parser_type = parser_type;
1986 entity->SetCompilerType(user_type);
1988 entity->m_flags &= ~(ClangExpressionVariable::EVUnknownType);
1996 ClangExpressionDeclMap::AddOneRegister (NameSearchContext &context,
1997 const RegisterInfo *reg_info,
1998 unsigned int current_id)
2000 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2002 CompilerType clang_type = ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (m_ast_context,
2004 reg_info->byte_size * 8);
2009 log->Printf(" Tried to add a type for %s, but couldn't get one", context.m_decl_name.getAsString().c_str());
2013 TypeFromParser parser_clang_type (clang_type);
2015 NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
2017 ClangExpressionVariable *entity(new ClangExpressionVariable(m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
2018 m_parser_vars->m_target_info.byte_order,
2019 m_parser_vars->m_target_info.address_byte_size));
2020 m_found_entities.AddNewlyConstructedVariable(entity);
2022 std::string decl_name(context.m_decl_name.getAsString());
2023 entity->SetName (ConstString (decl_name.c_str()));
2024 entity->SetRegisterInfo (reg_info);
2025 entity->EnableParserVars(GetParserID());
2026 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
2027 parser_vars->m_parser_type = parser_clang_type;
2028 parser_vars->m_named_decl = var_decl;
2029 parser_vars->m_llvm_value = NULL;
2030 parser_vars->m_lldb_value.Clear();
2031 entity->m_flags |= ClangExpressionVariable::EVBareRegister;
2035 ASTDumper ast_dumper(var_decl);
2036 log->Printf(" CEDM::FEVD[%d] Added register %s, returned %s", current_id, context.m_decl_name.getAsString().c_str(), ast_dumper.GetCString());
2041 ClangExpressionDeclMap::AddOneFunction (NameSearchContext &context,
2044 unsigned int current_id)
2046 assert (m_parser_vars.get());
2048 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2050 NamedDecl *function_decl = NULL;
2051 Address fun_address;
2052 CompilerType function_clang_type;
2054 bool is_indirect_function = false;
2058 Type *function_type = function->GetType();
2060 const lldb::LanguageType comp_unit_language = function->GetCompileUnit()->GetLanguage();
2061 const bool extern_c = Language::LanguageIsC(comp_unit_language) ||
2062 (Language::LanguageIsObjC(comp_unit_language) &&
2063 !Language::LanguageIsCPlusPlus(comp_unit_language));
2067 TypeSystem *type_system = function->GetDeclContext().GetTypeSystem();
2068 if (ClangASTContext *src_ast = llvm::dyn_cast<ClangASTContext>(type_system))
2070 clang::DeclContext *src_decl_context = (clang::DeclContext*)function->GetDeclContext().GetOpaqueDeclContext();
2071 clang::FunctionDecl *src_function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context);
2073 if (src_function_decl)
2075 if (clang::FunctionDecl *copied_function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(m_ast_importer_sp->CopyDecl(m_ast_context, src_ast->getASTContext(), src_function_decl)))
2079 ASTDumper ast_dumper((clang::Decl*)copied_function_decl);
2083 function->DumpSymbolContext(&ss);
2085 log->Printf(" CEDM::FEVD[%u] Imported decl for function %s (description %s), returned %s",
2087 copied_function_decl->getName().str().c_str(),
2089 ast_dumper.GetCString());
2093 context.AddNamedDecl(copied_function_decl);
2100 log->Printf (" Failed to import the function decl for '%s'",
2101 src_function_decl->getName().str().c_str());
2111 log->PutCString(" Skipped a function because it has no type");
2115 function_clang_type = function_type->GetFullCompilerType ();
2117 if (!function_clang_type)
2120 log->PutCString(" Skipped a function because it has no Clang type");
2124 fun_address = function->GetAddressRange().GetBaseAddress();
2126 CompilerType copied_function_type = GuardedCopyType(function_clang_type);
2127 if (copied_function_type)
2129 function_decl = context.AddFunDecl(copied_function_type, extern_c);
2135 log->Printf (" Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}",
2136 function_type->GetName().GetCString(),
2137 function_type->GetID());
2145 // We failed to copy the type we found
2148 log->Printf (" Failed to import the function type '%s' {0x%8.8" PRIx64 "} into the expression parser AST contenxt",
2149 function_type->GetName().GetCString(),
2150 function_type->GetID());
2158 fun_address = symbol->GetAddress();
2159 function_decl = context.AddGenericFunDecl();
2160 is_indirect_function = symbol->IsIndirect();
2165 log->PutCString(" AddOneFunction called with no function and no symbol");
2169 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
2171 lldb::addr_t load_addr = fun_address.GetCallableLoadAddress(target, is_indirect_function);
2173 ClangExpressionVariable *entity(new ClangExpressionVariable (m_parser_vars->m_exe_ctx.GetBestExecutionContextScope (),
2174 m_parser_vars->m_target_info.byte_order,
2175 m_parser_vars->m_target_info.address_byte_size));
2176 m_found_entities.AddNewlyConstructedVariable(entity);
2178 std::string decl_name(context.m_decl_name.getAsString());
2179 entity->SetName(ConstString(decl_name.c_str()));
2180 entity->SetCompilerType (function_clang_type);
2181 entity->EnableParserVars(GetParserID());
2183 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
2185 if (load_addr != LLDB_INVALID_ADDRESS)
2187 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
2188 parser_vars->m_lldb_value.GetScalar() = load_addr;
2192 // We have to try finding a file address.
2194 lldb::addr_t file_addr = fun_address.GetFileAddress();
2196 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress);
2197 parser_vars->m_lldb_value.GetScalar() = file_addr;
2201 parser_vars->m_named_decl = function_decl;
2202 parser_vars->m_llvm_value = NULL;
2206 ASTDumper ast_dumper(function_decl);
2210 fun_address.Dump(&ss, m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), Address::DumpStyleResolvedDescription);
2212 log->Printf(" CEDM::FEVD[%u] Found %s function %s (description %s), returned %s",
2214 (function ? "specific" : "generic"),
2217 ast_dumper.GetCString());
2222 ClangExpressionDeclMap::AddThisType(NameSearchContext &context,
2224 unsigned int current_id)
2226 CompilerType copied_clang_type = GuardedCopyType(ut);
2228 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2230 if (!copied_clang_type)
2233 log->Printf("ClangExpressionDeclMap::AddThisType - Couldn't import the type");
2238 if (copied_clang_type.IsAggregateType() && copied_clang_type.GetCompleteType ())
2240 CompilerType void_clang_type = ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid);
2241 CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
2243 CompilerType method_type = ClangASTContext::CreateFunctionType (m_ast_context,
2245 &void_ptr_clang_type,
2250 const bool is_virtual = false;
2251 const bool is_static = false;
2252 const bool is_inline = false;
2253 const bool is_explicit = false;
2254 const bool is_attr_used = true;
2255 const bool is_artificial = false;
2257 CXXMethodDecl *method_decl = ClangASTContext::GetASTContext(m_ast_context)->
2258 AddMethodToCXXRecordType (copied_clang_type.GetOpaqueQualType(),
2261 lldb::eAccessPublic,
2271 ASTDumper method_ast_dumper((clang::Decl*)method_decl);
2272 ASTDumper type_ast_dumper(copied_clang_type);
2274 log->Printf(" CEDM::AddThisType Added function $__lldb_expr (description %s) for this type %s",
2275 method_ast_dumper.GetCString(),
2276 type_ast_dumper.GetCString());
2280 if (!copied_clang_type.IsValid())
2283 TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
2285 if (!type_source_info)
2288 // Construct a typedef type because if "*this" is a templated type we can't just return ClassTemplateSpecializationDecls in response to name queries.
2289 // Using a typedef makes this much more robust.
2291 TypedefDecl *typedef_decl = TypedefDecl::Create(*m_ast_context,
2292 m_ast_context->getTranslationUnitDecl(),
2295 context.m_decl_name.getAsIdentifierInfo(),
2302 context.AddNamedDecl(typedef_decl);
2308 ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
2310 unsigned int current_id)
2312 CompilerType copied_clang_type = GuardedCopyType(ut);
2314 if (!copied_clang_type)
2316 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2319 log->Printf("ClangExpressionDeclMap::AddOneType - Couldn't import the type");
2324 context.AddTypeDecl(copied_clang_type);