1 //===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "IRForTarget.h"
11 #include "ClangExpressionDeclMap.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/LegacyPassManager.h"
19 #include "llvm/IR/Metadata.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/ValueSymbolTable.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Transforms/IPO.h"
25 #include "clang/AST/ASTContext.h"
27 #include "lldb/Core/dwarf.h"
28 #include "lldb/Expression/IRExecutionUnit.h"
29 #include "lldb/Expression/IRInterpreter.h"
30 #include "lldb/Symbol/ClangASTContext.h"
31 #include "lldb/Symbol/ClangUtil.h"
32 #include "lldb/Symbol/CompilerType.h"
33 #include "lldb/Utility/ConstString.h"
34 #include "lldb/Utility/DataBufferHeap.h"
35 #include "lldb/Utility/Endian.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/Scalar.h"
38 #include "lldb/Utility/StreamString.h"
46 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker)
47 : m_maker(maker), m_values() {}
49 IRForTarget::FunctionValueCache::~FunctionValueCache() {}
52 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) {
53 if (!m_values.count(function)) {
54 llvm::Value *ret = m_maker(function);
55 m_values[function] = ret;
58 return m_values[function];
61 static llvm::Value *FindEntryInstruction(llvm::Function *function) {
62 if (function->empty())
65 return function->getEntryBlock().getFirstNonPHIOrDbg();
68 IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
70 lldb_private::IRExecutionUnit &execution_unit,
71 lldb_private::Stream &error_stream,
72 const char *func_name)
73 : ModulePass(ID), m_resolve_vars(resolve_vars), m_func_name(func_name),
74 m_module(nullptr), m_decl_map(decl_map),
75 m_CFStringCreateWithBytes(nullptr), m_sel_registerName(nullptr),
76 m_objc_getClass(nullptr), m_intptr_ty(nullptr),
77 m_error_stream(error_stream), m_execution_unit(execution_unit),
78 m_result_store(nullptr), m_result_is_pointer(false),
79 m_reloc_placeholder(nullptr),
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 = nullptr;
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, nullptr, /* 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 bool missing_weak = false;
437 CFStringCreateWithBytes_addr =
438 m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str,
440 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS || missing_weak) {
442 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
444 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
445 "constant string requires "
446 "CFStringCreateWithBytes\n");
452 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64,
453 CFStringCreateWithBytes_addr);
455 // Build the function type:
457 // CFStringRef CFStringCreateWithBytes (
458 // CFAllocatorRef alloc,
459 // const UInt8 *bytes,
461 // CFStringEncoding encoding,
462 // Boolean isExternalRepresentation
465 // We make the following substitutions:
467 // CFStringRef -> i8*
468 // CFAllocatorRef -> i8*
470 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
471 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
473 Type *arg_type_array[5];
475 arg_type_array[0] = i8_ptr_ty;
476 arg_type_array[1] = i8_ptr_ty;
477 arg_type_array[2] = m_intptr_ty;
478 arg_type_array[3] = i32_ty;
479 arg_type_array[4] = i8_ty;
481 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
483 llvm::FunctionType *CFSCWB_ty =
484 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
486 // Build the constant containing the pointer to the function
487 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
488 Constant *CFSCWB_addr_int =
489 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
490 m_CFStringCreateWithBytes = {
491 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)};
494 ConstantDataSequential *string_array = nullptr;
497 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
499 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
500 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty)
501 : Constant::getNullValue(i8_ptr_ty);
502 Constant *numBytes_arg = ConstantInt::get(
503 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false);
504 int encoding_flags = 0;
505 switch (cstr ? string_array->getElementByteSize() : 1) {
507 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
510 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
513 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
516 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
517 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
519 string_array->getElementByteSize());
521 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
522 Constant *isExternal_arg =
523 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
525 Value *argument_array[5];
527 argument_array[0] = alloc_arg;
528 argument_array[1] = bytes_arg;
529 argument_array[2] = numBytes_arg;
530 argument_array[3] = encoding_arg;
531 argument_array[4] = isExternal_arg;
533 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
535 FunctionValueCache CFSCWB_Caller(
536 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
537 return CallInst::Create(
538 m_CFStringCreateWithBytes, CFSCWB_arguments,
539 "CFStringCreateWithBytes",
540 llvm::cast<Instruction>(
541 m_entry_instruction_finder.GetValue(function)));
544 if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder,
548 "Couldn't replace the NSString with the result of the call");
550 m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an "
551 "Objective-C constant string with a dynamic "
557 ns_str->eraseFromParent();
562 bool IRForTarget::RewriteObjCConstStrings() {
563 lldb_private::Log *log(
564 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
566 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
568 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
569 ve = value_symbol_table.end();
571 std::string value_name = vi->first().str();
572 const char *value_name_cstr = value_name.c_str();
574 if (strstr(value_name_cstr, "_unnamed_cfstring_")) {
575 Value *nsstring_value = vi->second;
577 GlobalVariable *nsstring_global =
578 dyn_cast<GlobalVariable>(nsstring_value);
580 if (!nsstring_global) {
582 log->PutCString("NSString variable is not a GlobalVariable");
584 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
585 "constant string is not a global variable\n");
590 if (!nsstring_global->hasInitializer()) {
592 log->PutCString("NSString variable does not have an initializer");
594 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
595 "constant string does not have an initializer\n");
600 ConstantStruct *nsstring_struct =
601 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
603 if (!nsstring_struct) {
606 "NSString variable's initializer is not a ConstantStruct");
608 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
609 "constant string is not a structure constant\n");
614 // We expect the following structure:
623 if (nsstring_struct->getNumOperands() != 4) {
625 log->Printf("NSString variable's initializer structure has an "
626 "unexpected number of members. Should be 4, is %d",
627 nsstring_struct->getNumOperands());
629 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
630 "Objective-C constant string is not as "
636 Constant *nsstring_member = nsstring_struct->getOperand(2);
638 if (!nsstring_member) {
640 log->PutCString("NSString initializer's str element was empty");
642 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
643 "constant string does not have a string "
649 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
651 if (!nsstring_expr) {
654 "NSString initializer's str element is not a ConstantExpr");
656 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
657 "constant string's string initializer is not "
663 GlobalVariable *cstr_global = nullptr;
665 if (nsstring_expr->getOpcode() == Instruction::GetElementPtr) {
666 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
667 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
668 } else if (nsstring_expr->getOpcode() == Instruction::BitCast) {
669 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
670 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
676 "NSString initializer's str element is not a GlobalVariable");
678 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
679 "constant string initializer\n");
684 if (!cstr_global->hasInitializer()) {
686 log->PutCString("NSString initializer's str element does not have an "
689 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
690 "constant string's string initializer doesn't "
691 "point to initialized data\n");
700 log->PutCString("NSString initializer's str element is not a
704 m_error_stream.Printf("Internal error [IRForTarget]: An
705 Objective-C constant string's string initializer doesn't point to an
711 if (!cstr_array->isCString())
714 log->PutCString("NSString initializer's str element is not a C
718 m_error_stream.Printf("Internal error [IRForTarget]: An
719 Objective-C constant string's string initializer doesn't point to a C
726 ConstantDataArray *cstr_array =
727 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
731 log->Printf("Found NSString constant %s, which contains \"%s\"",
732 value_name_cstr, cstr_array->getAsString().str().c_str());
734 log->Printf("Found NSString constant %s, which contains \"\"",
739 cstr_global = nullptr;
741 if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
743 log->PutCString("Error rewriting the constant string");
745 // We don't print an error message here because RewriteObjCConstString
746 // has done so for us.
753 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(),
754 ve = value_symbol_table.end();
756 std::string value_name = vi->first().str();
757 const char *value_name_cstr = value_name.c_str();
759 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) {
760 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
765 "__CFConstantStringClassReference is not a global variable");
767 m_error_stream.Printf("Internal error [IRForTarget]: Found a "
768 "CFConstantStringClassReference, but it is not a "
774 gv->eraseFromParent();
783 static bool IsObjCSelectorRef(Value *value) {
784 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
786 return !(!global_variable || !global_variable->hasName() ||
787 !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"));
790 // This function does not report errors; its callers are responsible.
791 bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
792 lldb_private::Log *log(
793 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
795 LoadInst *load = dyn_cast<LoadInst>(selector_load);
800 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend
801 // gets represented as
803 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> %call = call
804 // i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
806 // where %obj is the object pointer and %tmp is the selector.
808 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
809 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
810 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
812 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr)
813 // and get the string from its target
815 GlobalVariable *_objc_selector_references_ =
816 dyn_cast<GlobalVariable>(load->getPointerOperand());
818 if (!_objc_selector_references_ ||
819 !_objc_selector_references_->hasInitializer())
822 Constant *osr_initializer = _objc_selector_references_->getInitializer();
824 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
826 if (!osr_initializer_expr ||
827 osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
830 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
832 if (!osr_initializer_base)
835 // Find the string's initializer (a ConstantArray) and get the string from it
837 GlobalVariable *_objc_meth_var_name_ =
838 dyn_cast<GlobalVariable>(osr_initializer_base);
840 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
843 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
845 ConstantDataArray *omvn_initializer_array =
846 dyn_cast<ConstantDataArray>(omvn_initializer);
848 if (!omvn_initializer_array->isString())
851 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
854 log->Printf("Found Objective-C selector reference \"%s\"",
855 omvn_initializer_string.c_str());
857 // Construct a call to sel_registerName
859 if (!m_sel_registerName) {
860 lldb::addr_t sel_registerName_addr;
862 bool missing_weak = false;
863 static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
864 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str,
866 if (sel_registerName_addr == LLDB_INVALID_ADDRESS || missing_weak)
870 log->Printf("Found sel_registerName at 0x%" PRIx64,
871 sel_registerName_addr);
873 // Build the function type: struct objc_selector
874 // *sel_registerName(uint8_t*)
876 // The below code would be "more correct," but in actuality what's required
878 // Type *sel_type = StructType::get(m_module->getContext());
879 // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
880 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
884 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
886 ArrayRef<Type *> srN_arg_types(type_array, 1);
888 llvm::FunctionType *srN_type =
889 FunctionType::get(sel_ptr_type, srN_arg_types, false);
891 // Build the constant containing the pointer to the function
892 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
893 Constant *srN_addr_int =
894 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
895 m_sel_registerName = {srN_type,
896 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
899 Value *argument_array[1];
901 Constant *omvn_pointer = ConstantExpr::getBitCast(
902 _objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
904 argument_array[0] = omvn_pointer;
906 ArrayRef<Value *> srN_arguments(argument_array, 1);
908 CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments,
909 "sel_registerName", selector_load);
911 // Replace the load with the call in all users
913 selector_load->replaceAllUsesWith(srN_call);
915 selector_load->eraseFromParent();
920 bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
921 lldb_private::Log *log(
922 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
924 BasicBlock::iterator ii;
926 typedef SmallVector<Instruction *, 2> InstrList;
927 typedef InstrList::iterator InstrIterator;
929 InstrList selector_loads;
931 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
932 Instruction &inst = *ii;
934 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
935 if (IsObjCSelectorRef(load->getPointerOperand()))
936 selector_loads.push_back(&inst);
941 for (iter = selector_loads.begin(); iter != selector_loads.end(); ++iter) {
942 if (!RewriteObjCSelector(*iter)) {
943 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
944 "static reference to an Objective-C selector to a "
945 "dynamic reference\n");
949 "Couldn't rewrite a reference to an Objective-C selector");
958 static bool IsObjCClassReference(Value *value) {
959 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
961 return !(!global_variable || !global_variable->hasName() ||
962 !global_variable->getName().startswith("OBJC_CLASS_REFERENCES_"));
965 // This function does not report errors; its callers are responsible.
966 bool IRForTarget::RewriteObjCClassReference(Instruction *class_load) {
967 lldb_private::Log *log(
968 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
970 LoadInst *load = dyn_cast<LoadInst>(class_load);
975 // Unpack the class name from the reference. In LLVM IR, a reference to an
976 // Objective-C class gets represented as
978 // %tmp = load %struct._objc_class*,
979 // %struct._objc_class** @OBJC_CLASS_REFERENCES_, align 4
981 // @"OBJC_CLASS_REFERENCES_ is a bitcast of a character array called
982 // @OBJC_CLASS_NAME_. @OBJC_CLASS_NAME contains the string.
984 // Find the pointer's initializer (a ConstantExpr with opcode BitCast) and
985 // get the string from its target
987 GlobalVariable *_objc_class_references_ =
988 dyn_cast<GlobalVariable>(load->getPointerOperand());
990 if (!_objc_class_references_ ||
991 !_objc_class_references_->hasInitializer())
994 Constant *ocr_initializer = _objc_class_references_->getInitializer();
996 ConstantExpr *ocr_initializer_expr = dyn_cast<ConstantExpr>(ocr_initializer);
998 if (!ocr_initializer_expr ||
999 ocr_initializer_expr->getOpcode() != Instruction::BitCast)
1002 Value *ocr_initializer_base = ocr_initializer_expr->getOperand(0);
1004 if (!ocr_initializer_base)
1007 // Find the string's initializer (a ConstantArray) and get the string from it
1009 GlobalVariable *_objc_class_name_ =
1010 dyn_cast<GlobalVariable>(ocr_initializer_base);
1012 if (!_objc_class_name_ || !_objc_class_name_->hasInitializer())
1015 Constant *ocn_initializer = _objc_class_name_->getInitializer();
1017 ConstantDataArray *ocn_initializer_array =
1018 dyn_cast<ConstantDataArray>(ocn_initializer);
1020 if (!ocn_initializer_array->isString())
1023 std::string ocn_initializer_string = ocn_initializer_array->getAsString();
1026 log->Printf("Found Objective-C class reference \"%s\"",
1027 ocn_initializer_string.c_str());
1029 // Construct a call to objc_getClass
1031 if (!m_objc_getClass) {
1032 lldb::addr_t objc_getClass_addr;
1034 bool missing_weak = false;
1035 static lldb_private::ConstString g_objc_getClass_str("objc_getClass");
1036 objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str,
1038 if (objc_getClass_addr == LLDB_INVALID_ADDRESS || missing_weak)
1042 log->Printf("Found objc_getClass at 0x%" PRIx64,
1043 objc_getClass_addr);
1045 // Build the function type: %struct._objc_class *objc_getClass(i8*)
1047 Type *class_type = load->getType();
1048 Type *type_array[1];
1049 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1051 ArrayRef<Type *> ogC_arg_types(type_array, 1);
1053 llvm::FunctionType *ogC_type =
1054 FunctionType::get(class_type, ogC_arg_types, false);
1056 // Build the constant containing the pointer to the function
1057 PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type);
1058 Constant *ogC_addr_int =
1059 ConstantInt::get(m_intptr_ty, objc_getClass_addr, false);
1060 m_objc_getClass = {ogC_type,
1061 ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty)};
1064 Value *argument_array[1];
1066 Constant *ocn_pointer = ConstantExpr::getBitCast(
1067 _objc_class_name_, Type::getInt8PtrTy(m_module->getContext()));
1069 argument_array[0] = ocn_pointer;
1071 ArrayRef<Value *> ogC_arguments(argument_array, 1);
1073 CallInst *ogC_call = CallInst::Create(m_objc_getClass, ogC_arguments,
1074 "objc_getClass", class_load);
1076 // Replace the load with the call in all users
1078 class_load->replaceAllUsesWith(ogC_call);
1080 class_load->eraseFromParent();
1085 bool IRForTarget::RewriteObjCClassReferences(BasicBlock &basic_block) {
1086 lldb_private::Log *log(
1087 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1089 BasicBlock::iterator ii;
1091 typedef SmallVector<Instruction *, 2> InstrList;
1092 typedef InstrList::iterator InstrIterator;
1094 InstrList class_loads;
1096 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1097 Instruction &inst = *ii;
1099 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1100 if (IsObjCClassReference(load->getPointerOperand()))
1101 class_loads.push_back(&inst);
1106 for (iter = class_loads.begin(); iter != class_loads.end(); ++iter) {
1107 if (!RewriteObjCClassReference(*iter)) {
1108 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
1109 "static reference to an Objective-C class to a "
1110 "dynamic reference\n");
1114 "Couldn't rewrite a reference to an Objective-C class");
1123 // This function does not report errors; its callers are responsible.
1124 bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
1125 lldb_private::Log *log(
1126 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1128 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1130 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1132 if (!alloc_md || !alloc_md->getNumOperands())
1135 ConstantInt *constant_int =
1136 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
1141 // We attempt to register this as a new persistent variable with the DeclMap.
1143 uintptr_t ptr = constant_int->getZExtValue();
1145 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1147 lldb_private::TypeFromParser result_decl_type(
1148 decl->getType().getAsOpaquePtr(),
1149 lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext()));
1151 StringRef decl_name(decl->getName());
1152 lldb_private::ConstString persistent_variable_name(decl_name.data(),
1154 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
1155 result_decl_type, false, false))
1158 GlobalVariable *persistent_global = new GlobalVariable(
1159 (*m_module), alloc->getType(), false, /* not constant */
1160 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
1161 alloc->getName().str());
1163 // What we're going to do here is make believe this was a regular old
1164 // external variable. That means we need to make the metadata valid.
1166 NamedMDNode *named_metadata =
1167 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1169 llvm::Metadata *values[2];
1170 values[0] = ConstantAsMetadata::get(persistent_global);
1171 values[1] = ConstantAsMetadata::get(constant_int);
1173 ArrayRef<llvm::Metadata *> value_ref(values, 2);
1175 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1176 named_metadata->addOperand(persistent_global_md);
1178 // Now, since the variable is a pointer variable, we will drop in a load of
1179 // that pointer variable.
1181 LoadInst *persistent_load = new LoadInst(persistent_global, "", alloc);
1184 log->Printf("Replacing \"%s\" with \"%s\"", PrintValue(alloc).c_str(),
1185 PrintValue(persistent_load).c_str());
1187 alloc->replaceAllUsesWith(persistent_load);
1188 alloc->eraseFromParent();
1193 bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
1194 if (!m_resolve_vars)
1197 lldb_private::Log *log(
1198 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1200 BasicBlock::iterator ii;
1202 typedef SmallVector<Instruction *, 2> InstrList;
1203 typedef InstrList::iterator InstrIterator;
1205 InstrList pvar_allocs;
1207 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1208 Instruction &inst = *ii;
1210 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
1211 llvm::StringRef alloc_name = alloc->getName();
1213 if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) {
1214 if (alloc_name.find_first_of("0123456789") == 1) {
1216 log->Printf("Rejecting a numeric persistent variable.");
1218 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
1219 "$1, ... are reserved for use as result "
1225 pvar_allocs.push_back(alloc);
1232 for (iter = pvar_allocs.begin(); iter != pvar_allocs.end(); ++iter) {
1233 if (!RewritePersistentAlloc(*iter)) {
1234 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1235 "the creation of a persistent variable\n");
1239 "Couldn't rewrite the creation of a persistent variable");
1248 bool IRForTarget::MaterializeInitializer(uint8_t *data, Constant *initializer) {
1252 lldb_private::Log *log(
1253 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1255 if (log && log->GetVerbose())
1256 log->Printf(" MaterializeInitializer(%p, %s)", (void *)data,
1257 PrintValue(initializer).c_str());
1259 Type *initializer_type = initializer->getType();
1261 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) {
1262 size_t constant_size = m_target_data->getTypeStoreSize(initializer_type);
1263 lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc(
1264 llvm::NextPowerOf2(constant_size) * 8);
1266 lldb_private::Status get_data_error;
1267 return scalar.GetAsMemoryData(data, constant_size,
1268 lldb_private::endian::InlHostByteOrder(),
1269 get_data_error) != 0;
1270 } else if (ConstantDataArray *array_initializer =
1271 dyn_cast<ConstantDataArray>(initializer)) {
1272 if (array_initializer->isString()) {
1273 std::string array_initializer_string = array_initializer->getAsString();
1274 memcpy(data, array_initializer_string.c_str(),
1275 m_target_data->getTypeStoreSize(initializer_type));
1277 ArrayType *array_initializer_type = array_initializer->getType();
1278 Type *array_element_type = array_initializer_type->getElementType();
1280 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1282 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) {
1283 Value *operand_value = array_initializer->getOperand(i);
1284 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1286 if (!operand_constant)
1289 if (!MaterializeInitializer(data + (i * element_size),
1295 } else if (ConstantStruct *struct_initializer =
1296 dyn_cast<ConstantStruct>(initializer)) {
1297 StructType *struct_initializer_type = struct_initializer->getType();
1298 const StructLayout *struct_layout =
1299 m_target_data->getStructLayout(struct_initializer_type);
1301 for (unsigned i = 0; i < struct_initializer->getNumOperands(); ++i) {
1302 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i),
1303 struct_initializer->getOperand(i)))
1307 } else if (isa<ConstantAggregateZero>(initializer)) {
1308 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1314 // This function does not report errors; its callers are responsible.
1315 bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
1316 lldb_private::Log *log(
1317 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1320 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1322 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
1323 switch (constant_expr->getOpcode()) {
1326 case Instruction::GetElementPtr:
1327 case Instruction::BitCast:
1328 Value *s = constant_expr->getOperand(0);
1329 if (!MaybeHandleVariable(s))
1332 } else if (GlobalVariable *global_variable =
1333 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1334 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1337 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1340 if (IsObjCSelectorRef(llvm_value_ptr))
1343 if (!global_variable->hasExternalLinkage())
1347 log->Printf("Found global variable \"%s\" without metadata",
1348 global_variable->getName().str().c_str());
1353 std::string name(named_decl->getName().str());
1355 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1356 if (value_decl == nullptr)
1359 lldb_private::CompilerType compiler_type(&value_decl->getASTContext(),
1360 value_decl->getType());
1362 const Type *value_type = nullptr;
1364 if (name[0] == '$') {
1365 // The $__lldb_expr_result name indicates the return value has allocated
1366 // as a static variable. Per the comment at
1367 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1368 // variable need to be redirected to the result of dereferencing a
1369 // pointer that is passed in as one of the arguments.
1371 // Consequently, when reporting the size of the type, we report a pointer
1372 // type pointing to the type of $__lldb_expr_result, not the type itself.
1374 // We also do this for any user-declared persistent variables.
1375 compiler_type = compiler_type.GetPointerType();
1376 value_type = PointerType::get(global_variable->getType(), 0);
1378 value_type = global_variable->getType();
1381 llvm::Optional<uint64_t> value_size = compiler_type.GetByteSize(nullptr);
1384 lldb::offset_t value_alignment =
1385 (compiler_type.GetTypeBitAlign() + 7ull) / 8ull;
1388 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64
1389 ", align %" PRIu64 "]",
1391 lldb_private::ClangUtil::GetQualType(compiler_type)
1394 PrintType(value_type).c_str(), *value_size, value_alignment);
1398 !m_decl_map->AddValueToStruct(
1399 named_decl, lldb_private::ConstString(name.c_str()), llvm_value_ptr,
1400 *value_size, value_alignment)) {
1401 if (!global_variable->hasExternalLinkage())
1406 } else if (dyn_cast<llvm::Function>(llvm_value_ptr)) {
1408 log->Printf("Function pointers aren't handled right now");
1416 // This function does not report errors; its callers are responsible.
1417 bool IRForTarget::HandleSymbol(Value *symbol) {
1418 lldb_private::Log *log(
1419 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1421 lldb_private::ConstString name(symbol->getName().str().c_str());
1423 lldb::addr_t symbol_addr =
1424 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1426 if (symbol_addr == LLDB_INVALID_ADDRESS) {
1428 log->Printf("Symbol \"%s\" had no address", name.GetCString());
1434 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1436 Type *symbol_type = symbol->getType();
1438 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1440 Value *symbol_addr_ptr =
1441 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1444 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(),
1445 PrintValue(symbol_addr_ptr).c_str());
1447 symbol->replaceAllUsesWith(symbol_addr_ptr);
1452 bool IRForTarget::MaybeHandleCallArguments(CallInst *Old) {
1453 lldb_private::Log *log(
1454 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1457 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1459 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1460 op_index < num_ops; ++op_index)
1461 if (!MaybeHandleVariable(Old->getArgOperand(
1462 op_index))) // conservatively believe that this is a store
1464 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1465 "one of the arguments of a function call.\n");
1473 bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1474 lldb_private::Log *log(
1475 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1477 GlobalVariable *global_variable =
1478 dyn_cast<GlobalVariable>(classlist_reference);
1480 if (!global_variable)
1483 Constant *initializer = global_variable->getInitializer();
1488 if (!initializer->hasName())
1491 StringRef name(initializer->getName());
1492 lldb_private::ConstString name_cstr(name.str().c_str());
1493 lldb::addr_t class_ptr =
1494 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1497 log->Printf("Found reference to Objective-C class %s (0x%llx)",
1498 name_cstr.AsCString(), (unsigned long long)class_ptr);
1500 if (class_ptr == LLDB_INVALID_ADDRESS)
1503 if (global_variable->use_empty())
1506 SmallVector<LoadInst *, 2> load_instructions;
1508 for (llvm::User *u : global_variable->users()) {
1509 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1510 load_instructions.push_back(load_instruction);
1513 if (load_instructions.empty())
1516 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1518 for (LoadInst *load_instruction : load_instructions) {
1519 Constant *class_bitcast =
1520 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1522 load_instruction->replaceAllUsesWith(class_bitcast);
1524 load_instruction->eraseFromParent();
1530 bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1531 BasicBlock::iterator ii;
1533 std::vector<CallInst *> calls_to_remove;
1535 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1536 Instruction &inst = *ii;
1538 CallInst *call = dyn_cast<CallInst>(&inst);
1540 // MaybeHandleCallArguments handles error reporting; we are silent here
1544 bool remove = false;
1546 llvm::Function *func = call->getCalledFunction();
1548 if (func && func->getName() == "__cxa_atexit")
1551 llvm::Value *val = call->getCalledValue();
1553 if (val && val->getName() == "__cxa_atexit")
1557 calls_to_remove.push_back(call);
1560 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(),
1561 ce = calls_to_remove.end();
1563 (*ci)->eraseFromParent();
1569 bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1570 /////////////////////////////////////////////////////////////////////////
1571 // Prepare the current basic block for execution in the remote process
1574 BasicBlock::iterator ii;
1576 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1577 Instruction &inst = *ii;
1579 CallInst *call = dyn_cast<CallInst>(&inst);
1581 // MaybeHandleCallArguments handles error reporting; we are silent here
1582 if (call && !MaybeHandleCallArguments(call))
1589 bool IRForTarget::ResolveExternals(Function &llvm_function) {
1590 lldb_private::Log *log(
1591 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1593 for (GlobalVariable &global_var : m_module->globals()) {
1594 std::string global_name = global_var.getName().str();
1597 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1598 global_name.c_str(),
1599 static_cast<void *>(DeclForGlobal(&global_var)));
1601 if (global_name.find("OBJC_IVAR") == 0) {
1602 if (!HandleSymbol(&global_var)) {
1603 m_error_stream.Printf("Error [IRForTarget]: Couldn't find Objective-C "
1604 "indirect ivar symbol %s\n",
1605 global_name.c_str());
1609 } else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") !=
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 (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") !=
1619 if (!HandleObjCClass(&global_var)) {
1620 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1621 "for an Objective-C static method call\n");
1625 } else if (DeclForGlobal(&global_var)) {
1626 if (!MaybeHandleVariable(&global_var)) {
1627 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1628 "external variable %s\n",
1629 global_name.c_str());
1639 static bool isGuardVariableRef(Value *V) {
1640 Constant *Old = nullptr;
1642 if (!(Old = dyn_cast<Constant>(V)))
1645 ConstantExpr *CE = nullptr;
1647 if ((CE = dyn_cast<ConstantExpr>(V))) {
1648 if (CE->getOpcode() != Instruction::BitCast)
1651 Old = CE->getOperand(0);
1654 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
1656 if (!GV || !GV->hasName() ||
1657 (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable
1658 !GV->getName().endswith("@4IA"))) // Microsoft ABI guard variable
1666 void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1667 Constant *zero(Constant::getNullValue(guard_load->getType()));
1668 guard_load->replaceAllUsesWith(zero);
1669 guard_load->eraseFromParent();
1672 static void ExciseGuardStore(Instruction *guard_store) {
1673 guard_store->eraseFromParent();
1676 bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1677 ///////////////////////////////////////////////////////
1678 // Eliminate any reference to guard variables found.
1681 BasicBlock::iterator ii;
1683 typedef SmallVector<Instruction *, 2> InstrList;
1684 typedef InstrList::iterator InstrIterator;
1686 InstrList guard_loads;
1687 InstrList guard_stores;
1689 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) {
1690 Instruction &inst = *ii;
1692 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1693 if (isGuardVariableRef(load->getPointerOperand()))
1694 guard_loads.push_back(&inst);
1696 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1697 if (isGuardVariableRef(store->getPointerOperand()))
1698 guard_stores.push_back(&inst);
1703 for (iter = guard_loads.begin(); iter != guard_loads.end(); ++iter)
1704 TurnGuardLoadIntoZero(*iter);
1706 for (iter = guard_stores.begin(); iter != guard_stores.end(); ++iter)
1707 ExciseGuardStore(*iter);
1712 // This function does not report errors; its callers are responsible.
1713 bool IRForTarget::UnfoldConstant(Constant *old_constant,
1714 llvm::Function *llvm_function,
1715 FunctionValueCache &value_maker,
1716 FunctionValueCache &entry_instruction_finder,
1717 lldb_private::Stream &error_stream) {
1718 SmallVector<User *, 16> users;
1720 // We do this because the use list might change, invalidating our iterator.
1721 // Much better to keep a work list ourselves.
1722 for (llvm::User *u : old_constant->users())
1725 for (size_t i = 0; i < users.size(); ++i) {
1726 User *user = users[i];
1728 if (Constant *constant = dyn_cast<Constant>(user)) {
1729 // synthesize a new non-constant equivalent of the constant
1731 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1732 switch (constant_expr->getOpcode()) {
1734 error_stream.Printf("error [IRForTarget internal]: Unhandled "
1735 "constant expression type: \"%s\"",
1736 PrintValue(constant_expr).c_str());
1738 case Instruction::BitCast: {
1739 FunctionValueCache bit_cast_maker(
1740 [&value_maker, &entry_instruction_finder, old_constant,
1741 constant_expr](llvm::Function *function) -> llvm::Value * {
1743 // OperandList[0] is value
1745 if (constant_expr->getOperand(0) != old_constant)
1746 return constant_expr;
1748 return new BitCastInst(
1749 value_maker.GetValue(function), constant_expr->getType(),
1750 "", llvm::cast<Instruction>(
1751 entry_instruction_finder.GetValue(function)));
1754 if (!UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1755 entry_instruction_finder, error_stream))
1758 case Instruction::GetElementPtr: {
1759 // GetElementPtrConstantExpr
1760 // OperandList[0] is base
1761 // OperandList[1]... are indices
1763 FunctionValueCache get_element_pointer_maker(
1764 [&value_maker, &entry_instruction_finder, old_constant,
1765 constant_expr](llvm::Function *function) -> llvm::Value * {
1766 Value *ptr = constant_expr->getOperand(0);
1768 if (ptr == old_constant)
1769 ptr = value_maker.GetValue(function);
1771 std::vector<Value *> index_vector;
1773 unsigned operand_index;
1774 unsigned num_operands = constant_expr->getNumOperands();
1776 for (operand_index = 1; operand_index < num_operands;
1778 Value *operand = constant_expr->getOperand(operand_index);
1780 if (operand == old_constant)
1781 operand = value_maker.GetValue(function);
1783 index_vector.push_back(operand);
1786 ArrayRef<Value *> indices(index_vector);
1788 return GetElementPtrInst::Create(
1789 nullptr, ptr, indices, "",
1790 llvm::cast<Instruction>(
1791 entry_instruction_finder.GetValue(function)));
1794 if (!UnfoldConstant(constant_expr, llvm_function,
1795 get_element_pointer_maker,
1796 entry_instruction_finder, error_stream))
1801 error_stream.Printf(
1802 "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1803 PrintValue(constant).c_str());
1807 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1808 if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1809 error_stream.PutCString("error: Capturing non-local variables in "
1810 "expressions is unsupported.\n");
1813 inst->replaceUsesOfWith(
1814 old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1816 error_stream.Printf(
1817 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1818 PrintValue(user).c_str());
1824 if (!isa<GlobalValue>(old_constant)) {
1825 old_constant->destroyConstant();
1831 bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1832 if (!m_resolve_vars)
1835 lldb_private::Log *log(
1836 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1838 m_decl_map->DoStructLayout();
1841 log->Printf("Element arrangement:");
1843 uint32_t num_elements;
1844 uint32_t element_index;
1847 lldb::offset_t alignment;
1849 if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1852 Function::arg_iterator iter(llvm_function.arg_begin());
1854 if (iter == llvm_function.arg_end()) {
1855 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no "
1856 "arguments (should take at least a struct pointer)");
1861 Argument *argument = &*iter;
1863 if (argument->getName().equals("this")) {
1866 if (iter == llvm_function.arg_end()) {
1867 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1868 "'this' argument (should take a struct pointer "
1875 } else if (argument->getName().equals("self")) {
1878 if (iter == llvm_function.arg_end()) {
1879 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1880 "'self' argument (should take '_cmd' and a struct "
1886 if (!iter->getName().equals("_cmd")) {
1887 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes '%s' "
1888 "after 'self' argument (should take '_cmd')",
1889 iter->getName().str().c_str());
1896 if (iter == llvm_function.arg_end()) {
1897 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1898 "'self' and '_cmd' arguments (should take a struct "
1907 if (!argument->getName().equals("$__lldb_arg")) {
1908 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes an "
1909 "argument named '%s' instead of the struct pointer",
1910 argument->getName().str().c_str());
1916 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
1918 BasicBlock &entry_block(llvm_function.getEntryBlock());
1919 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1921 if (!FirstEntryInstruction) {
1922 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1923 "first instruction in the wrapper for use in "
1929 LLVMContext &context(m_module->getContext());
1930 IntegerType *offset_type(Type::getInt32Ty(context));
1933 m_error_stream.Printf(
1934 "Internal error [IRForTarget]: Couldn't produce an offset type");
1939 for (element_index = 0; element_index < num_elements; ++element_index) {
1940 const clang::NamedDecl *decl = nullptr;
1941 Value *value = nullptr;
1942 lldb::offset_t offset;
1943 lldb_private::ConstString name;
1945 if (!m_decl_map->GetStructElement(decl, value, offset, name,
1947 m_error_stream.Printf(
1948 "Internal error [IRForTarget]: Structure information is incomplete");
1954 log->Printf(" \"%s\" (\"%s\") placed at %" PRIu64, name.GetCString(),
1955 decl->getNameAsString().c_str(), offset);
1959 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
1961 FunctionValueCache body_result_maker(
1962 [this, name, offset_type, offset, argument,
1963 value](llvm::Function *function) -> llvm::Value * {
1964 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1965 // in cases where the result variable is an rvalue, we have to
1966 // synthesize a dereference of the appropriate structure entry in
1967 // order to produce the static variable that the AST thinks it is
1970 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1971 m_entry_instruction_finder.GetValue(function));
1973 ConstantInt *offset_int(
1974 ConstantInt::get(offset_type, offset, true));
1975 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(
1976 nullptr, argument, offset_int, "", entry_instruction);
1978 if (name == m_result_name && !m_result_is_pointer) {
1979 BitCastInst *bit_cast = new BitCastInst(
1980 get_element_ptr, value->getType()->getPointerTo(), "",
1983 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
1987 BitCastInst *bit_cast = new BitCastInst(
1988 get_element_ptr, value->getType(), "", entry_instruction);
1994 if (Constant *constant = dyn_cast<Constant>(value)) {
1995 if (!UnfoldConstant(constant, &llvm_function, body_result_maker,
1996 m_entry_instruction_finder, m_error_stream)) {
1999 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
2000 if (instruction->getParent()->getParent() != &llvm_function) {
2001 m_error_stream.PutCString("error: Capturing non-local variables in "
2002 "expressions is unsupported.\n");
2005 value->replaceAllUsesWith(
2006 body_result_maker.GetValue(instruction->getParent()->getParent()));
2009 log->Printf("Unhandled non-constant type: \"%s\"",
2010 PrintValue(value).c_str());
2014 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2015 var->eraseFromParent();
2020 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]",
2021 (int64_t)alignment, (uint64_t)size);
2026 llvm::Constant *IRForTarget::BuildRelocation(llvm::Type *type,
2028 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2030 llvm::Constant *offset_array[1];
2032 offset_array[0] = offset_int;
2034 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2035 llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext());
2036 llvm::Type *char_pointer_type = char_type->getPointerTo();
2038 llvm::Constant *reloc_placeholder_bitcast =
2039 ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type);
2040 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(
2041 char_type, reloc_placeholder_bitcast, offsets);
2042 llvm::Constant *reloc_bitcast =
2043 ConstantExpr::getBitCast(reloc_getelementptr, type);
2045 return reloc_bitcast;
2048 bool IRForTarget::runOnModule(Module &llvm_module) {
2049 lldb_private::Log *log(
2050 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2052 m_module = &llvm_module;
2053 m_target_data.reset(new DataLayout(m_module));
2054 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
2055 m_target_data->getPointerSizeInBits());
2059 raw_string_ostream oss(s);
2061 m_module->print(oss, nullptr);
2065 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2068 Function *const main_function =
2069 m_func_name.IsEmpty() ? nullptr
2070 : m_module->getFunction(m_func_name.GetStringRef());
2072 if (!m_func_name.IsEmpty() && !main_function) {
2074 log->Printf("Couldn't find \"%s()\" in the module",
2075 m_func_name.AsCString());
2077 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find wrapper "
2078 "'%s' in the module",
2079 m_func_name.AsCString());
2084 if (main_function) {
2085 if (!FixFunctionLinkage(*main_function)) {
2087 log->Printf("Couldn't fix the linkage for the function");
2093 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2095 m_reloc_placeholder = new llvm::GlobalVariable(
2096 (*m_module), int8_ty, false /* IsConstant */,
2097 GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty),
2098 "reloc_placeholder", nullptr /* InsertBefore */,
2099 GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */);
2101 ////////////////////////////////////////////////////////////
2102 // Replace $__lldb_expr_result with a persistent variable
2105 if (main_function) {
2106 if (!CreateResultVariable(*main_function)) {
2108 log->Printf("CreateResultVariable() failed");
2110 // CreateResultVariable() reports its own errors, so we don't do so here
2116 if (log && log->GetVerbose()) {
2118 raw_string_ostream oss(s);
2120 m_module->print(oss, nullptr);
2124 log->Printf("Module after creating the result variable: \n\"%s\"",
2128 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2130 llvm::Function *function = &*fi;
2132 if (function->begin() == function->end())
2135 Function::iterator bbi;
2137 for (bbi = function->begin(); bbi != function->end(); ++bbi) {
2138 if (!RemoveGuards(*bbi)) {
2140 log->Printf("RemoveGuards() failed");
2142 // RemoveGuards() reports its own errors, so we don't do so here
2147 if (!RewritePersistentAllocs(*bbi)) {
2149 log->Printf("RewritePersistentAllocs() failed");
2151 // RewritePersistentAllocs() reports its own errors, so we don't do so
2157 if (!RemoveCXAAtExit(*bbi)) {
2159 log->Printf("RemoveCXAAtExit() failed");
2161 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2168 ///////////////////////////////////////////////////////////////////////////////
2169 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2172 if (!RewriteObjCConstStrings()) {
2174 log->Printf("RewriteObjCConstStrings() failed");
2176 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2181 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2183 llvm::Function *function = &*fi;
2185 for (llvm::Function::iterator bbi = function->begin(),
2186 bbe = function->end();
2187 bbi != bbe; ++bbi) {
2188 if (!RewriteObjCSelectors(*bbi)) {
2190 log->Printf("RewriteObjCSelectors() failed");
2192 // RewriteObjCSelectors() reports its own errors, so we don't do so
2198 if (!RewriteObjCClassReferences(*bbi)) {
2200 log->Printf("RewriteObjCClassReferences() failed");
2202 // RewriteObjCClasses() reports its own errors, so we don't do so here
2209 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe;
2211 llvm::Function *function = &*fi;
2213 for (llvm::Function::iterator bbi = function->begin(),
2214 bbe = function->end();
2215 bbi != bbe; ++bbi) {
2216 if (!ResolveCalls(*bbi)) {
2218 log->Printf("ResolveCalls() failed");
2220 // ResolveCalls() reports its own errors, so we don't do so here
2227 ////////////////////////////////////////////////////////////////////////
2228 // Run function-level passes that only make sense on the main function
2231 if (main_function) {
2232 if (!ResolveExternals(*main_function)) {
2234 log->Printf("ResolveExternals() failed");
2236 // ResolveExternals() reports its own errors, so we don't do so here
2241 if (!ReplaceVariables(*main_function)) {
2243 log->Printf("ReplaceVariables() failed");
2245 // ReplaceVariables() reports its own errors, so we don't do so here
2251 if (log && log->GetVerbose()) {
2253 raw_string_ostream oss(s);
2255 m_module->print(oss, nullptr);
2259 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2265 void IRForTarget::assignPassManager(PMStack &pass_mgr_stack,
2266 PassManagerType pass_mgr_type) {}
2268 PassManagerType IRForTarget::getPotentialPassManagerType() const {
2269 return PMT_ModulePassManager;