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 "IRForTarget.h"
12 #include "ClangExpressionDeclMap.h"
14 #include "llvm/IR/Constants.h"
15 #include "llvm/IR/DataLayout.h"
16 #include "llvm/IR/InstrTypes.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/ValueSymbolTable.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/IPO.h"
26 #include "clang/AST/ASTContext.h"
28 #include "lldb/Core/dwarf.h"
29 #include "lldb/Expression/IRExecutionUnit.h"
30 #include "lldb/Expression/IRInterpreter.h"
31 #include "lldb/Symbol/ClangASTContext.h"
32 #include "lldb/Symbol/ClangUtil.h"
33 #include "lldb/Symbol/CompilerType.h"
34 #include "lldb/Utility/ConstString.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/Endian.h"
37 #include "lldb/Utility/Log.h"
38 #include "lldb/Utility/Scalar.h"
39 #include "lldb/Utility/StreamString.h"
47 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker)
48 : m_maker(maker), m_values() {}
50 IRForTarget::FunctionValueCache::~FunctionValueCache() {}
53 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) {
54 if (!m_values.count(function)) {
55 llvm::Value *ret = m_maker(function);
56 m_values[function] = ret;
59 return m_values[function];
62 static llvm::Value *FindEntryInstruction(llvm::Function *function) {
63 if (function->empty())
66 return function->getEntryBlock().getFirstNonPHIOrDbg();
69 IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
71 lldb_private::IRExecutionUnit &execution_unit,
72 lldb_private::Stream &error_stream,
73 const char *func_name)
74 : ModulePass(ID), m_resolve_vars(resolve_vars), m_func_name(func_name),
75 m_module(NULL), m_decl_map(decl_map), m_CFStringCreateWithBytes(NULL),
76 m_sel_registerName(NULL), m_objc_getClass(NULL), m_intptr_ty(NULL),
77 m_error_stream(error_stream),
78 m_execution_unit(execution_unit), m_result_store(NULL),
79 m_result_is_pointer(false), m_reloc_placeholder(NULL),
80 m_entry_instruction_finder(FindEntryInstruction) {}
82 /* Handy utility functions used at several places in the code */
84 static std::string PrintValue(const Value *value, bool truncate = false) {
87 raw_string_ostream rso(s);
91 s.resize(s.length() - 1);
96 static std::string PrintType(const llvm::Type *type, bool truncate = false) {
98 raw_string_ostream rso(s);
102 s.resize(s.length() - 1);
106 IRForTarget::~IRForTarget() {}
108 bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) {
109 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
114 clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val,
116 NamedMDNode *named_metadata =
117 module->getNamedMetadata("clang.global.decl.ptrs");
122 unsigned num_nodes = named_metadata->getNumOperands();
125 for (node_index = 0; node_index < num_nodes; ++node_index) {
126 llvm::MDNode *metadata_node =
127 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
131 if (metadata_node->getNumOperands() != 2)
134 if (mdconst::dyn_extract_or_null<GlobalValue>(
135 metadata_node->getOperand(0)) != global_val)
138 ConstantInt *constant_int =
139 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
144 uintptr_t ptr = constant_int->getZExtValue();
146 return reinterpret_cast<clang::NamedDecl *>(ptr);
152 clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) {
153 return DeclForGlobal(global_val, m_module);
156 bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
157 lldb_private::Log *log(
158 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
163 // Find the result variable. If it doesn't exist, we can give up right here.
165 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
167 std::string result_name_str;
168 const char *result_name = NULL;
170 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
171 ve = value_symbol_table.end();
173 result_name_str = vi->first().str();
174 const char *value_name = result_name_str.c_str();
176 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
177 strncmp(value_name, "_ZGV", 4)) {
178 result_name = value_name;
179 m_result_is_pointer = true;
183 if (strstr(value_name, "$__lldb_expr_result") &&
184 strncmp(value_name, "_ZGV", 4)) {
185 result_name = value_name;
186 m_result_is_pointer = false;
193 log->PutCString("Couldn't find result variable");
199 log->Printf("Result name: \"%s\"", result_name);
201 Value *result_value = m_module->getNamedValue(result_name);
205 log->PutCString("Result variable had no data");
207 m_error_stream.Printf("Internal error [IRForTarget]: Result variable's "
208 "name (%s) exists, but not its definition\n",
215 log->Printf("Found result in the IR: \"%s\"",
216 PrintValue(result_value, false).c_str());
218 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
220 if (!result_global) {
222 log->PutCString("Result variable isn't a GlobalVariable");
224 m_error_stream.Printf("Internal error [IRForTarget]: Result variable (%s) "
225 "is defined, but is not a global variable\n",
231 clang::NamedDecl *result_decl = DeclForGlobal(result_global);
234 log->PutCString("Result variable doesn't have a corresponding Decl");
236 m_error_stream.Printf("Internal error [IRForTarget]: Result variable (%s) "
237 "does not have a corresponding Clang entity\n",
244 std::string decl_desc_str;
245 raw_string_ostream decl_desc_stream(decl_desc_str);
246 result_decl->print(decl_desc_stream);
247 decl_desc_stream.flush();
249 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
252 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
255 log->PutCString("Result variable Decl isn't a VarDecl");
257 m_error_stream.Printf("Internal error [IRForTarget]: Result variable "
258 "(%s)'s corresponding Clang entity isn't a "
265 // Get the next available result name from m_decl_map and create the
266 // persistent variable for it
268 // If the result is an Lvalue, it is emitted as a pointer; see
269 // ASTResultSynthesizer::SynthesizeBodyResult.
270 if (m_result_is_pointer) {
271 clang::QualType pointer_qual_type = result_var->getType();
272 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
274 const clang::PointerType *pointer_pointertype =
275 pointer_type->getAs<clang::PointerType>();
276 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
277 pointer_type->getAs<clang::ObjCObjectPointerType>();
279 if (pointer_pointertype) {
280 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
282 m_result_type = lldb_private::TypeFromParser(
283 element_qual_type.getAsOpaquePtr(),
284 lldb_private::ClangASTContext::GetASTContext(
285 &result_decl->getASTContext()));
286 } else if (pointer_objcobjpointertype) {
287 clang::QualType element_qual_type =
288 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
290 m_result_type = lldb_private::TypeFromParser(
291 element_qual_type.getAsOpaquePtr(),
292 lldb_private::ClangASTContext::GetASTContext(
293 &result_decl->getASTContext()));
296 log->PutCString("Expected result to have pointer type, but it did not");
298 m_error_stream.Printf("Internal error [IRForTarget]: Lvalue result (%s) "
299 "is not a pointer variable\n",
305 m_result_type = lldb_private::TypeFromParser(
306 result_var->getType().getAsOpaquePtr(),
307 lldb_private::ClangASTContext::GetASTContext(
308 &result_decl->getASTContext()));
311 lldb::TargetSP target_sp(m_execution_unit.GetTarget());
312 lldb_private::ExecutionContext exe_ctx(target_sp, true);
313 llvm::Optional<uint64_t> bit_size =
314 m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope());
316 lldb_private::StreamString type_desc_stream;
317 m_result_type.DumpTypeDescription(&type_desc_stream);
320 log->Printf("Result type has unknown size");
322 m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' "
323 "couldn't be determined\n",
324 type_desc_stream.GetData());
329 lldb_private::StreamString type_desc_stream;
330 m_result_type.DumpTypeDescription(&type_desc_stream);
332 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
335 m_result_name = lldb_private::ConstString("$RESULT_NAME");
338 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
339 m_result_name.GetCString(),
340 m_result_type.GetByteSize(nullptr).getValueOr(0));
342 // Construct a new result global and set up its metadata
344 GlobalVariable *new_result_global = new GlobalVariable(
345 (*m_module), result_global->getType()->getElementType(),
346 false, /* not constant */
347 GlobalValue::ExternalLinkage, NULL, /* no initializer */
348 m_result_name.GetCString());
350 // It's too late in compilation to create a new VarDecl for this, but we
351 // don't need to. We point the metadata at the old VarDecl. This creates an
352 // odd anomaly: a variable with a Value whose name is something like $0 and a
353 // Decl whose name is $__lldb_expr_result. This condition is handled in
354 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
357 ConstantInt *new_constant_int =
358 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
359 reinterpret_cast<uint64_t>(result_decl), false);
361 llvm::Metadata *values[2];
362 values[0] = ConstantAsMetadata::get(new_result_global);
363 values[1] = ConstantAsMetadata::get(new_constant_int);
365 ArrayRef<Metadata *> value_ref(values, 2);
367 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
368 NamedMDNode *named_metadata =
369 m_module->getNamedMetadata("clang.global.decl.ptrs");
370 named_metadata->addOperand(persistent_global_md);
373 log->Printf("Replacing \"%s\" with \"%s\"",
374 PrintValue(result_global).c_str(),
375 PrintValue(new_result_global).c_str());
377 if (result_global->use_empty()) {
378 // We need to synthesize a store for this variable, because otherwise
379 // there's nothing to put into its equivalent persistent variable.
381 BasicBlock &entry_block(llvm_function.getEntryBlock());
382 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
384 if (!first_entry_instruction)
387 if (!result_global->hasInitializer()) {
389 log->Printf("Couldn't find initializer for unused variable");
391 m_error_stream.Printf("Internal error [IRForTarget]: Result variable "
392 "(%s) has no writes and no initializer\n",
398 Constant *initializer = result_global->getInitializer();
400 StoreInst *synthesized_store =
401 new StoreInst(initializer, new_result_global, first_entry_instruction);
404 log->Printf("Synthesized result store \"%s\"\n",
405 PrintValue(synthesized_store).c_str());
407 result_global->replaceAllUsesWith(new_result_global);
410 if (!m_decl_map->AddPersistentVariable(
411 result_decl, m_result_name, m_result_type, true, m_result_is_pointer))
414 result_global->eraseFromParent();
419 bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str,
420 llvm::GlobalVariable *cstr) {
421 lldb_private::Log *log(
422 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
424 Type *ns_str_ty = ns_str->getType();
426 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
427 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
428 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
430 if (!m_CFStringCreateWithBytes) {
431 lldb::addr_t CFStringCreateWithBytes_addr;
433 static lldb_private::ConstString g_CFStringCreateWithBytes_str(
434 "CFStringCreateWithBytes");
436 CFStringCreateWithBytes_addr =
437 m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str);
438 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS) {
440 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
442 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
443 "constant string requires "
444 "CFStringCreateWithBytes\n");
450 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64,
451 CFStringCreateWithBytes_addr);
453 // Build the function type:
455 // CFStringRef CFStringCreateWithBytes (
456 // CFAllocatorRef alloc,
457 // const UInt8 *bytes,
459 // CFStringEncoding encoding,
460 // Boolean isExternalRepresentation
463 // We make the following substitutions:
465 // CFStringRef -> i8*
466 // CFAllocatorRef -> i8*
468 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
469 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
471 Type *arg_type_array[5];
473 arg_type_array[0] = i8_ptr_ty;
474 arg_type_array[1] = i8_ptr_ty;
475 arg_type_array[2] = m_intptr_ty;
476 arg_type_array[3] = i32_ty;
477 arg_type_array[4] = i8_ty;
479 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
481 llvm::Type *CFSCWB_ty =
482 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
484 // Build the constant containing the pointer to the function
485 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
486 Constant *CFSCWB_addr_int =
487 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
488 m_CFStringCreateWithBytes =
489 ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
492 ConstantDataSequential *string_array = NULL;
495 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
497 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
498 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty)
499 : Constant::getNullValue(i8_ptr_ty);
500 Constant *numBytes_arg = ConstantInt::get(
501 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false);
502 int encoding_flags = 0;
503 switch (cstr ? string_array->getElementByteSize() : 1) {
505 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
508 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
511 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
514 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
515 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
517 string_array->getElementByteSize());
519 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
520 Constant *isExternal_arg =
521 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
523 Value *argument_array[5];
525 argument_array[0] = alloc_arg;
526 argument_array[1] = bytes_arg;
527 argument_array[2] = numBytes_arg;
528 argument_array[3] = encoding_arg;
529 argument_array[4] = isExternal_arg;
531 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
533 FunctionValueCache CFSCWB_Caller(
534 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
535 return CallInst::Create(
536 m_CFStringCreateWithBytes, CFSCWB_arguments,
537 "CFStringCreateWithBytes",
538 llvm::cast<Instruction>(
539 m_entry_instruction_finder.GetValue(function)));
542 if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder,
546 "Couldn't replace the NSString with the result of the call");
548 m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an "
549 "Objective-C constant string with a dynamic "
555 ns_str->eraseFromParent();
560 bool IRForTarget::RewriteObjCConstStrings() {
561 lldb_private::Log *log(
562 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
564 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
566 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
567 ve = value_symbol_table.end();
569 std::string value_name = vi->first().str();
570 const char *value_name_cstr = value_name.c_str();
572 if (strstr(value_name_cstr, "_unnamed_cfstring_")) {
573 Value *nsstring_value = vi->second;
575 GlobalVariable *nsstring_global =
576 dyn_cast<GlobalVariable>(nsstring_value);
578 if (!nsstring_global) {
580 log->PutCString("NSString variable is not a GlobalVariable");
582 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
583 "constant string is not a global variable\n");
588 if (!nsstring_global->hasInitializer()) {
590 log->PutCString("NSString variable does not have an initializer");
592 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
593 "constant string does not have an initializer\n");
598 ConstantStruct *nsstring_struct =
599 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
601 if (!nsstring_struct) {
604 "NSString variable's initializer is not a ConstantStruct");
606 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
607 "constant string is not a structure constant\n");
612 // We expect the following structure:
621 if (nsstring_struct->getNumOperands() != 4) {
623 log->Printf("NSString variable's initializer structure has an "
624 "unexpected number of members. Should be 4, is %d",
625 nsstring_struct->getNumOperands());
627 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
628 "Objective-C constant string is not as "
634 Constant *nsstring_member = nsstring_struct->getOperand(2);
636 if (!nsstring_member) {
638 log->PutCString("NSString initializer's str element was empty");
640 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
641 "constant string does not have a string "
647 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
649 if (!nsstring_expr) {
652 "NSString initializer's str element is not a ConstantExpr");
654 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
655 "constant string's string initializer is not "
661 GlobalVariable *cstr_global = nullptr;
663 if (nsstring_expr->getOpcode() == Instruction::GetElementPtr) {
664 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
665 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
666 } else if (nsstring_expr->getOpcode() == Instruction::BitCast) {
667 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
668 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
674 "NSString initializer's str element is not a GlobalVariable");
676 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
677 "constant string initializer\n");
682 if (!cstr_global->hasInitializer()) {
684 log->PutCString("NSString initializer's str element does not have an "
687 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
688 "constant string's string initializer doesn't "
689 "point to initialized data\n");
698 log->PutCString("NSString initializer's str element is not a
702 m_error_stream.Printf("Internal error [IRForTarget]: An
703 Objective-C constant string's string initializer doesn't point to an
709 if (!cstr_array->isCString())
712 log->PutCString("NSString initializer's str element is not a C
716 m_error_stream.Printf("Internal error [IRForTarget]: An
717 Objective-C constant string's string initializer doesn't point to a C
724 ConstantDataArray *cstr_array =
725 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
729 log->Printf("Found NSString constant %s, which contains \"%s\"",
730 value_name_cstr, cstr_array->getAsString().str().c_str());
732 log->Printf("Found NSString constant %s, which contains \"\"",
739 if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
741 log->PutCString("Error rewriting the constant string");
743 // We don't print an error message here because RewriteObjCConstString
744 // has done so for us.
751 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
752 ve = value_symbol_table.end();
754 std::string value_name = vi->first().str();
755 const char *value_name_cstr = value_name.c_str();
757 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) {
758 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
763 "__CFConstantStringClassReference is not a global variable");
765 m_error_stream.Printf("Internal error [IRForTarget]: Found a "
766 "CFConstantStringClassReference, but it is not a "
772 gv->eraseFromParent();
781 static bool IsObjCSelectorRef(Value *value) {
782 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
784 return !(!global_variable || !global_variable->hasName() ||
785 !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"));
788 // This function does not report errors; its callers are responsible.
789 bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
790 lldb_private::Log *log(
791 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
793 LoadInst *load = dyn_cast<LoadInst>(selector_load);
798 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend
799 // gets represented as
801 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> %call = call
802 // i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
804 // where %obj is the object pointer and %tmp is the selector.
806 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
807 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
808 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
810 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr)
811 // and get the string from its target
813 GlobalVariable *_objc_selector_references_ =
814 dyn_cast<GlobalVariable>(load->getPointerOperand());
816 if (!_objc_selector_references_ ||
817 !_objc_selector_references_->hasInitializer())
820 Constant *osr_initializer = _objc_selector_references_->getInitializer();
822 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
824 if (!osr_initializer_expr ||
825 osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
828 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
830 if (!osr_initializer_base)
833 // Find the string's initializer (a ConstantArray) and get the string from it
835 GlobalVariable *_objc_meth_var_name_ =
836 dyn_cast<GlobalVariable>(osr_initializer_base);
838 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
841 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
843 ConstantDataArray *omvn_initializer_array =
844 dyn_cast<ConstantDataArray>(omvn_initializer);
846 if (!omvn_initializer_array->isString())
849 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
852 log->Printf("Found Objective-C selector reference \"%s\"",
853 omvn_initializer_string.c_str());
855 // Construct a call to sel_registerName
857 if (!m_sel_registerName) {
858 lldb::addr_t sel_registerName_addr;
860 static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
861 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str);
862 if (sel_registerName_addr == LLDB_INVALID_ADDRESS)
866 log->Printf("Found sel_registerName at 0x%" PRIx64,
867 sel_registerName_addr);
869 // Build the function type: struct objc_selector
870 // *sel_registerName(uint8_t*)
872 // The below code would be "more correct," but in actuality what's required
874 // Type *sel_type = StructType::get(m_module->getContext());
875 // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
876 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
880 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
882 ArrayRef<Type *> srN_arg_types(type_array, 1);
884 llvm::Type *srN_type =
885 FunctionType::get(sel_ptr_type, srN_arg_types, false);
887 // Build the constant containing the pointer to the function
888 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
889 Constant *srN_addr_int =
890 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
891 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
894 Value *argument_array[1];
896 Constant *omvn_pointer = ConstantExpr::getBitCast(
897 _objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
899 argument_array[0] = omvn_pointer;
901 ArrayRef<Value *> srN_arguments(argument_array, 1);
903 CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments,
904 "sel_registerName", selector_load);
906 // Replace the load with the call in all users
908 selector_load->replaceAllUsesWith(srN_call);
910 selector_load->eraseFromParent();
915 bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
916 lldb_private::Log *log(
917 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
919 BasicBlock::iterator ii;
921 typedef SmallVector<Instruction *, 2> InstrList;
922 typedef InstrList::iterator InstrIterator;
924 InstrList selector_loads;
926 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
927 Instruction &inst = *ii;
929 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
930 if (IsObjCSelectorRef(load->getPointerOperand()))
931 selector_loads.push_back(&inst);
936 for (iter = selector_loads.begin(); iter != selector_loads.end(); ++iter) {
937 if (!RewriteObjCSelector(*iter)) {
938 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
939 "static reference to an Objective-C selector to a "
940 "dynamic reference\n");
944 "Couldn't rewrite a reference to an Objective-C selector");
953 static bool IsObjCClassReference(Value *value) {
954 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
956 return !(!global_variable || !global_variable->hasName() ||
957 !global_variable->getName().startswith("OBJC_CLASS_REFERENCES_"));
960 // This function does not report errors; its callers are responsible.
961 bool IRForTarget::RewriteObjCClassReference(Instruction *class_load) {
962 lldb_private::Log *log(
963 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
965 LoadInst *load = dyn_cast<LoadInst>(class_load);
970 // Unpack the class name from the reference. In LLVM IR, a reference to an
971 // Objective-C class gets represented as
973 // %tmp = load %struct._objc_class*,
974 // %struct._objc_class** @OBJC_CLASS_REFERENCES_, align 4
976 // @"OBJC_CLASS_REFERENCES_ is a bitcast of a character array called
977 // @OBJC_CLASS_NAME_. @OBJC_CLASS_NAME contains the string.
979 // Find the pointer's initializer (a ConstantExpr with opcode BitCast) and
980 // get the string from its target
982 GlobalVariable *_objc_class_references_ =
983 dyn_cast<GlobalVariable>(load->getPointerOperand());
985 if (!_objc_class_references_ ||
986 !_objc_class_references_->hasInitializer())
989 Constant *ocr_initializer = _objc_class_references_->getInitializer();
991 ConstantExpr *ocr_initializer_expr = dyn_cast<ConstantExpr>(ocr_initializer);
993 if (!ocr_initializer_expr ||
994 ocr_initializer_expr->getOpcode() != Instruction::BitCast)
997 Value *ocr_initializer_base = ocr_initializer_expr->getOperand(0);
999 if (!ocr_initializer_base)
1002 // Find the string's initializer (a ConstantArray) and get the string from it
1004 GlobalVariable *_objc_class_name_ =
1005 dyn_cast<GlobalVariable>(ocr_initializer_base);
1007 if (!_objc_class_name_ || !_objc_class_name_->hasInitializer())
1010 Constant *ocn_initializer = _objc_class_name_->getInitializer();
1012 ConstantDataArray *ocn_initializer_array =
1013 dyn_cast<ConstantDataArray>(ocn_initializer);
1015 if (!ocn_initializer_array->isString())
1018 std::string ocn_initializer_string = ocn_initializer_array->getAsString();
1021 log->Printf("Found Objective-C class reference \"%s\"",
1022 ocn_initializer_string.c_str());
1024 // Construct a call to objc_getClass
1026 if (!m_objc_getClass) {
1027 lldb::addr_t objc_getClass_addr;
1029 static lldb_private::ConstString g_objc_getClass_str("objc_getClass");
1030 objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str);
1031 if (objc_getClass_addr == LLDB_INVALID_ADDRESS)
1035 log->Printf("Found objc_getClass at 0x%" PRIx64,
1036 objc_getClass_addr);
1038 // Build the function type: %struct._objc_class *objc_getClass(i8*)
1040 Type *class_type = load->getType();
1041 Type *type_array[1];
1042 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1044 ArrayRef<Type *> ogC_arg_types(type_array, 1);
1046 llvm::Type *ogC_type =
1047 FunctionType::get(class_type, ogC_arg_types, false);
1049 // Build the constant containing the pointer to the function
1050 PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type);
1051 Constant *ogC_addr_int =
1052 ConstantInt::get(m_intptr_ty, objc_getClass_addr, false);
1053 m_objc_getClass = ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty);
1056 Value *argument_array[1];
1058 Constant *ocn_pointer = ConstantExpr::getBitCast(
1059 _objc_class_name_, Type::getInt8PtrTy(m_module->getContext()));
1061 argument_array[0] = ocn_pointer;
1063 ArrayRef<Value *> ogC_arguments(argument_array, 1);
1065 CallInst *ogC_call = CallInst::Create(m_objc_getClass, ogC_arguments,
1066 "objc_getClass", class_load);
1068 // Replace the load with the call in all users
1070 class_load->replaceAllUsesWith(ogC_call);
1072 class_load->eraseFromParent();
1077 bool IRForTarget::RewriteObjCClassReferences(BasicBlock &basic_block) {
1078 lldb_private::Log *log(
1079 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1081 BasicBlock::iterator ii;
1083 typedef SmallVector<Instruction *, 2> InstrList;
1084 typedef InstrList::iterator InstrIterator;
1086 InstrList class_loads;
1088 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1089 Instruction &inst = *ii;
1091 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1092 if (IsObjCClassReference(load->getPointerOperand()))
1093 class_loads.push_back(&inst);
1098 for (iter = class_loads.begin(); iter != class_loads.end(); ++iter) {
1099 if (!RewriteObjCClassReference(*iter)) {
1100 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
1101 "static reference to an Objective-C class to a "
1102 "dynamic reference\n");
1106 "Couldn't rewrite a reference to an Objective-C class");
1115 // This function does not report errors; its callers are responsible.
1116 bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
1117 lldb_private::Log *log(
1118 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1120 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1122 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1124 if (!alloc_md || !alloc_md->getNumOperands())
1127 ConstantInt *constant_int =
1128 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
1133 // We attempt to register this as a new persistent variable with the DeclMap.
1135 uintptr_t ptr = constant_int->getZExtValue();
1137 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1139 lldb_private::TypeFromParser result_decl_type(
1140 decl->getType().getAsOpaquePtr(),
1141 lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext()));
1143 StringRef decl_name(decl->getName());
1144 lldb_private::ConstString persistent_variable_name(decl_name.data(),
1146 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
1147 result_decl_type, false, false))
1150 GlobalVariable *persistent_global = new GlobalVariable(
1151 (*m_module), alloc->getType(), false, /* not constant */
1152 GlobalValue::ExternalLinkage, NULL, /* no initializer */
1153 alloc->getName().str());
1155 // What we're going to do here is make believe this was a regular old
1156 // external variable. That means we need to make the metadata valid.
1158 NamedMDNode *named_metadata =
1159 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1161 llvm::Metadata *values[2];
1162 values[0] = ConstantAsMetadata::get(persistent_global);
1163 values[1] = ConstantAsMetadata::get(constant_int);
1165 ArrayRef<llvm::Metadata *> value_ref(values, 2);
1167 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1168 named_metadata->addOperand(persistent_global_md);
1170 // Now, since the variable is a pointer variable, we will drop in a load of
1171 // that pointer variable.
1173 LoadInst *persistent_load = new LoadInst(persistent_global, "", alloc);
1176 log->Printf("Replacing \"%s\" with \"%s\"", PrintValue(alloc).c_str(),
1177 PrintValue(persistent_load).c_str());
1179 alloc->replaceAllUsesWith(persistent_load);
1180 alloc->eraseFromParent();
1185 bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
1186 if (!m_resolve_vars)
1189 lldb_private::Log *log(
1190 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1192 BasicBlock::iterator ii;
1194 typedef SmallVector<Instruction *, 2> InstrList;
1195 typedef InstrList::iterator InstrIterator;
1197 InstrList pvar_allocs;
1199 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1200 Instruction &inst = *ii;
1202 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
1203 llvm::StringRef alloc_name = alloc->getName();
1205 if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) {
1206 if (alloc_name.find_first_of("0123456789") == 1) {
1208 log->Printf("Rejecting a numeric persistent variable.");
1210 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
1211 "$1, ... are reserved for use as result "
1217 pvar_allocs.push_back(alloc);
1224 for (iter = pvar_allocs.begin(); iter != pvar_allocs.end(); ++iter) {
1225 if (!RewritePersistentAlloc(*iter)) {
1226 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1227 "the creation of a persistent variable\n");
1231 "Couldn't rewrite the creation of a persistent variable");
1240 bool IRForTarget::MaterializeInitializer(uint8_t *data, Constant *initializer) {
1244 lldb_private::Log *log(
1245 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1247 if (log && log->GetVerbose())
1248 log->Printf(" MaterializeInitializer(%p, %s)", (void *)data,
1249 PrintValue(initializer).c_str());
1251 Type *initializer_type = initializer->getType();
1253 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) {
1254 size_t constant_size = m_target_data->getTypeStoreSize(initializer_type);
1255 lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc(
1256 llvm::NextPowerOf2(constant_size) * 8);
1258 lldb_private::Status get_data_error;
1259 return scalar.GetAsMemoryData(data, constant_size,
1260 lldb_private::endian::InlHostByteOrder(),
1261 get_data_error) != 0;
1262 } else if (ConstantDataArray *array_initializer =
1263 dyn_cast<ConstantDataArray>(initializer)) {
1264 if (array_initializer->isString()) {
1265 std::string array_initializer_string = array_initializer->getAsString();
1266 memcpy(data, array_initializer_string.c_str(),
1267 m_target_data->getTypeStoreSize(initializer_type));
1269 ArrayType *array_initializer_type = array_initializer->getType();
1270 Type *array_element_type = array_initializer_type->getElementType();
1272 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1274 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) {
1275 Value *operand_value = array_initializer->getOperand(i);
1276 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1278 if (!operand_constant)
1281 if (!MaterializeInitializer(data + (i * element_size),
1287 } else if (ConstantStruct *struct_initializer =
1288 dyn_cast<ConstantStruct>(initializer)) {
1289 StructType *struct_initializer_type = struct_initializer->getType();
1290 const StructLayout *struct_layout =
1291 m_target_data->getStructLayout(struct_initializer_type);
1293 for (unsigned i = 0; i < struct_initializer->getNumOperands(); ++i) {
1294 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i),
1295 struct_initializer->getOperand(i)))
1299 } else if (isa<ConstantAggregateZero>(initializer)) {
1300 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1306 // This function does not report errors; its callers are responsible.
1307 bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
1308 lldb_private::Log *log(
1309 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1312 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1314 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
1315 switch (constant_expr->getOpcode()) {
1318 case Instruction::GetElementPtr:
1319 case Instruction::BitCast:
1320 Value *s = constant_expr->getOperand(0);
1321 if (!MaybeHandleVariable(s))
1324 } else if (GlobalVariable *global_variable =
1325 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1326 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1329 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1332 if (IsObjCSelectorRef(llvm_value_ptr))
1335 if (!global_variable->hasExternalLinkage())
1339 log->Printf("Found global variable \"%s\" without metadata",
1340 global_variable->getName().str().c_str());
1345 std::string name(named_decl->getName().str());
1347 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1348 if (value_decl == NULL)
1351 lldb_private::CompilerType compiler_type(&value_decl->getASTContext(),
1352 value_decl->getType());
1354 const Type *value_type = NULL;
1356 if (name[0] == '$') {
1357 // The $__lldb_expr_result name indicates the return value has allocated
1358 // as a static variable. Per the comment at
1359 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1360 // variable need to be redirected to the result of dereferencing a
1361 // pointer that is passed in as one of the arguments.
1363 // Consequently, when reporting the size of the type, we report a pointer
1364 // type pointing to the type of $__lldb_expr_result, not the type itself.
1366 // We also do this for any user-declared persistent variables.
1367 compiler_type = compiler_type.GetPointerType();
1368 value_type = PointerType::get(global_variable->getType(), 0);
1370 value_type = global_variable->getType();
1373 llvm::Optional<uint64_t> value_size = compiler_type.GetByteSize(nullptr);
1376 lldb::offset_t value_alignment =
1377 (compiler_type.GetTypeBitAlign() + 7ull) / 8ull;
1380 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64
1381 ", align %" PRIu64 "]",
1383 lldb_private::ClangUtil::GetQualType(compiler_type)
1386 PrintType(value_type).c_str(), *value_size, value_alignment);
1390 !m_decl_map->AddValueToStruct(
1391 named_decl, lldb_private::ConstString(name.c_str()), llvm_value_ptr,
1392 *value_size, value_alignment)) {
1393 if (!global_variable->hasExternalLinkage())
1398 } else if (dyn_cast<llvm::Function>(llvm_value_ptr)) {
1400 log->Printf("Function pointers aren't handled right now");
1408 // This function does not report errors; its callers are responsible.
1409 bool IRForTarget::HandleSymbol(Value *symbol) {
1410 lldb_private::Log *log(
1411 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1413 lldb_private::ConstString name(symbol->getName().str().c_str());
1415 lldb::addr_t symbol_addr =
1416 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1418 if (symbol_addr == LLDB_INVALID_ADDRESS) {
1420 log->Printf("Symbol \"%s\" had no address", name.GetCString());
1426 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1428 Type *symbol_type = symbol->getType();
1430 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1432 Value *symbol_addr_ptr =
1433 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1436 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(),
1437 PrintValue(symbol_addr_ptr).c_str());
1439 symbol->replaceAllUsesWith(symbol_addr_ptr);
1444 bool IRForTarget::MaybeHandleCallArguments(CallInst *Old) {
1445 lldb_private::Log *log(
1446 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1449 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1451 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1452 op_index < num_ops; ++op_index)
1453 if (!MaybeHandleVariable(Old->getArgOperand(
1454 op_index))) // conservatively believe that this is a store
1456 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1457 "one of the arguments of a function call.\n");
1465 bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1466 lldb_private::Log *log(
1467 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1469 GlobalVariable *global_variable =
1470 dyn_cast<GlobalVariable>(classlist_reference);
1472 if (!global_variable)
1475 Constant *initializer = global_variable->getInitializer();
1480 if (!initializer->hasName())
1483 StringRef name(initializer->getName());
1484 lldb_private::ConstString name_cstr(name.str().c_str());
1485 lldb::addr_t class_ptr =
1486 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1489 log->Printf("Found reference to Objective-C class %s (0x%llx)",
1490 name_cstr.AsCString(), (unsigned long long)class_ptr);
1492 if (class_ptr == LLDB_INVALID_ADDRESS)
1495 if (global_variable->use_empty())
1498 SmallVector<LoadInst *, 2> load_instructions;
1500 for (llvm::User *u : global_variable->users()) {
1501 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1502 load_instructions.push_back(load_instruction);
1505 if (load_instructions.empty())
1508 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1510 for (LoadInst *load_instruction : load_instructions) {
1511 Constant *class_bitcast =
1512 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1514 load_instruction->replaceAllUsesWith(class_bitcast);
1516 load_instruction->eraseFromParent();
1522 bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1523 BasicBlock::iterator ii;
1525 std::vector<CallInst *> calls_to_remove;
1527 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1528 Instruction &inst = *ii;
1530 CallInst *call = dyn_cast<CallInst>(&inst);
1532 // MaybeHandleCallArguments handles error reporting; we are silent here
1536 bool remove = false;
1538 llvm::Function *func = call->getCalledFunction();
1540 if (func && func->getName() == "__cxa_atexit")
1543 llvm::Value *val = call->getCalledValue();
1545 if (val && val->getName() == "__cxa_atexit")
1549 calls_to_remove.push_back(call);
1552 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(),
1553 ce = calls_to_remove.end();
1555 (*ci)->eraseFromParent();
1561 bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1562 /////////////////////////////////////////////////////////////////////////
1563 // Prepare the current basic block for execution in the remote process
1566 BasicBlock::iterator ii;
1568 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1569 Instruction &inst = *ii;
1571 CallInst *call = dyn_cast<CallInst>(&inst);
1573 // MaybeHandleCallArguments handles error reporting; we are silent here
1574 if (call && !MaybeHandleCallArguments(call))
1581 bool IRForTarget::ResolveExternals(Function &llvm_function) {
1582 lldb_private::Log *log(
1583 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1585 for (GlobalVariable &global_var : m_module->globals()) {
1586 std::string global_name = global_var.getName().str();
1589 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1590 global_name.c_str(),
1591 static_cast<void *>(DeclForGlobal(&global_var)));
1593 if (global_name.find("OBJC_IVAR") == 0) {
1594 if (!HandleSymbol(&global_var)) {
1595 m_error_stream.Printf("Error [IRForTarget]: Couldn't find Objective-C "
1596 "indirect ivar symbol %s\n",
1597 global_name.c_str());
1601 } else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") !=
1603 if (!HandleObjCClass(&global_var)) {
1604 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1605 "for an Objective-C static method call\n");
1609 } else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") !=
1611 if (!HandleObjCClass(&global_var)) {
1612 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1613 "for an Objective-C static method call\n");
1617 } else if (DeclForGlobal(&global_var)) {
1618 if (!MaybeHandleVariable(&global_var)) {
1619 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1620 "external variable %s\n",
1621 global_name.c_str());
1631 static bool isGuardVariableRef(Value *V) {
1632 Constant *Old = NULL;
1634 if (!(Old = dyn_cast<Constant>(V)))
1637 ConstantExpr *CE = NULL;
1639 if ((CE = dyn_cast<ConstantExpr>(V))) {
1640 if (CE->getOpcode() != Instruction::BitCast)
1643 Old = CE->getOperand(0);
1646 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
1648 if (!GV || !GV->hasName() ||
1649 (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable
1650 !GV->getName().endswith("@4IA"))) // Microsoft ABI guard variable
1658 void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1659 Constant *zero(Constant::getNullValue(guard_load->getType()));
1660 guard_load->replaceAllUsesWith(zero);
1661 guard_load->eraseFromParent();
1664 static void ExciseGuardStore(Instruction *guard_store) {
1665 guard_store->eraseFromParent();
1668 bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1669 ///////////////////////////////////////////////////////
1670 // Eliminate any reference to guard variables found.
1673 BasicBlock::iterator ii;
1675 typedef SmallVector<Instruction *, 2> InstrList;
1676 typedef InstrList::iterator InstrIterator;
1678 InstrList guard_loads;
1679 InstrList guard_stores;
1681 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1682 Instruction &inst = *ii;
1684 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1685 if (isGuardVariableRef(load->getPointerOperand()))
1686 guard_loads.push_back(&inst);
1688 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1689 if (isGuardVariableRef(store->getPointerOperand()))
1690 guard_stores.push_back(&inst);
1695 for (iter = guard_loads.begin(); iter != guard_loads.end(); ++iter)
1696 TurnGuardLoadIntoZero(*iter);
1698 for (iter = guard_stores.begin(); iter != guard_stores.end(); ++iter)
1699 ExciseGuardStore(*iter);
1704 // This function does not report errors; its callers are responsible.
1705 bool IRForTarget::UnfoldConstant(Constant *old_constant,
1706 llvm::Function *llvm_function,
1707 FunctionValueCache &value_maker,
1708 FunctionValueCache &entry_instruction_finder,
1709 lldb_private::Stream &error_stream) {
1710 SmallVector<User *, 16> users;
1712 // We do this because the use list might change, invalidating our iterator.
1713 // Much better to keep a work list ourselves.
1714 for (llvm::User *u : old_constant->users())
1717 for (size_t i = 0; i < users.size(); ++i) {
1718 User *user = users[i];
1720 if (Constant *constant = dyn_cast<Constant>(user)) {
1721 // synthesize a new non-constant equivalent of the constant
1723 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1724 switch (constant_expr->getOpcode()) {
1726 error_stream.Printf("error [IRForTarget internal]: Unhandled "
1727 "constant expression type: \"%s\"",
1728 PrintValue(constant_expr).c_str());
1730 case Instruction::BitCast: {
1731 FunctionValueCache bit_cast_maker(
1732 [&value_maker, &entry_instruction_finder, old_constant,
1733 constant_expr](llvm::Function *function) -> llvm::Value * {
1735 // OperandList[0] is value
1737 if (constant_expr->getOperand(0) != old_constant)
1738 return constant_expr;
1740 return new BitCastInst(
1741 value_maker.GetValue(function), constant_expr->getType(),
1742 "", llvm::cast<Instruction>(
1743 entry_instruction_finder.GetValue(function)));
1746 if (!UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1747 entry_instruction_finder, error_stream))
1750 case Instruction::GetElementPtr: {
1751 // GetElementPtrConstantExpr
1752 // OperandList[0] is base
1753 // OperandList[1]... are indices
1755 FunctionValueCache get_element_pointer_maker(
1756 [&value_maker, &entry_instruction_finder, old_constant,
1757 constant_expr](llvm::Function *function) -> llvm::Value * {
1758 Value *ptr = constant_expr->getOperand(0);
1760 if (ptr == old_constant)
1761 ptr = value_maker.GetValue(function);
1763 std::vector<Value *> index_vector;
1765 unsigned operand_index;
1766 unsigned num_operands = constant_expr->getNumOperands();
1768 for (operand_index = 1; operand_index < num_operands;
1770 Value *operand = constant_expr->getOperand(operand_index);
1772 if (operand == old_constant)
1773 operand = value_maker.GetValue(function);
1775 index_vector.push_back(operand);
1778 ArrayRef<Value *> indices(index_vector);
1780 return GetElementPtrInst::Create(
1781 nullptr, ptr, indices, "",
1782 llvm::cast<Instruction>(
1783 entry_instruction_finder.GetValue(function)));
1786 if (!UnfoldConstant(constant_expr, llvm_function,
1787 get_element_pointer_maker,
1788 entry_instruction_finder, error_stream))
1793 error_stream.Printf(
1794 "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1795 PrintValue(constant).c_str());
1799 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1800 if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1801 error_stream.PutCString("error: Capturing non-local variables in "
1802 "expressions is unsupported.\n");
1805 inst->replaceUsesOfWith(
1806 old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1808 error_stream.Printf(
1809 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1810 PrintValue(user).c_str());
1816 if (!isa<GlobalValue>(old_constant)) {
1817 old_constant->destroyConstant();
1823 bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1824 if (!m_resolve_vars)
1827 lldb_private::Log *log(
1828 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1830 m_decl_map->DoStructLayout();
1833 log->Printf("Element arrangement:");
1835 uint32_t num_elements;
1836 uint32_t element_index;
1839 lldb::offset_t alignment;
1841 if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1844 Function::arg_iterator iter(llvm_function.arg_begin());
1846 if (iter == llvm_function.arg_end()) {
1847 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no "
1848 "arguments (should take at least a struct pointer)");
1853 Argument *argument = &*iter;
1855 if (argument->getName().equals("this")) {
1858 if (iter == llvm_function.arg_end()) {
1859 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1860 "'this' argument (should take a struct pointer "
1867 } else if (argument->getName().equals("self")) {
1870 if (iter == llvm_function.arg_end()) {
1871 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1872 "'self' argument (should take '_cmd' and a struct "
1878 if (!iter->getName().equals("_cmd")) {
1879 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes '%s' "
1880 "after 'self' argument (should take '_cmd')",
1881 iter->getName().str().c_str());
1888 if (iter == llvm_function.arg_end()) {
1889 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1890 "'self' and '_cmd' arguments (should take a struct "
1899 if (!argument->getName().equals("$__lldb_arg")) {
1900 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes an "
1901 "argument named '%s' instead of the struct pointer",
1902 argument->getName().str().c_str());
1908 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
1910 BasicBlock &entry_block(llvm_function.getEntryBlock());
1911 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1913 if (!FirstEntryInstruction) {
1914 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1915 "first instruction in the wrapper for use in "
1921 LLVMContext &context(m_module->getContext());
1922 IntegerType *offset_type(Type::getInt32Ty(context));
1925 m_error_stream.Printf(
1926 "Internal error [IRForTarget]: Couldn't produce an offset type");
1931 for (element_index = 0; element_index < num_elements; ++element_index) {
1932 const clang::NamedDecl *decl = NULL;
1933 Value *value = NULL;
1934 lldb::offset_t offset;
1935 lldb_private::ConstString name;
1937 if (!m_decl_map->GetStructElement(decl, value, offset, name,
1939 m_error_stream.Printf(
1940 "Internal error [IRForTarget]: Structure information is incomplete");
1946 log->Printf(" \"%s\" (\"%s\") placed at %" PRIu64, name.GetCString(),
1947 decl->getNameAsString().c_str(), offset);
1951 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
1953 FunctionValueCache body_result_maker(
1954 [this, name, offset_type, offset, argument,
1955 value](llvm::Function *function) -> llvm::Value * {
1956 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1957 // in cases where the result variable is an rvalue, we have to
1958 // synthesize a dereference of the appropriate structure entry in
1959 // order to produce the static variable that the AST thinks it is
1962 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1963 m_entry_instruction_finder.GetValue(function));
1965 ConstantInt *offset_int(
1966 ConstantInt::get(offset_type, offset, true));
1967 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(
1968 nullptr, argument, offset_int, "", entry_instruction);
1970 if (name == m_result_name && !m_result_is_pointer) {
1971 BitCastInst *bit_cast = new BitCastInst(
1972 get_element_ptr, value->getType()->getPointerTo(), "",
1975 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
1979 BitCastInst *bit_cast = new BitCastInst(
1980 get_element_ptr, value->getType(), "", entry_instruction);
1986 if (Constant *constant = dyn_cast<Constant>(value)) {
1987 if (!UnfoldConstant(constant, &llvm_function, body_result_maker,
1988 m_entry_instruction_finder, m_error_stream)) {
1991 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1992 if (instruction->getParent()->getParent() != &llvm_function) {
1993 m_error_stream.PutCString("error: Capturing non-local variables in "
1994 "expressions is unsupported.\n");
1997 value->replaceAllUsesWith(
1998 body_result_maker.GetValue(instruction->getParent()->getParent()));
2001 log->Printf("Unhandled non-constant type: \"%s\"",
2002 PrintValue(value).c_str());
2006 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2007 var->eraseFromParent();
2012 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]",
2013 (int64_t)alignment, (uint64_t)size);
2018 llvm::Constant *IRForTarget::BuildRelocation(llvm::Type *type,
2020 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2022 llvm::Constant *offset_array[1];
2024 offset_array[0] = offset_int;
2026 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2027 llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext());
2028 llvm::Type *char_pointer_type = char_type->getPointerTo();
2030 llvm::Constant *reloc_placeholder_bitcast =
2031 ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type);
2032 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(
2033 char_type, reloc_placeholder_bitcast, offsets);
2034 llvm::Constant *reloc_bitcast =
2035 ConstantExpr::getBitCast(reloc_getelementptr, type);
2037 return reloc_bitcast;
2040 bool IRForTarget::runOnModule(Module &llvm_module) {
2041 lldb_private::Log *log(
2042 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2044 m_module = &llvm_module;
2045 m_target_data.reset(new DataLayout(m_module));
2046 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
2047 m_target_data->getPointerSizeInBits());
2051 raw_string_ostream oss(s);
2053 m_module->print(oss, NULL);
2057 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2060 Function *const main_function =
2061 m_func_name.IsEmpty() ? nullptr
2062 : m_module->getFunction(m_func_name.GetStringRef());
2064 if (!m_func_name.IsEmpty() && !main_function) {
2066 log->Printf("Couldn't find \"%s()\" in the module",
2067 m_func_name.AsCString());
2069 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find wrapper "
2070 "'%s' in the module",
2071 m_func_name.AsCString());
2076 if (main_function) {
2077 if (!FixFunctionLinkage(*main_function)) {
2079 log->Printf("Couldn't fix the linkage for the function");
2085 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2087 m_reloc_placeholder = new llvm::GlobalVariable(
2088 (*m_module), int8_ty, false /* IsConstant */,
2089 GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty),
2090 "reloc_placeholder", NULL /* InsertBefore */,
2091 GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */);
2093 ////////////////////////////////////////////////////////////
2094 // Replace $__lldb_expr_result with a persistent variable
2097 if (main_function) {
2098 if (!CreateResultVariable(*main_function)) {
2100 log->Printf("CreateResultVariable() failed");
2102 // CreateResultVariable() reports its own errors, so we don't do so here
2108 if (log && log->GetVerbose()) {
2110 raw_string_ostream oss(s);
2112 m_module->print(oss, NULL);
2116 log->Printf("Module after creating the result variable: \n\"%s\"",
2120 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2122 llvm::Function *function = &*fi;
2124 if (function->begin() == function->end())
2127 Function::iterator bbi;
2129 for (bbi = function->begin(); bbi != function->end(); ++bbi) {
2130 if (!RemoveGuards(*bbi)) {
2132 log->Printf("RemoveGuards() failed");
2134 // RemoveGuards() reports its own errors, so we don't do so here
2139 if (!RewritePersistentAllocs(*bbi)) {
2141 log->Printf("RewritePersistentAllocs() failed");
2143 // RewritePersistentAllocs() reports its own errors, so we don't do so
2149 if (!RemoveCXAAtExit(*bbi)) {
2151 log->Printf("RemoveCXAAtExit() failed");
2153 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2160 ///////////////////////////////////////////////////////////////////////////////
2161 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2164 if (!RewriteObjCConstStrings()) {
2166 log->Printf("RewriteObjCConstStrings() failed");
2168 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2173 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2175 llvm::Function *function = &*fi;
2177 for (llvm::Function::iterator bbi = function->begin(),
2178 bbe = function->end();
2179 bbi != bbe; ++bbi) {
2180 if (!RewriteObjCSelectors(*bbi)) {
2182 log->Printf("RewriteObjCSelectors() failed");
2184 // RewriteObjCSelectors() reports its own errors, so we don't do so
2190 if (!RewriteObjCClassReferences(*bbi)) {
2192 log->Printf("RewriteObjCClassReferences() failed");
2194 // RewriteObjCClasses() reports its own errors, so we don't do so here
2201 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2203 llvm::Function *function = &*fi;
2205 for (llvm::Function::iterator bbi = function->begin(),
2206 bbe = function->end();
2207 bbi != bbe; ++bbi) {
2208 if (!ResolveCalls(*bbi)) {
2210 log->Printf("ResolveCalls() failed");
2212 // ResolveCalls() reports its own errors, so we don't do so here
2219 ////////////////////////////////////////////////////////////////////////
2220 // Run function-level passes that only make sense on the main function
2223 if (main_function) {
2224 if (!ResolveExternals(*main_function)) {
2226 log->Printf("ResolveExternals() failed");
2228 // ResolveExternals() reports its own errors, so we don't do so here
2233 if (!ReplaceVariables(*main_function)) {
2235 log->Printf("ReplaceVariables() failed");
2237 // ReplaceVariables() reports its own errors, so we don't do so here
2243 if (log && log->GetVerbose()) {
2245 raw_string_ostream oss(s);
2247 m_module->print(oss, NULL);
2251 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2257 void IRForTarget::assignPassManager(PMStack &pass_mgr_stack,
2258 PassManagerType pass_mgr_type) {}
2260 PassManagerType IRForTarget::getPotentialPassManagerType() const {
2261 return PMT_ModulePassManager;