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