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