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