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