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/SymbolVendor.h"
40 #include "lldb/Symbol/Type.h"
41 #include "lldb/Symbol/TypeList.h"
42 #include "lldb/Symbol/Variable.h"
43 #include "lldb/Symbol/VariableList.h"
44 #include "lldb/Target/CPPLanguageRuntime.h"
45 #include "lldb/Target/ExecutionContext.h"
46 #include "lldb/Target/ObjCLanguageRuntime.h"
47 #include "lldb/Target/Process.h"
48 #include "lldb/Target/RegisterContext.h"
49 #include "lldb/Target/StackFrame.h"
50 #include "lldb/Target/Target.h"
51 #include "lldb/Target/Thread.h"
53 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
56 using namespace lldb_private;
57 using namespace clang;
59 ClangExpressionDeclMap::ClangExpressionDeclMap (bool keep_result_in_memory,
60 Materializer::PersistentVariableDelegate *result_delegate,
61 ExecutionContext &exe_ctx) :
62 ClangASTSource (exe_ctx.GetTargetSP()),
65 m_keep_result_in_memory (keep_result_in_memory),
66 m_result_delegate (result_delegate),
73 ClangExpressionDeclMap::~ClangExpressionDeclMap()
75 // Note: The model is now that the parser's AST context and all associated
76 // data does not vanish until the expression has been executed. This means
77 // that valuable lookup data (like namespaces) doesn't vanish, but
84 ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx,
85 Materializer *materializer)
87 ClangASTMetrics::ClearLocalCounters();
90 m_parser_vars->m_exe_ctx = exe_ctx;
92 Target *target = exe_ctx.GetTargetPtr();
93 if (exe_ctx.GetFramePtr())
94 m_parser_vars->m_sym_ctx = exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
95 else if (exe_ctx.GetThreadPtr() && exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0))
96 m_parser_vars->m_sym_ctx = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(lldb::eSymbolContextEverything);
97 else if (exe_ctx.GetProcessPtr())
99 m_parser_vars->m_sym_ctx.Clear(true);
100 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
104 m_parser_vars->m_sym_ctx.Clear(true);
105 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
110 m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>(target->GetPersistentExpressionStateForLanguage(eLanguageTypeC));
112 if (!target->GetScratchClangASTContext())
116 m_parser_vars->m_target_info = GetTargetInfo();
117 m_parser_vars->m_materializer = materializer;
123 ClangExpressionDeclMap::InstallCodeGenerator (clang::ASTConsumer *code_gen)
125 assert(m_parser_vars);
126 m_parser_vars->m_code_gen = code_gen;
130 ClangExpressionDeclMap::DidParse()
132 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
135 ClangASTMetrics::DumpCounters(log);
137 if (m_parser_vars.get())
139 for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
140 entity_index < num_entities;
143 ExpressionVariableSP var_sp(m_found_entities.GetVariableAtIndex(entity_index));
145 llvm::cast<ClangExpressionVariable>(var_sp.get())->DisableParserVars(GetParserID());
148 for (size_t pvar_index = 0, num_pvars = m_parser_vars->m_persistent_vars->GetSize();
149 pvar_index < num_pvars;
152 ExpressionVariableSP pvar_sp(m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
153 if (ClangExpressionVariable *clang_var = llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get()))
154 clang_var->DisableParserVars(GetParserID());
161 // Interface for IRForTarget
163 ClangExpressionDeclMap::TargetInfo
164 ClangExpressionDeclMap::GetTargetInfo()
166 assert (m_parser_vars.get());
170 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
172 Process *process = exe_ctx.GetProcessPtr();
175 ret.byte_order = process->GetByteOrder();
176 ret.address_byte_size = process->GetAddressByteSize();
180 Target *target = exe_ctx.GetTargetPtr();
183 ret.byte_order = target->GetArchitecture().GetByteOrder();
184 ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
192 ClangExpressionDeclMap::AddPersistentVariable
194 const NamedDecl *decl,
195 const ConstString &name,
196 TypeFromParser parser_type,
201 assert (m_parser_vars.get());
203 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(parser_type.GetTypeSystem());
207 if (m_parser_vars->m_materializer && is_result)
211 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
212 Target *target = exe_ctx.GetTargetPtr();
213 if (target == nullptr)
216 ClangASTContext *context(target->GetScratchClangASTContext());
218 TypeFromUser user_type(m_ast_importer_sp->DeportType(context->getASTContext(),
219 ast->getASTContext(),
220 parser_type.GetOpaqueQualType()),
223 uint32_t offset = m_parser_vars->m_materializer->AddResultVariable(user_type,
225 m_keep_result_in_memory,
229 ClangExpressionVariable *var = new ClangExpressionVariable(exe_ctx.GetBestExecutionContextScope(),
232 m_parser_vars->m_target_info.byte_order,
233 m_parser_vars->m_target_info.address_byte_size);
235 m_found_entities.AddNewlyConstructedVariable(var);
237 var->EnableParserVars(GetParserID());
239 ClangExpressionVariable::ParserVars *parser_vars = var->GetParserVars(GetParserID());
241 parser_vars->m_named_decl = decl;
242 parser_vars->m_parser_type = parser_type;
244 var->EnableJITVars(GetParserID());
246 ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID());
248 jit_vars->m_offset = offset;
253 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
254 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
255 Target *target = exe_ctx.GetTargetPtr();
259 ClangASTContext *context(target->GetScratchClangASTContext());
261 TypeFromUser user_type(m_ast_importer_sp->DeportType(context->getASTContext(),
262 ast->getASTContext(),
263 parser_type.GetOpaqueQualType()),
266 if (!user_type.GetOpaqueQualType())
269 log->Printf("Persistent variable's type wasn't copied successfully");
273 if (!m_parser_vars->m_target_info.IsValid())
276 ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>(m_parser_vars->m_persistent_vars->CreatePersistentVariable (exe_ctx.GetBestExecutionContextScope (),
279 m_parser_vars->m_target_info.byte_order,
280 m_parser_vars->m_target_info.address_byte_size).get());
285 var->m_frozen_sp->SetHasCompleteType();
288 var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
290 var->m_flags |= ClangExpressionVariable::EVKeepInTarget; // explicitly-declared persistent variables should persist
294 var->m_flags |= ClangExpressionVariable::EVIsProgramReference;
298 var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
299 var->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
302 if (m_keep_result_in_memory)
304 var->m_flags |= ClangExpressionVariable::EVKeepInTarget;
308 log->Printf("Created persistent variable with flags 0x%hx", var->m_flags);
310 var->EnableParserVars(GetParserID());
312 ClangExpressionVariable::ParserVars *parser_vars = var->GetParserVars(GetParserID());
314 parser_vars->m_named_decl = decl;
315 parser_vars->m_parser_type = parser_type;
321 ClangExpressionDeclMap::AddValueToStruct
323 const NamedDecl *decl,
324 const ConstString &name,
327 lldb::offset_t alignment
330 assert (m_struct_vars.get());
331 assert (m_parser_vars.get());
333 bool is_persistent_variable = false;
335 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
337 m_struct_vars->m_struct_laid_out = false;
339 if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl, GetParserID()))
342 ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList(m_found_entities, decl, GetParserID()));
346 var = ClangExpressionVariable::FindVariableInList(*m_parser_vars->m_persistent_vars, decl, GetParserID());
347 is_persistent_variable = true;
354 log->Printf("Adding value for (NamedDecl*)%p [%s - %s] to the structure",
355 static_cast<const void*>(decl), name.GetCString(),
356 var->GetName().GetCString());
358 // We know entity->m_parser_vars is valid because we used a parser variable
361 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID());
363 parser_vars->m_llvm_value = value;
365 if (ClangExpressionVariable::JITVars *jit_vars = llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID()))
367 // We already laid this out; do not touch
370 log->Printf("Already placed at 0x%llx", (unsigned long long)jit_vars->m_offset);
373 llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID());
375 ClangExpressionVariable::JITVars *jit_vars = llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID());
377 jit_vars->m_alignment = alignment;
378 jit_vars->m_size = size;
380 m_struct_members.AddVariable(var->shared_from_this());
382 if (m_parser_vars->m_materializer)
388 if (is_persistent_variable)
390 ExpressionVariableSP var_sp(var->shared_from_this());
391 offset = m_parser_vars->m_materializer->AddPersistentVariable(var_sp, nullptr, err);
395 if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym)
396 offset = m_parser_vars->m_materializer->AddSymbol(*sym, err);
397 else if (const RegisterInfo *reg_info = var->GetRegisterInfo())
398 offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err);
399 else if (parser_vars->m_lldb_var)
400 offset = m_parser_vars->m_materializer->AddVariable(parser_vars->m_lldb_var, err);
407 log->Printf("Placed at 0x%llx", (unsigned long long)offset);
409 jit_vars->m_offset = offset; // TODO DoStructLayout() should not change this.
416 ClangExpressionDeclMap::DoStructLayout ()
418 assert (m_struct_vars.get());
420 if (m_struct_vars->m_struct_laid_out)
423 if (!m_parser_vars->m_materializer)
426 m_struct_vars->m_struct_alignment = m_parser_vars->m_materializer->GetStructAlignment();
427 m_struct_vars->m_struct_size = m_parser_vars->m_materializer->GetStructByteSize();
428 m_struct_vars->m_struct_laid_out = true;
432 bool ClangExpressionDeclMap::GetStructInfo
434 uint32_t &num_elements,
436 lldb::offset_t &alignment
439 assert (m_struct_vars.get());
441 if (!m_struct_vars->m_struct_laid_out)
444 num_elements = m_struct_members.GetSize();
445 size = m_struct_vars->m_struct_size;
446 alignment = m_struct_vars->m_struct_alignment;
452 ClangExpressionDeclMap::GetStructElement
454 const NamedDecl *&decl,
456 lldb::offset_t &offset,
461 assert (m_struct_vars.get());
463 if (!m_struct_vars->m_struct_laid_out)
466 if (index >= m_struct_members.GetSize())
469 ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
474 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(member_sp.get())->GetParserVars(GetParserID());
475 ClangExpressionVariable::JITVars *jit_vars = llvm::cast<ClangExpressionVariable>(member_sp.get())->GetJITVars(GetParserID());
479 !member_sp->GetValueObject())
482 decl = parser_vars->m_named_decl;
483 value = parser_vars->m_llvm_value;
484 offset = jit_vars->m_offset;
485 name = member_sp->GetName();
491 ClangExpressionDeclMap::GetFunctionInfo
493 const NamedDecl *decl,
497 ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList(m_found_entities, decl, GetParserID()));
502 // We know m_parser_vars is valid since we searched for the variable by
505 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
507 ptr = parser_vars->m_lldb_value.GetScalar().ULongLong();
513 FindCodeSymbolInContext
515 const ConstString &name,
516 SymbolContext &sym_ctx,
517 uint32_t name_type_mask,
518 SymbolContextList &sc_list
522 SymbolContextList temp_sc_list;
523 if (sym_ctx.module_sp)
524 sym_ctx.module_sp->FindFunctions(name,
527 true, // include_symbols
528 false, // include_inlines
531 if (temp_sc_list.GetSize() == 0)
533 if (sym_ctx.target_sp)
534 sym_ctx.target_sp->GetImages().FindFunctions(name,
536 true, // include_symbols
537 false, // include_inlines
542 SymbolContextList internal_symbol_sc_list;
543 unsigned temp_sc_list_size = temp_sc_list.GetSize();
544 for (unsigned i = 0; i < temp_sc_list_size; i++)
547 temp_sc_list.GetContextAtIndex(i, sc);
554 if (sc.symbol->IsExternal())
560 internal_symbol_sc_list.Append(sc);
565 // If we had internal symbols and we didn't find any external symbols or
566 // functions in debug info, then fallback to the internal symbols
567 if (sc_list.GetSize() == 0 && internal_symbol_sc_list.GetSize())
569 sc_list = internal_symbol_sc_list;
574 ClangExpressionDeclMap::GetFunctionAddress
576 const ConstString &name,
580 assert (m_parser_vars.get());
582 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
583 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
584 Target *target = exe_ctx.GetTargetPtr();
585 // Back out in all cases where we're not fully initialized
588 if (!m_parser_vars->m_sym_ctx.target_sp)
591 SymbolContextList sc_list;
593 FindCodeSymbolInContext(name, m_parser_vars->m_sym_ctx, eFunctionNameTypeAuto, sc_list);
595 uint32_t sc_list_size = sc_list.GetSize();
597 if (sc_list_size == 0)
599 SymbolContext &sc = m_parser_vars->m_sym_ctx;
602 LanguageType lang_type = sc.comp_unit->GetLanguage();
603 if (Language::LanguageIsCPlusPlus(lang_type) &&
604 CPlusPlusLanguage::IsCPPMangledName(name.AsCString()))
606 // 1. Demangle the name
607 Mangled mangled(name, true);
608 ConstString demangled = mangled.GetDemangledName(lang_type);
612 FindCodeSymbolInContext(
613 demangled, m_parser_vars->m_sym_ctx, eFunctionNameTypeFull, sc_list);
614 sc_list_size = sc_list.GetSize();
620 if (sc_list_size == 0)
622 // We occasionally get debug information in which a const function is reported
623 // as non-const, so the mangled name is wrong. This is a hack to compensate.
625 if (!strncmp(name.GetCString(), "_ZN", 3) &&
626 strncmp(name.GetCString(), "_ZNK", 4))
628 std::string fixed_scratch("_ZNK");
629 fixed_scratch.append(name.GetCString() + 3);
630 ConstString fixed_name(fixed_scratch.c_str());
633 log->Printf("Failed to find symbols given non-const name %s; trying %s", name.GetCString(), fixed_name.GetCString());
635 FindCodeSymbolInContext(
636 fixed_name, m_parser_vars->m_sym_ctx, eFunctionNameTypeAuto, sc_list);
637 sc_list_size = sc_list.GetSize();
641 lldb::addr_t intern_callable_load_addr = LLDB_INVALID_ADDRESS;
643 for (uint32_t i=0; i<sc_list_size; ++i)
645 SymbolContext sym_ctx;
646 sc_list.GetContextAtIndex(i, sym_ctx);
649 lldb::addr_t callable_load_addr = LLDB_INVALID_ADDRESS;
651 if (sym_ctx.function)
653 const Address func_so_addr = sym_ctx.function->GetAddressRange().GetBaseAddress();
654 if (func_so_addr.IsValid())
656 callable_load_addr = func_so_addr.GetCallableLoadAddress(target, false);
659 else if (sym_ctx.symbol)
661 if (sym_ctx.symbol->IsExternal())
662 callable_load_addr = sym_ctx.symbol->ResolveCallableAddress(*target);
665 if (intern_callable_load_addr == LLDB_INVALID_ADDRESS)
666 intern_callable_load_addr = sym_ctx.symbol->ResolveCallableAddress(*target);
670 if (callable_load_addr != LLDB_INVALID_ADDRESS)
672 func_addr = callable_load_addr;
677 // See if we found an internal symbol
678 if (intern_callable_load_addr != LLDB_INVALID_ADDRESS)
680 func_addr = intern_callable_load_addr;
688 ClangExpressionDeclMap::GetSymbolAddress (Target &target,
690 const ConstString &name,
691 lldb::SymbolType symbol_type,
692 lldb_private::Module *module)
694 SymbolContextList sc_list;
697 module->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
699 target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list);
701 const uint32_t num_matches = sc_list.GetSize();
702 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
704 for (uint32_t i=0; i<num_matches && (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS); i++)
706 SymbolContext sym_ctx;
707 sc_list.GetContextAtIndex(i, sym_ctx);
709 const Address sym_address = sym_ctx.symbol->GetAddress();
711 if (!sym_address.IsValid())
714 switch (sym_ctx.symbol->GetType())
716 case eSymbolTypeCode:
717 case eSymbolTypeTrampoline:
718 symbol_load_addr = sym_address.GetCallableLoadAddress (&target);
721 case eSymbolTypeResolver:
722 symbol_load_addr = sym_address.GetCallableLoadAddress (&target, true);
725 case eSymbolTypeReExported:
727 ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName();
730 ModuleSP reexport_module_sp;
731 ModuleSpec reexport_module_spec;
732 reexport_module_spec.GetPlatformFileSpec() = sym_ctx.symbol->GetReExportedSymbolSharedLibrary();
733 if (reexport_module_spec.GetPlatformFileSpec())
735 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
736 if (!reexport_module_sp)
738 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
739 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
742 symbol_load_addr = GetSymbolAddress(target, process, sym_ctx.symbol->GetReExportedSymbolName(), symbol_type, reexport_module_sp.get());
747 case eSymbolTypeData:
748 case eSymbolTypeRuntime:
749 case eSymbolTypeVariable:
750 case eSymbolTypeLocal:
751 case eSymbolTypeParam:
752 case eSymbolTypeInvalid:
753 case eSymbolTypeAbsolute:
754 case eSymbolTypeException:
755 case eSymbolTypeSourceFile:
756 case eSymbolTypeHeaderFile:
757 case eSymbolTypeObjectFile:
758 case eSymbolTypeCommonBlock:
759 case eSymbolTypeBlock:
760 case eSymbolTypeVariableType:
761 case eSymbolTypeLineEntry:
762 case eSymbolTypeLineHeader:
763 case eSymbolTypeScopeBegin:
764 case eSymbolTypeScopeEnd:
765 case eSymbolTypeAdditional:
766 case eSymbolTypeCompiler:
767 case eSymbolTypeInstrumentation:
768 case eSymbolTypeUndefined:
769 case eSymbolTypeObjCClass:
770 case eSymbolTypeObjCMetaClass:
771 case eSymbolTypeObjCIVar:
772 symbol_load_addr = sym_address.GetLoadAddress (&target);
777 if (symbol_load_addr == LLDB_INVALID_ADDRESS && process)
779 ObjCLanguageRuntime *runtime = process->GetObjCLanguageRuntime();
783 symbol_load_addr = runtime->LookupRuntimeSymbol(name);
787 return symbol_load_addr;
791 ClangExpressionDeclMap::GetSymbolAddress (const ConstString &name, lldb::SymbolType symbol_type)
793 assert (m_parser_vars.get());
795 if (!m_parser_vars->m_exe_ctx.GetTargetPtr())
798 return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(), m_parser_vars->m_exe_ctx.GetProcessPtr(), name, symbol_type);
802 ClangExpressionDeclMap::FindGlobalDataSymbol (Target &target,
803 const ConstString &name,
804 lldb_private::Module *module)
806 SymbolContextList sc_list;
809 module->FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
811 target.GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
813 const uint32_t matches = sc_list.GetSize();
814 for (uint32_t i=0; i<matches; ++i)
816 SymbolContext sym_ctx;
817 sc_list.GetContextAtIndex(i, sym_ctx);
820 const Symbol *symbol = sym_ctx.symbol;
821 const Address sym_address = symbol->GetAddress();
823 if (sym_address.IsValid())
825 switch (symbol->GetType())
827 case eSymbolTypeData:
828 case eSymbolTypeRuntime:
829 case eSymbolTypeAbsolute:
830 case eSymbolTypeObjCClass:
831 case eSymbolTypeObjCMetaClass:
832 case eSymbolTypeObjCIVar:
833 if (symbol->GetDemangledNameIsSynthesized())
835 // If the demangled name was synthesized, then don't use it
836 // for expressions. Only let the symbol match if the mangled
837 // named matches for these symbols.
838 if (symbol->GetMangled().GetMangledName() != name)
843 case eSymbolTypeReExported:
845 ConstString reexport_name = symbol->GetReExportedSymbolName();
848 ModuleSP reexport_module_sp;
849 ModuleSpec reexport_module_spec;
850 reexport_module_spec.GetPlatformFileSpec() = symbol->GetReExportedSymbolSharedLibrary();
851 if (reexport_module_spec.GetPlatformFileSpec())
853 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
854 if (!reexport_module_sp)
856 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
857 reexport_module_sp = target.GetImages().FindFirstModule(reexport_module_spec);
860 // Don't allow us to try and resolve a re-exported symbol if it is the same
861 // as the current symbol
862 if (name == symbol->GetReExportedSymbolName() && module == reexport_module_sp.get())
865 return FindGlobalDataSymbol(target, symbol->GetReExportedSymbolName(), reexport_module_sp.get());
870 case eSymbolTypeCode: // We already lookup functions elsewhere
871 case eSymbolTypeVariable:
872 case eSymbolTypeLocal:
873 case eSymbolTypeParam:
874 case eSymbolTypeTrampoline:
875 case eSymbolTypeInvalid:
876 case eSymbolTypeException:
877 case eSymbolTypeSourceFile:
878 case eSymbolTypeHeaderFile:
879 case eSymbolTypeObjectFile:
880 case eSymbolTypeCommonBlock:
881 case eSymbolTypeBlock:
882 case eSymbolTypeVariableType:
883 case eSymbolTypeLineEntry:
884 case eSymbolTypeLineHeader:
885 case eSymbolTypeScopeBegin:
886 case eSymbolTypeScopeEnd:
887 case eSymbolTypeAdditional:
888 case eSymbolTypeCompiler:
889 case eSymbolTypeInstrumentation:
890 case eSymbolTypeUndefined:
891 case eSymbolTypeResolver:
902 ClangExpressionDeclMap::FindGlobalVariable
906 const ConstString &name,
907 CompilerDeclContext *namespace_decl,
913 if (module && namespace_decl)
914 module->FindGlobalVariables (name, namespace_decl, true, -1, vars);
916 target.GetImages().FindGlobalVariables(name, true, -1, vars);
922 for (size_t i = 0; i < vars.GetSize(); ++i)
924 VariableSP var_sp = vars.GetVariableAtIndex(i);
926 if (ClangASTContext::AreTypesSame(*type, var_sp->GetType()->GetFullCompilerType ()))
932 return vars.GetVariableAtIndex(0);
939 // Interface for ClangASTSource
942 ClangExpressionDeclMap::FindExternalVisibleDecls (NameSearchContext &context)
944 assert (m_ast_context);
946 ClangASTMetrics::RegisterVisibleQuery();
948 const ConstString name(context.m_decl_name.getAsString().c_str());
950 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
952 if (GetImportInProgress())
954 if (log && log->GetVerbose())
955 log->Printf("Ignoring a query during an import");
959 static unsigned int invocation_id = 0;
960 unsigned int current_id = invocation_id++;
964 if (!context.m_decl_context)
965 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for '%s' in a NULL DeclContext", current_id, name.GetCString());
966 else if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context.m_decl_context))
967 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for '%s' in '%s'", current_id, name.GetCString(), context_named_decl->getNameAsString().c_str());
969 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for '%s' in a '%s'", current_id, name.GetCString(), context.m_decl_context->getDeclKindName());
972 if (const NamespaceDecl *namespace_context = dyn_cast<NamespaceDecl>(context.m_decl_context))
974 ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp->GetNamespaceMap(namespace_context);
976 if (log && log->GetVerbose())
977 log->Printf(" CEDM::FEVD[%u] Inspecting (NamespaceMap*)%p (%d entries)",
978 current_id, static_cast<void*>(namespace_map.get()),
979 (int)namespace_map->size());
984 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), e = namespace_map->end();
989 log->Printf(" CEDM::FEVD[%u] Searching namespace %s in module %s",
991 i->second.GetName().AsCString(),
992 i->first->GetFileSpec().GetFilename().GetCString());
994 FindExternalVisibleDecls(context,
1000 else if (isa<TranslationUnitDecl>(context.m_decl_context))
1002 CompilerDeclContext namespace_decl;
1005 log->Printf(" CEDM::FEVD[%u] Searching the root namespace", current_id);
1007 FindExternalVisibleDecls(context,
1013 if (!context.m_found.variable)
1014 ClangASTSource::FindExternalVisibleDecls(context);
1018 ClangExpressionDeclMap::FindExternalVisibleDecls (NameSearchContext &context,
1019 lldb::ModuleSP module_sp,
1020 CompilerDeclContext &namespace_decl,
1021 unsigned int current_id)
1023 assert (m_ast_context);
1025 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1027 SymbolContextList sc_list;
1029 const ConstString name(context.m_decl_name.getAsString().c_str());
1031 const char *name_unique_cstr = name.GetCString();
1033 if (name_unique_cstr == NULL)
1036 static ConstString id_name("id");
1037 static ConstString Class_name("Class");
1039 if (name == id_name || name == Class_name)
1042 // Only look for functions by name out in our symbols if the function
1043 // doesn't start with our phony prefix of '$'
1044 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1045 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1046 SymbolContext sym_ctx;
1047 if (frame != nullptr)
1048 sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
1049 if (name_unique_cstr[0] == '$' && !namespace_decl)
1051 static ConstString g_lldb_class_name ("$__lldb_class");
1053 if (name == g_lldb_class_name)
1055 // Clang is looking for the type of "this"
1061 // Find the block that defines the function represented by "sym_ctx"
1062 Block *function_block = sym_ctx.GetFunctionBlock();
1064 if (!function_block)
1067 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
1069 if (!function_decl_ctx)
1072 clang::CXXMethodDecl *method_decl = ClangASTContext::DeclContextGetAsCXXMethodDecl(function_decl_ctx);
1076 clang::CXXRecordDecl *class_decl = method_decl->getParent();
1078 QualType class_qual_type(class_decl->getTypeForDecl(), 0);
1080 TypeFromUser class_user_type (class_qual_type.getAsOpaquePtr(),
1081 ClangASTContext::GetASTContext(&class_decl->getASTContext()));
1085 ASTDumper ast_dumper(class_qual_type);
1086 log->Printf(" CEDM::FEVD[%u] Adding type for $__lldb_class: %s", current_id, ast_dumper.GetCString());
1089 AddThisType(context, class_user_type, current_id);
1091 if (method_decl->isInstance())
1093 // self is a pointer to the object
1095 QualType class_pointer_type = method_decl->getASTContext().getPointerType(class_qual_type);
1097 TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
1098 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1100 m_struct_vars->m_object_pointer_type = self_user_type;
1105 // This branch will get hit if we are executing code in the context of a function that
1106 // claims to have an object pointer (through DW_AT_object_pointer?) but is not formally a
1107 // method of the class. In that case, just look up the "this" variable in the current
1108 // scope and use its type.
1109 // FIXME: This code is formally correct, but clang doesn't currently emit DW_AT_object_pointer
1110 // for C++ so it hasn't actually been tested.
1112 VariableList *vars = frame->GetVariableList(false);
1114 lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
1117 this_var->IsInScope(frame) &&
1118 this_var->LocationIsValidForFrame (frame))
1120 Type *this_type = this_var->GetType();
1125 TypeFromUser pointee_type = this_type->GetForwardCompilerType ().GetPointeeType();
1127 if (pointee_type.IsValid())
1131 ASTDumper ast_dumper(pointee_type);
1132 log->Printf(" FEVD[%u] Adding type for $__lldb_class: %s", current_id, ast_dumper.GetCString());
1135 AddThisType(context, pointee_type, current_id);
1136 TypeFromUser this_user_type(this_type->GetFullCompilerType ());
1137 m_struct_vars->m_object_pointer_type = this_user_type;
1146 static ConstString g_lldb_objc_class_name ("$__lldb_objc_class");
1147 if (name == g_lldb_objc_class_name)
1149 // Clang is looking for the type of "*self"
1154 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
1156 // Find the block that defines the function represented by "sym_ctx"
1157 Block *function_block = sym_ctx.GetFunctionBlock();
1159 if (!function_block)
1162 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
1164 if (!function_decl_ctx)
1167 clang::ObjCMethodDecl *method_decl = ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1171 ObjCInterfaceDecl* self_interface = method_decl->getClassInterface();
1173 if (!self_interface)
1176 const clang::Type *interface_type = self_interface->getTypeForDecl();
1178 if (!interface_type)
1179 return; // This is unlikely, but we have seen crashes where this occurred
1181 TypeFromUser class_user_type(QualType(interface_type, 0).getAsOpaquePtr(),
1182 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1186 ASTDumper ast_dumper(interface_type);
1187 log->Printf(" FEVD[%u] Adding type for $__lldb_objc_class: %s", current_id, ast_dumper.GetCString());
1190 AddOneType(context, class_user_type, current_id);
1192 if (method_decl->isInstanceMethod())
1194 // self is a pointer to the object
1196 QualType class_pointer_type = method_decl->getASTContext().getObjCObjectPointerType(QualType(interface_type, 0));
1198 TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
1199 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1201 m_struct_vars->m_object_pointer_type = self_user_type;
1205 // self is a Class pointer
1206 QualType class_type = method_decl->getASTContext().getObjCClassType();
1208 TypeFromUser self_user_type(class_type.getAsOpaquePtr(),
1209 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1211 m_struct_vars->m_object_pointer_type = self_user_type;
1218 // This branch will get hit if we are executing code in the context of a function that
1219 // claims to have an object pointer (through DW_AT_object_pointer?) but is not formally a
1220 // method of the class. In that case, just look up the "self" variable in the current
1221 // scope and use its type.
1223 VariableList *vars = frame->GetVariableList(false);
1225 lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
1228 self_var->IsInScope(frame) &&
1229 self_var->LocationIsValidForFrame (frame))
1231 Type *self_type = self_var->GetType();
1236 CompilerType self_clang_type = self_type->GetFullCompilerType ();
1238 if (ClangASTContext::IsObjCClassType(self_clang_type))
1242 else if (ClangASTContext::IsObjCObjectPointerType(self_clang_type))
1244 self_clang_type = self_clang_type.GetPointeeType();
1246 if (!self_clang_type)
1251 ASTDumper ast_dumper(self_type->GetFullCompilerType ());
1252 log->Printf(" FEVD[%u] Adding type for $__lldb_objc_class: %s", current_id, ast_dumper.GetCString());
1255 TypeFromUser class_user_type (self_clang_type);
1257 AddOneType(context, class_user_type, current_id);
1259 TypeFromUser self_user_type(self_type->GetFullCompilerType ());
1261 m_struct_vars->m_object_pointer_type = self_user_type;
1270 // any other $__lldb names should be weeded out now
1271 if (!::strncmp(name_unique_cstr, "$__lldb", sizeof("$__lldb") - 1))
1279 ClangASTContext *scratch_clang_ast_context = target->GetScratchClangASTContext();
1281 if (!scratch_clang_ast_context)
1284 ASTContext *scratch_ast_context = scratch_clang_ast_context->getASTContext();
1286 if (!scratch_ast_context)
1289 TypeDecl *ptype_type_decl = m_parser_vars->m_persistent_vars->GetPersistentType(name);
1291 if (!ptype_type_decl)
1294 Decl *parser_ptype_decl = m_ast_importer_sp->CopyDecl(m_ast_context, scratch_ast_context, ptype_type_decl);
1296 if (!parser_ptype_decl)
1299 TypeDecl *parser_ptype_type_decl = dyn_cast<TypeDecl>(parser_ptype_decl);
1301 if (!parser_ptype_type_decl)
1305 log->Printf(" CEDM::FEVD[%u] Found persistent type %s", current_id, name.GetCString());
1307 context.AddNamedDecl(parser_ptype_type_decl);
1310 ExpressionVariableSP pvar_sp(m_parser_vars->m_persistent_vars->GetVariable(name));
1314 AddOneVariable(context, pvar_sp, current_id);
1318 const char *reg_name(&name.GetCString()[1]);
1320 if (m_parser_vars->m_exe_ctx.GetRegisterContext())
1322 const RegisterInfo *reg_info(m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(reg_name));
1327 log->Printf(" CEDM::FEVD[%u] Found register %s", current_id, reg_info->name);
1329 AddOneRegister(context, reg_info, current_id);
1335 ValueObjectSP valobj;
1338 if (frame && !namespace_decl)
1340 CompilerDeclContext compiler_decl_context = sym_ctx.block != nullptr ? sym_ctx.block->GetDeclContext() : CompilerDeclContext();
1342 if (compiler_decl_context)
1344 // Make sure that the variables are parsed so that we have the declarations
1345 VariableListSP vars = frame->GetInScopeVariableList(true);
1346 for (size_t i = 0; i < vars->GetSize(); i++)
1347 vars->GetVariableAtIndex(i)->GetDecl();
1349 // Search for declarations matching the name
1350 std::vector<CompilerDecl> found_decls = compiler_decl_context.FindDeclByName(name);
1352 bool variable_found = false;
1353 for (CompilerDecl decl : found_decls)
1355 var = decl.GetAsVariable();
1358 variable_found = true;
1359 valobj = ValueObjectVariable::Create(frame, var);
1360 AddOneVariable(context, var, valobj, current_id);
1361 context.m_found.variable = true;
1370 var = FindGlobalVariable (*target,
1378 valobj = ValueObjectVariable::Create(target, var);
1379 AddOneVariable(context, var, valobj, current_id);
1380 context.m_found.variable = true;
1385 std::vector<clang::NamedDecl *> decls_from_modules;
1389 if (ClangModulesDeclVendor *decl_vendor = target->GetClangModulesDeclVendor())
1391 decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules);
1395 if (!context.m_found.variable)
1397 const bool include_inlines = false;
1398 const bool append = false;
1400 if (namespace_decl && module_sp)
1402 const bool include_symbols = false;
1404 module_sp->FindFunctions(name,
1406 eFunctionNameTypeBase,
1412 else if (target && !namespace_decl)
1414 const bool include_symbols = true;
1416 // TODO Fix FindFunctions so that it doesn't return
1417 // instance methods for eFunctionNameTypeBase.
1419 target->GetImages().FindFunctions(name,
1420 eFunctionNameTypeFull,
1427 // If we found more than one function, see if we can use the
1428 // frame's decl context to remove functions that are shadowed
1429 // by other functions which match in type but are nearer in scope.
1431 // AddOneFunction will not add a function whose type has already been
1432 // added, so if there's another function in the list with a matching
1433 // type, check to see if their decl context is a parent of the current
1434 // frame's or was imported via a and using statement, and pick the
1435 // best match according to lookup rules.
1436 if (sc_list.GetSize() > 1)
1438 // Collect some info about our frame's context.
1439 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1440 SymbolContext frame_sym_ctx;
1441 if (frame != nullptr)
1442 frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
1443 CompilerDeclContext frame_decl_context = frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext() : CompilerDeclContext();
1445 // We can't do this without a compiler decl context for our frame.
1446 if (frame_decl_context)
1448 clang::DeclContext *frame_decl_ctx = (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1449 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(frame_decl_context.GetTypeSystem());
1451 // Structure to hold the info needed when comparing function
1456 CompilerType m_copied_type;
1457 uint32_t m_decl_lvl;
1458 SymbolContext m_sym_ctx;
1461 // First, symplify things by looping through the symbol contexts
1462 // to remove unwanted functions and separate out the functions we
1463 // want to compare and prune into a separate list.
1464 // Cache the info needed about the function declarations in a
1465 // vector for efficiency.
1466 SymbolContextList sc_sym_list;
1467 uint32_t num_indices = sc_list.GetSize();
1468 std::vector<FuncDeclInfo> fdi_cache;
1469 fdi_cache.reserve(num_indices);
1470 for (uint32_t index = 0; index < num_indices; ++index)
1473 SymbolContext sym_ctx;
1474 sc_list.GetContextAtIndex(index, sym_ctx);
1476 // We don't know enough about symbols to compare them,
1477 // but we should keep them in the list.
1478 Function *function = sym_ctx.function;
1481 sc_sym_list.Append(sym_ctx);
1484 // Filter out functions without declaration contexts, as well as
1485 // class/instance methods, since they'll be skipped in the
1486 // code that follows anyway.
1487 CompilerDeclContext func_decl_context = function->GetDeclContext();
1488 if (!func_decl_context || func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1490 // We can only prune functions for which we can copy the type.
1491 CompilerType func_clang_type = function->GetType()->GetFullCompilerType();
1492 CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1493 if (!copied_func_type)
1495 sc_sym_list.Append(sym_ctx);
1499 fdi.m_sym_ctx = sym_ctx;
1500 fdi.m_name = function->GetName();
1501 fdi.m_copied_type = copied_func_type;
1502 fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1503 if (fdi.m_copied_type && func_decl_context)
1505 // Call CountDeclLevels to get the number of parent scopes we
1506 // have to look through before we find the function declaration.
1507 // When comparing functions of the same type, the one with a
1508 // lower count will be closer to us in the lookup scope and
1509 // shadows the other.
1510 clang::DeclContext *func_decl_ctx = (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1511 fdi.m_decl_lvl = ast->CountDeclLevels(frame_decl_ctx,
1514 &fdi.m_copied_type);
1516 fdi_cache.emplace_back(fdi);
1519 // Loop through the functions in our cache looking for matching types,
1520 // then compare their scope levels to see which is closer.
1521 std::multimap<CompilerType, const FuncDeclInfo*> matches;
1522 for (const FuncDeclInfo &fdi : fdi_cache)
1524 const CompilerType t = fdi.m_copied_type;
1525 auto q = matches.find(t);
1526 if (q != matches.end())
1528 if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1529 // This function is closer; remove the old set.
1531 else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1532 // The functions in our set are closer - skip this one.
1535 matches.insert(std::make_pair(t, &fdi));
1538 // Loop through our matches and add their symbol contexts to our list.
1539 SymbolContextList sc_func_list;
1540 for (const auto &q : matches)
1541 sc_func_list.Append(q.second->m_sym_ctx);
1543 // Rejoin the lists with the functions in front.
1544 sc_list = sc_func_list;
1545 sc_list.Append(sc_sym_list);
1549 if (sc_list.GetSize())
1551 Symbol *extern_symbol = NULL;
1552 Symbol *non_extern_symbol = NULL;
1554 for (uint32_t index = 0, num_indices = sc_list.GetSize();
1555 index < num_indices;
1558 SymbolContext sym_ctx;
1559 sc_list.GetContextAtIndex(index, sym_ctx);
1561 if (sym_ctx.function)
1563 CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1568 // Filter out class/instance methods.
1569 if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1572 AddOneFunction(context, sym_ctx.function, NULL, current_id);
1573 context.m_found.function_with_type_info = true;
1574 context.m_found.function = true;
1576 else if (sym_ctx.symbol)
1578 if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target)
1580 sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1581 if (sym_ctx.symbol == NULL)
1585 if (sym_ctx.symbol->IsExternal())
1586 extern_symbol = sym_ctx.symbol;
1588 non_extern_symbol = sym_ctx.symbol;
1592 if (!context.m_found.function_with_type_info)
1594 for (clang::NamedDecl *decl : decls_from_modules)
1596 if (llvm::isa<clang::FunctionDecl>(decl))
1598 clang::NamedDecl *copied_decl = llvm::cast<FunctionDecl>(m_ast_importer_sp->CopyDecl(m_ast_context, &decl->getASTContext(), decl));
1599 context.AddNamedDecl(copied_decl);
1600 context.m_found.function_with_type_info = true;
1605 if (!context.m_found.function_with_type_info)
1609 AddOneFunction (context, NULL, extern_symbol, current_id);
1610 context.m_found.function = true;
1612 else if (non_extern_symbol)
1614 AddOneFunction (context, NULL, non_extern_symbol, current_id);
1615 context.m_found.function = true;
1620 if (!context.m_found.function_with_type_info)
1622 // Try the modules next.
1626 if (ClangModulesDeclVendor *modules_decl_vendor = m_target->GetClangModulesDeclVendor())
1628 bool append = false;
1629 uint32_t max_matches = 1;
1630 std::vector <clang::NamedDecl *> decls;
1632 if (!modules_decl_vendor->FindDecls(name,
1638 clang::NamedDecl *const decl_from_modules = decls[0];
1640 if (llvm::isa<clang::FunctionDecl>(decl_from_modules))
1644 log->Printf(" CAS::FEVD[%u] Matching function found for \"%s\" in the modules",
1649 clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(m_ast_context, &decl_from_modules->getASTContext(), decl_from_modules);
1650 clang::FunctionDecl *copied_function_decl = copied_decl ? dyn_cast<clang::FunctionDecl>(copied_decl) : nullptr;
1652 if (!copied_function_decl)
1655 log->Printf(" CAS::FEVD[%u] - Couldn't export a function declaration from the modules",
1661 if (copied_function_decl->getBody() && m_parser_vars->m_code_gen)
1663 DeclGroupRef decl_group_ref(copied_function_decl);
1664 m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
1667 context.AddNamedDecl(copied_function_decl);
1669 context.m_found.function_with_type_info = true;
1670 context.m_found.function = true;
1672 else if (llvm::isa<clang::VarDecl>(decl_from_modules))
1676 log->Printf(" CAS::FEVD[%u] Matching variable found for \"%s\" in the modules",
1681 clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(m_ast_context, &decl_from_modules->getASTContext(), decl_from_modules);
1682 clang::VarDecl *copied_var_decl = copied_decl ? dyn_cast_or_null<clang::VarDecl>(copied_decl) : nullptr;
1684 if (!copied_var_decl)
1687 log->Printf(" CAS::FEVD[%u] - Couldn't export a variable declaration from the modules",
1693 context.AddNamedDecl(copied_var_decl);
1695 context.m_found.variable = true;
1701 if (target && !context.m_found.variable && !namespace_decl)
1703 // We couldn't find a non-symbol variable for this. Now we'll hunt for a generic
1704 // data symbol, and -- if it is found -- treat it as a variable.
1706 const Symbol *data_symbol = FindGlobalDataSymbol(*target, name);
1710 std::string warning("got name from symbols: ");
1711 warning.append(name.AsCString());
1712 const unsigned diag_id = m_ast_context->getDiagnostics().getCustomDiagID(clang::DiagnosticsEngine::Level::Warning, "%0");
1713 m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1714 AddOneGenericVariable(context, *data_symbol, current_id);
1715 context.m_found.variable = true;
1722 //static opaque_compiler_type_t
1723 //MaybePromoteToBlockPointerType
1725 // ASTContext *ast_context,
1726 // opaque_compiler_type_t candidate_type
1729 // if (!candidate_type)
1730 // return candidate_type;
1732 // QualType candidate_qual_type = QualType::getFromOpaquePtr(candidate_type);
1734 // const PointerType *candidate_pointer_type = dyn_cast<PointerType>(candidate_qual_type);
1736 // if (!candidate_pointer_type)
1737 // return candidate_type;
1739 // QualType pointee_qual_type = candidate_pointer_type->getPointeeType();
1741 // const RecordType *pointee_record_type = dyn_cast<RecordType>(pointee_qual_type);
1743 // if (!pointee_record_type)
1744 // return candidate_type;
1746 // RecordDecl *pointee_record_decl = pointee_record_type->getDecl();
1748 // if (!pointee_record_decl->isRecord())
1749 // return candidate_type;
1751 // if (!pointee_record_decl->getName().startswith(llvm::StringRef("__block_literal_")))
1752 // return candidate_type;
1754 // QualType generic_function_type = ast_context->getFunctionNoProtoType(ast_context->UnknownAnyTy);
1755 // QualType block_pointer_type = ast_context->getBlockPointerType(generic_function_type);
1757 // return block_pointer_type.getAsOpaquePtr();
1761 ClangExpressionDeclMap::GetVariableValue (VariableSP &var,
1762 lldb_private::Value &var_location,
1763 TypeFromUser *user_type,
1764 TypeFromParser *parser_type)
1766 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1768 Type *var_type = var->GetType();
1773 log->PutCString("Skipped a definition because it has no type");
1777 CompilerType var_clang_type = var_type->GetFullCompilerType ();
1779 if (!var_clang_type)
1782 log->PutCString("Skipped a definition because it has no Clang type");
1786 ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(var_type->GetForwardCompilerType().GetTypeSystem());
1791 log->PutCString("Skipped a definition because it has no Clang AST");
1796 ASTContext *ast = clang_ast->getASTContext();
1801 log->PutCString("There is no AST context for the current execution context");
1804 //var_clang_type = MaybePromoteToBlockPointerType (ast, var_clang_type);
1806 DWARFExpression &var_location_expr = var->LocationExpression();
1808 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1811 if (var->GetLocationIsConstantValueData())
1813 DataExtractor const_value_extractor;
1815 if (var_location_expr.GetExpressionData(const_value_extractor))
1817 var_location = Value(const_value_extractor.GetDataStart(), const_value_extractor.GetByteSize());
1818 var_location.SetValueType(Value::eValueTypeHostAddress);
1823 log->Printf("Error evaluating constant variable: %s", err.AsCString());
1828 CompilerType type_to_use = GuardedCopyType(var_clang_type);
1833 log->Printf("Couldn't copy a variable's type into the parser's AST context");
1839 *parser_type = TypeFromParser(type_to_use);
1841 if (var_location.GetContextType() == Value::eContextTypeInvalid)
1842 var_location.SetCompilerType(type_to_use);
1844 if (var_location.GetValueType() == Value::eValueTypeFileAddress)
1846 SymbolContext var_sc;
1847 var->CalculateSymbolContext(&var_sc);
1849 if (!var_sc.module_sp)
1852 Address so_addr(var_location.GetScalar().ULongLong(), var_sc.module_sp->GetSectionList());
1854 lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1856 if (load_addr != LLDB_INVALID_ADDRESS)
1858 var_location.GetScalar() = load_addr;
1859 var_location.SetValueType(Value::eValueTypeLoadAddress);
1864 *user_type = TypeFromUser(var_clang_type);
1870 ClangExpressionDeclMap::AddOneVariable (NameSearchContext &context, VariableSP var, ValueObjectSP valobj, unsigned int current_id)
1872 assert (m_parser_vars.get());
1874 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1880 if (!GetVariableValue (var, var_location, &ut, &pt))
1883 clang::QualType parser_opaque_type = QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1885 if (parser_opaque_type.isNull())
1888 if (const clang::Type *parser_type = parser_opaque_type.getTypePtr())
1890 if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1891 CompleteType(tag_type->getDecl());
1892 if (const ObjCObjectPointerType *objc_object_ptr_type = dyn_cast<ObjCObjectPointerType>(parser_type))
1893 CompleteType(objc_object_ptr_type->getInterfaceDecl());
1897 bool is_reference = pt.IsReferenceType();
1899 NamedDecl *var_decl = NULL;
1901 var_decl = context.AddVarDecl(pt);
1903 var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1905 std::string decl_name(context.m_decl_name.getAsString());
1906 ConstString entity_name(decl_name.c_str());
1907 ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1908 m_found_entities.AddNewlyConstructedVariable(entity);
1911 entity->EnableParserVars(GetParserID());
1912 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
1913 parser_vars->m_parser_type = pt;
1914 parser_vars->m_named_decl = var_decl;
1915 parser_vars->m_llvm_value = NULL;
1916 parser_vars->m_lldb_value = var_location;
1917 parser_vars->m_lldb_var = var;
1920 entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1924 ASTDumper orig_dumper(ut.GetOpaqueQualType());
1925 ASTDumper ast_dumper(var_decl);
1926 log->Printf(" CEDM::FEVD[%u] Found variable %s, returned %s (original %s)", current_id, decl_name.c_str(), ast_dumper.GetCString(), orig_dumper.GetCString());
1931 ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1932 ExpressionVariableSP &pvar_sp,
1933 unsigned int current_id)
1935 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1937 TypeFromUser user_type (llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1939 TypeFromParser parser_type (GuardedCopyType(user_type));
1941 if (!parser_type.GetOpaqueQualType())
1944 log->Printf(" CEDM::FEVD[%u] Couldn't import type for pvar %s", current_id, pvar_sp->GetName().GetCString());
1948 NamedDecl *var_decl = context.AddVarDecl(parser_type.GetLValueReferenceType());
1950 llvm::cast<ClangExpressionVariable>(pvar_sp.get())->EnableParserVars(GetParserID());
1951 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetParserVars(GetParserID());
1952 parser_vars->m_parser_type = parser_type;
1953 parser_vars->m_named_decl = var_decl;
1954 parser_vars->m_llvm_value = NULL;
1955 parser_vars->m_lldb_value.Clear();
1959 ASTDumper ast_dumper(var_decl);
1960 log->Printf(" CEDM::FEVD[%u] Added pvar %s, returned %s", current_id, pvar_sp->GetName().GetCString(), ast_dumper.GetCString());
1965 ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1966 const Symbol &symbol,
1967 unsigned int current_id)
1969 assert(m_parser_vars.get());
1971 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1973 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1978 ASTContext *scratch_ast_context = target->GetScratchClangASTContext()->getASTContext();
1980 TypeFromUser user_type (ClangASTContext::GetBasicType(scratch_ast_context, eBasicTypeVoid).GetPointerType().GetLValueReferenceType());
1981 TypeFromParser parser_type (ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid).GetPointerType().GetLValueReferenceType());
1982 NamedDecl *var_decl = context.AddVarDecl(parser_type);
1984 std::string decl_name(context.m_decl_name.getAsString());
1985 ConstString entity_name(decl_name.c_str());
1986 ClangExpressionVariable *entity(new ClangExpressionVariable(m_parser_vars->m_exe_ctx.GetBestExecutionContextScope (),
1989 m_parser_vars->m_target_info.byte_order,
1990 m_parser_vars->m_target_info.address_byte_size));
1991 m_found_entities.AddNewlyConstructedVariable(entity);
1993 entity->EnableParserVars(GetParserID());
1994 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
1996 const Address symbol_address = symbol.GetAddress();
1997 lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1999 //parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
2000 parser_vars->m_lldb_value.SetCompilerType(user_type);
2001 parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
2002 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
2004 parser_vars->m_parser_type = parser_type;
2005 parser_vars->m_named_decl = var_decl;
2006 parser_vars->m_llvm_value = NULL;
2007 parser_vars->m_lldb_sym = &symbol;
2011 ASTDumper ast_dumper(var_decl);
2013 log->Printf(" CEDM::FEVD[%u] Found variable %s, returned %s", current_id, decl_name.c_str(), ast_dumper.GetCString());
2018 ClangExpressionDeclMap::ResolveUnknownTypes()
2020 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2021 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
2023 ClangASTContext *scratch_ast_context = target->GetScratchClangASTContext();
2025 for (size_t index = 0, num_entities = m_found_entities.GetSize();
2026 index < num_entities;
2029 ExpressionVariableSP entity = m_found_entities.GetVariableAtIndex(index);
2031 ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(entity.get())->GetParserVars(GetParserID());
2033 if (entity->m_flags & ClangExpressionVariable::EVUnknownType)
2035 const NamedDecl *named_decl = parser_vars->m_named_decl;
2036 const VarDecl *var_decl = dyn_cast<VarDecl>(named_decl);
2041 log->Printf("Entity of unknown type does not have a VarDecl");
2047 ASTDumper ast_dumper(const_cast<VarDecl*>(var_decl));
2048 log->Printf("Variable of unknown type now has Decl %s", ast_dumper.GetCString());
2051 QualType var_type = var_decl->getType();
2052 TypeFromParser parser_type(var_type.getAsOpaquePtr(), ClangASTContext::GetASTContext(&var_decl->getASTContext()));
2054 lldb::opaque_compiler_type_t copied_type = m_ast_importer_sp->CopyType(scratch_ast_context->getASTContext(), &var_decl->getASTContext(), var_type.getAsOpaquePtr());
2059 log->Printf("ClangExpressionDeclMap::ResolveUnknownType - Couldn't import the type for a variable");
2061 return (bool) lldb::ExpressionVariableSP();
2064 TypeFromUser user_type(copied_type, scratch_ast_context);
2066 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
2067 parser_vars->m_lldb_value.SetCompilerType(user_type);
2068 parser_vars->m_parser_type = parser_type;
2070 entity->SetCompilerType(user_type);
2072 entity->m_flags &= ~(ClangExpressionVariable::EVUnknownType);
2080 ClangExpressionDeclMap::AddOneRegister (NameSearchContext &context,
2081 const RegisterInfo *reg_info,
2082 unsigned int current_id)
2084 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2086 CompilerType clang_type = ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (m_ast_context,
2088 reg_info->byte_size * 8);
2093 log->Printf(" Tried to add a type for %s, but couldn't get one", context.m_decl_name.getAsString().c_str());
2097 TypeFromParser parser_clang_type (clang_type);
2099 NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
2101 ClangExpressionVariable *entity(new ClangExpressionVariable(m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
2102 m_parser_vars->m_target_info.byte_order,
2103 m_parser_vars->m_target_info.address_byte_size));
2104 m_found_entities.AddNewlyConstructedVariable(entity);
2106 std::string decl_name(context.m_decl_name.getAsString());
2107 entity->SetName (ConstString (decl_name.c_str()));
2108 entity->SetRegisterInfo (reg_info);
2109 entity->EnableParserVars(GetParserID());
2110 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
2111 parser_vars->m_parser_type = parser_clang_type;
2112 parser_vars->m_named_decl = var_decl;
2113 parser_vars->m_llvm_value = NULL;
2114 parser_vars->m_lldb_value.Clear();
2115 entity->m_flags |= ClangExpressionVariable::EVBareRegister;
2119 ASTDumper ast_dumper(var_decl);
2120 log->Printf(" CEDM::FEVD[%d] Added register %s, returned %s", current_id, context.m_decl_name.getAsString().c_str(), ast_dumper.GetCString());
2125 ClangExpressionDeclMap::AddOneFunction (NameSearchContext &context,
2128 unsigned int current_id)
2130 assert (m_parser_vars.get());
2132 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2134 NamedDecl *function_decl = NULL;
2135 Address fun_address;
2136 CompilerType function_clang_type;
2138 bool is_indirect_function = false;
2142 Type *function_type = function->GetType();
2147 log->PutCString(" Skipped a function because it has no type");
2151 function_clang_type = function_type->GetFullCompilerType ();
2153 if (!function_clang_type)
2156 log->PutCString(" Skipped a function because it has no Clang type");
2160 fun_address = function->GetAddressRange().GetBaseAddress();
2162 CompilerType copied_function_type = GuardedCopyType(function_clang_type);
2163 if (copied_function_type)
2165 function_decl = context.AddFunDecl(copied_function_type);
2171 log->Printf (" Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}",
2172 function_type->GetName().GetCString(),
2173 function_type->GetID());
2181 // We failed to copy the type we found
2184 log->Printf (" Failed to import the function type '%s' {0x%8.8" PRIx64 "} into the expression parser AST contenxt",
2185 function_type->GetName().GetCString(),
2186 function_type->GetID());
2194 fun_address = symbol->GetAddress();
2195 function_decl = context.AddGenericFunDecl();
2196 is_indirect_function = symbol->IsIndirect();
2201 log->PutCString(" AddOneFunction called with no function and no symbol");
2205 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
2207 lldb::addr_t load_addr = fun_address.GetCallableLoadAddress(target, is_indirect_function);
2209 ClangExpressionVariable *entity(new ClangExpressionVariable (m_parser_vars->m_exe_ctx.GetBestExecutionContextScope (),
2210 m_parser_vars->m_target_info.byte_order,
2211 m_parser_vars->m_target_info.address_byte_size));
2212 m_found_entities.AddNewlyConstructedVariable(entity);
2214 std::string decl_name(context.m_decl_name.getAsString());
2215 entity->SetName(ConstString(decl_name.c_str()));
2216 entity->SetCompilerType (function_clang_type);
2217 entity->EnableParserVars(GetParserID());
2219 ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
2221 if (load_addr != LLDB_INVALID_ADDRESS)
2223 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
2224 parser_vars->m_lldb_value.GetScalar() = load_addr;
2228 // We have to try finding a file address.
2230 lldb::addr_t file_addr = fun_address.GetFileAddress();
2232 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress);
2233 parser_vars->m_lldb_value.GetScalar() = file_addr;
2237 parser_vars->m_named_decl = function_decl;
2238 parser_vars->m_llvm_value = NULL;
2242 ASTDumper ast_dumper(function_decl);
2246 fun_address.Dump(&ss, m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), Address::DumpStyleResolvedDescription);
2248 log->Printf(" CEDM::FEVD[%u] Found %s function %s (description %s), returned %s",
2250 (function ? "specific" : "generic"),
2253 ast_dumper.GetCString());
2258 ClangExpressionDeclMap::AddThisType(NameSearchContext &context,
2260 unsigned int current_id)
2262 CompilerType copied_clang_type = GuardedCopyType(ut);
2264 if (!copied_clang_type)
2266 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2269 log->Printf("ClangExpressionDeclMap::AddThisType - Couldn't import the type");
2274 if (copied_clang_type.IsAggregateType() && copied_clang_type.GetCompleteType ())
2276 CompilerType void_clang_type = ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid);
2277 CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
2279 CompilerType method_type = ClangASTContext::CreateFunctionType (m_ast_context,
2281 &void_ptr_clang_type,
2284 copied_clang_type.GetTypeQualifiers());
2286 const bool is_virtual = false;
2287 const bool is_static = false;
2288 const bool is_inline = false;
2289 const bool is_explicit = false;
2290 const bool is_attr_used = true;
2291 const bool is_artificial = false;
2293 ClangASTContext::GetASTContext(m_ast_context)->
2294 AddMethodToCXXRecordType (copied_clang_type.GetOpaqueQualType(),
2297 lldb::eAccessPublic,
2306 if (!copied_clang_type.IsValid())
2309 TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
2311 if (!type_source_info)
2314 // Construct a typedef type because if "*this" is a templated type we can't just return ClassTemplateSpecializationDecls in response to name queries.
2315 // Using a typedef makes this much more robust.
2317 TypedefDecl *typedef_decl = TypedefDecl::Create(*m_ast_context,
2318 m_ast_context->getTranslationUnitDecl(),
2321 context.m_decl_name.getAsIdentifierInfo(),
2328 context.AddNamedDecl(typedef_decl);
2334 ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
2336 unsigned int current_id)
2338 CompilerType copied_clang_type = GuardedCopyType(ut);
2340 if (!copied_clang_type)
2342 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2345 log->Printf("ClangExpressionDeclMap::AddOneType - Couldn't import the type");
2350 context.AddTypeDecl(copied_clang_type);