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),
108 m_error_stream(error_stream),
109 m_result_store(NULL),
110 m_result_is_pointer(false),
111 m_reloc_placeholder(NULL),
112 m_entry_instruction_finder (FindEntryInstruction)
116 /* Handy utility functions used at several places in the code */
119 PrintValue(const Value *value, bool truncate = false)
124 raw_string_ostream rso(s);
128 s.resize(s.length() - 1);
134 PrintType(const llvm::Type *type, bool truncate = false)
137 raw_string_ostream rso(s);
141 s.resize(s.length() - 1);
145 IRForTarget::~IRForTarget()
150 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
152 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
154 std::string name = llvm_function.getName().str();
160 IRForTarget::GetFunctionAddress (llvm::Function *fun,
162 lldb_private::ConstString &name,
163 Constant **&value_ptr)
165 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
167 fun_addr = LLDB_INVALID_ADDRESS;
171 if (fun->isIntrinsic())
173 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
175 switch (intrinsic_id)
179 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
182 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
185 case Intrinsic::memcpy:
187 static lldb_private::ConstString g_memcpy_str ("memcpy");
191 case Intrinsic::memset:
193 static lldb_private::ConstString g_memset_str ("memset");
200 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
204 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
207 // Find the address of the function.
209 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
213 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
215 lldb_private::ConstString altnernate_name;
216 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
219 // Check for an alternate mangling for "std::basic_string<char>"
220 // that is part of the itanium C++ name mangling scheme
221 const char *name_cstr = name.GetCString();
222 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
224 std::string alternate_mangling("_ZNKSs");
225 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
226 altnernate_name.SetCString(alternate_mangling.c_str());
227 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
233 lldb_private::Mangled mangled_name(name);
234 lldb_private::Mangled alt_mangled_name(altnernate_name);
237 if (alt_mangled_name)
238 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
239 mangled_name.GetName().GetCString(),
240 alt_mangled_name.GetName().GetCString());
242 log->Printf("Function \"%s\" had no address",
243 mangled_name.GetName().GetCString());
248 if (alt_mangled_name)
249 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
250 mangled_name.GetName().GetCString(),
251 alt_mangled_name.GetName().GetCString());
252 else if (mangled_name.GetMangledName())
253 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
254 mangled_name.GetName().GetCString(),
255 mangled_name.GetMangledName().GetCString());
257 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
258 mangled_name.GetName().GetCString());
266 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
269 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
272 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
279 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
285 IRForTarget::BuildFunctionPointer (llvm::Type *type,
288 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
289 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
290 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
291 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
292 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
296 IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
297 llvm::Value *function_ptr,
300 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
306 if (Instruction *user_inst = dyn_cast<Instruction>(user))
308 MDString* md_name = MDString::get(context, StringRef(name));
310 MDNode *metadata = MDNode::get(context, md_name);
312 user_inst->setMetadata("lldb.call.realName", metadata);
316 RegisterFunctionMetadata (context, user, name);
322 IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
324 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
326 for (llvm::Module::iterator fi = llvm_module.begin();
327 fi != llvm_module.end();
332 bool is_decl = fun->isDeclaration();
335 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
340 if (fun->hasNUses(0))
343 uint64_t addr = LLDB_INVALID_ADDRESS;
344 lldb_private::ConstString name;
345 Constant **value_ptr = NULL;
347 if (!GetFunctionAddress(fun,
351 return false; // GetFunctionAddress reports its own errors
353 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
355 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
360 // If we are replacing a function with the nobuiltin attribute, it may
361 // be called with the builtin attribute on call sites. Remove any such
362 // attributes since it's illegal to have a builtin call to something
363 // other than a nobuiltin function.
364 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
365 llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
367 for (auto u = fun->use_begin(), e = fun->use_end(); u != e; ++u) {
368 if (auto call = dyn_cast<CallInst>(*u)) {
369 call->removeAttribute(AttributeSet::FunctionIndex, builtin);
374 fun->replaceAllUsesWith(value);
382 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
384 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
389 unsigned num_nodes = named_metadata->getNumOperands();
393 node_index < num_nodes;
396 MDNode *metadata_node = named_metadata->getOperand(node_index);
401 if (metadata_node->getNumOperands() != 2)
404 if (metadata_node->getOperand(0) != global_val)
407 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
412 uintptr_t ptr = constant_int->getZExtValue();
414 return reinterpret_cast<clang::NamedDecl *>(ptr);
421 IRForTarget::DeclForGlobal (GlobalValue *global_val)
423 return DeclForGlobal(global_val, m_module);
427 IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
429 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
434 // Find the result variable. If it doesn't exist, we can give up right here.
436 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
438 std::string result_name_str;
439 const char *result_name = NULL;
441 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
445 result_name_str = vi->first().str();
446 const char *value_name = result_name_str.c_str();
448 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
449 strncmp(value_name, "_ZGV", 4))
451 result_name = value_name;
452 m_result_is_pointer = true;
456 if (strstr(value_name, "$__lldb_expr_result") &&
457 strncmp(value_name, "_ZGV", 4))
459 result_name = value_name;
460 m_result_is_pointer = false;
468 log->PutCString("Couldn't find result variable");
474 log->Printf("Result name: \"%s\"", result_name);
476 Value *result_value = m_module->getNamedValue(result_name);
481 log->PutCString("Result variable had no data");
484 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
490 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
492 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
497 log->PutCString("Result variable isn't a GlobalVariable");
500 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
505 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
509 log->PutCString("Result variable doesn't have a corresponding Decl");
512 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
519 std::string decl_desc_str;
520 raw_string_ostream decl_desc_stream(decl_desc_str);
521 result_decl->print(decl_desc_stream);
522 decl_desc_stream.flush();
524 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
527 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
531 log->PutCString("Result variable Decl isn't a VarDecl");
534 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
539 // Get the next available result name from m_decl_map and create the persistent
542 // If the result is an Lvalue, it is emitted as a pointer; see
543 // ASTResultSynthesizer::SynthesizeBodyResult.
544 if (m_result_is_pointer)
546 clang::QualType pointer_qual_type = result_var->getType();
547 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
549 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
550 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
552 if (pointer_pointertype)
554 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
556 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
557 &result_decl->getASTContext());
559 else if (pointer_objcobjpointertype)
561 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
563 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
564 &result_decl->getASTContext());
569 log->PutCString("Expected result to have pointer type, but it did not");
572 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
579 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
580 &result_decl->getASTContext());
583 if (m_result_type.GetBitSize() == 0)
585 lldb_private::StreamString type_desc_stream;
586 m_result_type.DumpTypeDescription(&type_desc_stream);
589 log->Printf("Result type has size 0");
592 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
593 type_desc_stream.GetData());
599 lldb_private::StreamString type_desc_stream;
600 m_result_type.DumpTypeDescription(&type_desc_stream);
602 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
605 m_result_name = lldb_private::ConstString("$RESULT_NAME");
608 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
609 m_result_name.GetCString(),
610 m_result_type.GetByteSize());
612 // Construct a new result global and set up its metadata
614 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
615 result_global->getType()->getElementType(),
616 false, /* not constant */
617 GlobalValue::ExternalLinkage,
618 NULL, /* no initializer */
619 m_result_name.GetCString ());
621 // It's too late in compilation to create a new VarDecl for this, but we don't
622 // need to. We point the metadata at the old VarDecl. This creates an odd
623 // anomaly: a variable with a Value whose name is something like $0 and a
624 // Decl whose name is $__lldb_expr_result. This condition is handled in
625 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
628 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
629 reinterpret_cast<uint64_t>(result_decl),
632 llvm::Value* values[2];
633 values[0] = new_result_global;
634 values[1] = new_constant_int;
636 ArrayRef<Value*> value_ref(values, 2);
638 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
639 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
640 named_metadata->addOperand(persistent_global_md);
643 log->Printf("Replacing \"%s\" with \"%s\"",
644 PrintValue(result_global).c_str(),
645 PrintValue(new_result_global).c_str());
647 if (result_global->hasNUses(0))
649 // We need to synthesize a store for this variable, because otherwise
650 // there's nothing to put into its equivalent persistent variable.
652 BasicBlock &entry_block(llvm_function.getEntryBlock());
653 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
655 if (!first_entry_instruction)
658 if (!result_global->hasInitializer())
661 log->Printf("Couldn't find initializer for unused variable");
664 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
669 Constant *initializer = result_global->getInitializer();
671 StoreInst *synthesized_store = new StoreInst(initializer,
673 first_entry_instruction);
676 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
680 result_global->replaceAllUsesWith(new_result_global);
683 if (!m_decl_map->AddPersistentVariable(result_decl,
687 m_result_is_pointer))
690 result_global->eraseFromParent();
696 static void DebugUsers(Log *log, Value *value, uint8_t depth)
704 log->Printf(" <Begin %d users>", value->getNumUses());
706 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
711 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
712 DebugUsers(log, *ui, depth);
716 log->Printf(" <End uses>");
721 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
722 llvm::GlobalVariable *cstr)
724 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
726 Type *ns_str_ty = ns_str->getType();
728 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
729 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
730 (m_module->getPointerSize()
731 == Module::Pointer64) ? 64 : 32);
732 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
733 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
735 if (!m_CFStringCreateWithBytes)
737 lldb::addr_t CFStringCreateWithBytes_addr;
739 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
741 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
744 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
747 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
753 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
755 // Build the function type:
757 // CFStringRef CFStringCreateWithBytes (
758 // CFAllocatorRef alloc,
759 // const UInt8 *bytes,
761 // CFStringEncoding encoding,
762 // Boolean isExternalRepresentation
765 // We make the following substitutions:
767 // CFStringRef -> i8*
768 // CFAllocatorRef -> i8*
770 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
771 // CFStringEncoding -> i32
774 Type *arg_type_array[5];
776 arg_type_array[0] = i8_ptr_ty;
777 arg_type_array[1] = i8_ptr_ty;
778 arg_type_array[2] = intptr_ty;
779 arg_type_array[3] = i32_ty;
780 arg_type_array[4] = i8_ty;
782 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
784 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
786 // Build the constant containing the pointer to the function
787 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
788 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
789 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
792 ConstantDataSequential *string_array = NULL;
795 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
797 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
798 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
799 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
800 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
801 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
803 Value *argument_array[5];
805 argument_array[0] = alloc_arg;
806 argument_array[1] = bytes_arg;
807 argument_array[2] = numBytes_arg;
808 argument_array[3] = encoding_arg;
809 argument_array[4] = isExternal_arg;
811 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
813 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
814 return CallInst::Create(m_CFStringCreateWithBytes,
816 "CFStringCreateWithBytes",
817 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
820 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
823 log->PutCString("Couldn't replace the NSString with the result of the call");
826 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
831 ns_str->eraseFromParent();
837 IRForTarget::RewriteObjCConstStrings()
839 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
841 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
843 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
847 std::string value_name = vi->first().str();
848 const char *value_name_cstr = value_name.c_str();
850 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
852 Value *nsstring_value = vi->second;
854 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
856 if (!nsstring_global)
859 log->PutCString("NSString variable is not a GlobalVariable");
862 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
867 if (!nsstring_global->hasInitializer())
870 log->PutCString("NSString variable does not have an initializer");
873 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
878 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
880 if (!nsstring_struct)
883 log->PutCString("NSString variable's initializer is not a ConstantStruct");
886 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
891 // We expect the following structure:
900 if (nsstring_struct->getNumOperands() != 4)
903 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
906 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
911 Constant *nsstring_member = nsstring_struct->getOperand(2);
913 if (!nsstring_member)
916 log->PutCString("NSString initializer's str element was empty");
919 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
924 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
929 log->PutCString("NSString initializer's str element is not a ConstantExpr");
932 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
937 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
940 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
943 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
948 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
950 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
955 log->PutCString("NSString initializer's str element is not a GlobalVariable");
958 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
963 if (!cstr_global->hasInitializer())
966 log->PutCString("NSString initializer's str element does not have an initializer");
969 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
978 log->PutCString("NSString initializer's str element is not a ConstantArray");
981 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
986 if (!cstr_array->isCString())
989 log->PutCString("NSString initializer's str element is not a C string array");
992 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
998 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
1003 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
1005 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
1011 if (!RewriteObjCConstString(nsstring_global, cstr_global))
1014 log->PutCString("Error rewriting the constant string");
1016 // We don't print an error message here because RewriteObjCConstString has done so for us.
1023 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1027 std::string value_name = vi->first().str();
1028 const char *value_name_cstr = value_name.c_str();
1030 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
1032 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1037 log->PutCString("__CFConstantStringClassReference is not a global variable");
1040 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1045 gv->eraseFromParent();
1054 static bool IsObjCSelectorRef (Value *value)
1056 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
1058 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
1064 // This function does not report errors; its callers are responsible.
1066 IRForTarget::RewriteObjCSelector (Instruction* selector_load)
1068 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1070 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1075 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1077 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1078 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1080 // where %obj is the object pointer and %tmp is the selector.
1082 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1083 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
1085 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1087 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1089 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1092 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1094 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1096 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1099 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1101 if (!osr_initializer_base)
1104 // Find the string's initializer (a ConstantArray) and get the string from it
1106 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1108 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1111 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1113 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
1115 if (!omvn_initializer_array->isString())
1118 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1121 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
1123 // Construct a call to sel_registerName
1125 if (!m_sel_registerName)
1127 lldb::addr_t sel_registerName_addr;
1129 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
1130 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
1134 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
1136 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1138 // The below code would be "more correct," but in actuality what's required is uint8_t*
1139 //Type *sel_type = StructType::get(m_module->getContext());
1140 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
1141 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
1143 Type *type_array[1];
1145 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1147 ArrayRef<Type *> srN_arg_types(type_array, 1);
1149 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1151 // Build the constant containing the pointer to the function
1152 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1153 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1154 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
1155 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
1156 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1159 Value *argument_array[1];
1161 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
1163 argument_array[0] = omvn_pointer;
1165 ArrayRef<Value *> srN_arguments(argument_array, 1);
1167 CallInst *srN_call = CallInst::Create(m_sel_registerName,
1172 // Replace the load with the call in all users
1174 selector_load->replaceAllUsesWith(srN_call);
1176 selector_load->eraseFromParent();
1182 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
1184 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1186 BasicBlock::iterator ii;
1188 typedef SmallVector <Instruction*, 2> InstrList;
1189 typedef InstrList::iterator InstrIterator;
1191 InstrList selector_loads;
1193 for (ii = basic_block.begin();
1194 ii != basic_block.end();
1197 Instruction &inst = *ii;
1199 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1200 if (IsObjCSelectorRef(load->getPointerOperand()))
1201 selector_loads.push_back(&inst);
1206 for (iter = selector_loads.begin();
1207 iter != selector_loads.end();
1210 if (!RewriteObjCSelector(*iter))
1213 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1216 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
1225 // This function does not report errors; its callers are responsible.
1227 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
1229 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1231 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1233 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1235 if (!alloc_md || !alloc_md->getNumOperands())
1238 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1243 // We attempt to register this as a new persistent variable with the DeclMap.
1245 uintptr_t ptr = constant_int->getZExtValue();
1247 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1249 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1250 &decl->getASTContext());
1252 StringRef decl_name (decl->getName());
1253 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
1254 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
1257 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
1259 false, /* not constant */
1260 GlobalValue::ExternalLinkage,
1261 NULL, /* no initializer */
1262 alloc->getName().str().c_str());
1264 // What we're going to do here is make believe this was a regular old external
1265 // variable. That means we need to make the metadata valid.
1267 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1269 llvm::Value* values[2];
1270 values[0] = persistent_global;
1271 values[1] = constant_int;
1273 ArrayRef<llvm::Value*> value_ref(values, 2);
1275 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1276 named_metadata->addOperand(persistent_global_md);
1278 // Now, since the variable is a pointer variable, we will drop in a load of that
1279 // pointer variable.
1281 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1284 log->Printf("Replacing \"%s\" with \"%s\"",
1285 PrintValue(alloc).c_str(),
1286 PrintValue(persistent_load).c_str());
1288 alloc->replaceAllUsesWith(persistent_load);
1289 alloc->eraseFromParent();
1295 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1297 if (!m_resolve_vars)
1300 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1302 BasicBlock::iterator ii;
1304 typedef SmallVector <Instruction*, 2> InstrList;
1305 typedef InstrList::iterator InstrIterator;
1307 InstrList pvar_allocs;
1309 for (ii = basic_block.begin();
1310 ii != basic_block.end();
1313 Instruction &inst = *ii;
1315 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1317 llvm::StringRef alloc_name = alloc->getName();
1319 if (alloc_name.startswith("$") &&
1320 !alloc_name.startswith("$__lldb"))
1322 if (alloc_name.find_first_of("0123456789") == 1)
1325 log->Printf("Rejecting a numeric persistent variable.");
1328 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1333 pvar_allocs.push_back(alloc);
1340 for (iter = pvar_allocs.begin();
1341 iter != pvar_allocs.end();
1344 if (!RewritePersistentAlloc(*iter))
1347 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1350 log->PutCString("Couldn't rewrite the creation of a persistent variable");
1360 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1365 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1367 if (log && log->GetVerbose())
1368 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1370 Type *initializer_type = initializer->getType();
1372 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1374 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1377 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1379 if (array_initializer->isString())
1381 std::string array_initializer_string = array_initializer->getAsString();
1382 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1386 ArrayType *array_initializer_type = array_initializer->getType();
1387 Type *array_element_type = array_initializer_type->getElementType();
1389 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1391 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1393 Value *operand_value = array_initializer->getOperand(i);
1394 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1396 if (!operand_constant)
1399 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1405 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1407 StructType *struct_initializer_type = struct_initializer->getType();
1408 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1410 for (unsigned i = 0;
1411 i < struct_initializer->getNumOperands();
1414 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1419 else if (isa<ConstantAggregateZero>(initializer))
1421 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1428 IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1430 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1433 if (global_variable == m_reloc_placeholder)
1436 uint64_t offset = m_data_allocator.GetStream().GetSize();
1438 llvm::Type *variable_type = global_variable->getType();
1440 Constant *initializer = global_variable->getInitializer();
1442 llvm::Type *initializer_type = initializer->getType();
1444 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1445 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1447 const size_t mask = (align - 1);
1448 uint64_t aligned_offset = (offset + mask) & ~mask;
1449 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
1450 offset = aligned_offset;
1452 lldb_private::DataBufferHeap data(size, '\0');
1455 if (!MaterializeInitializer(data.GetBytes(), initializer))
1458 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
1460 Constant *new_pointer = BuildRelocation(variable_type, offset);
1462 global_variable->replaceAllUsesWith(new_pointer);
1464 global_variable->eraseFromParent();
1469 // This function does not report errors; its callers are responsible.
1471 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1473 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1476 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1478 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1480 switch (constant_expr->getOpcode())
1484 case Instruction::GetElementPtr:
1485 case Instruction::BitCast:
1486 Value *s = constant_expr->getOperand(0);
1487 if (!MaybeHandleVariable(s))
1491 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1493 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1494 return MaterializeInternalVariable(global_variable);
1496 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1500 if (IsObjCSelectorRef(llvm_value_ptr))
1503 if (!global_variable->hasExternalLinkage())
1507 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1512 std::string name (named_decl->getName().str());
1514 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1515 if (value_decl == NULL)
1518 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
1520 const Type *value_type = NULL;
1524 // The $__lldb_expr_result name indicates the the return value has allocated as
1525 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1526 // accesses to this static variable need to be redirected to the result of dereferencing
1527 // a pointer that is passed in as one of the arguments.
1529 // Consequently, when reporting the size of the type, we report a pointer type pointing
1530 // to the type of $__lldb_expr_result, not the type itself.
1532 // We also do this for any user-declared persistent variables.
1533 clang_type = clang_type.GetPointerType();
1534 value_type = PointerType::get(global_variable->getType(), 0);
1538 value_type = global_variable->getType();
1541 const uint64_t value_size = clang_type.GetByteSize();
1542 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
1546 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
1548 clang_type.GetQualType().getAsString().c_str(),
1549 PrintType(value_type).c_str(),
1555 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1556 lldb_private::ConstString (name.c_str()),
1561 if (!global_variable->hasExternalLinkage())
1563 else if (HandleSymbol (global_variable))
1569 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1572 log->Printf("Function pointers aren't handled right now");
1580 // This function does not report errors; its callers are responsible.
1582 IRForTarget::HandleSymbol (Value *symbol)
1584 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1586 lldb_private::ConstString name(symbol->getName().str().c_str());
1588 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1590 if (symbol_addr == LLDB_INVALID_ADDRESS)
1593 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1599 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1601 Type *symbol_type = symbol->getType();
1602 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1603 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1605 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1607 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1610 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1612 symbol->replaceAllUsesWith(symbol_addr_ptr);
1618 IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1620 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1623 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1625 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1628 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1631 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1640 IRForTarget::HandleObjCClass(Value *classlist_reference)
1642 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1644 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1646 if (!global_variable)
1649 Constant *initializer = global_variable->getInitializer();
1654 if (!initializer->hasName())
1657 StringRef name(initializer->getName());
1658 lldb_private::ConstString name_cstr(name.str().c_str());
1659 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1662 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1664 if (class_ptr == LLDB_INVALID_ADDRESS)
1667 if (global_variable->use_begin() == global_variable->use_end())
1670 SmallVector<LoadInst *, 2> load_instructions;
1672 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1676 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1677 load_instructions.push_back(load_instruction);
1680 if (load_instructions.empty())
1683 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1684 (m_module->getPointerSize()
1685 == Module::Pointer64) ? 64 : 32);
1687 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1689 for (LoadInst *load_instruction : load_instructions)
1691 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1693 load_instruction->replaceAllUsesWith(class_bitcast);
1695 load_instruction->eraseFromParent();
1702 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1704 BasicBlock::iterator ii;
1706 std::vector<CallInst *> calls_to_remove;
1708 for (ii = basic_block.begin();
1709 ii != basic_block.end();
1712 Instruction &inst = *ii;
1714 CallInst *call = dyn_cast<CallInst>(&inst);
1716 // MaybeHandleCallArguments handles error reporting; we are silent here
1720 bool remove = false;
1722 llvm::Function *func = call->getCalledFunction();
1724 if (func && func->getName() == "__cxa_atexit")
1727 llvm::Value *val = call->getCalledValue();
1729 if (val && val->getName() == "__cxa_atexit")
1733 calls_to_remove.push_back(call);
1736 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1740 (*ci)->eraseFromParent();
1747 IRForTarget::ResolveCalls(BasicBlock &basic_block)
1749 /////////////////////////////////////////////////////////////////////////
1750 // Prepare the current basic block for execution in the remote process
1753 BasicBlock::iterator ii;
1755 for (ii = basic_block.begin();
1756 ii != basic_block.end();
1759 Instruction &inst = *ii;
1761 CallInst *call = dyn_cast<CallInst>(&inst);
1763 // MaybeHandleCallArguments handles error reporting; we are silent here
1764 if (call && !MaybeHandleCallArguments(call))
1772 IRForTarget::ResolveExternals (Function &llvm_function)
1774 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1776 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
1783 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1788 std::string global_name = (*global).getName().str();
1791 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1792 global_name.c_str(),
1793 DeclForGlobal(global));
1795 if (global_name.find("OBJC_IVAR") == 0)
1797 if (!HandleSymbol(global))
1800 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1805 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1807 if (!HandleObjCClass(global))
1810 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1815 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1817 if (!HandleObjCClass(global))
1820 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1825 else if (DeclForGlobal(global))
1827 if (!MaybeHandleVariable (global))
1830 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1841 IRForTarget::ReplaceStrings ()
1843 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1845 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1849 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1853 GlobalVariable *gv = gi;
1855 if (!gv->hasInitializer())
1858 Constant *gc = gv->getInitializer();
1862 if (gc->isNullValue())
1864 Type *gc_type = gc->getType();
1866 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1871 Type *gc_element_type = gc_array_type->getElementType();
1873 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1875 if (gc_integer_type->getBitWidth() != 8)
1882 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
1887 if (!gc_array->isCString())
1891 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1893 str = gc_array->getAsString();
1896 offsets[gv] = m_data_allocator.GetStream().GetSize();
1898 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
1901 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
1903 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1907 GlobalVariable *gv = oi->first;
1908 size_t offset = oi->second;
1910 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1913 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1915 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1920 log->Printf("Found use %s", PrintValue(*ui).c_str());
1922 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1923 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1927 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1930 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1935 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1936 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1938 const_expr->replaceAllUsesWith(new_gep);
1940 else if (store_inst)
1942 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1944 store_inst->setOperand(0, bit_cast);
1949 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1955 gv->eraseFromParent();
1962 IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1964 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1966 typedef SmallVector <Value*, 2> ConstantList;
1967 typedef SmallVector <llvm::Instruction*, 2> UserList;
1968 typedef ConstantList::iterator ConstantIterator;
1969 typedef UserList::iterator UserIterator;
1971 ConstantList static_constants;
1972 UserList static_users;
1974 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1978 llvm::Instruction &inst = *ii;
1980 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1984 Value *operand_val = oi->get();
1986 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1988 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
1990 static_constants.push_back(operand_val);
1991 static_users.push_back(ii);
1996 ConstantIterator constant_iter;
1997 UserIterator user_iter;
1999 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2000 constant_iter != static_constants.end();
2001 ++constant_iter, ++user_iter)
2003 Value *operand_val = *constant_iter;
2004 llvm::Instruction *inst = *user_iter;
2006 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2008 if (operand_constant_fp)
2010 Type *operand_type = operand_constant_fp->getType();
2012 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2013 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2015 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2016 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2021 raw_string_ostream ss(s);
2022 for (size_t index = 0;
2023 index < operand_data_size;
2026 ss << (uint32_t)operand_raw_data[index];
2031 log->Printf("Found ConstantFP with size %zu and raw data %s", operand_data_size, s.c_str());
2034 lldb_private::DataBufferHeap data(operand_data_size, 0);
2036 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
2038 uint8_t *data_bytes = data.GetBytes();
2040 for (size_t index = 0;
2041 index < operand_data_size;
2044 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2049 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2052 uint64_t offset = m_data_allocator.GetStream().GetSize();
2054 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2056 const size_t mask = (align - 1);
2057 uint64_t aligned_offset = (offset + mask) & ~mask;
2058 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
2059 offset = aligned_offset;
2061 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
2063 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
2065 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
2067 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2069 operand_constant_fp->replaceAllUsesWith(fp_load);
2076 static bool isGuardVariableRef(Value *V)
2078 Constant *Old = NULL;
2080 if (!(Old = dyn_cast<Constant>(V)))
2083 ConstantExpr *CE = NULL;
2085 if ((CE = dyn_cast<ConstantExpr>(V)))
2087 if (CE->getOpcode() != Instruction::BitCast)
2090 Old = CE->getOperand(0);
2093 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
2095 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2102 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
2104 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
2106 Value::use_iterator ui;
2108 for (ui = guard_load->use_begin();
2109 ui != guard_load->use_end();
2112 if (isa<Constant>(*ui))
2114 // do nothing for the moment
2118 ui->replaceUsesOfWith(guard_load, zero);
2122 guard_load->eraseFromParent();
2125 static void ExciseGuardStore(Instruction* guard_store)
2127 guard_store->eraseFromParent();
2131 IRForTarget::RemoveGuards(BasicBlock &basic_block)
2133 ///////////////////////////////////////////////////////
2134 // Eliminate any reference to guard variables found.
2137 BasicBlock::iterator ii;
2139 typedef SmallVector <Instruction*, 2> InstrList;
2140 typedef InstrList::iterator InstrIterator;
2142 InstrList guard_loads;
2143 InstrList guard_stores;
2145 for (ii = basic_block.begin();
2146 ii != basic_block.end();
2149 Instruction &inst = *ii;
2151 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2152 if (isGuardVariableRef(load->getPointerOperand()))
2153 guard_loads.push_back(&inst);
2155 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2156 if (isGuardVariableRef(store->getPointerOperand()))
2157 guard_stores.push_back(&inst);
2162 for (iter = guard_loads.begin();
2163 iter != guard_loads.end();
2165 TurnGuardLoadIntoZero(*iter);
2167 for (iter = guard_stores.begin();
2168 iter != guard_stores.end();
2170 ExciseGuardStore(*iter);
2175 // This function does not report errors; its callers are responsible.
2177 IRForTarget::UnfoldConstant(Constant *old_constant,
2178 FunctionValueCache &value_maker,
2179 FunctionValueCache &entry_instruction_finder)
2181 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2183 Value::use_iterator ui;
2185 SmallVector<User*, 16> users;
2187 // We do this because the use list might change, invalidating our iterator.
2188 // Much better to keep a work list ourselves.
2189 for (ui = old_constant->use_begin();
2190 ui != old_constant->use_end();
2192 users.push_back(*ui);
2198 User *user = users[i];
2200 if (Constant *constant = dyn_cast<Constant>(user))
2202 // synthesize a new non-constant equivalent of the constant
2204 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2206 switch (constant_expr->getOpcode())
2210 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
2212 case Instruction::BitCast:
2214 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2216 // OperandList[0] is value
2218 if (constant_expr->getOperand(0) != old_constant)
2219 return constant_expr;
2221 return new BitCastInst(value_maker.GetValue(function),
2222 constant_expr->getType(),
2224 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2227 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2231 case Instruction::GetElementPtr:
2233 // GetElementPtrConstantExpr
2234 // OperandList[0] is base
2235 // OperandList[1]... are indices
2237 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2238 Value *ptr = constant_expr->getOperand(0);
2240 if (ptr == old_constant)
2241 ptr = value_maker.GetValue(function);
2243 std::vector<Value*> index_vector;
2245 unsigned operand_index;
2246 unsigned num_operands = constant_expr->getNumOperands();
2248 for (operand_index = 1;
2249 operand_index < num_operands;
2252 Value *operand = constant_expr->getOperand(operand_index);
2254 if (operand == old_constant)
2255 operand = value_maker.GetValue(function);
2257 index_vector.push_back(operand);
2260 ArrayRef <Value*> indices(index_vector);
2262 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2265 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2274 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
2280 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2282 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2287 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2293 if (!isa<GlobalValue>(old_constant))
2295 old_constant->destroyConstant();
2302 IRForTarget::ReplaceVariables (Function &llvm_function)
2304 if (!m_resolve_vars)
2307 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2309 m_decl_map->DoStructLayout();
2312 log->Printf("Element arrangement:");
2314 uint32_t num_elements;
2315 uint32_t element_index;
2320 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2323 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
2325 if (iter == llvm_function.getArgumentList().end())
2328 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2333 Argument *argument = iter;
2335 if (argument->getName().equals("this"))
2339 if (iter == llvm_function.getArgumentList().end())
2342 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2349 else if (argument->getName().equals("self"))
2353 if (iter == llvm_function.getArgumentList().end())
2356 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2361 if (!iter->getName().equals("_cmd"))
2364 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2371 if (iter == llvm_function.getArgumentList().end())
2374 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2382 if (!argument->getName().equals("$__lldb_arg"))
2385 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2391 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
2393 BasicBlock &entry_block(llvm_function.getEntryBlock());
2394 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
2396 if (!FirstEntryInstruction)
2399 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2404 LLVMContext &context(m_module->getContext());
2405 IntegerType *offset_type(Type::getInt32Ty(context));
2410 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2415 for (element_index = 0; element_index < num_elements; ++element_index)
2417 const clang::NamedDecl *decl = NULL;
2418 Value *value = NULL;
2420 lldb_private::ConstString name;
2422 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
2425 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2431 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
2433 decl->getNameAsString().c_str(),
2439 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
2441 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2442 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2443 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2444 // entry in order to produce the static variable that the AST thinks it is accessing.
2446 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
2448 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2449 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2454 if (name == m_result_name && !m_result_is_pointer)
2456 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2457 value->getType()->getPointerTo(),
2461 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2467 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2473 if (Constant *constant = dyn_cast<Constant>(value))
2475 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2477 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2479 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2484 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2488 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2489 var->eraseFromParent();
2494 log->Printf("Total structure [align %" PRId64 ", size %zu]", alignment, size);
2500 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
2502 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2503 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
2505 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
2507 llvm::Constant *offset_array[1];
2509 offset_array[0] = offset_int;
2511 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2513 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
2514 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2516 return reloc_getbitcast;
2520 IRForTarget::CompleteDataAllocation ()
2522 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2524 if (!m_data_allocator.GetStream().GetSize())
2527 lldb::addr_t allocation = m_data_allocator.Allocate();
2532 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2534 log->Printf("Failed to allocate static data");
2537 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
2540 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2541 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
2543 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2544 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2546 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2548 m_reloc_placeholder->eraseFromParent();
2554 IRForTarget::StripAllGVs (Module &llvm_module)
2556 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2557 std::vector<GlobalVariable *> global_vars;
2558 std::set<GlobalVariable *>erased_vars;
2566 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2570 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2572 global_var->removeDeadConstantUsers();
2574 if (global_var->use_empty())
2577 log->Printf("Did remove %s",
2578 PrintValue(global_var).c_str());
2579 global_var->eraseFromParent();
2586 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2590 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2592 GlobalValue::use_iterator ui = global_var->use_begin();
2595 log->Printf("Couldn't remove %s because of %s",
2596 PrintValue(global_var).c_str(),
2597 PrintValue(*ui).c_str());
2604 IRForTarget::runOnModule (Module &llvm_module)
2606 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2608 m_module = &llvm_module;
2609 m_target_data.reset(new DataLayout(m_module));
2614 raw_string_ostream oss(s);
2616 m_module->print(oss, NULL);
2620 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2623 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2628 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2631 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2636 if (!FixFunctionLinkage (*main_function))
2639 log->Printf("Couldn't fix the linkage for the function");
2644 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
2646 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2648 false /* IsConstant */,
2649 GlobalVariable::InternalLinkage,
2650 Constant::getNullValue(intptr_ty),
2651 "reloc_placeholder",
2652 NULL /* InsertBefore */,
2653 GlobalVariable::NotThreadLocal /* ThreadLocal */,
2654 0 /* AddressSpace */);
2656 ////////////////////////////////////////////////////////////
2657 // Replace $__lldb_expr_result with a persistent variable
2660 if (!CreateResultVariable(*main_function))
2663 log->Printf("CreateResultVariable() failed");
2665 // CreateResultVariable() reports its own errors, so we don't do so here
2670 if (log && log->GetVerbose())
2673 raw_string_ostream oss(s);
2675 m_module->print(oss, NULL);
2679 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2682 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2686 llvm::Function *function = fi;
2688 if (function->begin() == function->end())
2691 Function::iterator bbi;
2693 for (bbi = function->begin();
2694 bbi != function->end();
2697 if (!RemoveGuards(*bbi))
2700 log->Printf("RemoveGuards() failed");
2702 // RemoveGuards() reports its own errors, so we don't do so here
2707 if (!RewritePersistentAllocs(*bbi))
2710 log->Printf("RewritePersistentAllocs() failed");
2712 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2717 if (!RemoveCXAAtExit(*bbi))
2720 log->Printf("RemoveCXAAtExit() failed");
2722 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2729 ///////////////////////////////////////////////////////////////////////////////
2730 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2733 if (!RewriteObjCConstStrings())
2736 log->Printf("RewriteObjCConstStrings() failed");
2738 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2743 ///////////////////////////////
2744 // Resolve function pointers
2747 if (!ResolveFunctionPointers(llvm_module))
2750 log->Printf("ResolveFunctionPointers() failed");
2752 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2757 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2761 llvm::Function *function = fi;
2763 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2767 if (!RewriteObjCSelectors(*bbi))
2770 log->Printf("RewriteObjCSelectors() failed");
2772 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2779 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2783 llvm::Function *function = fi;
2785 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2789 if (!ResolveCalls(*bbi))
2792 log->Printf("ResolveCalls() failed");
2794 // ResolveCalls() reports its own errors, so we don't do so here
2799 if (!ReplaceStaticLiterals(*bbi))
2802 log->Printf("ReplaceStaticLiterals() failed");
2809 ////////////////////////////////////////////////////////////////////////
2810 // Run function-level passes that only make sense on the main function
2813 if (!ResolveExternals(*main_function))
2816 log->Printf("ResolveExternals() failed");
2818 // ResolveExternals() reports its own errors, so we don't do so here
2823 if (!ReplaceVariables(*main_function))
2826 log->Printf("ReplaceVariables() failed");
2828 // ReplaceVariables() reports its own errors, so we don't do so here
2833 if (!ReplaceStrings())
2836 log->Printf("ReplaceStrings() failed");
2841 if (!CompleteDataAllocation())
2844 log->Printf("CompleteDataAllocation() failed");
2849 if (!StripAllGVs(llvm_module))
2852 log->Printf("StripAllGVs() failed");
2855 if (log && log->GetVerbose())
2858 raw_string_ostream oss(s);
2860 m_module->print(oss, NULL);
2864 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2871 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2876 IRForTarget::getPotentialPassManagerType() const
2878 return PMT_ModulePassManager;