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