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