1 //===-- ClangExpressionDeclMap.cpp -----------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ClangExpressionDeclMap.h"
10 
11 #include "ClangASTSource.h"
12 #include "ClangModulesDeclVendor.h"
13 #include "ClangPersistentVariables.h"
14 
15 #include "lldb/Core/Address.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/ValueObjectConstResult.h"
19 #include "lldb/Core/ValueObjectVariable.h"
20 #include "lldb/Expression/Materializer.h"
21 #include "lldb/Symbol/ClangASTContext.h"
22 #include "lldb/Symbol/ClangUtil.h"
23 #include "lldb/Symbol/CompileUnit.h"
24 #include "lldb/Symbol/CompilerDecl.h"
25 #include "lldb/Symbol/CompilerDeclContext.h"
26 #include "lldb/Symbol/Function.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/SymbolFile.h"
30 #include "lldb/Symbol/SymbolVendor.h"
31 #include "lldb/Symbol/Type.h"
32 #include "lldb/Symbol/TypeList.h"
33 #include "lldb/Symbol/Variable.h"
34 #include "lldb/Symbol/VariableList.h"
35 #include "lldb/Target/ExecutionContext.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/RegisterContext.h"
38 #include "lldb/Target/StackFrame.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Utility/Endian.h"
42 #include "lldb/Utility/Log.h"
43 #include "lldb/Utility/RegisterValue.h"
44 #include "lldb/Utility/Status.h"
45 #include "lldb/lldb-private.h"
46 #include "clang/AST/ASTConsumer.h"
47 #include "clang/AST/ASTContext.h"
48 #include "clang/AST/ASTImporter.h"
49 #include "clang/AST/Decl.h"
50 #include "clang/AST/DeclarationName.h"
51 #include "clang/AST/RecursiveASTVisitor.h"
52 
53 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
54 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"
55 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
56 
57 using namespace lldb;
58 using namespace lldb_private;
59 using namespace clang;
60 
61 namespace {
62 const char *g_lldb_local_vars_namespace_cstr = "$__lldb_local_vars";
63 } // anonymous namespace
64 
65 ClangExpressionDeclMap::ClangExpressionDeclMap(
66     bool keep_result_in_memory,
67     Materializer::PersistentVariableDelegate *result_delegate,
68     const lldb::TargetSP &target, const lldb::ClangASTImporterSP &importer,
69     ValueObject *ctx_obj)
70     : ClangASTSource(target, importer), m_found_entities(), m_struct_members(),
71       m_keep_result_in_memory(keep_result_in_memory),
72       m_result_delegate(result_delegate), m_ctx_obj(ctx_obj), m_parser_vars(),
73       m_struct_vars() {
74   EnableStructVars();
75 }
76 
77 ClangExpressionDeclMap::~ClangExpressionDeclMap() {
78   // Note: The model is now that the parser's AST context and all associated
79   //   data does not vanish until the expression has been executed.  This means
80   //   that valuable lookup data (like namespaces) doesn't vanish, but
81 
82   DidParse();
83   DisableStructVars();
84 }
85 
86 bool ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx,
87                                        Materializer *materializer) {
88   EnableParserVars();
89   m_parser_vars->m_exe_ctx = exe_ctx;
90 
91   Target *target = exe_ctx.GetTargetPtr();
92   if (exe_ctx.GetFramePtr())
93     m_parser_vars->m_sym_ctx =
94         exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
95   else if (exe_ctx.GetThreadPtr() &&
96            exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0))
97     m_parser_vars->m_sym_ctx =
98         exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(
99             lldb::eSymbolContextEverything);
100   else if (exe_ctx.GetProcessPtr()) {
101     m_parser_vars->m_sym_ctx.Clear(true);
102     m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
103   } else if (target) {
104     m_parser_vars->m_sym_ctx.Clear(true);
105     m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
106   }
107 
108   if (target) {
109     m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>(
110         target->GetPersistentExpressionStateForLanguage(eLanguageTypeC));
111 
112     if (!ClangASTContext::GetScratch(*target))
113       return false;
114   }
115 
116   m_parser_vars->m_target_info = GetTargetInfo();
117   m_parser_vars->m_materializer = materializer;
118 
119   return true;
120 }
121 
122 void ClangExpressionDeclMap::InstallCodeGenerator(
123     clang::ASTConsumer *code_gen) {
124   assert(m_parser_vars);
125   m_parser_vars->m_code_gen = code_gen;
126 }
127 
128 void ClangExpressionDeclMap::DidParse() {
129   if (m_parser_vars) {
130     for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
131          entity_index < num_entities; ++entity_index) {
132       ExpressionVariableSP var_sp(
133           m_found_entities.GetVariableAtIndex(entity_index));
134       if (var_sp)
135         llvm::cast<ClangExpressionVariable>(var_sp.get())
136             ->DisableParserVars(GetParserID());
137     }
138 
139     for (size_t pvar_index = 0,
140                 num_pvars = m_parser_vars->m_persistent_vars->GetSize();
141          pvar_index < num_pvars; ++pvar_index) {
142       ExpressionVariableSP pvar_sp(
143           m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
144       if (ClangExpressionVariable *clang_var =
145               llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get()))
146         clang_var->DisableParserVars(GetParserID());
147     }
148 
149     DisableParserVars();
150   }
151 }
152 
153 // Interface for IRForTarget
154 
155 ClangExpressionDeclMap::TargetInfo ClangExpressionDeclMap::GetTargetInfo() {
156   assert(m_parser_vars.get());
157 
158   TargetInfo ret;
159 
160   ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
161 
162   Process *process = exe_ctx.GetProcessPtr();
163   if (process) {
164     ret.byte_order = process->GetByteOrder();
165     ret.address_byte_size = process->GetAddressByteSize();
166   } else {
167     Target *target = exe_ctx.GetTargetPtr();
168     if (target) {
169       ret.byte_order = target->GetArchitecture().GetByteOrder();
170       ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
171     }
172   }
173 
174   return ret;
175 }
176 
177 TypeFromUser ClangExpressionDeclMap::DeportType(ClangASTContext &target,
178                                                 ClangASTContext &source,
179                                                 TypeFromParser parser_type) {
180   assert(&target == ClangASTContext::GetScratch(*m_target));
181   assert((TypeSystem *)&source == parser_type.GetTypeSystem());
182   assert(source.getASTContext() == m_ast_context);
183 
184   if (m_ast_importer_sp) {
185     return TypeFromUser(m_ast_importer_sp->DeportType(target, parser_type));
186   } else {
187     lldbassert(0 && "No mechanism for deporting a type!");
188     return TypeFromUser();
189   }
190 }
191 
192 bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl,
193                                                    ConstString name,
194                                                    TypeFromParser parser_type,
195                                                    bool is_result,
196                                                    bool is_lvalue) {
197   assert(m_parser_vars.get());
198 
199   ClangASTContext *ast =
200       llvm::dyn_cast_or_null<ClangASTContext>(parser_type.GetTypeSystem());
201   if (ast == nullptr)
202     return false;
203 
204   if (m_parser_vars->m_materializer && is_result) {
205     Status err;
206 
207     ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
208     Target *target = exe_ctx.GetTargetPtr();
209     if (target == nullptr)
210       return false;
211 
212     auto *clang_ast_context = ClangASTContext::GetScratch(*target);
213     if (!clang_ast_context)
214       return false;
215 
216     TypeFromUser user_type = DeportType(*clang_ast_context, *ast, parser_type);
217 
218     uint32_t offset = m_parser_vars->m_materializer->AddResultVariable(
219         user_type, is_lvalue, m_keep_result_in_memory, m_result_delegate, err);
220 
221     ClangExpressionVariable *var = new ClangExpressionVariable(
222         exe_ctx.GetBestExecutionContextScope(), name, user_type,
223         m_parser_vars->m_target_info.byte_order,
224         m_parser_vars->m_target_info.address_byte_size);
225 
226     m_found_entities.AddNewlyConstructedVariable(var);
227 
228     var->EnableParserVars(GetParserID());
229 
230     ClangExpressionVariable::ParserVars *parser_vars =
231         var->GetParserVars(GetParserID());
232 
233     parser_vars->m_named_decl = decl;
234     parser_vars->m_parser_type = parser_type;
235 
236     var->EnableJITVars(GetParserID());
237 
238     ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID());
239 
240     jit_vars->m_offset = offset;
241 
242     return true;
243   }
244 
245   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
246   ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
247   Target *target = exe_ctx.GetTargetPtr();
248   if (target == nullptr)
249     return false;
250 
251   ClangASTContext *context = ClangASTContext::GetScratch(*target);
252   if (!context)
253     return false;
254 
255   TypeFromUser user_type = DeportType(*context, *ast, parser_type);
256 
257   if (!user_type.GetOpaqueQualType()) {
258     LLDB_LOGF(log, "Persistent variable's type wasn't copied successfully");
259     return false;
260   }
261 
262   if (!m_parser_vars->m_target_info.IsValid())
263     return false;
264 
265   ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>(
266       m_parser_vars->m_persistent_vars
267           ->CreatePersistentVariable(
268               exe_ctx.GetBestExecutionContextScope(), name, user_type,
269               m_parser_vars->m_target_info.byte_order,
270               m_parser_vars->m_target_info.address_byte_size)
271           .get());
272 
273   if (!var)
274     return false;
275 
276   var->m_frozen_sp->SetHasCompleteType();
277 
278   if (is_result)
279     var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
280   else
281     var->m_flags |=
282         ClangExpressionVariable::EVKeepInTarget; // explicitly-declared
283                                                  // persistent variables should
284                                                  // persist
285 
286   if (is_lvalue) {
287     var->m_flags |= ClangExpressionVariable::EVIsProgramReference;
288   } else {
289     var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
290     var->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
291   }
292 
293   if (m_keep_result_in_memory) {
294     var->m_flags |= ClangExpressionVariable::EVKeepInTarget;
295   }
296 
297   LLDB_LOGF(log, "Created persistent variable with flags 0x%hx", var->m_flags);
298 
299   var->EnableParserVars(GetParserID());
300 
301   ClangExpressionVariable::ParserVars *parser_vars =
302       var->GetParserVars(GetParserID());
303 
304   parser_vars->m_named_decl = decl;
305   parser_vars->m_parser_type = parser_type;
306 
307   return true;
308 }
309 
310 bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl,
311                                               ConstString name,
312                                               llvm::Value *value, size_t size,
313                                               lldb::offset_t alignment) {
314   assert(m_struct_vars.get());
315   assert(m_parser_vars.get());
316 
317   bool is_persistent_variable = false;
318 
319   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
320 
321   m_struct_vars->m_struct_laid_out = false;
322 
323   if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl,
324                                                   GetParserID()))
325     return true;
326 
327   ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList(
328       m_found_entities, decl, GetParserID()));
329 
330   if (!var) {
331     var = ClangExpressionVariable::FindVariableInList(
332         *m_parser_vars->m_persistent_vars, decl, GetParserID());
333     is_persistent_variable = true;
334   }
335 
336   if (!var)
337     return false;
338 
339   LLDB_LOGF(log, "Adding value for (NamedDecl*)%p [%s - %s] to the structure",
340             static_cast<const void *>(decl), name.GetCString(),
341             var->GetName().GetCString());
342 
343   // We know entity->m_parser_vars is valid because we used a parser variable
344   // to find it
345 
346   ClangExpressionVariable::ParserVars *parser_vars =
347       llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID());
348 
349   parser_vars->m_llvm_value = value;
350 
351   if (ClangExpressionVariable::JITVars *jit_vars =
352           llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID())) {
353     // We already laid this out; do not touch
354 
355     LLDB_LOGF(log, "Already placed at 0x%llx",
356               (unsigned long long)jit_vars->m_offset);
357   }
358 
359   llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID());
360 
361   ClangExpressionVariable::JITVars *jit_vars =
362       llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID());
363 
364   jit_vars->m_alignment = alignment;
365   jit_vars->m_size = size;
366 
367   m_struct_members.AddVariable(var->shared_from_this());
368 
369   if (m_parser_vars->m_materializer) {
370     uint32_t offset = 0;
371 
372     Status err;
373 
374     if (is_persistent_variable) {
375       ExpressionVariableSP var_sp(var->shared_from_this());
376       offset = m_parser_vars->m_materializer->AddPersistentVariable(
377           var_sp, nullptr, err);
378     } else {
379       if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym)
380         offset = m_parser_vars->m_materializer->AddSymbol(*sym, err);
381       else if (const RegisterInfo *reg_info = var->GetRegisterInfo())
382         offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err);
383       else if (parser_vars->m_lldb_var)
384         offset = m_parser_vars->m_materializer->AddVariable(
385             parser_vars->m_lldb_var, err);
386     }
387 
388     if (!err.Success())
389       return false;
390 
391     LLDB_LOGF(log, "Placed at 0x%llx", (unsigned long long)offset);
392 
393     jit_vars->m_offset =
394         offset; // TODO DoStructLayout() should not change this.
395   }
396 
397   return true;
398 }
399 
400 bool ClangExpressionDeclMap::DoStructLayout() {
401   assert(m_struct_vars.get());
402 
403   if (m_struct_vars->m_struct_laid_out)
404     return true;
405 
406   if (!m_parser_vars->m_materializer)
407     return false;
408 
409   m_struct_vars->m_struct_alignment =
410       m_parser_vars->m_materializer->GetStructAlignment();
411   m_struct_vars->m_struct_size =
412       m_parser_vars->m_materializer->GetStructByteSize();
413   m_struct_vars->m_struct_laid_out = true;
414   return true;
415 }
416 
417 bool ClangExpressionDeclMap::GetStructInfo(uint32_t &num_elements, size_t &size,
418                                            lldb::offset_t &alignment) {
419   assert(m_struct_vars.get());
420 
421   if (!m_struct_vars->m_struct_laid_out)
422     return false;
423 
424   num_elements = m_struct_members.GetSize();
425   size = m_struct_vars->m_struct_size;
426   alignment = m_struct_vars->m_struct_alignment;
427 
428   return true;
429 }
430 
431 bool ClangExpressionDeclMap::GetStructElement(const NamedDecl *&decl,
432                                               llvm::Value *&value,
433                                               lldb::offset_t &offset,
434                                               ConstString &name,
435                                               uint32_t index) {
436   assert(m_struct_vars.get());
437 
438   if (!m_struct_vars->m_struct_laid_out)
439     return false;
440 
441   if (index >= m_struct_members.GetSize())
442     return false;
443 
444   ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
445 
446   if (!member_sp)
447     return false;
448 
449   ClangExpressionVariable::ParserVars *parser_vars =
450       llvm::cast<ClangExpressionVariable>(member_sp.get())
451           ->GetParserVars(GetParserID());
452   ClangExpressionVariable::JITVars *jit_vars =
453       llvm::cast<ClangExpressionVariable>(member_sp.get())
454           ->GetJITVars(GetParserID());
455 
456   if (!parser_vars || !jit_vars || !member_sp->GetValueObject())
457     return false;
458 
459   decl = parser_vars->m_named_decl;
460   value = parser_vars->m_llvm_value;
461   offset = jit_vars->m_offset;
462   name = member_sp->GetName();
463 
464   return true;
465 }
466 
467 bool ClangExpressionDeclMap::GetFunctionInfo(const NamedDecl *decl,
468                                              uint64_t &ptr) {
469   ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList(
470       m_found_entities, decl, GetParserID()));
471 
472   if (!entity)
473     return false;
474 
475   // We know m_parser_vars is valid since we searched for the variable by its
476   // NamedDecl
477 
478   ClangExpressionVariable::ParserVars *parser_vars =
479       entity->GetParserVars(GetParserID());
480 
481   ptr = parser_vars->m_lldb_value.GetScalar().ULongLong();
482 
483   return true;
484 }
485 
486 addr_t ClangExpressionDeclMap::GetSymbolAddress(Target &target,
487                                                 Process *process,
488                                                 ConstString name,
489                                                 lldb::SymbolType symbol_type,
490                                                 lldb_private::Module *module) {
491   SymbolContextList sc_list;
492 
493   if (module)
494     module->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
495   else
496     target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list);
497 
498   const uint32_t num_matches = sc_list.GetSize();
499   addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
500 
501   for (uint32_t i = 0;
502        i < num_matches &&
503        (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS);
504        i++) {
505     SymbolContext sym_ctx;
506     sc_list.GetContextAtIndex(i, sym_ctx);
507 
508     const Address sym_address = sym_ctx.symbol->GetAddress();
509 
510     if (!sym_address.IsValid())
511       continue;
512 
513     switch (sym_ctx.symbol->GetType()) {
514     case eSymbolTypeCode:
515     case eSymbolTypeTrampoline:
516       symbol_load_addr = sym_address.GetCallableLoadAddress(&target);
517       break;
518 
519     case eSymbolTypeResolver:
520       symbol_load_addr = sym_address.GetCallableLoadAddress(&target, true);
521       break;
522 
523     case eSymbolTypeReExported: {
524       ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName();
525       if (reexport_name) {
526         ModuleSP reexport_module_sp;
527         ModuleSpec reexport_module_spec;
528         reexport_module_spec.GetPlatformFileSpec() =
529             sym_ctx.symbol->GetReExportedSymbolSharedLibrary();
530         if (reexport_module_spec.GetPlatformFileSpec()) {
531           reexport_module_sp =
532               target.GetImages().FindFirstModule(reexport_module_spec);
533           if (!reexport_module_sp) {
534             reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
535             reexport_module_sp =
536                 target.GetImages().FindFirstModule(reexport_module_spec);
537           }
538         }
539         symbol_load_addr = GetSymbolAddress(
540             target, process, sym_ctx.symbol->GetReExportedSymbolName(),
541             symbol_type, reexport_module_sp.get());
542       }
543     } break;
544 
545     case eSymbolTypeData:
546     case eSymbolTypeRuntime:
547     case eSymbolTypeVariable:
548     case eSymbolTypeLocal:
549     case eSymbolTypeParam:
550     case eSymbolTypeInvalid:
551     case eSymbolTypeAbsolute:
552     case eSymbolTypeException:
553     case eSymbolTypeSourceFile:
554     case eSymbolTypeHeaderFile:
555     case eSymbolTypeObjectFile:
556     case eSymbolTypeCommonBlock:
557     case eSymbolTypeBlock:
558     case eSymbolTypeVariableType:
559     case eSymbolTypeLineEntry:
560     case eSymbolTypeLineHeader:
561     case eSymbolTypeScopeBegin:
562     case eSymbolTypeScopeEnd:
563     case eSymbolTypeAdditional:
564     case eSymbolTypeCompiler:
565     case eSymbolTypeInstrumentation:
566     case eSymbolTypeUndefined:
567     case eSymbolTypeObjCClass:
568     case eSymbolTypeObjCMetaClass:
569     case eSymbolTypeObjCIVar:
570       symbol_load_addr = sym_address.GetLoadAddress(&target);
571       break;
572     }
573   }
574 
575   if (symbol_load_addr == LLDB_INVALID_ADDRESS && process) {
576     ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process);
577 
578     if (runtime) {
579       symbol_load_addr = runtime->LookupRuntimeSymbol(name);
580     }
581   }
582 
583   return symbol_load_addr;
584 }
585 
586 addr_t ClangExpressionDeclMap::GetSymbolAddress(ConstString name,
587                                                 lldb::SymbolType symbol_type) {
588   assert(m_parser_vars.get());
589 
590   if (!m_parser_vars->m_exe_ctx.GetTargetPtr())
591     return false;
592 
593   return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(),
594                           m_parser_vars->m_exe_ctx.GetProcessPtr(), name,
595                           symbol_type);
596 }
597 
598 lldb::VariableSP ClangExpressionDeclMap::FindGlobalVariable(
599     Target &target, ModuleSP &module, ConstString name,
600     CompilerDeclContext *namespace_decl, TypeFromUser *type) {
601   VariableList vars;
602 
603   if (module && namespace_decl)
604     module->FindGlobalVariables(name, namespace_decl, -1, vars);
605   else
606     target.GetImages().FindGlobalVariables(name, -1, vars);
607 
608   if (vars.GetSize()) {
609     if (type) {
610       for (VariableSP var_sp : vars) {
611         if (ClangASTContext::AreTypesSame(
612                 *type, var_sp->GetType()->GetFullCompilerType()))
613           return var_sp;
614       }
615     } else {
616       return vars.GetVariableAtIndex(0);
617     }
618   }
619 
620   return VariableSP();
621 }
622 
623 ClangASTContext *ClangExpressionDeclMap::GetClangASTContext() {
624   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
625   if (frame == nullptr)
626     return nullptr;
627 
628   SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
629                                                   lldb::eSymbolContextBlock);
630   if (sym_ctx.block == nullptr)
631     return nullptr;
632 
633   CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
634   if (!frame_decl_context)
635     return nullptr;
636 
637   return llvm::dyn_cast_or_null<ClangASTContext>(
638       frame_decl_context.GetTypeSystem());
639 }
640 
641 // Interface for ClangASTSource
642 
643 void ClangExpressionDeclMap::FindExternalVisibleDecls(
644     NameSearchContext &context) {
645   assert(m_ast_context);
646 
647   const ConstString name(context.m_decl_name.getAsString().c_str());
648 
649   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
650 
651   if (GetImportInProgress()) {
652     if (log && log->GetVerbose())
653       LLDB_LOGF(log, "Ignoring a query during an import");
654     return;
655   }
656 
657   static unsigned int invocation_id = 0;
658   unsigned int current_id = invocation_id++;
659 
660   if (log) {
661     if (!context.m_decl_context)
662       LLDB_LOGF(log,
663                 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
664                 "'%s' in a NULL DeclContext",
665                 current_id, name.GetCString());
666     else if (const NamedDecl *context_named_decl =
667                  dyn_cast<NamedDecl>(context.m_decl_context))
668       LLDB_LOGF(log,
669                 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
670                 "'%s' in '%s'",
671                 current_id, name.GetCString(),
672                 context_named_decl->getNameAsString().c_str());
673     else
674       LLDB_LOGF(log,
675                 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
676                 "'%s' in a '%s'",
677                 current_id, name.GetCString(),
678                 context.m_decl_context->getDeclKindName());
679   }
680 
681   if (const NamespaceDecl *namespace_context =
682           dyn_cast<NamespaceDecl>(context.m_decl_context)) {
683     if (namespace_context->getName().str() ==
684         std::string(g_lldb_local_vars_namespace_cstr)) {
685       CompilerDeclContext compiler_decl_ctx(
686           GetClangASTContext(), const_cast<void *>(static_cast<const void *>(
687                                     context.m_decl_context)));
688       FindExternalVisibleDecls(context, lldb::ModuleSP(), compiler_decl_ctx,
689                                current_id);
690       return;
691     }
692 
693     ClangASTImporter::NamespaceMapSP namespace_map =
694         m_ast_importer_sp
695             ? m_ast_importer_sp->GetNamespaceMap(namespace_context)
696             : ClangASTImporter::NamespaceMapSP();
697 
698     if (!namespace_map)
699       return;
700 
701     if (log && log->GetVerbose())
702       log->Printf("  CEDM::FEVD[%u] Inspecting (NamespaceMap*)%p (%d entries)",
703                   current_id, static_cast<void *>(namespace_map.get()),
704                   (int)namespace_map->size());
705 
706     for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
707                                                   e = namespace_map->end();
708          i != e; ++i) {
709       if (log)
710         log->Printf("  CEDM::FEVD[%u] Searching namespace %s in module %s",
711                     current_id, i->second.GetName().AsCString(),
712                     i->first->GetFileSpec().GetFilename().GetCString());
713 
714       FindExternalVisibleDecls(context, i->first, i->second, current_id);
715     }
716   } else if (isa<TranslationUnitDecl>(context.m_decl_context)) {
717     CompilerDeclContext namespace_decl;
718 
719     if (log)
720       log->Printf("  CEDM::FEVD[%u] Searching the root namespace", current_id);
721 
722     FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
723                              current_id);
724   }
725 
726   ClangASTSource::FindExternalVisibleDecls(context);
727 }
728 
729 void ClangExpressionDeclMap::MaybeRegisterFunctionBody(
730     FunctionDecl *copied_function_decl) {
731   if (copied_function_decl->getBody() && m_parser_vars->m_code_gen) {
732     clang::DeclGroupRef decl_group_ref(copied_function_decl);
733     m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
734   }
735 }
736 
737 clang::NamedDecl *ClangExpressionDeclMap::GetPersistentDecl(ConstString name) {
738   if (!m_parser_vars)
739     return nullptr;
740   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
741   if (!target)
742     return nullptr;
743 
744   ClangASTContext *scratch_clang_ast_context =
745       ClangASTContext::GetScratch(*target);
746 
747   if (!scratch_clang_ast_context)
748     return nullptr;
749 
750   ASTContext *scratch_ast_context = scratch_clang_ast_context->getASTContext();
751 
752   if (!scratch_ast_context)
753     return nullptr;
754 
755   return m_parser_vars->m_persistent_vars->GetPersistentDecl(name);
756 }
757 
758 void ClangExpressionDeclMap::SearchPersistenDecls(NameSearchContext &context,
759                                                   const ConstString name,
760                                                   unsigned int current_id) {
761   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
762 
763   NamedDecl *persistent_decl = GetPersistentDecl(name);
764 
765   if (!persistent_decl)
766     return;
767 
768   Decl *parser_persistent_decl = CopyDecl(persistent_decl);
769 
770   if (!parser_persistent_decl)
771     return;
772 
773   NamedDecl *parser_named_decl = dyn_cast<NamedDecl>(parser_persistent_decl);
774 
775   if (!parser_named_decl)
776     return;
777 
778   if (clang::FunctionDecl *parser_function_decl =
779           llvm::dyn_cast<clang::FunctionDecl>(parser_named_decl)) {
780     MaybeRegisterFunctionBody(parser_function_decl);
781   }
782 
783   LLDB_LOGF(log, "  CEDM::FEVD[%u] Found persistent decl %s", current_id,
784             name.GetCString());
785 
786   context.AddNamedDecl(parser_named_decl);
787 }
788 
789 void ClangExpressionDeclMap::LookUpLldbClass(NameSearchContext &context,
790                                              unsigned int current_id) {
791   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
792 
793   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
794   SymbolContext sym_ctx;
795   if (frame != nullptr)
796     sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
797                                       lldb::eSymbolContextBlock);
798 
799   if (m_ctx_obj) {
800     Status status;
801     lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status);
802     if (!ctx_obj_ptr || status.Fail())
803       return;
804 
805     AddThisType(context, TypeFromUser(m_ctx_obj->GetCompilerType()),
806                 current_id);
807 
808     m_struct_vars->m_object_pointer_type =
809         TypeFromUser(ctx_obj_ptr->GetCompilerType());
810 
811     return;
812   }
813 
814   // Clang is looking for the type of "this"
815 
816   if (frame == nullptr)
817     return;
818 
819   // Find the block that defines the function represented by "sym_ctx"
820   Block *function_block = sym_ctx.GetFunctionBlock();
821 
822   if (!function_block)
823     return;
824 
825   CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
826 
827   if (!function_decl_ctx)
828     return;
829 
830   clang::CXXMethodDecl *method_decl =
831       ClangASTContext::DeclContextGetAsCXXMethodDecl(function_decl_ctx);
832 
833   if (method_decl) {
834     clang::CXXRecordDecl *class_decl = method_decl->getParent();
835 
836     QualType class_qual_type(class_decl->getTypeForDecl(), 0);
837 
838     TypeFromUser class_user_type(
839         class_qual_type.getAsOpaquePtr(),
840         ClangASTContext::GetASTContext(&class_decl->getASTContext()));
841 
842     LLDB_LOG(log, "  CEDM::FEVD[{0}] Adding type for $__lldb_class: {1}",
843              current_id, class_qual_type.getAsString());
844 
845     AddThisType(context, class_user_type, current_id);
846 
847     if (method_decl->isInstance()) {
848       // self is a pointer to the object
849 
850       QualType class_pointer_type =
851           method_decl->getASTContext().getPointerType(class_qual_type);
852 
853       TypeFromUser self_user_type(
854           class_pointer_type.getAsOpaquePtr(),
855           ClangASTContext::GetASTContext(&method_decl->getASTContext()));
856 
857       m_struct_vars->m_object_pointer_type = self_user_type;
858     }
859     return;
860   }
861 
862   // This branch will get hit if we are executing code in the context of
863   // a function that claims to have an object pointer (through
864   // DW_AT_object_pointer?) but is not formally a method of the class.
865   // In that case, just look up the "this" variable in the current scope
866   // and use its type.
867   // FIXME: This code is formally correct, but clang doesn't currently
868   // emit DW_AT_object_pointer
869   // for C++ so it hasn't actually been tested.
870 
871   VariableList *vars = frame->GetVariableList(false);
872 
873   lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
874 
875   if (this_var && this_var->IsInScope(frame) &&
876       this_var->LocationIsValidForFrame(frame)) {
877     Type *this_type = this_var->GetType();
878 
879     if (!this_type)
880       return;
881 
882     TypeFromUser pointee_type =
883         this_type->GetForwardCompilerType().GetPointeeType();
884 
885     LLDB_LOG(log, "  FEVD[{0}] Adding type for $__lldb_class: {1}", current_id,
886              ClangUtil::GetQualType(pointee_type).getAsString());
887 
888     AddThisType(context, pointee_type, current_id);
889     TypeFromUser this_user_type(this_type->GetFullCompilerType());
890     m_struct_vars->m_object_pointer_type = this_user_type;
891   }
892 }
893 
894 void ClangExpressionDeclMap::LookUpLldbObjCClass(NameSearchContext &context,
895                                                  unsigned int current_id) {
896   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
897 
898   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
899 
900   if (m_ctx_obj) {
901     Status status;
902     lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status);
903     if (!ctx_obj_ptr || status.Fail())
904       return;
905 
906     AddOneType(context, TypeFromUser(m_ctx_obj->GetCompilerType()), current_id);
907 
908     m_struct_vars->m_object_pointer_type =
909         TypeFromUser(ctx_obj_ptr->GetCompilerType());
910 
911     return;
912   }
913 
914   // Clang is looking for the type of "*self"
915 
916   if (!frame)
917     return;
918 
919   SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
920                                                   lldb::eSymbolContextBlock);
921 
922   // Find the block that defines the function represented by "sym_ctx"
923   Block *function_block = sym_ctx.GetFunctionBlock();
924 
925   if (!function_block)
926     return;
927 
928   CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
929 
930   if (!function_decl_ctx)
931     return;
932 
933   clang::ObjCMethodDecl *method_decl =
934       ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
935 
936   if (method_decl) {
937     ObjCInterfaceDecl *self_interface = method_decl->getClassInterface();
938 
939     if (!self_interface)
940       return;
941 
942     const clang::Type *interface_type = self_interface->getTypeForDecl();
943 
944     if (!interface_type)
945       return; // This is unlikely, but we have seen crashes where this
946               // occurred
947 
948     TypeFromUser class_user_type(
949         QualType(interface_type, 0).getAsOpaquePtr(),
950         ClangASTContext::GetASTContext(&method_decl->getASTContext()));
951 
952     LLDB_LOG(log, "  FEVD[{0}] Adding type for $__lldb_objc_class: {1}",
953              current_id, ClangUtil::ToString(interface_type));
954 
955     AddOneType(context, class_user_type, current_id);
956 
957     if (method_decl->isInstanceMethod()) {
958       // self is a pointer to the object
959 
960       QualType class_pointer_type =
961           method_decl->getASTContext().getObjCObjectPointerType(
962               QualType(interface_type, 0));
963 
964       TypeFromUser self_user_type(
965           class_pointer_type.getAsOpaquePtr(),
966           ClangASTContext::GetASTContext(&method_decl->getASTContext()));
967 
968       m_struct_vars->m_object_pointer_type = self_user_type;
969     } else {
970       // self is a Class pointer
971       QualType class_type = method_decl->getASTContext().getObjCClassType();
972 
973       TypeFromUser self_user_type(
974           class_type.getAsOpaquePtr(),
975           ClangASTContext::GetASTContext(&method_decl->getASTContext()));
976 
977       m_struct_vars->m_object_pointer_type = self_user_type;
978     }
979 
980     return;
981   }
982   // This branch will get hit if we are executing code in the context of
983   // a function that claims to have an object pointer (through
984   // DW_AT_object_pointer?) but is not formally a method of the class.
985   // In that case, just look up the "self" variable in the current scope
986   // and use its type.
987 
988   VariableList *vars = frame->GetVariableList(false);
989 
990   lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
991 
992   if (!self_var)
993     return;
994   if (!self_var->IsInScope(frame))
995     return;
996   if (!self_var->LocationIsValidForFrame(frame))
997     return;
998 
999   Type *self_type = self_var->GetType();
1000 
1001   if (!self_type)
1002     return;
1003 
1004   CompilerType self_clang_type = self_type->GetFullCompilerType();
1005 
1006   if (ClangASTContext::IsObjCClassType(self_clang_type)) {
1007     return;
1008   }
1009   if (!ClangASTContext::IsObjCObjectPointerType(self_clang_type))
1010     return;
1011   self_clang_type = self_clang_type.GetPointeeType();
1012 
1013   if (!self_clang_type)
1014     return;
1015 
1016   LLDB_LOG(log, "  FEVD[{0}] Adding type for $__lldb_objc_class: {1}",
1017            current_id, ClangUtil::ToString(self_type->GetFullCompilerType()));
1018 
1019   TypeFromUser class_user_type(self_clang_type);
1020 
1021   AddOneType(context, class_user_type, current_id);
1022 
1023   TypeFromUser self_user_type(self_type->GetFullCompilerType());
1024 
1025   m_struct_vars->m_object_pointer_type = self_user_type;
1026 }
1027 
1028 void ClangExpressionDeclMap::LookupLocalVarNamespace(
1029     SymbolContext &sym_ctx, NameSearchContext &name_context) {
1030   if (sym_ctx.block == nullptr)
1031     return;
1032 
1033   CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
1034   if (!frame_decl_context)
1035     return;
1036 
1037   ClangASTContext *frame_ast = llvm::dyn_cast_or_null<ClangASTContext>(
1038       frame_decl_context.GetTypeSystem());
1039   if (!frame_ast)
1040     return;
1041 
1042   clang::NamespaceDecl *namespace_decl =
1043       m_clang_ast_context->GetUniqueNamespaceDeclaration(
1044           g_lldb_local_vars_namespace_cstr, nullptr);
1045   if (!namespace_decl)
1046     return;
1047 
1048   name_context.AddNamedDecl(namespace_decl);
1049   clang::DeclContext *ctxt = clang::Decl::castToDeclContext(namespace_decl);
1050   ctxt->setHasExternalVisibleStorage(true);
1051   name_context.m_found.local_vars_nsp = true;
1052 }
1053 
1054 void ClangExpressionDeclMap::LookupInModulesDeclVendor(
1055     NameSearchContext &context, ConstString name, unsigned current_id) {
1056   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1057 
1058   if (!m_target)
1059     return;
1060 
1061   auto *modules_decl_vendor = m_target->GetClangModulesDeclVendor();
1062   if (!modules_decl_vendor)
1063     return;
1064 
1065   bool append = false;
1066   uint32_t max_matches = 1;
1067   std::vector<clang::NamedDecl *> decls;
1068 
1069   if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
1070     return;
1071 
1072   assert(!decls.empty() && "FindDecls returned true but no decls?");
1073   clang::NamedDecl *const decl_from_modules = decls[0];
1074 
1075   LLDB_LOG(log,
1076            "  CAS::FEVD[{0}] Matching decl found for "
1077            "\"{1}\" in the modules",
1078            current_id, name);
1079 
1080   clang::Decl *copied_decl = CopyDecl(decl_from_modules);
1081   if (!copied_decl) {
1082     LLDB_LOG(log,
1083              "  CAS::FEVD[{0}] - Couldn't export a "
1084              "declaration from the modules",
1085              current_id);
1086     return;
1087   }
1088 
1089   if (auto copied_function = dyn_cast<clang::FunctionDecl>(copied_decl)) {
1090     MaybeRegisterFunctionBody(copied_function);
1091 
1092     context.AddNamedDecl(copied_function);
1093 
1094     context.m_found.function_with_type_info = true;
1095     context.m_found.function = true;
1096   } else if (auto copied_var = dyn_cast<clang::VarDecl>(copied_decl)) {
1097     context.AddNamedDecl(copied_var);
1098     context.m_found.variable = true;
1099   }
1100 }
1101 
1102 bool ClangExpressionDeclMap::LookupLocalVariable(
1103     NameSearchContext &context, ConstString name, unsigned current_id,
1104     SymbolContext &sym_ctx, CompilerDeclContext &namespace_decl) {
1105   if (sym_ctx.block == nullptr)
1106     return false;
1107 
1108   CompilerDeclContext decl_context = sym_ctx.block->GetDeclContext();
1109   if (!decl_context)
1110     return false;
1111 
1112   // Make sure that the variables are parsed so that we have the
1113   // declarations.
1114   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1115   VariableListSP vars = frame->GetInScopeVariableList(true);
1116   for (size_t i = 0; i < vars->GetSize(); i++)
1117     vars->GetVariableAtIndex(i)->GetDecl();
1118 
1119   // Search for declarations matching the name. Do not include imported
1120   // decls in the search if we are looking for decls in the artificial
1121   // namespace $__lldb_local_vars.
1122   std::vector<CompilerDecl> found_decls =
1123       decl_context.FindDeclByName(name, namespace_decl.IsValid());
1124 
1125   VariableSP var;
1126   bool variable_found = false;
1127   for (CompilerDecl decl : found_decls) {
1128     for (size_t vi = 0, ve = vars->GetSize(); vi != ve; ++vi) {
1129       VariableSP candidate_var = vars->GetVariableAtIndex(vi);
1130       if (candidate_var->GetDecl() == decl) {
1131         var = candidate_var;
1132         break;
1133       }
1134     }
1135 
1136     if (var && !variable_found) {
1137       variable_found = true;
1138       ValueObjectSP valobj = ValueObjectVariable::Create(frame, var);
1139       AddOneVariable(context, var, valobj, current_id);
1140       context.m_found.variable = true;
1141     }
1142   }
1143   return variable_found;
1144 }
1145 
1146 /// Structure to hold the info needed when comparing function
1147 /// declarations.
1148 namespace {
1149 struct FuncDeclInfo {
1150   ConstString m_name;
1151   CompilerType m_copied_type;
1152   uint32_t m_decl_lvl;
1153   SymbolContext m_sym_ctx;
1154 };
1155 } // namespace
1156 
1157 SymbolContextList ClangExpressionDeclMap::SearchFunctionsInSymbolContexts(
1158     const SymbolContextList &sc_list,
1159     const CompilerDeclContext &frame_decl_context) {
1160   // First, symplify things by looping through the symbol contexts to
1161   // remove unwanted functions and separate out the functions we want to
1162   // compare and prune into a separate list. Cache the info needed about
1163   // the function declarations in a vector for efficiency.
1164   uint32_t num_indices = sc_list.GetSize();
1165   SymbolContextList sc_sym_list;
1166   std::vector<FuncDeclInfo> decl_infos;
1167   decl_infos.reserve(num_indices);
1168   clang::DeclContext *frame_decl_ctx =
1169       (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1170   ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(
1171       frame_decl_context.GetTypeSystem());
1172 
1173   for (uint32_t index = 0; index < num_indices; ++index) {
1174     FuncDeclInfo fdi;
1175     SymbolContext sym_ctx;
1176     sc_list.GetContextAtIndex(index, sym_ctx);
1177 
1178     // We don't know enough about symbols to compare them, but we should
1179     // keep them in the list.
1180     Function *function = sym_ctx.function;
1181     if (!function) {
1182       sc_sym_list.Append(sym_ctx);
1183       continue;
1184     }
1185     // Filter out functions without declaration contexts, as well as
1186     // class/instance methods, since they'll be skipped in the code that
1187     // follows anyway.
1188     CompilerDeclContext func_decl_context = function->GetDeclContext();
1189     if (!func_decl_context ||
1190         func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1191       continue;
1192     // We can only prune functions for which we can copy the type.
1193     CompilerType func_clang_type = function->GetType()->GetFullCompilerType();
1194     CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1195     if (!copied_func_type) {
1196       sc_sym_list.Append(sym_ctx);
1197       continue;
1198     }
1199 
1200     fdi.m_sym_ctx = sym_ctx;
1201     fdi.m_name = function->GetName();
1202     fdi.m_copied_type = copied_func_type;
1203     fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1204     if (fdi.m_copied_type && func_decl_context) {
1205       // Call CountDeclLevels to get the number of parent scopes we have
1206       // to look through before we find the function declaration. When
1207       // comparing functions of the same type, the one with a lower count
1208       // will be closer to us in the lookup scope and shadows the other.
1209       clang::DeclContext *func_decl_ctx =
1210           (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1211       fdi.m_decl_lvl = ast->CountDeclLevels(frame_decl_ctx, func_decl_ctx,
1212                                             &fdi.m_name, &fdi.m_copied_type);
1213     }
1214     decl_infos.emplace_back(fdi);
1215   }
1216 
1217   // Loop through the functions in our cache looking for matching types,
1218   // then compare their scope levels to see which is closer.
1219   std::multimap<CompilerType, const FuncDeclInfo *> matches;
1220   for (const FuncDeclInfo &fdi : decl_infos) {
1221     const CompilerType t = fdi.m_copied_type;
1222     auto q = matches.find(t);
1223     if (q != matches.end()) {
1224       if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1225         // This function is closer; remove the old set.
1226         matches.erase(t);
1227       else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1228         // The functions in our set are closer - skip this one.
1229         continue;
1230     }
1231     matches.insert(std::make_pair(t, &fdi));
1232   }
1233 
1234   // Loop through our matches and add their symbol contexts to our list.
1235   SymbolContextList sc_func_list;
1236   for (const auto &q : matches)
1237     sc_func_list.Append(q.second->m_sym_ctx);
1238 
1239   // Rejoin the lists with the functions in front.
1240   sc_func_list.Append(sc_sym_list);
1241   return sc_func_list;
1242 }
1243 
1244 void ClangExpressionDeclMap::LookupFunction(NameSearchContext &context,
1245                                             lldb::ModuleSP module_sp,
1246                                             ConstString name,
1247                                             CompilerDeclContext &namespace_decl,
1248                                             unsigned current_id) {
1249   if (!m_parser_vars)
1250     return;
1251 
1252   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1253 
1254   std::vector<clang::NamedDecl *> decls_from_modules;
1255 
1256   if (target) {
1257     if (ClangModulesDeclVendor *decl_vendor =
1258             target->GetClangModulesDeclVendor()) {
1259       decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules);
1260     }
1261   }
1262 
1263   const bool include_inlines = false;
1264   SymbolContextList sc_list;
1265   if (namespace_decl && module_sp) {
1266     const bool include_symbols = false;
1267 
1268     module_sp->FindFunctions(name, &namespace_decl, eFunctionNameTypeBase,
1269                              include_symbols, include_inlines, sc_list);
1270   } else if (target && !namespace_decl) {
1271     const bool include_symbols = true;
1272 
1273     // TODO Fix FindFunctions so that it doesn't return
1274     //   instance methods for eFunctionNameTypeBase.
1275 
1276     target->GetImages().FindFunctions(name, eFunctionNameTypeFull,
1277                                       include_symbols, include_inlines,
1278                                       sc_list);
1279   }
1280 
1281   // If we found more than one function, see if we can use the frame's decl
1282   // context to remove functions that are shadowed by other functions which
1283   // match in type but are nearer in scope.
1284   //
1285   // AddOneFunction will not add a function whose type has already been
1286   // added, so if there's another function in the list with a matching type,
1287   // check to see if their decl context is a parent of the current frame's or
1288   // was imported via a and using statement, and pick the best match
1289   // according to lookup rules.
1290   if (sc_list.GetSize() > 1) {
1291     // Collect some info about our frame's context.
1292     StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1293     SymbolContext frame_sym_ctx;
1294     if (frame != nullptr)
1295       frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1296                                               lldb::eSymbolContextBlock);
1297     CompilerDeclContext frame_decl_context =
1298         frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext()
1299                                        : CompilerDeclContext();
1300 
1301     // We can't do this without a compiler decl context for our frame.
1302     if (frame_decl_context) {
1303       sc_list = SearchFunctionsInSymbolContexts(sc_list, frame_decl_context);
1304     }
1305   }
1306 
1307   if (sc_list.GetSize()) {
1308     Symbol *extern_symbol = nullptr;
1309     Symbol *non_extern_symbol = nullptr;
1310 
1311     for (uint32_t index = 0, num_indices = sc_list.GetSize();
1312          index < num_indices; ++index) {
1313       SymbolContext sym_ctx;
1314       sc_list.GetContextAtIndex(index, sym_ctx);
1315 
1316       if (sym_ctx.function) {
1317         CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1318 
1319         if (!decl_ctx)
1320           continue;
1321 
1322         // Filter out class/instance methods.
1323         if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1324           continue;
1325 
1326         AddOneFunction(context, sym_ctx.function, nullptr, current_id);
1327         context.m_found.function_with_type_info = true;
1328         context.m_found.function = true;
1329       } else if (sym_ctx.symbol) {
1330         if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) {
1331           sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1332           if (sym_ctx.symbol == nullptr)
1333             continue;
1334         }
1335 
1336         if (sym_ctx.symbol->IsExternal())
1337           extern_symbol = sym_ctx.symbol;
1338         else
1339           non_extern_symbol = sym_ctx.symbol;
1340       }
1341     }
1342 
1343     if (!context.m_found.function_with_type_info) {
1344       for (clang::NamedDecl *decl : decls_from_modules) {
1345         if (llvm::isa<clang::FunctionDecl>(decl)) {
1346           clang::NamedDecl *copied_decl =
1347               llvm::cast_or_null<FunctionDecl>(CopyDecl(decl));
1348           if (copied_decl) {
1349             context.AddNamedDecl(copied_decl);
1350             context.m_found.function_with_type_info = true;
1351           }
1352         }
1353       }
1354     }
1355 
1356     if (!context.m_found.function_with_type_info) {
1357       if (extern_symbol) {
1358         AddOneFunction(context, nullptr, extern_symbol, current_id);
1359         context.m_found.function = true;
1360       } else if (non_extern_symbol) {
1361         AddOneFunction(context, nullptr, non_extern_symbol, current_id);
1362         context.m_found.function = true;
1363       }
1364     }
1365   }
1366 }
1367 
1368 void ClangExpressionDeclMap::FindExternalVisibleDecls(
1369     NameSearchContext &context, lldb::ModuleSP module_sp,
1370     CompilerDeclContext &namespace_decl, unsigned int current_id) {
1371   assert(m_ast_context);
1372 
1373   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1374 
1375   const ConstString name(context.m_decl_name.getAsString().c_str());
1376   if (IgnoreName(name, false))
1377     return;
1378 
1379   // Only look for functions by name out in our symbols if the function doesn't
1380   // start with our phony prefix of '$'
1381 
1382   Target *target = nullptr;
1383   StackFrame *frame = nullptr;
1384   SymbolContext sym_ctx;
1385   if (m_parser_vars) {
1386     target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1387     frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1388   }
1389   if (frame != nullptr)
1390     sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1391                                       lldb::eSymbolContextBlock);
1392 
1393   // Try the persistent decls, which take precedence over all else.
1394   if (!namespace_decl)
1395     SearchPersistenDecls(context, name, current_id);
1396 
1397   if (name.GetStringRef().startswith("$") && !namespace_decl) {
1398     if (name == "$__lldb_class") {
1399       LookUpLldbClass(context, current_id);
1400       return;
1401     }
1402 
1403     if (name == "$__lldb_objc_class") {
1404       LookUpLldbObjCClass(context, current_id);
1405       return;
1406     }
1407     if (name == g_lldb_local_vars_namespace_cstr) {
1408       LookupLocalVarNamespace(sym_ctx, context);
1409       return;
1410     }
1411 
1412     // any other $__lldb names should be weeded out now
1413     if (name.GetStringRef().startswith("$__lldb"))
1414       return;
1415 
1416     // No ParserVars means we can't do register or variable lookup.
1417     if (!m_parser_vars)
1418       return;
1419 
1420     ExpressionVariableSP pvar_sp(
1421         m_parser_vars->m_persistent_vars->GetVariable(name));
1422 
1423     if (pvar_sp) {
1424       AddOneVariable(context, pvar_sp, current_id);
1425       return;
1426     }
1427 
1428     assert(name.GetStringRef().startswith("$"));
1429     llvm::StringRef reg_name = name.GetStringRef().substr(1);
1430 
1431     if (m_parser_vars->m_exe_ctx.GetRegisterContext()) {
1432       const RegisterInfo *reg_info(
1433           m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(
1434               reg_name));
1435 
1436       if (reg_info) {
1437         LLDB_LOGF(log, "  CEDM::FEVD[%u] Found register %s", current_id,
1438                   reg_info->name);
1439 
1440         AddOneRegister(context, reg_info, current_id);
1441       }
1442     }
1443     return;
1444   }
1445 
1446   bool local_var_lookup = !namespace_decl || (namespace_decl.GetName() ==
1447                                               g_lldb_local_vars_namespace_cstr);
1448   if (frame && local_var_lookup)
1449     if (LookupLocalVariable(context, name, current_id, sym_ctx, namespace_decl))
1450       return;
1451 
1452   if (target) {
1453     ValueObjectSP valobj;
1454     VariableSP var;
1455     var =
1456         FindGlobalVariable(*target, module_sp, name, &namespace_decl, nullptr);
1457 
1458     if (var) {
1459       valobj = ValueObjectVariable::Create(target, var);
1460       AddOneVariable(context, var, valobj, current_id);
1461       context.m_found.variable = true;
1462       return;
1463     }
1464   }
1465 
1466   LookupFunction(context, module_sp, name, namespace_decl, current_id);
1467 
1468   // Try the modules next.
1469   if (!context.m_found.function_with_type_info)
1470     LookupInModulesDeclVendor(context, name, current_id);
1471 
1472   if (target && !context.m_found.variable && !namespace_decl) {
1473     // We couldn't find a non-symbol variable for this.  Now we'll hunt for a
1474     // generic data symbol, and -- if it is found -- treat it as a variable.
1475     Status error;
1476 
1477     const Symbol *data_symbol =
1478         m_parser_vars->m_sym_ctx.FindBestGlobalDataSymbol(name, error);
1479 
1480     if (!error.Success()) {
1481       const unsigned diag_id =
1482           m_ast_context->getDiagnostics().getCustomDiagID(
1483               clang::DiagnosticsEngine::Level::Error, "%0");
1484       m_ast_context->getDiagnostics().Report(diag_id) << error.AsCString();
1485     }
1486 
1487     if (data_symbol) {
1488       std::string warning("got name from symbols: ");
1489       warning.append(name.AsCString());
1490       const unsigned diag_id =
1491           m_ast_context->getDiagnostics().getCustomDiagID(
1492               clang::DiagnosticsEngine::Level::Warning, "%0");
1493       m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1494       AddOneGenericVariable(context, *data_symbol, current_id);
1495       context.m_found.variable = true;
1496     }
1497   }
1498 }
1499 
1500 bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var,
1501                                               lldb_private::Value &var_location,
1502                                               TypeFromUser *user_type,
1503                                               TypeFromParser *parser_type) {
1504   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1505 
1506   Type *var_type = var->GetType();
1507 
1508   if (!var_type) {
1509     if (log)
1510       log->PutCString("Skipped a definition because it has no type");
1511     return false;
1512   }
1513 
1514   CompilerType var_clang_type = var_type->GetFullCompilerType();
1515 
1516   if (!var_clang_type) {
1517     if (log)
1518       log->PutCString("Skipped a definition because it has no Clang type");
1519     return false;
1520   }
1521 
1522   ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(
1523       var_type->GetForwardCompilerType().GetTypeSystem());
1524 
1525   if (!clang_ast) {
1526     if (log)
1527       log->PutCString("Skipped a definition because it has no Clang AST");
1528     return false;
1529   }
1530 
1531   ASTContext *ast = clang_ast->getASTContext();
1532 
1533   if (!ast) {
1534     if (log)
1535       log->PutCString(
1536           "There is no AST context for the current execution context");
1537     return false;
1538   }
1539 
1540   DWARFExpression &var_location_expr = var->LocationExpression();
1541 
1542   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1543   Status err;
1544 
1545   if (var->GetLocationIsConstantValueData()) {
1546     DataExtractor const_value_extractor;
1547 
1548     if (var_location_expr.GetExpressionData(const_value_extractor)) {
1549       var_location = Value(const_value_extractor.GetDataStart(),
1550                            const_value_extractor.GetByteSize());
1551       var_location.SetValueType(Value::eValueTypeHostAddress);
1552     } else {
1553       LLDB_LOGF(log, "Error evaluating constant variable: %s", err.AsCString());
1554       return false;
1555     }
1556   }
1557 
1558   CompilerType type_to_use = GuardedCopyType(var_clang_type);
1559 
1560   if (!type_to_use) {
1561     LLDB_LOGF(log,
1562               "Couldn't copy a variable's type into the parser's AST context");
1563 
1564     return false;
1565   }
1566 
1567   if (parser_type)
1568     *parser_type = TypeFromParser(type_to_use);
1569 
1570   if (var_location.GetContextType() == Value::eContextTypeInvalid)
1571     var_location.SetCompilerType(type_to_use);
1572 
1573   if (var_location.GetValueType() == Value::eValueTypeFileAddress) {
1574     SymbolContext var_sc;
1575     var->CalculateSymbolContext(&var_sc);
1576 
1577     if (!var_sc.module_sp)
1578       return false;
1579 
1580     Address so_addr(var_location.GetScalar().ULongLong(),
1581                     var_sc.module_sp->GetSectionList());
1582 
1583     lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1584 
1585     if (load_addr != LLDB_INVALID_ADDRESS) {
1586       var_location.GetScalar() = load_addr;
1587       var_location.SetValueType(Value::eValueTypeLoadAddress);
1588     }
1589   }
1590 
1591   if (user_type)
1592     *user_type = TypeFromUser(var_clang_type);
1593 
1594   return true;
1595 }
1596 
1597 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1598                                             VariableSP var,
1599                                             ValueObjectSP valobj,
1600                                             unsigned int current_id) {
1601   assert(m_parser_vars.get());
1602 
1603   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1604 
1605   TypeFromUser ut;
1606   TypeFromParser pt;
1607   Value var_location;
1608 
1609   if (!GetVariableValue(var, var_location, &ut, &pt))
1610     return;
1611 
1612   clang::QualType parser_opaque_type =
1613       QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1614 
1615   if (parser_opaque_type.isNull())
1616     return;
1617 
1618   if (const clang::Type *parser_type = parser_opaque_type.getTypePtr()) {
1619     if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1620       CompleteType(tag_type->getDecl());
1621     if (const ObjCObjectPointerType *objc_object_ptr_type =
1622             dyn_cast<ObjCObjectPointerType>(parser_type))
1623       CompleteType(objc_object_ptr_type->getInterfaceDecl());
1624   }
1625 
1626   bool is_reference = pt.IsReferenceType();
1627 
1628   NamedDecl *var_decl = nullptr;
1629   if (is_reference)
1630     var_decl = context.AddVarDecl(pt);
1631   else
1632     var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1633 
1634   std::string decl_name(context.m_decl_name.getAsString());
1635   ConstString entity_name(decl_name.c_str());
1636   ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1637   m_found_entities.AddNewlyConstructedVariable(entity);
1638 
1639   assert(entity);
1640   entity->EnableParserVars(GetParserID());
1641   ClangExpressionVariable::ParserVars *parser_vars =
1642       entity->GetParserVars(GetParserID());
1643   parser_vars->m_parser_type = pt;
1644   parser_vars->m_named_decl = var_decl;
1645   parser_vars->m_llvm_value = nullptr;
1646   parser_vars->m_lldb_value = var_location;
1647   parser_vars->m_lldb_var = var;
1648 
1649   if (is_reference)
1650     entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1651 
1652   LLDB_LOG(log,
1653            "  CEDM::FEVD[{0}] Found variable {1}, returned\n{2} (original {3})",
1654            current_id, decl_name, ClangUtil::DumpDecl(var_decl),
1655            ClangUtil::ToString(ut));
1656 }
1657 
1658 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1659                                             ExpressionVariableSP &pvar_sp,
1660                                             unsigned int current_id) {
1661   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1662 
1663   TypeFromUser user_type(
1664       llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1665 
1666   TypeFromParser parser_type(GuardedCopyType(user_type));
1667 
1668   if (!parser_type.GetOpaqueQualType()) {
1669     LLDB_LOGF(log, "  CEDM::FEVD[%u] Couldn't import type for pvar %s",
1670               current_id, pvar_sp->GetName().GetCString());
1671     return;
1672   }
1673 
1674   NamedDecl *var_decl =
1675       context.AddVarDecl(parser_type.GetLValueReferenceType());
1676 
1677   llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1678       ->EnableParserVars(GetParserID());
1679   ClangExpressionVariable::ParserVars *parser_vars =
1680       llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1681           ->GetParserVars(GetParserID());
1682   parser_vars->m_parser_type = parser_type;
1683   parser_vars->m_named_decl = var_decl;
1684   parser_vars->m_llvm_value = nullptr;
1685   parser_vars->m_lldb_value.Clear();
1686 
1687   LLDB_LOG(log, "  CEDM::FEVD[{0}] Added pvar {1}, returned\n{2}", current_id,
1688            pvar_sp->GetName(), ClangUtil::DumpDecl(var_decl));
1689 }
1690 
1691 void ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1692                                                    const Symbol &symbol,
1693                                                    unsigned int current_id) {
1694   assert(m_parser_vars.get());
1695 
1696   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1697 
1698   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1699 
1700   if (target == nullptr)
1701     return;
1702 
1703   ClangASTContext *scratch_ast_context = ClangASTContext::GetScratch(*target);
1704   if (!scratch_ast_context)
1705     return;
1706 
1707   TypeFromUser user_type(scratch_ast_context->GetBasicType(eBasicTypeVoid)
1708                              .GetPointerType()
1709                              .GetLValueReferenceType());
1710   TypeFromParser parser_type(m_clang_ast_context->GetBasicType(eBasicTypeVoid)
1711                                  .GetPointerType()
1712                                  .GetLValueReferenceType());
1713   NamedDecl *var_decl = context.AddVarDecl(parser_type);
1714 
1715   std::string decl_name(context.m_decl_name.getAsString());
1716   ConstString entity_name(decl_name.c_str());
1717   ClangExpressionVariable *entity(new ClangExpressionVariable(
1718       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), entity_name,
1719       user_type, m_parser_vars->m_target_info.byte_order,
1720       m_parser_vars->m_target_info.address_byte_size));
1721   m_found_entities.AddNewlyConstructedVariable(entity);
1722 
1723   entity->EnableParserVars(GetParserID());
1724   ClangExpressionVariable::ParserVars *parser_vars =
1725       entity->GetParserVars(GetParserID());
1726 
1727   const Address symbol_address = symbol.GetAddress();
1728   lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1729 
1730   // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType,
1731   // user_type.GetOpaqueQualType());
1732   parser_vars->m_lldb_value.SetCompilerType(user_type);
1733   parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
1734   parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
1735 
1736   parser_vars->m_parser_type = parser_type;
1737   parser_vars->m_named_decl = var_decl;
1738   parser_vars->m_llvm_value = nullptr;
1739   parser_vars->m_lldb_sym = &symbol;
1740 
1741   LLDB_LOG(log, "  CEDM::FEVD[{0}] Found variable {1}, returned\n{2}",
1742            current_id, decl_name, ClangUtil::DumpDecl(var_decl));
1743 }
1744 
1745 void ClangExpressionDeclMap::AddOneRegister(NameSearchContext &context,
1746                                             const RegisterInfo *reg_info,
1747                                             unsigned int current_id) {
1748   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1749 
1750   CompilerType clang_type =
1751       m_clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1752           reg_info->encoding, reg_info->byte_size * 8);
1753 
1754   if (!clang_type) {
1755     LLDB_LOGF(log, "  Tried to add a type for %s, but couldn't get one",
1756               context.m_decl_name.getAsString().c_str());
1757     return;
1758   }
1759 
1760   TypeFromParser parser_clang_type(clang_type);
1761 
1762   NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
1763 
1764   ClangExpressionVariable *entity(new ClangExpressionVariable(
1765       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1766       m_parser_vars->m_target_info.byte_order,
1767       m_parser_vars->m_target_info.address_byte_size));
1768   m_found_entities.AddNewlyConstructedVariable(entity);
1769 
1770   std::string decl_name(context.m_decl_name.getAsString());
1771   entity->SetName(ConstString(decl_name.c_str()));
1772   entity->SetRegisterInfo(reg_info);
1773   entity->EnableParserVars(GetParserID());
1774   ClangExpressionVariable::ParserVars *parser_vars =
1775       entity->GetParserVars(GetParserID());
1776   parser_vars->m_parser_type = parser_clang_type;
1777   parser_vars->m_named_decl = var_decl;
1778   parser_vars->m_llvm_value = nullptr;
1779   parser_vars->m_lldb_value.Clear();
1780   entity->m_flags |= ClangExpressionVariable::EVBareRegister;
1781 
1782   LLDB_LOG(log, "  CEDM::FEVD[{0}] Added register {1}, returned\n{2}",
1783            current_id, context.m_decl_name.getAsString(),
1784            ClangUtil::DumpDecl(var_decl));
1785 }
1786 
1787 void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context,
1788                                             Function *function, Symbol *symbol,
1789                                             unsigned int current_id) {
1790   assert(m_parser_vars.get());
1791 
1792   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1793 
1794   NamedDecl *function_decl = nullptr;
1795   Address fun_address;
1796   CompilerType function_clang_type;
1797 
1798   bool is_indirect_function = false;
1799 
1800   if (function) {
1801     Type *function_type = function->GetType();
1802 
1803     const auto lang = function->GetCompileUnit()->GetLanguage();
1804     const auto name = function->GetMangled().GetMangledName().AsCString();
1805     const bool extern_c = (Language::LanguageIsC(lang) &&
1806                            !CPlusPlusLanguage::IsCPPMangledName(name)) ||
1807                           (Language::LanguageIsObjC(lang) &&
1808                            !Language::LanguageIsCPlusPlus(lang));
1809 
1810     if (!extern_c) {
1811       TypeSystem *type_system = function->GetDeclContext().GetTypeSystem();
1812       if (llvm::isa<ClangASTContext>(type_system)) {
1813         clang::DeclContext *src_decl_context =
1814             (clang::DeclContext *)function->GetDeclContext()
1815                 .GetOpaqueDeclContext();
1816         clang::FunctionDecl *src_function_decl =
1817             llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context);
1818         if (src_function_decl &&
1819             src_function_decl->getTemplateSpecializationInfo()) {
1820           clang::FunctionTemplateDecl *function_template =
1821               src_function_decl->getTemplateSpecializationInfo()->getTemplate();
1822           clang::FunctionTemplateDecl *copied_function_template =
1823               llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(
1824                   CopyDecl(function_template));
1825           if (copied_function_template) {
1826             if (log) {
1827               StreamString ss;
1828 
1829               function->DumpSymbolContext(&ss);
1830 
1831               LLDB_LOG(log,
1832                        "  CEDM::FEVD[{0}] Imported decl for function template"
1833                        " {1} (description {2}), returned\n{3}",
1834                        current_id, copied_function_template->getNameAsString(),
1835                        ss.GetData(),
1836                        ClangUtil::DumpDecl(copied_function_template));
1837             }
1838 
1839             context.AddNamedDecl(copied_function_template);
1840           }
1841         } else if (src_function_decl) {
1842           if (clang::FunctionDecl *copied_function_decl =
1843                   llvm::dyn_cast_or_null<clang::FunctionDecl>(
1844                       CopyDecl(src_function_decl))) {
1845             if (log) {
1846               StreamString ss;
1847 
1848               function->DumpSymbolContext(&ss);
1849 
1850               LLDB_LOG(log,
1851                        "  CEDM::FEVD[{0}]] Imported decl for function {1} "
1852                        "(description {2}), returned\n{3}",
1853                        current_id, copied_function_decl->getNameAsString(),
1854                        ss.GetData(), ClangUtil::DumpDecl(copied_function_decl));
1855             }
1856 
1857             context.AddNamedDecl(copied_function_decl);
1858             return;
1859           } else {
1860             if (log) {
1861               LLDB_LOGF(log, "  Failed to import the function decl for '%s'",
1862                         src_function_decl->getName().str().c_str());
1863             }
1864           }
1865         }
1866       }
1867     }
1868 
1869     if (!function_type) {
1870       if (log)
1871         log->PutCString("  Skipped a function because it has no type");
1872       return;
1873     }
1874 
1875     function_clang_type = function_type->GetFullCompilerType();
1876 
1877     if (!function_clang_type) {
1878       if (log)
1879         log->PutCString("  Skipped a function because it has no Clang type");
1880       return;
1881     }
1882 
1883     fun_address = function->GetAddressRange().GetBaseAddress();
1884 
1885     CompilerType copied_function_type = GuardedCopyType(function_clang_type);
1886     if (copied_function_type) {
1887       function_decl = context.AddFunDecl(copied_function_type, extern_c);
1888 
1889       if (!function_decl) {
1890         if (log) {
1891           LLDB_LOGF(
1892               log,
1893               "  Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}",
1894               function_type->GetName().GetCString(), function_type->GetID());
1895         }
1896 
1897         return;
1898       }
1899     } else {
1900       // We failed to copy the type we found
1901       if (log) {
1902         LLDB_LOGF(log,
1903                   "  Failed to import the function type '%s' {0x%8.8" PRIx64
1904                   "} into the expression parser AST contenxt",
1905                   function_type->GetName().GetCString(),
1906                   function_type->GetID());
1907       }
1908 
1909       return;
1910     }
1911   } else if (symbol) {
1912     fun_address = symbol->GetAddress();
1913     function_decl = context.AddGenericFunDecl();
1914     is_indirect_function = symbol->IsIndirect();
1915   } else {
1916     if (log)
1917       log->PutCString("  AddOneFunction called with no function and no symbol");
1918     return;
1919   }
1920 
1921   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1922 
1923   lldb::addr_t load_addr =
1924       fun_address.GetCallableLoadAddress(target, is_indirect_function);
1925 
1926   ClangExpressionVariable *entity(new ClangExpressionVariable(
1927       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1928       m_parser_vars->m_target_info.byte_order,
1929       m_parser_vars->m_target_info.address_byte_size));
1930   m_found_entities.AddNewlyConstructedVariable(entity);
1931 
1932   std::string decl_name(context.m_decl_name.getAsString());
1933   entity->SetName(ConstString(decl_name.c_str()));
1934   entity->SetCompilerType(function_clang_type);
1935   entity->EnableParserVars(GetParserID());
1936 
1937   ClangExpressionVariable::ParserVars *parser_vars =
1938       entity->GetParserVars(GetParserID());
1939 
1940   if (load_addr != LLDB_INVALID_ADDRESS) {
1941     parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
1942     parser_vars->m_lldb_value.GetScalar() = load_addr;
1943   } else {
1944     // We have to try finding a file address.
1945 
1946     lldb::addr_t file_addr = fun_address.GetFileAddress();
1947 
1948     parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress);
1949     parser_vars->m_lldb_value.GetScalar() = file_addr;
1950   }
1951 
1952   parser_vars->m_named_decl = function_decl;
1953   parser_vars->m_llvm_value = nullptr;
1954 
1955   if (log) {
1956     StreamString ss;
1957 
1958     fun_address.Dump(&ss,
1959                      m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1960                      Address::DumpStyleResolvedDescription);
1961 
1962     LLDB_LOG(log,
1963              "  CEDM::FEVD[{0}] Found {1} function {2} (description {3}), "
1964              "returned\n{4}",
1965              current_id, (function ? "specific" : "generic"), decl_name,
1966              ss.GetData(), ClangUtil::DumpDecl(function_decl));
1967   }
1968 }
1969 
1970 void ClangExpressionDeclMap::AddThisType(NameSearchContext &context,
1971                                          const TypeFromUser &ut,
1972                                          unsigned int current_id) {
1973   CompilerType copied_clang_type = GuardedCopyType(ut);
1974 
1975   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1976 
1977   if (!copied_clang_type) {
1978     if (log)
1979       LLDB_LOGF(
1980           log,
1981           "ClangExpressionDeclMap::AddThisType - Couldn't import the type");
1982 
1983     return;
1984   }
1985 
1986   if (copied_clang_type.IsAggregateType() &&
1987       copied_clang_type.GetCompleteType()) {
1988     CompilerType void_clang_type =
1989         m_clang_ast_context->GetBasicType(eBasicTypeVoid);
1990     CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
1991 
1992     CompilerType method_type = ClangASTContext::CreateFunctionType(
1993         m_ast_context, void_clang_type, &void_ptr_clang_type, 1, false, 0);
1994 
1995     const bool is_virtual = false;
1996     const bool is_static = false;
1997     const bool is_inline = false;
1998     const bool is_explicit = false;
1999     const bool is_attr_used = true;
2000     const bool is_artificial = false;
2001 
2002     CXXMethodDecl *method_decl = m_clang_ast_context->AddMethodToCXXRecordType(
2003         copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", nullptr,
2004         method_type, lldb::eAccessPublic, is_virtual, is_static, is_inline,
2005         is_explicit, is_attr_used, is_artificial);
2006 
2007     LLDB_LOG(log,
2008              "  CEDM::AddThisType Added function $__lldb_expr "
2009              "(description {0}) for this type\n{1}",
2010              ClangUtil::ToString(copied_clang_type),
2011              ClangUtil::DumpDecl(method_decl));
2012   }
2013 
2014   if (!copied_clang_type.IsValid())
2015     return;
2016 
2017   TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(
2018       QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
2019 
2020   if (!type_source_info)
2021     return;
2022 
2023   // Construct a typedef type because if "*this" is a templated type we can't
2024   // just return ClassTemplateSpecializationDecls in response to name queries.
2025   // Using a typedef makes this much more robust.
2026 
2027   TypedefDecl *typedef_decl = TypedefDecl::Create(
2028       *m_ast_context, m_ast_context->getTranslationUnitDecl(), SourceLocation(),
2029       SourceLocation(), context.m_decl_name.getAsIdentifierInfo(),
2030       type_source_info);
2031 
2032   if (!typedef_decl)
2033     return;
2034 
2035   context.AddNamedDecl(typedef_decl);
2036 
2037   return;
2038 }
2039 
2040 void ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
2041                                         const TypeFromUser &ut,
2042                                         unsigned int current_id) {
2043   CompilerType copied_clang_type = GuardedCopyType(ut);
2044 
2045   if (!copied_clang_type) {
2046     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2047 
2048     if (log)
2049       LLDB_LOGF(
2050           log, "ClangExpressionDeclMap::AddOneType - Couldn't import the type");
2051 
2052     return;
2053   }
2054 
2055   context.AddTypeDecl(copied_clang_type);
2056 }
2057