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