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