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