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