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