IRForTarget.cpp revision 263508
1//===-- IRForTarget.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/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
13#include "llvm/IR/Constants.h"
14#include "llvm/IR/DataLayout.h"
15#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
19#include "llvm/PassManager.h"
20#include "llvm/Transforms/IPO.h"
21#include "llvm/IR/ValueSymbolTable.h"
22
23#include "clang/AST/ASTContext.h"
24
25#include "lldb/Core/dwarf.h"
26#include "lldb/Core/ConstString.h"
27#include "lldb/Core/DataBufferHeap.h"
28#include "lldb/Core/Log.h"
29#include "lldb/Core/Scalar.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Expression/ClangExpressionDeclMap.h"
32#include "lldb/Expression/IRExecutionUnit.h"
33#include "lldb/Expression/IRInterpreter.h"
34#include "lldb/Host/Endian.h"
35#include "lldb/Symbol/ClangASTContext.h"
36#include "lldb/Symbol/ClangASTType.h"
37
38#include <map>
39
40using namespace llvm;
41
42static char ID;
43
44IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45    m_execution_unit(execution_unit),
46    m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
47    m_allocation(LLDB_INVALID_ADDRESS)
48{
49}
50
51IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
52    m_maker(maker),
53    m_values()
54{
55}
56
57IRForTarget::FunctionValueCache::~FunctionValueCache()
58{
59}
60
61llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
62{
63    if (!m_values.count(function))
64    {
65        llvm::Value *ret = m_maker(function);
66        m_values[function] = ret;
67        return ret;
68    }
69    return m_values[function];
70}
71
72lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
73{
74    lldb_private::Error err;
75
76    if (m_allocation != LLDB_INVALID_ADDRESS)
77    {
78        m_execution_unit.FreeNow(m_allocation);
79        m_allocation = LLDB_INVALID_ADDRESS;
80    }
81
82    m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
83
84    return m_allocation;
85}
86
87static llvm::Value *FindEntryInstruction (llvm::Function *function)
88{
89    if (function->empty())
90        return NULL;
91
92    return function->getEntryBlock().getFirstNonPHIOrDbg();
93}
94
95IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
96                          bool resolve_vars,
97                          lldb_private::IRExecutionUnit &execution_unit,
98                          lldb_private::Stream *error_stream,
99                          const char *func_name) :
100    ModulePass(ID),
101    m_resolve_vars(resolve_vars),
102    m_func_name(func_name),
103    m_module(NULL),
104    m_decl_map(decl_map),
105    m_data_allocator(execution_unit),
106    m_CFStringCreateWithBytes(NULL),
107    m_sel_registerName(NULL),
108    m_error_stream(error_stream),
109    m_result_store(NULL),
110    m_result_is_pointer(false),
111    m_reloc_placeholder(NULL),
112    m_entry_instruction_finder (FindEntryInstruction)
113{
114}
115
116/* Handy utility functions used at several places in the code */
117
118static std::string
119PrintValue(const Value *value, bool truncate = false)
120{
121    std::string s;
122    if (value)
123    {
124        raw_string_ostream rso(s);
125        value->print(rso);
126        rso.flush();
127        if (truncate)
128            s.resize(s.length() - 1);
129    }
130    return s;
131}
132
133static std::string
134PrintType(const llvm::Type *type, bool truncate = false)
135{
136    std::string s;
137    raw_string_ostream rso(s);
138    type->print(rso);
139    rso.flush();
140    if (truncate)
141        s.resize(s.length() - 1);
142    return s;
143}
144
145IRForTarget::~IRForTarget()
146{
147}
148
149bool
150IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
151{
152    llvm_function.setLinkage(GlobalValue::ExternalLinkage);
153
154    std::string name = llvm_function.getName().str();
155
156    return true;
157}
158
159bool
160IRForTarget::GetFunctionAddress (llvm::Function *fun,
161                                 uint64_t &fun_addr,
162                                 lldb_private::ConstString &name,
163                                 Constant **&value_ptr)
164{
165    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
166
167    fun_addr = LLDB_INVALID_ADDRESS;
168    name.Clear();
169    value_ptr = NULL;
170
171    if (fun->isIntrinsic())
172    {
173        Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
174
175        switch (intrinsic_id)
176        {
177        default:
178            if (log)
179                log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
180
181            if (m_error_stream)
182                m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
183
184            return false;
185        case Intrinsic::memcpy:
186            {
187                static lldb_private::ConstString g_memcpy_str ("memcpy");
188                name = g_memcpy_str;
189            }
190            break;
191        case Intrinsic::memset:
192            {
193                static lldb_private::ConstString g_memset_str ("memset");
194                name = g_memset_str;
195            }
196            break;
197        }
198
199        if (log && name)
200            log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
201    }
202    else
203    {
204        name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
205    }
206
207    // Find the address of the function.
208
209    clang::NamedDecl *fun_decl = DeclForGlobal (fun);
210
211    if (fun_decl)
212    {
213        if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
214        {
215            lldb_private::ConstString altnernate_name;
216            bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
217            if (!found_it)
218            {
219                // Check for an alternate mangling for "std::basic_string<char>"
220                // that is part of the itanium C++ name mangling scheme
221                const char *name_cstr = name.GetCString();
222                if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
223                {
224                    std::string alternate_mangling("_ZNKSs");
225                    alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
226                    altnernate_name.SetCString(alternate_mangling.c_str());
227                    found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
228                }
229            }
230
231            if (!found_it)
232            {
233                lldb_private::Mangled mangled_name(name);
234                lldb_private::Mangled alt_mangled_name(altnernate_name);
235                if (log)
236                {
237                    if (alt_mangled_name)
238                        log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
239                                    mangled_name.GetName().GetCString(),
240                                    alt_mangled_name.GetName().GetCString());
241                    else
242                        log->Printf("Function \"%s\" had no address",
243                                    mangled_name.GetName().GetCString());
244                }
245
246                if (m_error_stream)
247                {
248                    if (alt_mangled_name)
249                        m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
250                                               mangled_name.GetName().GetCString(),
251                                               alt_mangled_name.GetName().GetCString());
252                    else if (mangled_name.GetMangledName())
253                        m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
254                                               mangled_name.GetName().GetCString(),
255                                               mangled_name.GetMangledName().GetCString());
256                    else
257                        m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
258                                               mangled_name.GetName().GetCString());
259                }
260                return false;
261            }
262        }
263    }
264    else
265    {
266        if (!m_decl_map->GetFunctionAddress (name, fun_addr))
267        {
268            if (log)
269                log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
270
271            if (m_error_stream)
272                m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
273
274            return false;
275        }
276    }
277
278    if (log)
279        log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
280
281    return true;
282}
283
284llvm::Constant *
285IRForTarget::BuildFunctionPointer (llvm::Type *type,
286                                   uint64_t ptr)
287{
288    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
289                                             (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
290    PointerType *fun_ptr_ty = PointerType::getUnqual(type);
291    Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
292    return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
293}
294
295void
296IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
297                                      llvm::Value *function_ptr,
298                                      const char *name)
299{
300    for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
301         i != e;
302         ++i)
303    {
304        Value *user = *i;
305
306        if (Instruction *user_inst = dyn_cast<Instruction>(user))
307        {
308            MDString* md_name = MDString::get(context, StringRef(name));
309
310            MDNode *metadata = MDNode::get(context, md_name);
311
312            user_inst->setMetadata("lldb.call.realName", metadata);
313        }
314        else
315        {
316            RegisterFunctionMetadata (context, user, name);
317        }
318    }
319}
320
321bool
322IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
323{
324    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
325
326    for (llvm::Module::iterator fi = llvm_module.begin();
327         fi != llvm_module.end();
328         ++fi)
329    {
330        Function *fun = fi;
331
332        bool is_decl = fun->isDeclaration();
333
334        if (log)
335            log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
336
337        if (!is_decl)
338            continue;
339
340        if (fun->hasNUses(0))
341            continue; // ignore
342
343        uint64_t addr = LLDB_INVALID_ADDRESS;
344        lldb_private::ConstString name;
345        Constant **value_ptr = NULL;
346
347        if (!GetFunctionAddress(fun,
348                                addr,
349                                name,
350                                value_ptr))
351            return false; // GetFunctionAddress reports its own errors
352
353        Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
354
355        RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
356
357        if (value_ptr)
358            *value_ptr = value;
359
360        // If we are replacing a function with the nobuiltin attribute, it may
361        // be called with the builtin attribute on call sites. Remove any such
362        // attributes since it's illegal to have a builtin call to something
363        // other than a nobuiltin function.
364        if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
365            llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
366
367            for (auto u = fun->use_begin(), e = fun->use_end(); u != e; ++u) {
368                if (auto call = dyn_cast<CallInst>(*u)) {
369                    call->removeAttribute(AttributeSet::FunctionIndex, builtin);
370                }
371            }
372        }
373
374        fun->replaceAllUsesWith(value);
375    }
376
377    return true;
378}
379
380
381clang::NamedDecl *
382IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
383{
384    NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
385
386    if (!named_metadata)
387        return NULL;
388
389    unsigned num_nodes = named_metadata->getNumOperands();
390    unsigned node_index;
391
392    for (node_index = 0;
393         node_index < num_nodes;
394         ++node_index)
395    {
396        MDNode *metadata_node = named_metadata->getOperand(node_index);
397
398        if (!metadata_node)
399            return NULL;
400
401        if (metadata_node->getNumOperands() != 2)
402            continue;
403
404        if (metadata_node->getOperand(0) != global_val)
405            continue;
406
407        ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
408
409        if (!constant_int)
410            return NULL;
411
412        uintptr_t ptr = constant_int->getZExtValue();
413
414        return reinterpret_cast<clang::NamedDecl *>(ptr);
415    }
416
417    return NULL;
418}
419
420clang::NamedDecl *
421IRForTarget::DeclForGlobal (GlobalValue *global_val)
422{
423    return DeclForGlobal(global_val, m_module);
424}
425
426bool
427IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
428{
429    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
430
431    if (!m_resolve_vars)
432        return true;
433
434    // Find the result variable.  If it doesn't exist, we can give up right here.
435
436    ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
437
438    std::string result_name_str;
439    const char *result_name = NULL;
440
441    for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
442         vi != ve;
443         ++vi)
444    {
445        result_name_str = vi->first().str();
446        const char *value_name = result_name_str.c_str();
447
448        if (strstr(value_name, "$__lldb_expr_result_ptr") &&
449            strncmp(value_name, "_ZGV", 4))
450        {
451            result_name = value_name;
452            m_result_is_pointer = true;
453            break;
454        }
455
456        if (strstr(value_name, "$__lldb_expr_result") &&
457            strncmp(value_name, "_ZGV", 4))
458        {
459            result_name = value_name;
460            m_result_is_pointer = false;
461            break;
462        }
463    }
464
465    if (!result_name)
466    {
467        if (log)
468            log->PutCString("Couldn't find result variable");
469
470        return true;
471    }
472
473    if (log)
474        log->Printf("Result name: \"%s\"", result_name);
475
476    Value *result_value = m_module->getNamedValue(result_name);
477
478    if (!result_value)
479    {
480        if (log)
481            log->PutCString("Result variable had no data");
482
483        if (m_error_stream)
484            m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
485
486        return false;
487    }
488
489    if (log)
490        log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
491
492    GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
493
494    if (!result_global)
495    {
496        if (log)
497            log->PutCString("Result variable isn't a GlobalVariable");
498
499        if (m_error_stream)
500            m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
501
502        return false;
503    }
504
505    clang::NamedDecl *result_decl = DeclForGlobal (result_global);
506    if (!result_decl)
507    {
508        if (log)
509            log->PutCString("Result variable doesn't have a corresponding Decl");
510
511        if (m_error_stream)
512            m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
513
514        return false;
515    }
516
517    if (log)
518    {
519        std::string decl_desc_str;
520        raw_string_ostream decl_desc_stream(decl_desc_str);
521        result_decl->print(decl_desc_stream);
522        decl_desc_stream.flush();
523
524        log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
525    }
526
527    clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
528    if (!result_var)
529    {
530        if (log)
531            log->PutCString("Result variable Decl isn't a VarDecl");
532
533        if (m_error_stream)
534            m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
535
536        return false;
537    }
538
539    // Get the next available result name from m_decl_map and create the persistent
540    // variable for it
541
542    // If the result is an Lvalue, it is emitted as a pointer; see
543    // ASTResultSynthesizer::SynthesizeBodyResult.
544    if (m_result_is_pointer)
545    {
546        clang::QualType pointer_qual_type = result_var->getType();
547        const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
548
549        const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
550        const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
551
552        if (pointer_pointertype)
553        {
554            clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
555
556            m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
557                                                         &result_decl->getASTContext());
558        }
559        else if (pointer_objcobjpointertype)
560        {
561            clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
562
563            m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
564                                                         &result_decl->getASTContext());
565        }
566        else
567        {
568            if (log)
569                log->PutCString("Expected result to have pointer type, but it did not");
570
571            if (m_error_stream)
572                m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
573
574            return false;
575        }
576    }
577    else
578    {
579        m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
580                                                     &result_decl->getASTContext());
581    }
582
583    if (m_result_type.GetBitSize() == 0)
584    {
585        lldb_private::StreamString type_desc_stream;
586        m_result_type.DumpTypeDescription(&type_desc_stream);
587
588        if (log)
589            log->Printf("Result type has size 0");
590
591        if (m_error_stream)
592            m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
593                                   type_desc_stream.GetData());
594        return false;
595    }
596
597    if (log)
598    {
599        lldb_private::StreamString type_desc_stream;
600        m_result_type.DumpTypeDescription(&type_desc_stream);
601
602        log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
603    }
604
605    m_result_name = lldb_private::ConstString("$RESULT_NAME");
606
607    if (log)
608        log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
609                    m_result_name.GetCString(),
610                    m_result_type.GetByteSize());
611
612    // Construct a new result global and set up its metadata
613
614    GlobalVariable *new_result_global = new GlobalVariable((*m_module),
615                                                           result_global->getType()->getElementType(),
616                                                           false, /* not constant */
617                                                           GlobalValue::ExternalLinkage,
618                                                           NULL, /* no initializer */
619                                                           m_result_name.GetCString ());
620
621    // It's too late in compilation to create a new VarDecl for this, but we don't
622    // need to.  We point the metadata at the old VarDecl.  This creates an odd
623    // anomaly: a variable with a Value whose name is something like $0 and a
624    // Decl whose name is $__lldb_expr_result.  This condition is handled in
625    // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
626    // fixed up.
627
628    ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
629                                                     reinterpret_cast<uint64_t>(result_decl),
630                                                     false);
631
632    llvm::Value* values[2];
633    values[0] = new_result_global;
634    values[1] = new_constant_int;
635
636    ArrayRef<Value*> value_ref(values, 2);
637
638    MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
639    NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
640    named_metadata->addOperand(persistent_global_md);
641
642    if (log)
643        log->Printf("Replacing \"%s\" with \"%s\"",
644                    PrintValue(result_global).c_str(),
645                    PrintValue(new_result_global).c_str());
646
647    if (result_global->hasNUses(0))
648    {
649        // We need to synthesize a store for this variable, because otherwise
650        // there's nothing to put into its equivalent persistent variable.
651
652        BasicBlock &entry_block(llvm_function.getEntryBlock());
653        Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
654
655        if (!first_entry_instruction)
656            return false;
657
658        if (!result_global->hasInitializer())
659        {
660            if (log)
661                log->Printf("Couldn't find initializer for unused variable");
662
663            if (m_error_stream)
664                m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
665
666            return false;
667        }
668
669        Constant *initializer = result_global->getInitializer();
670
671        StoreInst *synthesized_store = new StoreInst(initializer,
672                                                     new_result_global,
673                                                     first_entry_instruction);
674
675        if (log)
676            log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
677    }
678    else
679    {
680        result_global->replaceAllUsesWith(new_result_global);
681    }
682
683    if (!m_decl_map->AddPersistentVariable(result_decl,
684                                           m_result_name,
685                                           m_result_type,
686                                           true,
687                                           m_result_is_pointer))
688        return false;
689
690    result_global->eraseFromParent();
691
692    return true;
693}
694
695#if 0
696static void DebugUsers(Log *log, Value *value, uint8_t depth)
697{
698    if (!depth)
699        return;
700
701    depth--;
702
703    if (log)
704        log->Printf("  <Begin %d users>", value->getNumUses());
705
706    for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
707         ui != ue;
708         ++ui)
709    {
710        if (log)
711            log->Printf("  <Use %p> %s", *ui, PrintValue(*ui).c_str());
712        DebugUsers(log, *ui, depth);
713    }
714
715    if (log)
716        log->Printf("  <End uses>");
717}
718#endif
719
720bool
721IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
722                                     llvm::GlobalVariable *cstr)
723{
724    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
725
726    Type *ns_str_ty = ns_str->getType();
727
728    Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
729    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
730                                                   (m_module->getPointerSize()
731                                                    == Module::Pointer64) ? 64 : 32);
732    Type *i32_ty = Type::getInt32Ty(m_module->getContext());
733    Type *i8_ty = Type::getInt8Ty(m_module->getContext());
734
735    if (!m_CFStringCreateWithBytes)
736    {
737        lldb::addr_t CFStringCreateWithBytes_addr;
738
739        static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
740
741        if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
742        {
743            if (log)
744                log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
745
746            if (m_error_stream)
747                m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
748
749            return false;
750        }
751
752        if (log)
753            log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
754
755        // Build the function type:
756        //
757        // CFStringRef CFStringCreateWithBytes (
758        //   CFAllocatorRef alloc,
759        //   const UInt8 *bytes,
760        //   CFIndex numBytes,
761        //   CFStringEncoding encoding,
762        //   Boolean isExternalRepresentation
763        // );
764        //
765        // We make the following substitutions:
766        //
767        // CFStringRef -> i8*
768        // CFAllocatorRef -> i8*
769        // UInt8 * -> i8*
770        // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
771        // CFStringEncoding -> i32
772        // Boolean -> i8
773
774        Type *arg_type_array[5];
775
776        arg_type_array[0] = i8_ptr_ty;
777        arg_type_array[1] = i8_ptr_ty;
778        arg_type_array[2] = intptr_ty;
779        arg_type_array[3] = i32_ty;
780        arg_type_array[4] = i8_ty;
781
782        ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
783
784        llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
785
786        // Build the constant containing the pointer to the function
787        PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
788        Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
789        m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
790    }
791
792    ConstantDataSequential *string_array = NULL;
793
794    if (cstr)
795        string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
796
797    Constant *alloc_arg         = Constant::getNullValue(i8_ptr_ty);
798    Constant *bytes_arg         = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
799    Constant *numBytes_arg      = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
800    Constant *encoding_arg      = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
801    Constant *isExternal_arg    = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
802
803    Value *argument_array[5];
804
805    argument_array[0] = alloc_arg;
806    argument_array[1] = bytes_arg;
807    argument_array[2] = numBytes_arg;
808    argument_array[3] = encoding_arg;
809    argument_array[4] = isExternal_arg;
810
811    ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
812
813    FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
814        return CallInst::Create(m_CFStringCreateWithBytes,
815                                CFSCWB_arguments,
816                                "CFStringCreateWithBytes",
817                                llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
818    });
819
820    if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
821    {
822        if (log)
823            log->PutCString("Couldn't replace the NSString with the result of the call");
824
825        if (m_error_stream)
826            m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
827
828        return false;
829    }
830
831    ns_str->eraseFromParent();
832
833    return true;
834}
835
836bool
837IRForTarget::RewriteObjCConstStrings()
838{
839    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
840
841    ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
842
843    for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
844         vi != ve;
845         ++vi)
846    {
847        std::string value_name = vi->first().str();
848        const char *value_name_cstr = value_name.c_str();
849
850        if (strstr(value_name_cstr, "_unnamed_cfstring_"))
851        {
852            Value *nsstring_value = vi->second;
853
854            GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
855
856            if (!nsstring_global)
857            {
858                if (log)
859                    log->PutCString("NSString variable is not a GlobalVariable");
860
861                if (m_error_stream)
862                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
863
864                return false;
865            }
866
867            if (!nsstring_global->hasInitializer())
868            {
869                if (log)
870                    log->PutCString("NSString variable does not have an initializer");
871
872                if (m_error_stream)
873                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
874
875                return false;
876            }
877
878            ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
879
880            if (!nsstring_struct)
881            {
882                if (log)
883                    log->PutCString("NSString variable's initializer is not a ConstantStruct");
884
885                if (m_error_stream)
886                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
887
888                return false;
889            }
890
891            // We expect the following structure:
892            //
893            // struct {
894            //   int *isa;
895            //   int flags;
896            //   char *str;
897            //   long length;
898            // };
899
900            if (nsstring_struct->getNumOperands() != 4)
901            {
902                if (log)
903                    log->Printf("NSString variable's initializer structure has an unexpected number of members.  Should be 4, is %d", nsstring_struct->getNumOperands());
904
905                if (m_error_stream)
906                    m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
907
908                return false;
909            }
910
911            Constant *nsstring_member = nsstring_struct->getOperand(2);
912
913            if (!nsstring_member)
914            {
915                if (log)
916                    log->PutCString("NSString initializer's str element was empty");
917
918                if (m_error_stream)
919                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
920
921                return false;
922            }
923
924            ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
925
926            if (!nsstring_expr)
927            {
928                if (log)
929                    log->PutCString("NSString initializer's str element is not a ConstantExpr");
930
931                if (m_error_stream)
932                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
933
934                return false;
935            }
936
937            if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
938            {
939                if (log)
940                    log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
941
942                if (m_error_stream)
943                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
944
945                return false;
946            }
947
948            Constant *nsstring_cstr = nsstring_expr->getOperand(0);
949
950            GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
951
952            if (!cstr_global)
953            {
954                if (log)
955                    log->PutCString("NSString initializer's str element is not a GlobalVariable");
956
957                if (m_error_stream)
958                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
959
960                return false;
961            }
962
963            if (!cstr_global->hasInitializer())
964            {
965                if (log)
966                    log->PutCString("NSString initializer's str element does not have an initializer");
967
968                if (m_error_stream)
969                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
970
971                return false;
972            }
973
974            /*
975            if (!cstr_array)
976            {
977                if (log)
978                    log->PutCString("NSString initializer's str element is not a ConstantArray");
979
980                if (m_error_stream)
981                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
982
983                return false;
984            }
985
986            if (!cstr_array->isCString())
987            {
988                if (log)
989                    log->PutCString("NSString initializer's str element is not a C string array");
990
991                if (m_error_stream)
992                    m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
993
994                return false;
995            }
996            */
997
998            ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
999
1000            if (log)
1001            {
1002                if (cstr_array)
1003                    log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
1004                else
1005                    log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
1006            }
1007
1008            if (!cstr_array)
1009                cstr_global = NULL;
1010
1011            if (!RewriteObjCConstString(nsstring_global, cstr_global))
1012            {
1013                if (log)
1014                    log->PutCString("Error rewriting the constant string");
1015
1016                // We don't print an error message here because RewriteObjCConstString has done so for us.
1017
1018                return false;
1019            }
1020        }
1021    }
1022
1023    for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1024         vi != ve;
1025         ++vi)
1026    {
1027        std::string value_name = vi->first().str();
1028        const char *value_name_cstr = value_name.c_str();
1029
1030        if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
1031        {
1032            GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1033
1034            if (!gv)
1035            {
1036                if (log)
1037                    log->PutCString("__CFConstantStringClassReference is not a global variable");
1038
1039                if (m_error_stream)
1040                    m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1041
1042                return false;
1043            }
1044
1045            gv->eraseFromParent();
1046
1047            break;
1048        }
1049    }
1050
1051    return true;
1052}
1053
1054static bool IsObjCSelectorRef (Value *value)
1055{
1056    GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
1057
1058    if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
1059        return false;
1060
1061    return true;
1062}
1063
1064// This function does not report errors; its callers are responsible.
1065bool
1066IRForTarget::RewriteObjCSelector (Instruction* selector_load)
1067{
1068    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1069
1070    LoadInst *load = dyn_cast<LoadInst>(selector_load);
1071
1072    if (!load)
1073        return false;
1074
1075    // Unpack the message name from the selector.  In LLVM IR, an objc_msgSend gets represented as
1076    //
1077    // %tmp     = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1078    // %call    = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1079    //
1080    // where %obj is the object pointer and %tmp is the selector.
1081    //
1082    // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1083    // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
1084
1085    // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1086
1087    GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1088
1089    if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1090        return false;
1091
1092    Constant *osr_initializer = _objc_selector_references_->getInitializer();
1093
1094    ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1095
1096    if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1097        return false;
1098
1099    Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1100
1101    if (!osr_initializer_base)
1102        return false;
1103
1104    // Find the string's initializer (a ConstantArray) and get the string from it
1105
1106    GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1107
1108    if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1109        return false;
1110
1111    Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1112
1113    ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
1114
1115    if (!omvn_initializer_array->isString())
1116        return false;
1117
1118    std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1119
1120    if (log)
1121        log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
1122
1123    // Construct a call to sel_registerName
1124
1125    if (!m_sel_registerName)
1126    {
1127        lldb::addr_t sel_registerName_addr;
1128
1129        static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
1130        if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
1131            return false;
1132
1133        if (log)
1134            log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
1135
1136        // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1137
1138        // The below code would be "more correct," but in actuality what's required is uint8_t*
1139        //Type *sel_type = StructType::get(m_module->getContext());
1140        //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
1141        Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
1142
1143        Type *type_array[1];
1144
1145        type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1146
1147        ArrayRef<Type *> srN_arg_types(type_array, 1);
1148
1149        llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1150
1151        // Build the constant containing the pointer to the function
1152        IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1153                                                 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1154        PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
1155        Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
1156        m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1157    }
1158
1159    Value *argument_array[1];
1160
1161    Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
1162
1163    argument_array[0] = omvn_pointer;
1164
1165    ArrayRef<Value *> srN_arguments(argument_array, 1);
1166
1167    CallInst *srN_call = CallInst::Create(m_sel_registerName,
1168                                          srN_arguments,
1169                                          "sel_registerName",
1170                                          selector_load);
1171
1172    // Replace the load with the call in all users
1173
1174    selector_load->replaceAllUsesWith(srN_call);
1175
1176    selector_load->eraseFromParent();
1177
1178    return true;
1179}
1180
1181bool
1182IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
1183{
1184    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1185
1186    BasicBlock::iterator ii;
1187
1188    typedef SmallVector <Instruction*, 2> InstrList;
1189    typedef InstrList::iterator InstrIterator;
1190
1191    InstrList selector_loads;
1192
1193    for (ii = basic_block.begin();
1194         ii != basic_block.end();
1195         ++ii)
1196    {
1197        Instruction &inst = *ii;
1198
1199        if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1200            if (IsObjCSelectorRef(load->getPointerOperand()))
1201                selector_loads.push_back(&inst);
1202    }
1203
1204    InstrIterator iter;
1205
1206    for (iter = selector_loads.begin();
1207         iter != selector_loads.end();
1208         ++iter)
1209    {
1210        if (!RewriteObjCSelector(*iter))
1211        {
1212            if (m_error_stream)
1213                m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1214
1215            if (log)
1216                log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
1217
1218            return false;
1219        }
1220    }
1221
1222    return true;
1223}
1224
1225// This function does not report errors; its callers are responsible.
1226bool
1227IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
1228{
1229    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1230
1231    AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1232
1233    MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1234
1235    if (!alloc_md || !alloc_md->getNumOperands())
1236        return false;
1237
1238    ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1239
1240    if (!constant_int)
1241        return false;
1242
1243    // We attempt to register this as a new persistent variable with the DeclMap.
1244
1245    uintptr_t ptr = constant_int->getZExtValue();
1246
1247    clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1248
1249    lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1250                                                   &decl->getASTContext());
1251
1252    StringRef decl_name (decl->getName());
1253    lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
1254    if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
1255        return false;
1256
1257    GlobalVariable *persistent_global = new GlobalVariable((*m_module),
1258                                                           alloc->getType(),
1259                                                           false, /* not constant */
1260                                                           GlobalValue::ExternalLinkage,
1261                                                           NULL, /* no initializer */
1262                                                           alloc->getName().str().c_str());
1263
1264    // What we're going to do here is make believe this was a regular old external
1265    // variable.  That means we need to make the metadata valid.
1266
1267    NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1268
1269    llvm::Value* values[2];
1270    values[0] = persistent_global;
1271    values[1] = constant_int;
1272
1273    ArrayRef<llvm::Value*> value_ref(values, 2);
1274
1275    MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1276    named_metadata->addOperand(persistent_global_md);
1277
1278    // Now, since the variable is a pointer variable, we will drop in a load of that
1279    // pointer variable.
1280
1281    LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1282
1283    if (log)
1284        log->Printf("Replacing \"%s\" with \"%s\"",
1285                    PrintValue(alloc).c_str(),
1286                    PrintValue(persistent_load).c_str());
1287
1288    alloc->replaceAllUsesWith(persistent_load);
1289    alloc->eraseFromParent();
1290
1291    return true;
1292}
1293
1294bool
1295IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1296{
1297    if (!m_resolve_vars)
1298        return true;
1299
1300    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1301
1302    BasicBlock::iterator ii;
1303
1304    typedef SmallVector <Instruction*, 2> InstrList;
1305    typedef InstrList::iterator InstrIterator;
1306
1307    InstrList pvar_allocs;
1308
1309    for (ii = basic_block.begin();
1310         ii != basic_block.end();
1311         ++ii)
1312    {
1313        Instruction &inst = *ii;
1314
1315        if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1316        {
1317            llvm::StringRef alloc_name = alloc->getName();
1318
1319            if (alloc_name.startswith("$") &&
1320                !alloc_name.startswith("$__lldb"))
1321            {
1322                if (alloc_name.find_first_of("0123456789") == 1)
1323                {
1324                    if (log)
1325                        log->Printf("Rejecting a numeric persistent variable.");
1326
1327                    if (m_error_stream)
1328                        m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1329
1330                    return false;
1331                }
1332
1333                pvar_allocs.push_back(alloc);
1334            }
1335        }
1336    }
1337
1338    InstrIterator iter;
1339
1340    for (iter = pvar_allocs.begin();
1341         iter != pvar_allocs.end();
1342         ++iter)
1343    {
1344        if (!RewritePersistentAlloc(*iter))
1345        {
1346            if (m_error_stream)
1347                m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1348
1349            if (log)
1350                log->PutCString("Couldn't rewrite the creation of a persistent variable");
1351
1352            return false;
1353        }
1354    }
1355
1356    return true;
1357}
1358
1359bool
1360IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1361{
1362    if (!initializer)
1363        return true;
1364
1365    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1366
1367    if (log && log->GetVerbose())
1368        log->Printf("  MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1369
1370    Type *initializer_type = initializer->getType();
1371
1372    if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1373    {
1374        memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1375        return true;
1376    }
1377    else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1378    {
1379        if (array_initializer->isString())
1380        {
1381            std::string array_initializer_string = array_initializer->getAsString();
1382            memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1383        }
1384        else
1385        {
1386            ArrayType *array_initializer_type = array_initializer->getType();
1387            Type *array_element_type = array_initializer_type->getElementType();
1388
1389            size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1390
1391            for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1392            {
1393                Value *operand_value = array_initializer->getOperand(i);
1394                Constant *operand_constant = dyn_cast<Constant>(operand_value);
1395
1396                if (!operand_constant)
1397                    return false;
1398
1399                if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1400                    return false;
1401            }
1402        }
1403        return true;
1404    }
1405    else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1406    {
1407        StructType *struct_initializer_type = struct_initializer->getType();
1408        const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1409
1410        for (unsigned i = 0;
1411             i < struct_initializer->getNumOperands();
1412             ++i)
1413        {
1414            if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1415                return false;
1416        }
1417        return true;
1418    }
1419    else if (isa<ConstantAggregateZero>(initializer))
1420    {
1421        memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1422        return true;
1423    }
1424    return false;
1425}
1426
1427bool
1428IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1429{
1430    if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1431        return false;
1432
1433    if (global_variable == m_reloc_placeholder)
1434        return true;
1435
1436    uint64_t offset = m_data_allocator.GetStream().GetSize();
1437
1438    llvm::Type *variable_type = global_variable->getType();
1439
1440    Constant *initializer = global_variable->getInitializer();
1441
1442    llvm::Type *initializer_type = initializer->getType();
1443
1444    size_t size = m_target_data->getTypeAllocSize(initializer_type);
1445    size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1446
1447    const size_t mask = (align - 1);
1448    uint64_t aligned_offset = (offset + mask) & ~mask;
1449    m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
1450    offset = aligned_offset;
1451
1452    lldb_private::DataBufferHeap data(size, '\0');
1453
1454    if (initializer)
1455        if (!MaterializeInitializer(data.GetBytes(), initializer))
1456            return false;
1457
1458    m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
1459
1460    Constant *new_pointer = BuildRelocation(variable_type, offset);
1461
1462    global_variable->replaceAllUsesWith(new_pointer);
1463
1464    global_variable->eraseFromParent();
1465
1466    return true;
1467}
1468
1469// This function does not report errors; its callers are responsible.
1470bool
1471IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1472{
1473    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1474
1475    if (log)
1476        log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1477
1478    if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1479    {
1480        switch (constant_expr->getOpcode())
1481        {
1482        default:
1483            break;
1484        case Instruction::GetElementPtr:
1485        case Instruction::BitCast:
1486            Value *s = constant_expr->getOperand(0);
1487            if (!MaybeHandleVariable(s))
1488                return false;
1489        }
1490    }
1491    else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1492    {
1493        if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1494            return MaterializeInternalVariable(global_variable);
1495
1496        clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1497
1498        if (!named_decl)
1499        {
1500            if (IsObjCSelectorRef(llvm_value_ptr))
1501                return true;
1502
1503            if (!global_variable->hasExternalLinkage())
1504                return true;
1505
1506            if (log)
1507                log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1508
1509            return false;
1510        }
1511
1512        std::string name (named_decl->getName().str());
1513
1514        clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1515        if (value_decl == NULL)
1516            return false;
1517
1518        lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
1519
1520        const Type *value_type = NULL;
1521
1522        if (name[0] == '$')
1523        {
1524            // The $__lldb_expr_result name indicates the the return value has allocated as
1525            // a static variable.  Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1526            // accesses to this static variable need to be redirected to the result of dereferencing
1527            // a pointer that is passed in as one of the arguments.
1528            //
1529            // Consequently, when reporting the size of the type, we report a pointer type pointing
1530            // to the type of $__lldb_expr_result, not the type itself.
1531            //
1532            // We also do this for any user-declared persistent variables.
1533            clang_type = clang_type.GetPointerType();
1534            value_type = PointerType::get(global_variable->getType(), 0);
1535        }
1536        else
1537        {
1538            value_type = global_variable->getType();
1539        }
1540
1541        const uint64_t value_size = clang_type.GetByteSize();
1542        off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
1543
1544        if (log)
1545        {
1546            log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
1547                        name.c_str(),
1548                        clang_type.GetQualType().getAsString().c_str(),
1549                        PrintType(value_type).c_str(),
1550                        value_size,
1551                        value_alignment);
1552        }
1553
1554
1555        if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1556                                                        lldb_private::ConstString (name.c_str()),
1557                                                        llvm_value_ptr,
1558                                                        value_size,
1559                                                        value_alignment))
1560        {
1561            if (!global_variable->hasExternalLinkage())
1562                return true;
1563            else if (HandleSymbol (global_variable))
1564                return true;
1565            else
1566                return false;
1567        }
1568    }
1569    else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1570    {
1571        if (log)
1572            log->Printf("Function pointers aren't handled right now");
1573
1574        return false;
1575    }
1576
1577    return true;
1578}
1579
1580// This function does not report errors; its callers are responsible.
1581bool
1582IRForTarget::HandleSymbol (Value *symbol)
1583{
1584    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1585
1586    lldb_private::ConstString name(symbol->getName().str().c_str());
1587
1588    lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1589
1590    if (symbol_addr == LLDB_INVALID_ADDRESS)
1591    {
1592        if (log)
1593            log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1594
1595        return false;
1596    }
1597
1598    if (log)
1599        log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1600
1601    Type *symbol_type = symbol->getType();
1602    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1603                                             (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1604
1605    Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1606
1607    Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1608
1609    if (log)
1610        log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1611
1612    symbol->replaceAllUsesWith(symbol_addr_ptr);
1613
1614    return true;
1615}
1616
1617bool
1618IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1619{
1620    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1621
1622    if (log)
1623        log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1624
1625    for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1626         op_index < num_ops;
1627         ++op_index)
1628        if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1629        {
1630            if (m_error_stream)
1631                m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1632
1633            return false;
1634        }
1635
1636    return true;
1637}
1638
1639bool
1640IRForTarget::HandleObjCClass(Value *classlist_reference)
1641{
1642    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1643
1644    GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1645
1646    if (!global_variable)
1647        return false;
1648
1649    Constant *initializer = global_variable->getInitializer();
1650
1651    if (!initializer)
1652        return false;
1653
1654    if (!initializer->hasName())
1655        return false;
1656
1657    StringRef name(initializer->getName());
1658    lldb_private::ConstString name_cstr(name.str().c_str());
1659    lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1660
1661    if (log)
1662        log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1663
1664    if (class_ptr == LLDB_INVALID_ADDRESS)
1665        return false;
1666
1667    if (global_variable->use_begin() == global_variable->use_end())
1668        return false;
1669
1670    SmallVector<LoadInst *, 2> load_instructions;
1671
1672    for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1673         i != e;
1674         ++i)
1675    {
1676        if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1677            load_instructions.push_back(load_instruction);
1678    }
1679
1680    if (load_instructions.empty())
1681        return false;
1682
1683    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1684                                             (m_module->getPointerSize()
1685                                              == Module::Pointer64) ? 64 : 32);
1686
1687    Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1688
1689    for (LoadInst *load_instruction : load_instructions)
1690    {
1691        Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1692
1693        load_instruction->replaceAllUsesWith(class_bitcast);
1694
1695        load_instruction->eraseFromParent();
1696    }
1697
1698    return true;
1699}
1700
1701bool
1702IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1703{
1704    BasicBlock::iterator ii;
1705
1706    std::vector<CallInst *> calls_to_remove;
1707
1708    for (ii = basic_block.begin();
1709         ii != basic_block.end();
1710         ++ii)
1711    {
1712        Instruction &inst = *ii;
1713
1714        CallInst *call = dyn_cast<CallInst>(&inst);
1715
1716        // MaybeHandleCallArguments handles error reporting; we are silent here
1717        if (!call)
1718            continue;
1719
1720        bool remove = false;
1721
1722        llvm::Function *func = call->getCalledFunction();
1723
1724        if (func && func->getName() == "__cxa_atexit")
1725            remove = true;
1726
1727        llvm::Value *val = call->getCalledValue();
1728
1729        if (val && val->getName() == "__cxa_atexit")
1730            remove = true;
1731
1732        if (remove)
1733            calls_to_remove.push_back(call);
1734    }
1735
1736    for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1737         ci != ce;
1738         ++ci)
1739    {
1740        (*ci)->eraseFromParent();
1741    }
1742
1743    return true;
1744}
1745
1746bool
1747IRForTarget::ResolveCalls(BasicBlock &basic_block)
1748{
1749    /////////////////////////////////////////////////////////////////////////
1750    // Prepare the current basic block for execution in the remote process
1751    //
1752
1753    BasicBlock::iterator ii;
1754
1755    for (ii = basic_block.begin();
1756         ii != basic_block.end();
1757         ++ii)
1758    {
1759        Instruction &inst = *ii;
1760
1761        CallInst *call = dyn_cast<CallInst>(&inst);
1762
1763        // MaybeHandleCallArguments handles error reporting; we are silent here
1764        if (call && !MaybeHandleCallArguments(call))
1765            return false;
1766    }
1767
1768    return true;
1769}
1770
1771bool
1772IRForTarget::ResolveExternals (Function &llvm_function)
1773{
1774    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1775
1776    for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
1777         global != end;
1778         ++global)
1779    {
1780        if (!global)
1781        {
1782            if (m_error_stream)
1783                m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1784
1785            return false;
1786        }
1787
1788        std::string global_name = (*global).getName().str();
1789
1790        if (log)
1791            log->Printf("Examining %s, DeclForGlobalValue returns %p",
1792                        global_name.c_str(),
1793                        DeclForGlobal(global));
1794
1795        if (global_name.find("OBJC_IVAR") == 0)
1796        {
1797            if (!HandleSymbol(global))
1798            {
1799                if (m_error_stream)
1800                    m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1801
1802                return false;
1803            }
1804        }
1805        else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1806        {
1807            if (!HandleObjCClass(global))
1808            {
1809                if (m_error_stream)
1810                    m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1811
1812                return false;
1813            }
1814        }
1815        else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1816        {
1817            if (!HandleObjCClass(global))
1818            {
1819                if (m_error_stream)
1820                    m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1821
1822                return false;
1823            }
1824        }
1825        else if (DeclForGlobal(global))
1826        {
1827            if (!MaybeHandleVariable (global))
1828            {
1829                if (m_error_stream)
1830                    m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1831
1832                return false;
1833            }
1834        }
1835    }
1836
1837    return true;
1838}
1839
1840bool
1841IRForTarget::ReplaceStrings ()
1842{
1843    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1844
1845    typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1846
1847    OffsetsTy offsets;
1848
1849    for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1850         gi != ge;
1851         ++gi)
1852    {
1853        GlobalVariable *gv = gi;
1854
1855        if (!gv->hasInitializer())
1856            continue;
1857
1858        Constant *gc = gv->getInitializer();
1859
1860        std::string str;
1861
1862        if (gc->isNullValue())
1863        {
1864            Type *gc_type = gc->getType();
1865
1866            ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1867
1868            if (!gc_array_type)
1869                continue;
1870
1871            Type *gc_element_type = gc_array_type->getElementType();
1872
1873            IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1874
1875            if (gc_integer_type->getBitWidth() != 8)
1876                continue;
1877
1878            str = "";
1879        }
1880        else
1881        {
1882            ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
1883
1884            if (!gc_array)
1885                continue;
1886
1887            if (!gc_array->isCString())
1888                continue;
1889
1890            if (log)
1891                log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1892
1893            str = gc_array->getAsString();
1894        }
1895
1896        offsets[gv] = m_data_allocator.GetStream().GetSize();
1897
1898        m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
1899    }
1900
1901    Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
1902
1903    for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1904         oi != oe;
1905         ++oi)
1906    {
1907        GlobalVariable *gv = oi->first;
1908        size_t offset = oi->second;
1909
1910        Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1911
1912        if (log)
1913            log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1914
1915        for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1916             ui != ue;
1917             ++ui)
1918        {
1919            if (log)
1920                log->Printf("Found use %s", PrintValue(*ui).c_str());
1921
1922            ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1923            StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1924
1925            if (const_expr)
1926            {
1927                if (const_expr->getOpcode() != Instruction::GetElementPtr)
1928                {
1929                    if (log)
1930                        log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1931
1932                    return false;
1933                }
1934
1935                Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1936                Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1937
1938                const_expr->replaceAllUsesWith(new_gep);
1939            }
1940            else if (store_inst)
1941            {
1942                Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1943
1944                store_inst->setOperand(0, bit_cast);
1945            }
1946            else
1947            {
1948                if (log)
1949                    log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1950
1951                return false;
1952            }
1953        }
1954
1955        gv->eraseFromParent();
1956    }
1957
1958    return true;
1959}
1960
1961bool
1962IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1963{
1964    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1965
1966    typedef SmallVector <Value*, 2> ConstantList;
1967    typedef SmallVector <llvm::Instruction*, 2> UserList;
1968    typedef ConstantList::iterator ConstantIterator;
1969    typedef UserList::iterator UserIterator;
1970
1971    ConstantList static_constants;
1972    UserList static_users;
1973
1974    for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1975         ii != ie;
1976         ++ii)
1977    {
1978        llvm::Instruction &inst = *ii;
1979
1980        for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1981             oi != oe;
1982             ++oi)
1983        {
1984            Value *operand_val = oi->get();
1985
1986            ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1987
1988            if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
1989            {
1990                static_constants.push_back(operand_val);
1991                static_users.push_back(ii);
1992            }
1993        }
1994    }
1995
1996    ConstantIterator constant_iter;
1997    UserIterator user_iter;
1998
1999    for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2000         constant_iter != static_constants.end();
2001         ++constant_iter, ++user_iter)
2002    {
2003        Value *operand_val = *constant_iter;
2004        llvm::Instruction *inst = *user_iter;
2005
2006        ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2007
2008        if (operand_constant_fp)
2009        {
2010            Type *operand_type = operand_constant_fp->getType();
2011
2012            APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2013            APInt operand_apint = operand_apfloat.bitcastToAPInt();
2014
2015            const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2016            size_t operand_data_size = operand_apint.getBitWidth() / 8;
2017
2018            if (log)
2019            {
2020                std::string s;
2021                raw_string_ostream ss(s);
2022                for (size_t index = 0;
2023                     index < operand_data_size;
2024                     ++index)
2025                {
2026                    ss << (uint32_t)operand_raw_data[index];
2027                    ss << " ";
2028                }
2029                ss.flush();
2030
2031                log->Printf("Found ConstantFP with size %zu and raw data %s", operand_data_size, s.c_str());
2032            }
2033
2034            lldb_private::DataBufferHeap data(operand_data_size, 0);
2035
2036            if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
2037            {
2038                uint8_t *data_bytes = data.GetBytes();
2039
2040                for (size_t index = 0;
2041                     index < operand_data_size;
2042                     ++index)
2043                {
2044                    data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2045                }
2046            }
2047            else
2048            {
2049                memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2050            }
2051
2052            uint64_t offset = m_data_allocator.GetStream().GetSize();
2053
2054            size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2055
2056            const size_t mask = (align - 1);
2057            uint64_t aligned_offset = (offset + mask) & ~mask;
2058            m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
2059            offset = aligned_offset;
2060
2061            m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
2062
2063            llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
2064
2065            Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
2066
2067            llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2068
2069            operand_constant_fp->replaceAllUsesWith(fp_load);
2070        }
2071    }
2072
2073    return true;
2074}
2075
2076static bool isGuardVariableRef(Value *V)
2077{
2078    Constant *Old = NULL;
2079
2080    if (!(Old = dyn_cast<Constant>(V)))
2081        return false;
2082
2083    ConstantExpr *CE = NULL;
2084
2085    if ((CE = dyn_cast<ConstantExpr>(V)))
2086    {
2087        if (CE->getOpcode() != Instruction::BitCast)
2088            return false;
2089
2090        Old = CE->getOperand(0);
2091    }
2092
2093    GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
2094
2095    if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2096        return false;
2097
2098    return true;
2099}
2100
2101void
2102IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
2103{
2104    Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
2105
2106    Value::use_iterator ui;
2107
2108    for (ui = guard_load->use_begin();
2109         ui != guard_load->use_end();
2110         ++ui)
2111    {
2112        if (isa<Constant>(*ui))
2113        {
2114            // do nothing for the moment
2115        }
2116        else
2117        {
2118            ui->replaceUsesOfWith(guard_load, zero);
2119        }
2120    }
2121
2122    guard_load->eraseFromParent();
2123}
2124
2125static void ExciseGuardStore(Instruction* guard_store)
2126{
2127    guard_store->eraseFromParent();
2128}
2129
2130bool
2131IRForTarget::RemoveGuards(BasicBlock &basic_block)
2132{
2133    ///////////////////////////////////////////////////////
2134    // Eliminate any reference to guard variables found.
2135    //
2136
2137    BasicBlock::iterator ii;
2138
2139    typedef SmallVector <Instruction*, 2> InstrList;
2140    typedef InstrList::iterator InstrIterator;
2141
2142    InstrList guard_loads;
2143    InstrList guard_stores;
2144
2145    for (ii = basic_block.begin();
2146         ii != basic_block.end();
2147         ++ii)
2148    {
2149        Instruction &inst = *ii;
2150
2151        if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2152            if (isGuardVariableRef(load->getPointerOperand()))
2153                guard_loads.push_back(&inst);
2154
2155        if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2156            if (isGuardVariableRef(store->getPointerOperand()))
2157                guard_stores.push_back(&inst);
2158    }
2159
2160    InstrIterator iter;
2161
2162    for (iter = guard_loads.begin();
2163         iter != guard_loads.end();
2164         ++iter)
2165        TurnGuardLoadIntoZero(*iter);
2166
2167    for (iter = guard_stores.begin();
2168         iter != guard_stores.end();
2169         ++iter)
2170        ExciseGuardStore(*iter);
2171
2172    return true;
2173}
2174
2175// This function does not report errors; its callers are responsible.
2176bool
2177IRForTarget::UnfoldConstant(Constant *old_constant,
2178                            FunctionValueCache &value_maker,
2179                            FunctionValueCache &entry_instruction_finder)
2180{
2181    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2182
2183    Value::use_iterator ui;
2184
2185    SmallVector<User*, 16> users;
2186
2187    // We do this because the use list might change, invalidating our iterator.
2188    // Much better to keep a work list ourselves.
2189    for (ui = old_constant->use_begin();
2190         ui != old_constant->use_end();
2191         ++ui)
2192        users.push_back(*ui);
2193
2194    for (size_t i = 0;
2195         i < users.size();
2196         ++i)
2197    {
2198        User *user = users[i];
2199
2200        if (Constant *constant = dyn_cast<Constant>(user))
2201        {
2202            // synthesize a new non-constant equivalent of the constant
2203
2204            if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2205            {
2206                switch (constant_expr->getOpcode())
2207                {
2208                default:
2209                    if (log)
2210                        log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
2211                    return false;
2212                case Instruction::BitCast:
2213                    {
2214                        FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2215                            // UnaryExpr
2216                            //   OperandList[0] is value
2217
2218                            if (constant_expr->getOperand(0) != old_constant)
2219                                return constant_expr;
2220
2221                            return new BitCastInst(value_maker.GetValue(function),
2222                                                   constant_expr->getType(),
2223                                                   "",
2224                                                   llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2225                        });
2226
2227                        if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2228                            return false;
2229                    }
2230                    break;
2231                case Instruction::GetElementPtr:
2232                    {
2233                        // GetElementPtrConstantExpr
2234                        //   OperandList[0] is base
2235                        //   OperandList[1]... are indices
2236
2237                        FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2238                            Value *ptr = constant_expr->getOperand(0);
2239
2240                            if (ptr == old_constant)
2241                                ptr = value_maker.GetValue(function);
2242
2243                            std::vector<Value*> index_vector;
2244
2245                            unsigned operand_index;
2246                            unsigned num_operands = constant_expr->getNumOperands();
2247
2248                            for (operand_index = 1;
2249                                 operand_index < num_operands;
2250                                 ++operand_index)
2251                            {
2252                                Value *operand = constant_expr->getOperand(operand_index);
2253
2254                                if (operand == old_constant)
2255                                    operand = value_maker.GetValue(function);
2256
2257                                index_vector.push_back(operand);
2258                            }
2259
2260                            ArrayRef <Value*> indices(index_vector);
2261
2262                            return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2263                        });
2264
2265                        if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2266                            return false;
2267                    }
2268                    break;
2269                }
2270            }
2271            else
2272            {
2273                if (log)
2274                    log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
2275                return false;
2276            }
2277        }
2278        else
2279        {
2280            if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2281            {
2282                inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2283            }
2284            else
2285            {
2286                if (log)
2287                    log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2288                return false;
2289            }
2290        }
2291    }
2292
2293    if (!isa<GlobalValue>(old_constant))
2294    {
2295        old_constant->destroyConstant();
2296    }
2297
2298    return true;
2299}
2300
2301bool
2302IRForTarget::ReplaceVariables (Function &llvm_function)
2303{
2304    if (!m_resolve_vars)
2305        return true;
2306
2307    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2308
2309    m_decl_map->DoStructLayout();
2310
2311    if (log)
2312        log->Printf("Element arrangement:");
2313
2314    uint32_t num_elements;
2315    uint32_t element_index;
2316
2317    size_t size;
2318    off_t alignment;
2319
2320    if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2321        return false;
2322
2323    Function::arg_iterator iter(llvm_function.getArgumentList().begin());
2324
2325    if (iter == llvm_function.getArgumentList().end())
2326    {
2327        if (m_error_stream)
2328            m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2329
2330        return false;
2331    }
2332
2333    Argument *argument = iter;
2334
2335    if (argument->getName().equals("this"))
2336    {
2337        ++iter;
2338
2339        if (iter == llvm_function.getArgumentList().end())
2340        {
2341            if (m_error_stream)
2342                m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2343
2344            return false;
2345        }
2346
2347        argument = iter;
2348    }
2349    else if (argument->getName().equals("self"))
2350    {
2351        ++iter;
2352
2353        if (iter == llvm_function.getArgumentList().end())
2354        {
2355            if (m_error_stream)
2356                m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2357
2358            return false;
2359        }
2360
2361        if (!iter->getName().equals("_cmd"))
2362        {
2363            if (m_error_stream)
2364                m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2365
2366            return false;
2367        }
2368
2369        ++iter;
2370
2371        if (iter == llvm_function.getArgumentList().end())
2372        {
2373            if (m_error_stream)
2374                m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2375
2376            return false;
2377        }
2378
2379        argument = iter;
2380    }
2381
2382    if (!argument->getName().equals("$__lldb_arg"))
2383    {
2384        if (m_error_stream)
2385            m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2386
2387        return false;
2388    }
2389
2390    if (log)
2391        log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
2392
2393    BasicBlock &entry_block(llvm_function.getEntryBlock());
2394    Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
2395
2396    if (!FirstEntryInstruction)
2397    {
2398        if (m_error_stream)
2399            m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2400
2401        return false;
2402    }
2403
2404    LLVMContext &context(m_module->getContext());
2405    IntegerType *offset_type(Type::getInt32Ty(context));
2406
2407    if (!offset_type)
2408    {
2409        if (m_error_stream)
2410            m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2411
2412        return false;
2413    }
2414
2415    for (element_index = 0; element_index < num_elements; ++element_index)
2416    {
2417        const clang::NamedDecl *decl = NULL;
2418        Value *value = NULL;
2419        off_t offset;
2420        lldb_private::ConstString name;
2421
2422        if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
2423        {
2424            if (m_error_stream)
2425                m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2426
2427            return false;
2428        }
2429
2430        if (log)
2431            log->Printf("  \"%s\" (\"%s\") placed at %" PRId64,
2432                        name.GetCString(),
2433                        decl->getNameAsString().c_str(),
2434                        offset);
2435
2436        if (value)
2437        {
2438            if (log)
2439                log->Printf("    Replacing [%s]", PrintValue(value).c_str());
2440
2441            FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2442                // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2443                // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2444                // entry in order to produce the static variable that the AST thinks it is accessing.
2445
2446                llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
2447
2448                ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2449                GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2450                                                                               offset_int,
2451                                                                               "",
2452                                                                               entry_instruction);
2453
2454                if (name == m_result_name && !m_result_is_pointer)
2455                {
2456                    BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2457                                                            value->getType()->getPointerTo(),
2458                                                            "",
2459                                                            entry_instruction);
2460
2461                    LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2462
2463                    return load;
2464                }
2465                else
2466                {
2467                    BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2468
2469                    return bit_cast;
2470                }
2471            });
2472
2473            if (Constant *constant = dyn_cast<Constant>(value))
2474            {
2475                UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2476            }
2477            else if (Instruction *instruction = dyn_cast<Instruction>(value))
2478            {
2479                value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2480            }
2481            else
2482            {
2483                if (log)
2484                    log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2485                return false;
2486            }
2487
2488            if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2489                var->eraseFromParent();
2490        }
2491    }
2492
2493    if (log)
2494        log->Printf("Total structure [align %" PRId64 ", size %zu]", alignment, size);
2495
2496    return true;
2497}
2498
2499llvm::Constant *
2500IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
2501{
2502    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2503                                             (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
2504
2505    llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
2506
2507    llvm::Constant *offset_array[1];
2508
2509    offset_array[0] = offset_int;
2510
2511    llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2512
2513    llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
2514    llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2515
2516    return reloc_getbitcast;
2517}
2518
2519bool
2520IRForTarget::CompleteDataAllocation ()
2521{
2522    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2523
2524    if (!m_data_allocator.GetStream().GetSize())
2525        return true;
2526
2527    lldb::addr_t allocation = m_data_allocator.Allocate();
2528
2529    if (log)
2530    {
2531        if (allocation)
2532            log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2533        else
2534            log->Printf("Failed to allocate static data");
2535    }
2536
2537    if (!allocation || allocation == LLDB_INVALID_ADDRESS)
2538        return false;
2539
2540    IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2541                                             (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
2542
2543    Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2544    Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2545
2546    m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2547
2548    m_reloc_placeholder->eraseFromParent();
2549
2550    return true;
2551}
2552
2553bool
2554IRForTarget::StripAllGVs (Module &llvm_module)
2555{
2556    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2557    std::vector<GlobalVariable *> global_vars;
2558    std::set<GlobalVariable *>erased_vars;
2559
2560    bool erased = true;
2561
2562    while (erased)
2563    {
2564        erased = false;
2565
2566        for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2567             gi != ge;
2568             ++gi)
2569        {
2570            GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2571
2572            global_var->removeDeadConstantUsers();
2573
2574            if (global_var->use_empty())
2575            {
2576                if (log)
2577                    log->Printf("Did remove %s",
2578                                PrintValue(global_var).c_str());
2579                global_var->eraseFromParent();
2580                erased = true;
2581                break;
2582            }
2583        }
2584    }
2585
2586    for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2587         gi != ge;
2588         ++gi)
2589    {
2590        GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2591
2592        GlobalValue::use_iterator ui = global_var->use_begin();
2593
2594        if (log)
2595            log->Printf("Couldn't remove %s because of %s",
2596                        PrintValue(global_var).c_str(),
2597                        PrintValue(*ui).c_str());
2598    }
2599
2600    return true;
2601}
2602
2603bool
2604IRForTarget::runOnModule (Module &llvm_module)
2605{
2606    lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2607
2608    m_module = &llvm_module;
2609    m_target_data.reset(new DataLayout(m_module));
2610
2611    if (log)
2612    {
2613        std::string s;
2614        raw_string_ostream oss(s);
2615
2616        m_module->print(oss, NULL);
2617
2618        oss.flush();
2619
2620        log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2621    }
2622
2623    Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2624
2625    if (!main_function)
2626    {
2627        if (log)
2628            log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2629
2630        if (m_error_stream)
2631            m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2632
2633        return false;
2634    }
2635
2636    if (!FixFunctionLinkage (*main_function))
2637    {
2638        if (log)
2639            log->Printf("Couldn't fix the linkage for the function");
2640
2641        return false;
2642    }
2643
2644    llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
2645
2646    m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2647                                                   intptr_ty,
2648                                                   false /* IsConstant */,
2649                                                   GlobalVariable::InternalLinkage,
2650                                                   Constant::getNullValue(intptr_ty),
2651                                                   "reloc_placeholder",
2652                                                   NULL /* InsertBefore */,
2653                                                   GlobalVariable::NotThreadLocal /* ThreadLocal */,
2654                                                   0 /* AddressSpace */);
2655
2656    ////////////////////////////////////////////////////////////
2657    // Replace $__lldb_expr_result with a persistent variable
2658    //
2659
2660    if (!CreateResultVariable(*main_function))
2661    {
2662        if (log)
2663            log->Printf("CreateResultVariable() failed");
2664
2665        // CreateResultVariable() reports its own errors, so we don't do so here
2666
2667        return false;
2668    }
2669
2670    if (log && log->GetVerbose())
2671    {
2672        std::string s;
2673        raw_string_ostream oss(s);
2674
2675        m_module->print(oss, NULL);
2676
2677        oss.flush();
2678
2679        log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2680    }
2681
2682    for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2683         fi != fe;
2684         ++fi)
2685    {
2686        llvm::Function *function = fi;
2687
2688        if (function->begin() == function->end())
2689            continue;
2690
2691        Function::iterator bbi;
2692
2693        for (bbi = function->begin();
2694             bbi != function->end();
2695             ++bbi)
2696        {
2697            if (!RemoveGuards(*bbi))
2698            {
2699                if (log)
2700                    log->Printf("RemoveGuards() failed");
2701
2702                // RemoveGuards() reports its own errors, so we don't do so here
2703
2704                return false;
2705            }
2706
2707            if (!RewritePersistentAllocs(*bbi))
2708            {
2709                if (log)
2710                    log->Printf("RewritePersistentAllocs() failed");
2711
2712                // RewritePersistentAllocs() reports its own errors, so we don't do so here
2713
2714                return false;
2715            }
2716
2717            if (!RemoveCXAAtExit(*bbi))
2718            {
2719                if (log)
2720                    log->Printf("RemoveCXAAtExit() failed");
2721
2722                // RemoveCXAAtExit() reports its own errors, so we don't do so here
2723
2724                return false;
2725            }
2726        }
2727    }
2728
2729    ///////////////////////////////////////////////////////////////////////////////
2730    // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2731    //
2732
2733    if (!RewriteObjCConstStrings())
2734    {
2735        if (log)
2736            log->Printf("RewriteObjCConstStrings() failed");
2737
2738        // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2739
2740        return false;
2741    }
2742
2743    ///////////////////////////////
2744    // Resolve function pointers
2745    //
2746
2747    if (!ResolveFunctionPointers(llvm_module))
2748    {
2749        if (log)
2750            log->Printf("ResolveFunctionPointers() failed");
2751
2752        // ResolveFunctionPointers() reports its own errors, so we don't do so here
2753
2754        return false;
2755    }
2756
2757    for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2758         fi != fe;
2759         ++fi)
2760    {
2761        llvm::Function *function = fi;
2762
2763        for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2764             bbi != bbe;
2765             ++bbi)
2766        {
2767            if (!RewriteObjCSelectors(*bbi))
2768            {
2769                if (log)
2770                    log->Printf("RewriteObjCSelectors() failed");
2771
2772                // RewriteObjCSelectors() reports its own errors, so we don't do so here
2773
2774                return false;
2775            }
2776        }
2777    }
2778
2779    for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2780         fi != fe;
2781         ++fi)
2782    {
2783        llvm::Function *function = fi;
2784
2785        for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2786             bbi != bbe;
2787             ++bbi)
2788        {
2789            if (!ResolveCalls(*bbi))
2790            {
2791                if (log)
2792                    log->Printf("ResolveCalls() failed");
2793
2794                // ResolveCalls() reports its own errors, so we don't do so here
2795
2796                return false;
2797            }
2798
2799            if (!ReplaceStaticLiterals(*bbi))
2800            {
2801                if (log)
2802                    log->Printf("ReplaceStaticLiterals() failed");
2803
2804                return false;
2805            }
2806        }
2807    }
2808
2809    ////////////////////////////////////////////////////////////////////////
2810    // Run function-level passes that only make sense on the main function
2811    //
2812
2813    if (!ResolveExternals(*main_function))
2814    {
2815        if (log)
2816            log->Printf("ResolveExternals() failed");
2817
2818        // ResolveExternals() reports its own errors, so we don't do so here
2819
2820        return false;
2821    }
2822
2823    if (!ReplaceVariables(*main_function))
2824    {
2825        if (log)
2826            log->Printf("ReplaceVariables() failed");
2827
2828        // ReplaceVariables() reports its own errors, so we don't do so here
2829
2830        return false;
2831    }
2832
2833    if (!ReplaceStrings())
2834    {
2835        if (log)
2836            log->Printf("ReplaceStrings() failed");
2837
2838        return false;
2839    }
2840
2841    if (!CompleteDataAllocation())
2842    {
2843        if (log)
2844            log->Printf("CompleteDataAllocation() failed");
2845
2846        return false;
2847    }
2848
2849    if (!StripAllGVs(llvm_module))
2850    {
2851        if (log)
2852            log->Printf("StripAllGVs() failed");
2853    }
2854
2855    if (log && log->GetVerbose())
2856    {
2857        std::string s;
2858        raw_string_ostream oss(s);
2859
2860        m_module->print(oss, NULL);
2861
2862        oss.flush();
2863
2864        log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2865    }
2866
2867    return true;
2868}
2869
2870void
2871IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2872{
2873}
2874
2875PassManagerType
2876IRForTarget::getPotentialPassManagerType() const
2877{
2878    return PMT_ModulePassManager;
2879}
2880