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