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