1 //===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Expression/IRForTarget.h"
12 #include "llvm/Support/raw_ostream.h"
13 #include "llvm/IR/Constants.h"
14 #include "llvm/IR/DataLayout.h"
15 #include "llvm/IR/InstrTypes.h"
16 #include "llvm/IR/Instructions.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/IR/ValueSymbolTable.h"
23 #include "clang/AST/ASTContext.h"
25 #include "lldb/Core/dwarf.h"
26 #include "lldb/Core/ConstString.h"
27 #include "lldb/Core/DataBufferHeap.h"
28 #include "lldb/Core/Log.h"
29 #include "lldb/Core/Scalar.h"
30 #include "lldb/Core/StreamString.h"
31 #include "lldb/Expression/ClangExpressionDeclMap.h"
32 #include "lldb/Expression/IRExecutionUnit.h"
33 #include "lldb/Expression/IRInterpreter.h"
34 #include "lldb/Host/Endian.h"
35 #include "lldb/Symbol/ClangASTContext.h"
36 #include "lldb/Symbol/ClangASTType.h"
44 IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45 m_execution_unit(execution_unit),
46 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
47 m_allocation(LLDB_INVALID_ADDRESS)
51 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
57 IRForTarget::FunctionValueCache::~FunctionValueCache()
61 llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
63 if (!m_values.count(function))
65 llvm::Value *ret = m_maker(function);
66 m_values[function] = ret;
69 return m_values[function];
72 lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
74 lldb_private::Error err;
76 if (m_allocation != LLDB_INVALID_ADDRESS)
78 m_execution_unit.FreeNow(m_allocation);
79 m_allocation = LLDB_INVALID_ADDRESS;
82 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
87 static llvm::Value *FindEntryInstruction (llvm::Function *function)
89 if (function->empty())
92 return function->getEntryBlock().getFirstNonPHIOrDbg();
95 IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
97 lldb_private::IRExecutionUnit &execution_unit,
98 lldb_private::Stream *error_stream,
99 const char *func_name) :
101 m_resolve_vars(resolve_vars),
102 m_func_name(func_name),
104 m_decl_map(decl_map),
105 m_data_allocator(execution_unit),
106 m_CFStringCreateWithBytes(NULL),
107 m_sel_registerName(NULL),
109 m_error_stream(error_stream),
110 m_result_store(NULL),
111 m_result_is_pointer(false),
112 m_reloc_placeholder(NULL),
113 m_entry_instruction_finder (FindEntryInstruction)
117 /* Handy utility functions used at several places in the code */
120 PrintValue(const Value *value, bool truncate = false)
125 raw_string_ostream rso(s);
129 s.resize(s.length() - 1);
135 PrintType(const llvm::Type *type, bool truncate = false)
138 raw_string_ostream rso(s);
142 s.resize(s.length() - 1);
146 IRForTarget::~IRForTarget()
151 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
153 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
155 std::string name = llvm_function.getName().str();
161 IRForTarget::GetFunctionAddress (llvm::Function *fun,
163 lldb_private::ConstString &name,
164 Constant **&value_ptr)
166 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
168 fun_addr = LLDB_INVALID_ADDRESS;
172 if (fun->isIntrinsic())
174 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
176 switch (intrinsic_id)
180 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
183 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
186 case Intrinsic::memcpy:
188 static lldb_private::ConstString g_memcpy_str ("memcpy");
192 case Intrinsic::memset:
194 static lldb_private::ConstString g_memset_str ("memset");
201 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
205 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
208 // Find the address of the function.
210 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
214 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
216 lldb_private::ConstString altnernate_name;
217 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
220 // Check for an alternate mangling for "std::basic_string<char>"
221 // that is part of the itanium C++ name mangling scheme
222 const char *name_cstr = name.GetCString();
223 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
225 std::string alternate_mangling("_ZNKSs");
226 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
227 altnernate_name.SetCString(alternate_mangling.c_str());
228 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
234 lldb_private::Mangled mangled_name(name);
235 lldb_private::Mangled alt_mangled_name(altnernate_name);
238 if (alt_mangled_name)
239 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
240 mangled_name.GetName().GetCString(),
241 alt_mangled_name.GetName().GetCString());
243 log->Printf("Function \"%s\" had no address",
244 mangled_name.GetName().GetCString());
249 if (alt_mangled_name)
250 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
251 mangled_name.GetName().GetCString(),
252 alt_mangled_name.GetName().GetCString());
253 else if (mangled_name.GetMangledName())
254 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
255 mangled_name.GetName().GetCString(),
256 mangled_name.GetMangledName().GetCString());
258 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
259 mangled_name.GetName().GetCString());
267 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
270 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
273 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
280 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
286 IRForTarget::BuildFunctionPointer (llvm::Type *type,
289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
290 Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false);
291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
295 IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
299 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
305 if (Instruction *user_inst = dyn_cast<Instruction>(user))
307 MDString* md_name = MDString::get(context, StringRef(name));
309 MDNode *metadata = MDNode::get(context, md_name);
311 user_inst->setMetadata("lldb.call.realName", metadata);
315 RegisterFunctionMetadata (context, user, name);
321 IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
323 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
325 for (llvm::Module::iterator fi = llvm_module.begin();
326 fi != llvm_module.end();
331 bool is_decl = fun->isDeclaration();
334 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
339 if (fun->hasNUses(0))
342 uint64_t addr = LLDB_INVALID_ADDRESS;
343 lldb_private::ConstString name;
344 Constant **value_ptr = NULL;
346 if (!GetFunctionAddress(fun,
350 return false; // GetFunctionAddress reports its own errors
352 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
354 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
359 // If we are replacing a function with the nobuiltin attribute, it may
360 // be called with the builtin attribute on call sites. Remove any such
361 // attributes since it's illegal to have a builtin call to something
362 // other than a nobuiltin function.
363 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
364 llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
366 for (auto u = fun->use_begin(), e = fun->use_end(); u != e; ++u) {
367 if (auto call = dyn_cast<CallInst>(*u)) {
368 call->removeAttribute(AttributeSet::FunctionIndex, builtin);
373 fun->replaceAllUsesWith(value);
381 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
383 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
388 unsigned num_nodes = named_metadata->getNumOperands();
392 node_index < num_nodes;
395 MDNode *metadata_node = named_metadata->getOperand(node_index);
400 if (metadata_node->getNumOperands() != 2)
403 if (metadata_node->getOperand(0) != global_val)
406 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
411 uintptr_t ptr = constant_int->getZExtValue();
413 return reinterpret_cast<clang::NamedDecl *>(ptr);
420 IRForTarget::DeclForGlobal (GlobalValue *global_val)
422 return DeclForGlobal(global_val, m_module);
426 IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
428 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
433 // Find the result variable. If it doesn't exist, we can give up right here.
435 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
437 std::string result_name_str;
438 const char *result_name = NULL;
440 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
444 result_name_str = vi->first().str();
445 const char *value_name = result_name_str.c_str();
447 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
448 strncmp(value_name, "_ZGV", 4))
450 result_name = value_name;
451 m_result_is_pointer = true;
455 if (strstr(value_name, "$__lldb_expr_result") &&
456 strncmp(value_name, "_ZGV", 4))
458 result_name = value_name;
459 m_result_is_pointer = false;
467 log->PutCString("Couldn't find result variable");
473 log->Printf("Result name: \"%s\"", result_name);
475 Value *result_value = m_module->getNamedValue(result_name);
480 log->PutCString("Result variable had no data");
483 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
489 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
491 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
496 log->PutCString("Result variable isn't a GlobalVariable");
499 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
504 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
508 log->PutCString("Result variable doesn't have a corresponding Decl");
511 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
518 std::string decl_desc_str;
519 raw_string_ostream decl_desc_stream(decl_desc_str);
520 result_decl->print(decl_desc_stream);
521 decl_desc_stream.flush();
523 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
526 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
530 log->PutCString("Result variable Decl isn't a VarDecl");
533 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
538 // Get the next available result name from m_decl_map and create the persistent
541 // If the result is an Lvalue, it is emitted as a pointer; see
542 // ASTResultSynthesizer::SynthesizeBodyResult.
543 if (m_result_is_pointer)
545 clang::QualType pointer_qual_type = result_var->getType();
546 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
548 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
549 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
551 if (pointer_pointertype)
553 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
555 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
556 &result_decl->getASTContext());
558 else if (pointer_objcobjpointertype)
560 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
562 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
563 &result_decl->getASTContext());
568 log->PutCString("Expected result to have pointer type, but it did not");
571 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
578 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
579 &result_decl->getASTContext());
582 if (m_result_type.GetBitSize() == 0)
584 lldb_private::StreamString type_desc_stream;
585 m_result_type.DumpTypeDescription(&type_desc_stream);
588 log->Printf("Result type has size 0");
591 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
592 type_desc_stream.GetData());
598 lldb_private::StreamString type_desc_stream;
599 m_result_type.DumpTypeDescription(&type_desc_stream);
601 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
604 m_result_name = lldb_private::ConstString("$RESULT_NAME");
607 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
608 m_result_name.GetCString(),
609 m_result_type.GetByteSize());
611 // Construct a new result global and set up its metadata
613 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
614 result_global->getType()->getElementType(),
615 false, /* not constant */
616 GlobalValue::ExternalLinkage,
617 NULL, /* no initializer */
618 m_result_name.GetCString ());
620 // It's too late in compilation to create a new VarDecl for this, but we don't
621 // need to. We point the metadata at the old VarDecl. This creates an odd
622 // anomaly: a variable with a Value whose name is something like $0 and a
623 // Decl whose name is $__lldb_expr_result. This condition is handled in
624 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
627 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
628 reinterpret_cast<uint64_t>(result_decl),
631 llvm::Value* values[2];
632 values[0] = new_result_global;
633 values[1] = new_constant_int;
635 ArrayRef<Value*> value_ref(values, 2);
637 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
638 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
639 named_metadata->addOperand(persistent_global_md);
642 log->Printf("Replacing \"%s\" with \"%s\"",
643 PrintValue(result_global).c_str(),
644 PrintValue(new_result_global).c_str());
646 if (result_global->hasNUses(0))
648 // We need to synthesize a store for this variable, because otherwise
649 // there's nothing to put into its equivalent persistent variable.
651 BasicBlock &entry_block(llvm_function.getEntryBlock());
652 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
654 if (!first_entry_instruction)
657 if (!result_global->hasInitializer())
660 log->Printf("Couldn't find initializer for unused variable");
663 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
668 Constant *initializer = result_global->getInitializer();
670 StoreInst *synthesized_store = new StoreInst(initializer,
672 first_entry_instruction);
675 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
679 result_global->replaceAllUsesWith(new_result_global);
682 if (!m_decl_map->AddPersistentVariable(result_decl,
686 m_result_is_pointer))
689 result_global->eraseFromParent();
695 static void DebugUsers(Log *log, Value *value, uint8_t depth)
703 log->Printf(" <Begin %d users>", value->getNumUses());
705 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
710 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
711 DebugUsers(log, *ui, depth);
715 log->Printf(" <End uses>");
720 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
721 llvm::GlobalVariable *cstr)
723 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
725 Type *ns_str_ty = ns_str->getType();
727 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
728 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
729 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
731 if (!m_CFStringCreateWithBytes)
733 lldb::addr_t CFStringCreateWithBytes_addr;
735 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
737 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
740 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
743 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
749 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
751 // Build the function type:
753 // CFStringRef CFStringCreateWithBytes (
754 // CFAllocatorRef alloc,
755 // const UInt8 *bytes,
757 // CFStringEncoding encoding,
758 // Boolean isExternalRepresentation
761 // We make the following substitutions:
763 // CFStringRef -> i8*
764 // CFAllocatorRef -> i8*
766 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
767 // CFStringEncoding -> i32
770 Type *arg_type_array[5];
772 arg_type_array[0] = i8_ptr_ty;
773 arg_type_array[1] = i8_ptr_ty;
774 arg_type_array[2] = m_intptr_ty;
775 arg_type_array[3] = i32_ty;
776 arg_type_array[4] = i8_ty;
778 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
780 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
782 // Build the constant containing the pointer to the function
783 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
784 Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
785 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
788 ConstantDataSequential *string_array = NULL;
791 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
793 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
794 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
795 Constant *numBytes_arg = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
796 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
797 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
799 Value *argument_array[5];
801 argument_array[0] = alloc_arg;
802 argument_array[1] = bytes_arg;
803 argument_array[2] = numBytes_arg;
804 argument_array[3] = encoding_arg;
805 argument_array[4] = isExternal_arg;
807 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
809 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
810 return CallInst::Create(m_CFStringCreateWithBytes,
812 "CFStringCreateWithBytes",
813 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
816 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
819 log->PutCString("Couldn't replace the NSString with the result of the call");
822 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
827 ns_str->eraseFromParent();
833 IRForTarget::RewriteObjCConstStrings()
835 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
837 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
839 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
843 std::string value_name = vi->first().str();
844 const char *value_name_cstr = value_name.c_str();
846 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
848 Value *nsstring_value = vi->second;
850 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
852 if (!nsstring_global)
855 log->PutCString("NSString variable is not a GlobalVariable");
858 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
863 if (!nsstring_global->hasInitializer())
866 log->PutCString("NSString variable does not have an initializer");
869 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
874 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
876 if (!nsstring_struct)
879 log->PutCString("NSString variable's initializer is not a ConstantStruct");
882 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
887 // We expect the following structure:
896 if (nsstring_struct->getNumOperands() != 4)
899 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
902 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
907 Constant *nsstring_member = nsstring_struct->getOperand(2);
909 if (!nsstring_member)
912 log->PutCString("NSString initializer's str element was empty");
915 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
920 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
925 log->PutCString("NSString initializer's str element is not a ConstantExpr");
928 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
933 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
936 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
939 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
944 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
946 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
951 log->PutCString("NSString initializer's str element is not a GlobalVariable");
954 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
959 if (!cstr_global->hasInitializer())
962 log->PutCString("NSString initializer's str element does not have an initializer");
965 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
974 log->PutCString("NSString initializer's str element is not a ConstantArray");
977 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
982 if (!cstr_array->isCString())
985 log->PutCString("NSString initializer's str element is not a C string array");
988 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
994 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
999 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
1001 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
1007 if (!RewriteObjCConstString(nsstring_global, cstr_global))
1010 log->PutCString("Error rewriting the constant string");
1012 // We don't print an error message here because RewriteObjCConstString has done so for us.
1019 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1023 std::string value_name = vi->first().str();
1024 const char *value_name_cstr = value_name.c_str();
1026 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
1028 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1033 log->PutCString("__CFConstantStringClassReference is not a global variable");
1036 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1041 gv->eraseFromParent();
1050 static bool IsObjCSelectorRef (Value *value)
1052 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
1054 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
1060 // This function does not report errors; its callers are responsible.
1062 IRForTarget::RewriteObjCSelector (Instruction* selector_load)
1064 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1066 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1071 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1073 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1074 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1076 // where %obj is the object pointer and %tmp is the selector.
1078 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1079 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
1081 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1083 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1085 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1088 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1090 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1092 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1095 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1097 if (!osr_initializer_base)
1100 // Find the string's initializer (a ConstantArray) and get the string from it
1102 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1104 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1107 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1109 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
1111 if (!omvn_initializer_array->isString())
1114 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1117 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
1119 // Construct a call to sel_registerName
1121 if (!m_sel_registerName)
1123 lldb::addr_t sel_registerName_addr;
1125 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
1126 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
1130 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
1132 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1134 // The below code would be "more correct," but in actuality what's required is uint8_t*
1135 //Type *sel_type = StructType::get(m_module->getContext());
1136 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
1137 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
1139 Type *type_array[1];
1141 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1143 ArrayRef<Type *> srN_arg_types(type_array, 1);
1145 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1147 // Build the constant containing the pointer to the function
1148 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
1149 Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
1150 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1153 Value *argument_array[1];
1155 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
1157 argument_array[0] = omvn_pointer;
1159 ArrayRef<Value *> srN_arguments(argument_array, 1);
1161 CallInst *srN_call = CallInst::Create(m_sel_registerName,
1166 // Replace the load with the call in all users
1168 selector_load->replaceAllUsesWith(srN_call);
1170 selector_load->eraseFromParent();
1176 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
1178 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1180 BasicBlock::iterator ii;
1182 typedef SmallVector <Instruction*, 2> InstrList;
1183 typedef InstrList::iterator InstrIterator;
1185 InstrList selector_loads;
1187 for (ii = basic_block.begin();
1188 ii != basic_block.end();
1191 Instruction &inst = *ii;
1193 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1194 if (IsObjCSelectorRef(load->getPointerOperand()))
1195 selector_loads.push_back(&inst);
1200 for (iter = selector_loads.begin();
1201 iter != selector_loads.end();
1204 if (!RewriteObjCSelector(*iter))
1207 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1210 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
1219 // This function does not report errors; its callers are responsible.
1221 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
1223 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1225 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1227 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1229 if (!alloc_md || !alloc_md->getNumOperands())
1232 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1237 // We attempt to register this as a new persistent variable with the DeclMap.
1239 uintptr_t ptr = constant_int->getZExtValue();
1241 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1243 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1244 &decl->getASTContext());
1246 StringRef decl_name (decl->getName());
1247 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
1248 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
1251 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
1253 false, /* not constant */
1254 GlobalValue::ExternalLinkage,
1255 NULL, /* no initializer */
1256 alloc->getName().str().c_str());
1258 // What we're going to do here is make believe this was a regular old external
1259 // variable. That means we need to make the metadata valid.
1261 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1263 llvm::Value* values[2];
1264 values[0] = persistent_global;
1265 values[1] = constant_int;
1267 ArrayRef<llvm::Value*> value_ref(values, 2);
1269 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1270 named_metadata->addOperand(persistent_global_md);
1272 // Now, since the variable is a pointer variable, we will drop in a load of that
1273 // pointer variable.
1275 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1278 log->Printf("Replacing \"%s\" with \"%s\"",
1279 PrintValue(alloc).c_str(),
1280 PrintValue(persistent_load).c_str());
1282 alloc->replaceAllUsesWith(persistent_load);
1283 alloc->eraseFromParent();
1289 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1291 if (!m_resolve_vars)
1294 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1296 BasicBlock::iterator ii;
1298 typedef SmallVector <Instruction*, 2> InstrList;
1299 typedef InstrList::iterator InstrIterator;
1301 InstrList pvar_allocs;
1303 for (ii = basic_block.begin();
1304 ii != basic_block.end();
1307 Instruction &inst = *ii;
1309 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1311 llvm::StringRef alloc_name = alloc->getName();
1313 if (alloc_name.startswith("$") &&
1314 !alloc_name.startswith("$__lldb"))
1316 if (alloc_name.find_first_of("0123456789") == 1)
1319 log->Printf("Rejecting a numeric persistent variable.");
1322 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1327 pvar_allocs.push_back(alloc);
1334 for (iter = pvar_allocs.begin();
1335 iter != pvar_allocs.end();
1338 if (!RewritePersistentAlloc(*iter))
1341 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1344 log->PutCString("Couldn't rewrite the creation of a persistent variable");
1354 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1359 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1361 if (log && log->GetVerbose())
1362 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1364 Type *initializer_type = initializer->getType();
1366 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1368 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1371 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1373 if (array_initializer->isString())
1375 std::string array_initializer_string = array_initializer->getAsString();
1376 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1380 ArrayType *array_initializer_type = array_initializer->getType();
1381 Type *array_element_type = array_initializer_type->getElementType();
1383 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1385 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1387 Value *operand_value = array_initializer->getOperand(i);
1388 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1390 if (!operand_constant)
1393 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1399 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1401 StructType *struct_initializer_type = struct_initializer->getType();
1402 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1404 for (unsigned i = 0;
1405 i < struct_initializer->getNumOperands();
1408 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1413 else if (isa<ConstantAggregateZero>(initializer))
1415 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1422 IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1424 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1427 if (global_variable == m_reloc_placeholder)
1430 uint64_t offset = m_data_allocator.GetStream().GetSize();
1432 llvm::Type *variable_type = global_variable->getType();
1434 Constant *initializer = global_variable->getInitializer();
1436 llvm::Type *initializer_type = initializer->getType();
1438 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1439 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1441 const size_t mask = (align - 1);
1442 uint64_t aligned_offset = (offset + mask) & ~mask;
1443 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
1444 offset = aligned_offset;
1446 lldb_private::DataBufferHeap data(size, '\0');
1449 if (!MaterializeInitializer(data.GetBytes(), initializer))
1452 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
1454 Constant *new_pointer = BuildRelocation(variable_type, offset);
1456 global_variable->replaceAllUsesWith(new_pointer);
1458 global_variable->eraseFromParent();
1463 // This function does not report errors; its callers are responsible.
1465 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1467 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1470 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1472 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1474 switch (constant_expr->getOpcode())
1478 case Instruction::GetElementPtr:
1479 case Instruction::BitCast:
1480 Value *s = constant_expr->getOperand(0);
1481 if (!MaybeHandleVariable(s))
1485 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1487 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1488 return MaterializeInternalVariable(global_variable);
1490 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1494 if (IsObjCSelectorRef(llvm_value_ptr))
1497 if (!global_variable->hasExternalLinkage())
1501 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1506 std::string name (named_decl->getName().str());
1508 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1509 if (value_decl == NULL)
1512 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
1514 const Type *value_type = NULL;
1518 // The $__lldb_expr_result name indicates the the return value has allocated as
1519 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1520 // accesses to this static variable need to be redirected to the result of dereferencing
1521 // a pointer that is passed in as one of the arguments.
1523 // Consequently, when reporting the size of the type, we report a pointer type pointing
1524 // to the type of $__lldb_expr_result, not the type itself.
1526 // We also do this for any user-declared persistent variables.
1527 clang_type = clang_type.GetPointerType();
1528 value_type = PointerType::get(global_variable->getType(), 0);
1532 value_type = global_variable->getType();
1535 const uint64_t value_size = clang_type.GetByteSize();
1536 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
1540 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
1542 clang_type.GetQualType().getAsString().c_str(),
1543 PrintType(value_type).c_str(),
1549 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1550 lldb_private::ConstString (name.c_str()),
1555 if (!global_variable->hasExternalLinkage())
1557 else if (HandleSymbol (global_variable))
1563 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1566 log->Printf("Function pointers aren't handled right now");
1574 // This function does not report errors; its callers are responsible.
1576 IRForTarget::HandleSymbol (Value *symbol)
1578 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1580 lldb_private::ConstString name(symbol->getName().str().c_str());
1582 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1584 if (symbol_addr == LLDB_INVALID_ADDRESS)
1587 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1593 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1595 Type *symbol_type = symbol->getType();
1597 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1599 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1602 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1604 symbol->replaceAllUsesWith(symbol_addr_ptr);
1610 IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1612 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1615 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1617 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1620 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1623 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1632 IRForTarget::HandleObjCClass(Value *classlist_reference)
1634 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1636 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1638 if (!global_variable)
1641 Constant *initializer = global_variable->getInitializer();
1646 if (!initializer->hasName())
1649 StringRef name(initializer->getName());
1650 lldb_private::ConstString name_cstr(name.str().c_str());
1651 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1654 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1656 if (class_ptr == LLDB_INVALID_ADDRESS)
1659 if (global_variable->use_begin() == global_variable->use_end())
1662 SmallVector<LoadInst *, 2> load_instructions;
1664 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1668 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1669 load_instructions.push_back(load_instruction);
1672 if (load_instructions.empty())
1675 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1677 for (LoadInst *load_instruction : load_instructions)
1679 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1681 load_instruction->replaceAllUsesWith(class_bitcast);
1683 load_instruction->eraseFromParent();
1690 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1692 BasicBlock::iterator ii;
1694 std::vector<CallInst *> calls_to_remove;
1696 for (ii = basic_block.begin();
1697 ii != basic_block.end();
1700 Instruction &inst = *ii;
1702 CallInst *call = dyn_cast<CallInst>(&inst);
1704 // MaybeHandleCallArguments handles error reporting; we are silent here
1708 bool remove = false;
1710 llvm::Function *func = call->getCalledFunction();
1712 if (func && func->getName() == "__cxa_atexit")
1715 llvm::Value *val = call->getCalledValue();
1717 if (val && val->getName() == "__cxa_atexit")
1721 calls_to_remove.push_back(call);
1724 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1728 (*ci)->eraseFromParent();
1735 IRForTarget::ResolveCalls(BasicBlock &basic_block)
1737 /////////////////////////////////////////////////////////////////////////
1738 // Prepare the current basic block for execution in the remote process
1741 BasicBlock::iterator ii;
1743 for (ii = basic_block.begin();
1744 ii != basic_block.end();
1747 Instruction &inst = *ii;
1749 CallInst *call = dyn_cast<CallInst>(&inst);
1751 // MaybeHandleCallArguments handles error reporting; we are silent here
1752 if (call && !MaybeHandleCallArguments(call))
1760 IRForTarget::ResolveExternals (Function &llvm_function)
1762 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1764 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
1771 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1776 std::string global_name = (*global).getName().str();
1779 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1780 global_name.c_str(),
1781 DeclForGlobal(global));
1783 if (global_name.find("OBJC_IVAR") == 0)
1785 if (!HandleSymbol(global))
1788 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1793 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1795 if (!HandleObjCClass(global))
1798 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1803 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1805 if (!HandleObjCClass(global))
1808 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1813 else if (DeclForGlobal(global))
1815 if (!MaybeHandleVariable (global))
1818 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1829 IRForTarget::ReplaceStrings ()
1831 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1833 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1837 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1841 GlobalVariable *gv = gi;
1843 if (!gv->hasInitializer())
1846 Constant *gc = gv->getInitializer();
1850 if (gc->isNullValue())
1852 Type *gc_type = gc->getType();
1854 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1859 Type *gc_element_type = gc_array_type->getElementType();
1861 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1863 if (gc_integer_type->getBitWidth() != 8)
1870 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
1875 if (!gc_array->isCString())
1879 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1881 str = gc_array->getAsString();
1884 offsets[gv] = m_data_allocator.GetStream().GetSize();
1886 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
1889 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
1891 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1895 GlobalVariable *gv = oi->first;
1896 size_t offset = oi->second;
1898 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1901 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1903 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1908 log->Printf("Found use %s", PrintValue(*ui).c_str());
1910 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1911 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1915 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1918 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1923 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1924 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1926 const_expr->replaceAllUsesWith(new_gep);
1928 else if (store_inst)
1930 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1932 store_inst->setOperand(0, bit_cast);
1937 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1943 gv->eraseFromParent();
1950 IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1952 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1954 typedef SmallVector <Value*, 2> ConstantList;
1955 typedef SmallVector <llvm::Instruction*, 2> UserList;
1956 typedef ConstantList::iterator ConstantIterator;
1957 typedef UserList::iterator UserIterator;
1959 ConstantList static_constants;
1960 UserList static_users;
1962 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1966 llvm::Instruction &inst = *ii;
1968 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1972 Value *operand_val = oi->get();
1974 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1976 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
1978 static_constants.push_back(operand_val);
1979 static_users.push_back(ii);
1984 ConstantIterator constant_iter;
1985 UserIterator user_iter;
1987 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1988 constant_iter != static_constants.end();
1989 ++constant_iter, ++user_iter)
1991 Value *operand_val = *constant_iter;
1992 llvm::Instruction *inst = *user_iter;
1994 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1996 if (operand_constant_fp)
1998 Type *operand_type = operand_constant_fp->getType();
2000 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2001 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2003 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2004 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2009 raw_string_ostream ss(s);
2010 for (size_t index = 0;
2011 index < operand_data_size;
2014 ss << (uint32_t)operand_raw_data[index];
2019 log->Printf("Found ConstantFP with size %zu and raw data %s", operand_data_size, s.c_str());
2022 lldb_private::DataBufferHeap data(operand_data_size, 0);
2024 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
2026 uint8_t *data_bytes = data.GetBytes();
2028 for (size_t index = 0;
2029 index < operand_data_size;
2032 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2037 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2040 uint64_t offset = m_data_allocator.GetStream().GetSize();
2042 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2044 const size_t mask = (align - 1);
2045 uint64_t aligned_offset = (offset + mask) & ~mask;
2046 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
2047 offset = aligned_offset;
2049 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
2051 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
2053 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
2055 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2057 operand_constant_fp->replaceAllUsesWith(fp_load);
2064 static bool isGuardVariableRef(Value *V)
2066 Constant *Old = NULL;
2068 if (!(Old = dyn_cast<Constant>(V)))
2071 ConstantExpr *CE = NULL;
2073 if ((CE = dyn_cast<ConstantExpr>(V)))
2075 if (CE->getOpcode() != Instruction::BitCast)
2078 Old = CE->getOperand(0);
2081 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
2083 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2090 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
2092 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
2094 Value::use_iterator ui;
2096 for (ui = guard_load->use_begin();
2097 ui != guard_load->use_end();
2100 if (isa<Constant>(*ui))
2102 // do nothing for the moment
2106 ui->replaceUsesOfWith(guard_load, zero);
2110 guard_load->eraseFromParent();
2113 static void ExciseGuardStore(Instruction* guard_store)
2115 guard_store->eraseFromParent();
2119 IRForTarget::RemoveGuards(BasicBlock &basic_block)
2121 ///////////////////////////////////////////////////////
2122 // Eliminate any reference to guard variables found.
2125 BasicBlock::iterator ii;
2127 typedef SmallVector <Instruction*, 2> InstrList;
2128 typedef InstrList::iterator InstrIterator;
2130 InstrList guard_loads;
2131 InstrList guard_stores;
2133 for (ii = basic_block.begin();
2134 ii != basic_block.end();
2137 Instruction &inst = *ii;
2139 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2140 if (isGuardVariableRef(load->getPointerOperand()))
2141 guard_loads.push_back(&inst);
2143 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2144 if (isGuardVariableRef(store->getPointerOperand()))
2145 guard_stores.push_back(&inst);
2150 for (iter = guard_loads.begin();
2151 iter != guard_loads.end();
2153 TurnGuardLoadIntoZero(*iter);
2155 for (iter = guard_stores.begin();
2156 iter != guard_stores.end();
2158 ExciseGuardStore(*iter);
2163 // This function does not report errors; its callers are responsible.
2165 IRForTarget::UnfoldConstant(Constant *old_constant,
2166 FunctionValueCache &value_maker,
2167 FunctionValueCache &entry_instruction_finder)
2169 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2171 Value::use_iterator ui;
2173 SmallVector<User*, 16> users;
2175 // We do this because the use list might change, invalidating our iterator.
2176 // Much better to keep a work list ourselves.
2177 for (ui = old_constant->use_begin();
2178 ui != old_constant->use_end();
2180 users.push_back(*ui);
2186 User *user = users[i];
2188 if (Constant *constant = dyn_cast<Constant>(user))
2190 // synthesize a new non-constant equivalent of the constant
2192 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2194 switch (constant_expr->getOpcode())
2198 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
2200 case Instruction::BitCast:
2202 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2204 // OperandList[0] is value
2206 if (constant_expr->getOperand(0) != old_constant)
2207 return constant_expr;
2209 return new BitCastInst(value_maker.GetValue(function),
2210 constant_expr->getType(),
2212 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2215 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2219 case Instruction::GetElementPtr:
2221 // GetElementPtrConstantExpr
2222 // OperandList[0] is base
2223 // OperandList[1]... are indices
2225 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2226 Value *ptr = constant_expr->getOperand(0);
2228 if (ptr == old_constant)
2229 ptr = value_maker.GetValue(function);
2231 std::vector<Value*> index_vector;
2233 unsigned operand_index;
2234 unsigned num_operands = constant_expr->getNumOperands();
2236 for (operand_index = 1;
2237 operand_index < num_operands;
2240 Value *operand = constant_expr->getOperand(operand_index);
2242 if (operand == old_constant)
2243 operand = value_maker.GetValue(function);
2245 index_vector.push_back(operand);
2248 ArrayRef <Value*> indices(index_vector);
2250 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2253 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2262 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
2268 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2270 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2275 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2281 if (!isa<GlobalValue>(old_constant))
2283 old_constant->destroyConstant();
2290 IRForTarget::ReplaceVariables (Function &llvm_function)
2292 if (!m_resolve_vars)
2295 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2297 m_decl_map->DoStructLayout();
2300 log->Printf("Element arrangement:");
2302 uint32_t num_elements;
2303 uint32_t element_index;
2308 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2311 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
2313 if (iter == llvm_function.getArgumentList().end())
2316 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2321 Argument *argument = iter;
2323 if (argument->getName().equals("this"))
2327 if (iter == llvm_function.getArgumentList().end())
2330 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2337 else if (argument->getName().equals("self"))
2341 if (iter == llvm_function.getArgumentList().end())
2344 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2349 if (!iter->getName().equals("_cmd"))
2352 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2359 if (iter == llvm_function.getArgumentList().end())
2362 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2370 if (!argument->getName().equals("$__lldb_arg"))
2373 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2379 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
2381 BasicBlock &entry_block(llvm_function.getEntryBlock());
2382 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
2384 if (!FirstEntryInstruction)
2387 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2392 LLVMContext &context(m_module->getContext());
2393 IntegerType *offset_type(Type::getInt32Ty(context));
2398 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2403 for (element_index = 0; element_index < num_elements; ++element_index)
2405 const clang::NamedDecl *decl = NULL;
2406 Value *value = NULL;
2408 lldb_private::ConstString name;
2410 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
2413 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2419 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
2421 decl->getNameAsString().c_str(),
2427 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
2429 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2430 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2431 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2432 // entry in order to produce the static variable that the AST thinks it is accessing.
2434 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
2436 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2437 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2442 if (name == m_result_name && !m_result_is_pointer)
2444 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2445 value->getType()->getPointerTo(),
2449 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2455 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2461 if (Constant *constant = dyn_cast<Constant>(value))
2463 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2465 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2467 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2472 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2476 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2477 var->eraseFromParent();
2482 log->Printf("Total structure [align %" PRId64 ", size %zu]", alignment, size);
2488 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
2490 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2492 llvm::Constant *offset_array[1];
2494 offset_array[0] = offset_int;
2496 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2498 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
2499 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2501 return reloc_getbitcast;
2505 IRForTarget::CompleteDataAllocation ()
2507 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2509 if (!m_data_allocator.GetStream().GetSize())
2512 lldb::addr_t allocation = m_data_allocator.Allocate();
2517 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2519 log->Printf("Failed to allocate static data");
2522 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
2525 Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation);
2526 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2528 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2530 m_reloc_placeholder->eraseFromParent();
2536 IRForTarget::StripAllGVs (Module &llvm_module)
2538 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2539 std::vector<GlobalVariable *> global_vars;
2540 std::set<GlobalVariable *>erased_vars;
2548 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2552 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2554 global_var->removeDeadConstantUsers();
2556 if (global_var->use_empty())
2559 log->Printf("Did remove %s",
2560 PrintValue(global_var).c_str());
2561 global_var->eraseFromParent();
2568 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2572 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2574 GlobalValue::use_iterator ui = global_var->use_begin();
2577 log->Printf("Couldn't remove %s because of %s",
2578 PrintValue(global_var).c_str(),
2579 PrintValue(*ui).c_str());
2586 IRForTarget::runOnModule (Module &llvm_module)
2588 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2590 m_module = &llvm_module;
2591 m_target_data.reset(new DataLayout(m_module));
2592 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
2597 raw_string_ostream oss(s);
2599 m_module->print(oss, NULL);
2603 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2606 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2611 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2614 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2619 if (!FixFunctionLinkage (*main_function))
2622 log->Printf("Couldn't fix the linkage for the function");
2627 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2629 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2631 false /* IsConstant */,
2632 GlobalVariable::InternalLinkage,
2633 Constant::getNullValue(int8_ty),
2634 "reloc_placeholder",
2635 NULL /* InsertBefore */,
2636 GlobalVariable::NotThreadLocal /* ThreadLocal */,
2637 0 /* AddressSpace */);
2639 ////////////////////////////////////////////////////////////
2640 // Replace $__lldb_expr_result with a persistent variable
2643 if (!CreateResultVariable(*main_function))
2646 log->Printf("CreateResultVariable() failed");
2648 // CreateResultVariable() reports its own errors, so we don't do so here
2653 if (log && log->GetVerbose())
2656 raw_string_ostream oss(s);
2658 m_module->print(oss, NULL);
2662 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2665 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2669 llvm::Function *function = fi;
2671 if (function->begin() == function->end())
2674 Function::iterator bbi;
2676 for (bbi = function->begin();
2677 bbi != function->end();
2680 if (!RemoveGuards(*bbi))
2683 log->Printf("RemoveGuards() failed");
2685 // RemoveGuards() reports its own errors, so we don't do so here
2690 if (!RewritePersistentAllocs(*bbi))
2693 log->Printf("RewritePersistentAllocs() failed");
2695 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2700 if (!RemoveCXAAtExit(*bbi))
2703 log->Printf("RemoveCXAAtExit() failed");
2705 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2712 ///////////////////////////////////////////////////////////////////////////////
2713 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2716 if (!RewriteObjCConstStrings())
2719 log->Printf("RewriteObjCConstStrings() failed");
2721 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2726 ///////////////////////////////
2727 // Resolve function pointers
2730 if (!ResolveFunctionPointers(llvm_module))
2733 log->Printf("ResolveFunctionPointers() failed");
2735 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2740 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2744 llvm::Function *function = fi;
2746 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2750 if (!RewriteObjCSelectors(*bbi))
2753 log->Printf("RewriteObjCSelectors() failed");
2755 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2762 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2766 llvm::Function *function = fi;
2768 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2772 if (!ResolveCalls(*bbi))
2775 log->Printf("ResolveCalls() failed");
2777 // ResolveCalls() reports its own errors, so we don't do so here
2782 if (!ReplaceStaticLiterals(*bbi))
2785 log->Printf("ReplaceStaticLiterals() failed");
2792 ////////////////////////////////////////////////////////////////////////
2793 // Run function-level passes that only make sense on the main function
2796 if (!ResolveExternals(*main_function))
2799 log->Printf("ResolveExternals() failed");
2801 // ResolveExternals() reports its own errors, so we don't do so here
2806 if (!ReplaceVariables(*main_function))
2809 log->Printf("ReplaceVariables() failed");
2811 // ReplaceVariables() reports its own errors, so we don't do so here
2816 if (!ReplaceStrings())
2819 log->Printf("ReplaceStrings() failed");
2824 if (!CompleteDataAllocation())
2827 log->Printf("CompleteDataAllocation() failed");
2832 if (!StripAllGVs(llvm_module))
2835 log->Printf("StripAllGVs() failed");
2838 if (log && log->GetVerbose())
2841 raw_string_ostream oss(s);
2843 m_module->print(oss, NULL);
2847 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2854 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2859 IRForTarget::getPotentialPassManagerType() const
2861 return PMT_ModulePassManager;