]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp
Vendor import of stripped lldb trunk r256633:
[FreeBSD/FreeBSD.git] / source / Plugins / ExpressionParser / Clang / ClangExpressionDeclMap.cpp
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 we found more than one function, see if we can use the
1428             // frame's decl context to remove functions that are shadowed
1429             // by other functions which match in type but are nearer in scope.
1430             //
1431             // AddOneFunction will not add a function whose type has already been
1432             // added, so if there's another function in the list with a matching
1433             // type, check to see if their decl context is a parent of the current
1434             // frame's or was imported via a and using statement, and pick the
1435             // best match according to lookup rules.
1436             if (sc_list.GetSize() > 1)
1437             {
1438                 // Collect some info about our frame's context.
1439                 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1440                 SymbolContext frame_sym_ctx;
1441                 if (frame != nullptr)
1442                     frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction|lldb::eSymbolContextBlock);
1443                 CompilerDeclContext frame_decl_context = frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext() : CompilerDeclContext();
1444
1445                 // We can't do this without a compiler decl context for our frame.
1446                 if (frame_decl_context)
1447                 {
1448                     clang::DeclContext *frame_decl_ctx = (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1449                     ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(frame_decl_context.GetTypeSystem());
1450
1451                     // Structure to hold the info needed when comparing function
1452                     // declarations.
1453                     struct FuncDeclInfo
1454                     {
1455                         ConstString m_name;
1456                         CompilerType m_copied_type;
1457                         uint32_t m_decl_lvl;
1458                         SymbolContext m_sym_ctx;
1459                     };
1460
1461                     // First, symplify things by looping through the symbol contexts
1462                     // to remove unwanted functions and separate out the functions we
1463                     // want to compare and prune into a separate list.
1464                     // Cache the info needed about the function declarations in a
1465                     // vector for efficiency.
1466                     SymbolContextList sc_sym_list;
1467                     uint32_t num_indices = sc_list.GetSize();
1468                     std::vector<FuncDeclInfo> fdi_cache;
1469                     fdi_cache.reserve(num_indices);
1470                     for (uint32_t index = 0; index < num_indices; ++index)
1471                     {
1472                         FuncDeclInfo fdi;
1473                         SymbolContext sym_ctx;
1474                         sc_list.GetContextAtIndex(index, sym_ctx);
1475
1476                         // We don't know enough about symbols to compare them,
1477                         // but we should keep them in the list.
1478                         Function *function = sym_ctx.function;
1479                         if (!function)
1480                         {
1481                             sc_sym_list.Append(sym_ctx);
1482                             continue;
1483                         }
1484                         // Filter out functions without declaration contexts, as well as
1485                         // class/instance methods, since they'll be skipped in the
1486                         // code that follows anyway.
1487                         CompilerDeclContext func_decl_context = function->GetDeclContext();
1488                         if (!func_decl_context || func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1489                             continue;
1490                         // We can only prune functions for which we can copy the type.
1491                         CompilerType func_clang_type = function->GetType()->GetFullCompilerType();
1492                         CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1493                         if (!copied_func_type)
1494                         {
1495                             sc_sym_list.Append(sym_ctx);
1496                             continue;
1497                         }
1498
1499                         fdi.m_sym_ctx = sym_ctx;
1500                         fdi.m_name = function->GetName();
1501                         fdi.m_copied_type = copied_func_type;
1502                         fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1503                         if (fdi.m_copied_type && func_decl_context)
1504                         {
1505                             // Call CountDeclLevels to get the number of parent scopes we
1506                             // have to look through before we find the function declaration.
1507                             // When comparing functions of the same type, the one with a
1508                             // lower count will be closer to us in the lookup scope and
1509                             // shadows the other.
1510                             clang::DeclContext *func_decl_ctx = (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1511                             fdi.m_decl_lvl = ast->CountDeclLevels(frame_decl_ctx,
1512                                                                   func_decl_ctx,
1513                                                                   &fdi.m_name,
1514                                                                   &fdi.m_copied_type);
1515                         }
1516                         fdi_cache.emplace_back(fdi);
1517                     }
1518
1519                     // Loop through the functions in our cache looking for matching types,
1520                     // then compare their scope levels to see which is closer.
1521                     std::multimap<CompilerType, const FuncDeclInfo*> matches;
1522                     for (const FuncDeclInfo &fdi : fdi_cache)
1523                     {
1524                         const CompilerType t = fdi.m_copied_type;
1525                         auto q = matches.find(t);
1526                         if (q != matches.end())
1527                         {
1528                             if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1529                                 // This function is closer; remove the old set.
1530                                 matches.erase(t);
1531                             else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1532                                 // The functions in our set are closer - skip this one.
1533                                 continue;
1534                         }
1535                         matches.insert(std::make_pair(t, &fdi));
1536                     }
1537
1538                     // Loop through our matches and add their symbol contexts to our list.
1539                     SymbolContextList sc_func_list;
1540                     for (const auto &q : matches)
1541                         sc_func_list.Append(q.second->m_sym_ctx);
1542
1543                     // Rejoin the lists with the functions in front.
1544                     sc_list = sc_func_list;
1545                     sc_list.Append(sc_sym_list);
1546                 }
1547             }
1548
1549             if (sc_list.GetSize())
1550             {
1551                 Symbol *extern_symbol = NULL;
1552                 Symbol *non_extern_symbol = NULL;
1553
1554                 for (uint32_t index = 0, num_indices = sc_list.GetSize();
1555                      index < num_indices;
1556                      ++index)
1557                 {
1558                     SymbolContext sym_ctx;
1559                     sc_list.GetContextAtIndex(index, sym_ctx);
1560
1561                     if (sym_ctx.function)
1562                     {
1563                         CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1564
1565                         if (!decl_ctx)
1566                             continue;
1567
1568                         // Filter out class/instance methods.
1569                         if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1570                             continue;
1571
1572                         AddOneFunction(context, sym_ctx.function, NULL, current_id);
1573                         context.m_found.function_with_type_info = true;
1574                         context.m_found.function = true;
1575                     }
1576                     else if (sym_ctx.symbol)
1577                     {
1578                         if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target)
1579                         {
1580                             sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1581                             if (sym_ctx.symbol == NULL)
1582                                 continue;
1583                         }
1584
1585                         if (sym_ctx.symbol->IsExternal())
1586                             extern_symbol = sym_ctx.symbol;
1587                         else
1588                             non_extern_symbol = sym_ctx.symbol;
1589                     }
1590                 }
1591                 
1592                 if (!context.m_found.function_with_type_info)
1593                 {
1594                     for (clang::NamedDecl *decl : decls_from_modules)
1595                     {
1596                         if (llvm::isa<clang::FunctionDecl>(decl))
1597                         {
1598                             clang::NamedDecl *copied_decl = llvm::cast<FunctionDecl>(m_ast_importer_sp->CopyDecl(m_ast_context, &decl->getASTContext(), decl));
1599                             context.AddNamedDecl(copied_decl);
1600                             context.m_found.function_with_type_info = true;
1601                         }
1602                     }
1603                 }
1604
1605                 if (!context.m_found.function_with_type_info)
1606                 {
1607                     if (extern_symbol)
1608                     {
1609                         AddOneFunction (context, NULL, extern_symbol, current_id);
1610                         context.m_found.function = true;
1611                     }
1612                     else if (non_extern_symbol)
1613                     {
1614                         AddOneFunction (context, NULL, non_extern_symbol, current_id);
1615                         context.m_found.function = true;
1616                     }
1617                 }
1618             }
1619             
1620             if (!context.m_found.function_with_type_info)
1621             {
1622                 // Try the modules next.
1623                 
1624                 do
1625                 {
1626                     if (ClangModulesDeclVendor *modules_decl_vendor = m_target->GetClangModulesDeclVendor())
1627                     {
1628                         bool append = false;
1629                         uint32_t max_matches = 1;
1630                         std::vector <clang::NamedDecl *> decls;
1631                         
1632                         if (!modules_decl_vendor->FindDecls(name,
1633                                                             append,
1634                                                             max_matches,
1635                                                             decls))
1636                             break;
1637                         
1638                         clang::NamedDecl *const decl_from_modules = decls[0];
1639                         
1640                         if (llvm::isa<clang::FunctionDecl>(decl_from_modules))
1641                         {
1642                             if (log)
1643                             {
1644                                 log->Printf("  CAS::FEVD[%u] Matching function found for \"%s\" in the modules",
1645                                             current_id,
1646                                             name.GetCString());
1647                             }
1648                             
1649                             clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(m_ast_context, &decl_from_modules->getASTContext(), decl_from_modules);
1650                             clang::FunctionDecl *copied_function_decl = copied_decl ? dyn_cast<clang::FunctionDecl>(copied_decl) : nullptr;
1651                             
1652                             if (!copied_function_decl)
1653                             {
1654                                 if (log)
1655                                     log->Printf("  CAS::FEVD[%u] - Couldn't export a function declaration from the modules",
1656                                                 current_id);
1657                                 
1658                                 break;
1659                             }
1660                             
1661                             if (copied_function_decl->getBody() && m_parser_vars->m_code_gen)
1662                             {
1663                                 DeclGroupRef decl_group_ref(copied_function_decl);
1664                                 m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
1665                             }
1666                             
1667                             context.AddNamedDecl(copied_function_decl);
1668                             
1669                             context.m_found.function_with_type_info = true;
1670                             context.m_found.function = true;
1671                         }
1672                         else if (llvm::isa<clang::VarDecl>(decl_from_modules))
1673                         {
1674                             if (log)
1675                             {
1676                                 log->Printf("  CAS::FEVD[%u] Matching variable found for \"%s\" in the modules",
1677                                             current_id,
1678                                             name.GetCString());
1679                             }
1680                             
1681                             clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(m_ast_context, &decl_from_modules->getASTContext(), decl_from_modules);
1682                             clang::VarDecl *copied_var_decl = copied_decl ? dyn_cast_or_null<clang::VarDecl>(copied_decl) : nullptr;
1683                             
1684                             if (!copied_var_decl)
1685                             {
1686                                 if (log)
1687                                     log->Printf("  CAS::FEVD[%u] - Couldn't export a variable declaration from the modules",
1688                                                 current_id);
1689                                 
1690                                 break;
1691                             }
1692                             
1693                             context.AddNamedDecl(copied_var_decl);
1694                             
1695                             context.m_found.variable = true;
1696                         }
1697                     }
1698                 } while (0);
1699             }
1700
1701             if (target && !context.m_found.variable && !namespace_decl)
1702             {
1703                 // We couldn't find a non-symbol variable for this.  Now we'll hunt for a generic
1704                 // data symbol, and -- if it is found -- treat it as a variable.
1705
1706                 const Symbol *data_symbol = FindGlobalDataSymbol(*target, name);
1707
1708                 if (data_symbol)
1709                 {
1710                     std::string warning("got name from symbols: ");
1711                     warning.append(name.AsCString());
1712                     const unsigned diag_id = m_ast_context->getDiagnostics().getCustomDiagID(clang::DiagnosticsEngine::Level::Warning, "%0");
1713                     m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1714                     AddOneGenericVariable(context, *data_symbol, current_id);
1715                     context.m_found.variable = true;
1716                 }
1717             }
1718         }
1719     }
1720 }
1721
1722 //static opaque_compiler_type_t
1723 //MaybePromoteToBlockPointerType
1724 //(
1725 //    ASTContext *ast_context,
1726 //    opaque_compiler_type_t candidate_type
1727 //)
1728 //{
1729 //    if (!candidate_type)
1730 //        return candidate_type;
1731 //
1732 //    QualType candidate_qual_type = QualType::getFromOpaquePtr(candidate_type);
1733 //
1734 //    const PointerType *candidate_pointer_type = dyn_cast<PointerType>(candidate_qual_type);
1735 //
1736 //    if (!candidate_pointer_type)
1737 //        return candidate_type;
1738 //
1739 //    QualType pointee_qual_type = candidate_pointer_type->getPointeeType();
1740 //
1741 //    const RecordType *pointee_record_type = dyn_cast<RecordType>(pointee_qual_type);
1742 //
1743 //    if (!pointee_record_type)
1744 //        return candidate_type;
1745 //
1746 //    RecordDecl *pointee_record_decl = pointee_record_type->getDecl();
1747 //
1748 //    if (!pointee_record_decl->isRecord())
1749 //        return candidate_type;
1750 //
1751 //    if (!pointee_record_decl->getName().startswith(llvm::StringRef("__block_literal_")))
1752 //        return candidate_type;
1753 //
1754 //    QualType generic_function_type = ast_context->getFunctionNoProtoType(ast_context->UnknownAnyTy);
1755 //    QualType block_pointer_type = ast_context->getBlockPointerType(generic_function_type);
1756 //
1757 //    return block_pointer_type.getAsOpaquePtr();
1758 //}
1759
1760 bool
1761 ClangExpressionDeclMap::GetVariableValue (VariableSP &var,
1762                                           lldb_private::Value &var_location,
1763                                           TypeFromUser *user_type,
1764                                           TypeFromParser *parser_type)
1765 {
1766     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1767
1768     Type *var_type = var->GetType();
1769
1770     if (!var_type)
1771     {
1772         if (log)
1773             log->PutCString("Skipped a definition because it has no type");
1774         return false;
1775     }
1776
1777     CompilerType var_clang_type = var_type->GetFullCompilerType ();
1778
1779     if (!var_clang_type)
1780     {
1781         if (log)
1782             log->PutCString("Skipped a definition because it has no Clang type");
1783         return false;
1784     }
1785
1786     ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(var_type->GetForwardCompilerType().GetTypeSystem());
1787
1788     if (!clang_ast)
1789     {
1790         if (log)
1791             log->PutCString("Skipped a definition because it has no Clang AST");
1792         return false;
1793     }
1794
1795
1796     ASTContext *ast = clang_ast->getASTContext();
1797
1798     if (!ast)
1799     {
1800         if (log)
1801             log->PutCString("There is no AST context for the current execution context");
1802         return false;
1803     }
1804     //var_clang_type = MaybePromoteToBlockPointerType (ast, var_clang_type);
1805
1806     DWARFExpression &var_location_expr = var->LocationExpression();
1807
1808     Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1809     Error err;
1810
1811     if (var->GetLocationIsConstantValueData())
1812     {
1813         DataExtractor const_value_extractor;
1814
1815         if (var_location_expr.GetExpressionData(const_value_extractor))
1816         {
1817             var_location = Value(const_value_extractor.GetDataStart(), const_value_extractor.GetByteSize());
1818             var_location.SetValueType(Value::eValueTypeHostAddress);
1819         }
1820         else
1821         {
1822             if (log)
1823                 log->Printf("Error evaluating constant variable: %s", err.AsCString());
1824             return false;
1825         }
1826     }
1827
1828     CompilerType type_to_use = GuardedCopyType(var_clang_type);
1829
1830     if (!type_to_use)
1831     {
1832         if (log)
1833             log->Printf("Couldn't copy a variable's type into the parser's AST context");
1834
1835         return false;
1836     }
1837
1838     if (parser_type)
1839         *parser_type = TypeFromParser(type_to_use);
1840
1841     if (var_location.GetContextType() == Value::eContextTypeInvalid)
1842         var_location.SetCompilerType(type_to_use);
1843
1844     if (var_location.GetValueType() == Value::eValueTypeFileAddress)
1845     {
1846         SymbolContext var_sc;
1847         var->CalculateSymbolContext(&var_sc);
1848
1849         if (!var_sc.module_sp)
1850             return false;
1851
1852         Address so_addr(var_location.GetScalar().ULongLong(), var_sc.module_sp->GetSectionList());
1853
1854         lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1855
1856         if (load_addr != LLDB_INVALID_ADDRESS)
1857         {
1858             var_location.GetScalar() = load_addr;
1859             var_location.SetValueType(Value::eValueTypeLoadAddress);
1860         }
1861     }
1862
1863     if (user_type)
1864         *user_type = TypeFromUser(var_clang_type);
1865
1866     return true;
1867 }
1868
1869 void
1870 ClangExpressionDeclMap::AddOneVariable (NameSearchContext &context, VariableSP var, ValueObjectSP valobj, unsigned int current_id)
1871 {
1872     assert (m_parser_vars.get());
1873
1874     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1875
1876     TypeFromUser ut;
1877     TypeFromParser pt;
1878     Value var_location;
1879
1880     if (!GetVariableValue (var, var_location, &ut, &pt))
1881         return;
1882
1883     clang::QualType parser_opaque_type = QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1884
1885     if (parser_opaque_type.isNull())
1886         return;
1887
1888     if (const clang::Type *parser_type = parser_opaque_type.getTypePtr())
1889     {
1890         if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1891             CompleteType(tag_type->getDecl());
1892         if (const ObjCObjectPointerType *objc_object_ptr_type = dyn_cast<ObjCObjectPointerType>(parser_type))
1893             CompleteType(objc_object_ptr_type->getInterfaceDecl());
1894     }
1895
1896
1897     bool is_reference = pt.IsReferenceType();
1898
1899     NamedDecl *var_decl = NULL;
1900     if (is_reference)
1901         var_decl = context.AddVarDecl(pt);
1902     else
1903         var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1904
1905     std::string decl_name(context.m_decl_name.getAsString());
1906     ConstString entity_name(decl_name.c_str());
1907     ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1908     m_found_entities.AddNewlyConstructedVariable(entity);
1909
1910     assert (entity);
1911     entity->EnableParserVars(GetParserID());
1912     ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
1913     parser_vars->m_parser_type = pt;
1914     parser_vars->m_named_decl  = var_decl;
1915     parser_vars->m_llvm_value  = NULL;
1916     parser_vars->m_lldb_value  = var_location;
1917     parser_vars->m_lldb_var    = var;
1918
1919     if (is_reference)
1920         entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1921
1922     if (log)
1923     {
1924         ASTDumper orig_dumper(ut.GetOpaqueQualType());
1925         ASTDumper ast_dumper(var_decl);
1926         log->Printf("  CEDM::FEVD[%u] Found variable %s, returned %s (original %s)", current_id, decl_name.c_str(), ast_dumper.GetCString(), orig_dumper.GetCString());
1927     }
1928 }
1929
1930 void
1931 ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1932                                        ExpressionVariableSP &pvar_sp,
1933                                        unsigned int current_id)
1934 {
1935     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1936
1937     TypeFromUser user_type (llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1938
1939     TypeFromParser parser_type (GuardedCopyType(user_type));
1940
1941     if (!parser_type.GetOpaqueQualType())
1942     {
1943         if (log)
1944             log->Printf("  CEDM::FEVD[%u] Couldn't import type for pvar %s", current_id, pvar_sp->GetName().GetCString());
1945         return;
1946     }
1947
1948     NamedDecl *var_decl = context.AddVarDecl(parser_type.GetLValueReferenceType());
1949
1950     llvm::cast<ClangExpressionVariable>(pvar_sp.get())->EnableParserVars(GetParserID());
1951     ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetParserVars(GetParserID());
1952     parser_vars->m_parser_type = parser_type;
1953     parser_vars->m_named_decl = var_decl;
1954     parser_vars->m_llvm_value = NULL;
1955     parser_vars->m_lldb_value.Clear();
1956
1957     if (log)
1958     {
1959         ASTDumper ast_dumper(var_decl);
1960         log->Printf("  CEDM::FEVD[%u] Added pvar %s, returned %s", current_id, pvar_sp->GetName().GetCString(), ast_dumper.GetCString());
1961     }
1962 }
1963
1964 void
1965 ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1966                                               const Symbol &symbol,
1967                                               unsigned int current_id)
1968 {
1969     assert(m_parser_vars.get());
1970
1971     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1972
1973     Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1974
1975     if (target == NULL)
1976         return;
1977
1978     ASTContext *scratch_ast_context = target->GetScratchClangASTContext()->getASTContext();
1979
1980     TypeFromUser user_type (ClangASTContext::GetBasicType(scratch_ast_context, eBasicTypeVoid).GetPointerType().GetLValueReferenceType());
1981     TypeFromParser parser_type (ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid).GetPointerType().GetLValueReferenceType());
1982     NamedDecl *var_decl = context.AddVarDecl(parser_type);
1983
1984     std::string decl_name(context.m_decl_name.getAsString());
1985     ConstString entity_name(decl_name.c_str());
1986     ClangExpressionVariable *entity(new ClangExpressionVariable(m_parser_vars->m_exe_ctx.GetBestExecutionContextScope (),
1987                                                                 entity_name,
1988                                                                 user_type,
1989                                                                 m_parser_vars->m_target_info.byte_order,
1990                                                                 m_parser_vars->m_target_info.address_byte_size));
1991     m_found_entities.AddNewlyConstructedVariable(entity);
1992     
1993     entity->EnableParserVars(GetParserID());
1994     ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
1995
1996     const Address symbol_address = symbol.GetAddress();
1997     lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1998
1999     //parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
2000     parser_vars->m_lldb_value.SetCompilerType(user_type);
2001     parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
2002     parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
2003
2004     parser_vars->m_parser_type = parser_type;
2005     parser_vars->m_named_decl  = var_decl;
2006     parser_vars->m_llvm_value  = NULL;
2007     parser_vars->m_lldb_sym    = &symbol;
2008
2009     if (log)
2010     {
2011         ASTDumper ast_dumper(var_decl);
2012
2013         log->Printf("  CEDM::FEVD[%u] Found variable %s, returned %s", current_id, decl_name.c_str(), ast_dumper.GetCString());
2014     }
2015 }
2016
2017 bool
2018 ClangExpressionDeclMap::ResolveUnknownTypes()
2019 {
2020     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2021     Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
2022
2023     ClangASTContext *scratch_ast_context = target->GetScratchClangASTContext();
2024
2025     for (size_t index = 0, num_entities = m_found_entities.GetSize();
2026          index < num_entities;
2027          ++index)
2028     {
2029         ExpressionVariableSP entity = m_found_entities.GetVariableAtIndex(index);
2030
2031         ClangExpressionVariable::ParserVars *parser_vars = llvm::cast<ClangExpressionVariable>(entity.get())->GetParserVars(GetParserID());
2032
2033         if (entity->m_flags & ClangExpressionVariable::EVUnknownType)
2034         {
2035             const NamedDecl *named_decl = parser_vars->m_named_decl;
2036             const VarDecl *var_decl = dyn_cast<VarDecl>(named_decl);
2037
2038             if (!var_decl)
2039             {
2040                 if (log)
2041                     log->Printf("Entity of unknown type does not have a VarDecl");
2042                 return false;
2043             }
2044
2045             if (log)
2046             {
2047                 ASTDumper ast_dumper(const_cast<VarDecl*>(var_decl));
2048                 log->Printf("Variable of unknown type now has Decl %s", ast_dumper.GetCString());
2049             }
2050
2051             QualType var_type = var_decl->getType();
2052             TypeFromParser parser_type(var_type.getAsOpaquePtr(), ClangASTContext::GetASTContext(&var_decl->getASTContext()));
2053
2054             lldb::opaque_compiler_type_t copied_type = m_ast_importer_sp->CopyType(scratch_ast_context->getASTContext(), &var_decl->getASTContext(), var_type.getAsOpaquePtr());
2055
2056             if (!copied_type)
2057             {
2058                 if (log)
2059                     log->Printf("ClangExpressionDeclMap::ResolveUnknownType - Couldn't import the type for a variable");
2060
2061                 return (bool) lldb::ExpressionVariableSP();
2062             }
2063
2064             TypeFromUser user_type(copied_type, scratch_ast_context);
2065
2066 //            parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
2067             parser_vars->m_lldb_value.SetCompilerType(user_type);
2068             parser_vars->m_parser_type = parser_type;
2069
2070             entity->SetCompilerType(user_type);
2071
2072             entity->m_flags &= ~(ClangExpressionVariable::EVUnknownType);
2073         }
2074     }
2075
2076     return true;
2077 }
2078
2079 void
2080 ClangExpressionDeclMap::AddOneRegister (NameSearchContext &context,
2081                                         const RegisterInfo *reg_info,
2082                                         unsigned int current_id)
2083 {
2084     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2085
2086     CompilerType clang_type = ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (m_ast_context,
2087                                                                                     reg_info->encoding,
2088                                                                                     reg_info->byte_size * 8);
2089
2090     if (!clang_type)
2091     {
2092         if (log)
2093             log->Printf("  Tried to add a type for %s, but couldn't get one", context.m_decl_name.getAsString().c_str());
2094         return;
2095     }
2096
2097     TypeFromParser parser_clang_type (clang_type);
2098
2099     NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
2100
2101     ClangExpressionVariable *entity(new ClangExpressionVariable(m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
2102                                                                 m_parser_vars->m_target_info.byte_order,
2103                                                                 m_parser_vars->m_target_info.address_byte_size));
2104     m_found_entities.AddNewlyConstructedVariable(entity);
2105
2106     std::string decl_name(context.m_decl_name.getAsString());
2107     entity->SetName (ConstString (decl_name.c_str()));
2108     entity->SetRegisterInfo (reg_info);
2109     entity->EnableParserVars(GetParserID());
2110     ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
2111     parser_vars->m_parser_type = parser_clang_type;
2112     parser_vars->m_named_decl = var_decl;
2113     parser_vars->m_llvm_value = NULL;
2114     parser_vars->m_lldb_value.Clear();
2115     entity->m_flags |= ClangExpressionVariable::EVBareRegister;
2116
2117     if (log)
2118     {
2119         ASTDumper ast_dumper(var_decl);
2120         log->Printf("  CEDM::FEVD[%d] Added register %s, returned %s", current_id, context.m_decl_name.getAsString().c_str(), ast_dumper.GetCString());
2121     }
2122 }
2123
2124 void
2125 ClangExpressionDeclMap::AddOneFunction (NameSearchContext &context,
2126                                         Function* function,
2127                                         Symbol* symbol,
2128                                         unsigned int current_id)
2129 {
2130     assert (m_parser_vars.get());
2131
2132     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2133
2134     NamedDecl *function_decl = NULL;
2135     Address fun_address;
2136     CompilerType function_clang_type;
2137
2138     bool is_indirect_function = false;
2139
2140     if (function)
2141     {
2142         Type *function_type = function->GetType();
2143
2144         if (!function_type)
2145         {
2146             if (log)
2147                 log->PutCString("  Skipped a function because it has no type");
2148             return;
2149         }
2150
2151         function_clang_type = function_type->GetFullCompilerType ();
2152
2153         if (!function_clang_type)
2154         {
2155             if (log)
2156                 log->PutCString("  Skipped a function because it has no Clang type");
2157             return;
2158         }
2159
2160         fun_address = function->GetAddressRange().GetBaseAddress();
2161
2162         CompilerType copied_function_type = GuardedCopyType(function_clang_type);
2163         if (copied_function_type)
2164         {
2165             function_decl = context.AddFunDecl(copied_function_type);
2166
2167             if (!function_decl)
2168             {
2169                 if (log)
2170                 {
2171                     log->Printf ("  Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}",
2172                                  function_type->GetName().GetCString(),
2173                                  function_type->GetID());
2174                 }
2175
2176                 return;
2177             }
2178         }
2179         else
2180         {
2181             // We failed to copy the type we found
2182             if (log)
2183             {
2184                 log->Printf ("  Failed to import the function type '%s' {0x%8.8" PRIx64 "} into the expression parser AST contenxt",
2185                              function_type->GetName().GetCString(),
2186                              function_type->GetID());
2187             }
2188
2189             return;
2190         }
2191     }
2192     else if (symbol)
2193     {
2194         fun_address = symbol->GetAddress();
2195         function_decl = context.AddGenericFunDecl();
2196         is_indirect_function = symbol->IsIndirect();
2197     }
2198     else
2199     {
2200         if (log)
2201             log->PutCString("  AddOneFunction called with no function and no symbol");
2202         return;
2203     }
2204
2205     Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
2206
2207     lldb::addr_t load_addr = fun_address.GetCallableLoadAddress(target, is_indirect_function);
2208
2209     ClangExpressionVariable *entity(new ClangExpressionVariable (m_parser_vars->m_exe_ctx.GetBestExecutionContextScope (),
2210                                                                  m_parser_vars->m_target_info.byte_order,
2211                                                                  m_parser_vars->m_target_info.address_byte_size));
2212     m_found_entities.AddNewlyConstructedVariable(entity);
2213
2214     std::string decl_name(context.m_decl_name.getAsString());
2215     entity->SetName(ConstString(decl_name.c_str()));
2216     entity->SetCompilerType (function_clang_type);
2217     entity->EnableParserVars(GetParserID());
2218
2219     ClangExpressionVariable::ParserVars *parser_vars = entity->GetParserVars(GetParserID());
2220
2221     if (load_addr != LLDB_INVALID_ADDRESS)
2222     {
2223         parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
2224         parser_vars->m_lldb_value.GetScalar() = load_addr;
2225     }
2226     else
2227     {
2228         // We have to try finding a file address.
2229
2230         lldb::addr_t file_addr = fun_address.GetFileAddress();
2231
2232         parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress);
2233         parser_vars->m_lldb_value.GetScalar() = file_addr;
2234     }
2235
2236
2237     parser_vars->m_named_decl  = function_decl;
2238     parser_vars->m_llvm_value  = NULL;
2239
2240     if (log)
2241     {
2242         ASTDumper ast_dumper(function_decl);
2243
2244         StreamString ss;
2245
2246         fun_address.Dump(&ss, m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), Address::DumpStyleResolvedDescription);
2247
2248         log->Printf("  CEDM::FEVD[%u] Found %s function %s (description %s), returned %s",
2249                     current_id,
2250                     (function ? "specific" : "generic"),
2251                     decl_name.c_str(),
2252                     ss.GetData(),
2253                     ast_dumper.GetCString());
2254     }
2255 }
2256
2257 void
2258 ClangExpressionDeclMap::AddThisType(NameSearchContext &context,
2259                                     TypeFromUser &ut,
2260                                     unsigned int current_id)
2261 {
2262     CompilerType copied_clang_type = GuardedCopyType(ut);
2263
2264     if (!copied_clang_type)
2265     {
2266         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2267
2268         if (log)
2269             log->Printf("ClangExpressionDeclMap::AddThisType - Couldn't import the type");
2270
2271         return;
2272     }
2273
2274     if (copied_clang_type.IsAggregateType() && copied_clang_type.GetCompleteType ())
2275     {
2276         CompilerType void_clang_type = ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid);
2277         CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
2278
2279         CompilerType method_type = ClangASTContext::CreateFunctionType (m_ast_context,
2280                                                                         void_clang_type,
2281                                                                         &void_ptr_clang_type,
2282                                                                         1,
2283                                                                         false,
2284                                                                         copied_clang_type.GetTypeQualifiers());
2285
2286         const bool is_virtual = false;
2287         const bool is_static = false;
2288         const bool is_inline = false;
2289         const bool is_explicit = false;
2290         const bool is_attr_used = true;
2291         const bool is_artificial = false;
2292
2293         ClangASTContext::GetASTContext(m_ast_context)->
2294             AddMethodToCXXRecordType (copied_clang_type.GetOpaqueQualType(),
2295                                       "$__lldb_expr",
2296                                       method_type,
2297                                       lldb::eAccessPublic,
2298                                       is_virtual,
2299                                       is_static,
2300                                       is_inline,
2301                                       is_explicit,
2302                                       is_attr_used,
2303                                       is_artificial);
2304     }
2305
2306     if (!copied_clang_type.IsValid())
2307         return;
2308     
2309     TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
2310     
2311     if (!type_source_info)
2312         return;
2313     
2314     // Construct a typedef type because if "*this" is a templated type we can't just return ClassTemplateSpecializationDecls in response to name queries.
2315     // Using a typedef makes this much more robust.
2316     
2317     TypedefDecl *typedef_decl = TypedefDecl::Create(*m_ast_context,
2318                                                     m_ast_context->getTranslationUnitDecl(),
2319                                                     SourceLocation(),
2320                                                     SourceLocation(),
2321                                                     context.m_decl_name.getAsIdentifierInfo(),
2322                                                     type_source_info);
2323     
2324     
2325     if (!typedef_decl)
2326         return;
2327     
2328     context.AddNamedDecl(typedef_decl);
2329
2330     return;
2331 }
2332
2333 void
2334 ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
2335                                    TypeFromUser &ut,
2336                                    unsigned int current_id)
2337 {
2338     CompilerType copied_clang_type = GuardedCopyType(ut);
2339
2340     if (!copied_clang_type)
2341     {
2342         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2343
2344         if (log)
2345             log->Printf("ClangExpressionDeclMap::AddOneType - Couldn't import the type");
2346
2347         return;
2348     }
2349
2350     context.AddTypeDecl(copied_clang_type);
2351 }