16#include "llvm/IR/Constants.h"
17#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/Operator.h"
19#include "llvm/IR/InstrTypes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/IR/Metadata.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/ValueSymbolTable.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/Transforms/IPO.h"
29#include "clang/AST/ASTContext.h"
59 llvm::Value *ret =
m_maker(function);
67 if (function->empty())
70 return &*function->getEntryBlock().getFirstNonPHIOrDbg();
78 const char *func_name)
86static std::string
PrintValue(
const Value *value,
bool truncate =
false) {
89 raw_string_ostream rso(s);
92 s.resize(s.length() - 1);
97static std::string
PrintType(
const llvm::Type *type,
bool truncate =
false) {
99 raw_string_ostream rso(s);
102 s.resize(s.length() - 1);
107 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
114 NamedMDNode *named_metadata =
115 module->getNamedMetadata("clang.global.decl.ptrs");
120 unsigned num_nodes = named_metadata->getNumOperands();
123 for (node_index = 0; node_index < num_nodes; ++node_index) {
124 llvm::MDNode *metadata_node =
125 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
129 if (metadata_node->getNumOperands() != 2)
132 if (mdconst::dyn_extract_or_null<GlobalValue>(
133 metadata_node->getOperand(0)) != global_val)
136 ConstantInt *constant_int =
137 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
142 uintptr_t ptr = constant_int->getZExtValue();
144 return reinterpret_cast<clang::NamedDecl *
>(ptr);
156 bool check_ms_abi =
true) {
158 mangled_symbol.starts_with(
"_ZGV");
160 result |= mangled_symbol.ends_with(
"@4IA");
172 ValueSymbolTable &value_symbol_table =
m_module->getValueSymbolTable();
174 llvm::StringRef result_name;
175 bool found_result =
false;
177 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
178 result_name = value_symbol.first();
184 if (result_name.contains(
"$__lldb_expr_result_ptr") && !is_guard_var) {
190 if (result_name.contains(
"$__lldb_expr_result") && !is_guard_var) {
198 LLDB_LOG(log,
"Couldn't find result variable");
203 LLDB_LOG(log,
"Result name: \"{0}\"", result_name);
205 Value *result_value =
m_module->getNamedValue(result_name);
208 LLDB_LOG(log,
"Result variable had no data");
210 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable's "
211 "name ({0}) exists, but not its definition\n",
217 LLDB_LOG(log,
"Found result in the IR: \"{0}\"",
220 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
222 if (!result_global) {
223 LLDB_LOG(log,
"Result variable isn't a GlobalVariable");
225 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable ({0}) "
226 "is defined, but is not a global variable\n",
232 clang::NamedDecl *result_decl =
DeclForGlobal(result_global);
234 LLDB_LOG(log,
"Result variable doesn't have a corresponding Decl");
236 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable ({0}) "
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);
248 LLDB_LOG(log,
"Found result decl: \"{0}\"", decl_desc_str);
251 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
253 LLDB_LOG(log,
"Result variable Decl isn't a VarDecl");
255 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable "
256 "({0})'s corresponding Clang entity isn't a "
269 clang::QualType pointer_qual_type = result_var->getType();
270 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
272 const clang::PointerType *pointer_pointertype =
273 pointer_type->getAs<clang::PointerType>();
274 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
275 pointer_type->getAs<clang::ObjCObjectPointerType>();
277 if (pointer_pointertype) {
278 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
281 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
282 }
else if (pointer_objcobjpointertype) {
283 clang::QualType element_qual_type =
284 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
287 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
289 LLDB_LOG(log,
"Expected result to have pointer type, but it did not");
291 m_error_stream.Format(
"Internal error [IRForTarget]: Lvalue result ({0}) "
292 "is not a pointer variable\n",
299 m_decl_map->GetTypeSystem()->GetType(result_var->getType()));
303 auto bit_size_or_err =
m_result_type.GetBitSize(target_sp.get());
304 if (!bit_size_or_err) {
308 LLDB_LOG(log,
"Result type has unknown size");
310 m_error_stream.Printf(
"Error [IRForTarget]: Size of result type '%s' "
311 "couldn't be determined\n%s",
313 llvm::toString(bit_size_or_err.takeError()).c_str());
321 LLDB_LOG(log,
"Result decl type: \"{0}\"", type_desc_stream.
GetData());
326 LLDB_LOG(log,
"Creating a new result global: \"{0}\" with size {1}",
328 llvm::expectedToOptional(
m_result_type.GetByteSize(target_sp.get()))
333 GlobalVariable *new_result_global =
new GlobalVariable(
334 (*
m_module), result_global->getValueType(),
false,
335 GlobalValue::ExternalLinkage,
nullptr,
345 ConstantInt *new_constant_int =
346 ConstantInt::get(llvm::Type::getInt64Ty(
m_module->getContext()),
347 reinterpret_cast<uintptr_t
>(result_decl),
false);
349 llvm::Metadata *values[2];
350 values[0] = ConstantAsMetadata::get(new_result_global);
351 values[1] = ConstantAsMetadata::get(new_constant_int);
353 ArrayRef<Metadata *> value_ref(values, 2);
355 MDNode *persistent_global_md = MDNode::get(
m_module->getContext(), value_ref);
356 NamedMDNode *named_metadata =
357 m_module->getNamedMetadata(
"clang.global.decl.ptrs");
358 named_metadata->addOperand(persistent_global_md);
363 if (result_global->use_empty()) {
367 BasicBlock &entry_block(llvm_function.getEntryBlock());
368 Instruction *first_entry_instruction(&*entry_block.getFirstNonPHIOrDbg());
370 if (!first_entry_instruction)
373 if (!result_global->hasInitializer()) {
374 LLDB_LOG(log,
"Couldn't find initializer for unused variable");
376 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable "
377 "({0}) has no writes and no initializer\n",
383 Constant *initializer = result_global->getInitializer();
385 StoreInst *synthesized_store =
new StoreInst(
386 initializer, new_result_global, first_entry_instruction->getIterator());
388 LLDB_LOG(log,
"Synthesized result store \"{0}\"\n",
391 result_global->replaceAllUsesWith(new_result_global);
398 result_global->eraseFromParent();
404 llvm::GlobalVariable *cstr) {
407 Type *ns_str_ty = ns_str->getType();
409 Type *i8_ptr_ty = PointerType::getUnqual(
m_module->getContext());
410 Type *i32_ty = Type::getInt32Ty(
m_module->getContext());
411 Type *i8_ty = Type::getInt8Ty(
m_module->getContext());
417 "CFStringCreateWithBytes");
419 bool missing_weak =
false;
421 g_CFStringCreateWithBytes_str, missing_weak);
423 LLDB_LOG(log,
"Couldn't find CFStringCreateWithBytes in the target");
425 m_error_stream.Printf(
"Error [IRForTarget]: Rewriting an Objective-C "
426 "constant string requires "
427 "CFStringCreateWithBytes\n");
432 LLDB_LOG(log,
"Found CFStringCreateWithBytes at {0}",
433 CFStringCreateWithBytes_addr);
453 Type *arg_type_array[5];
455 arg_type_array[0] = i8_ptr_ty;
456 arg_type_array[1] = i8_ptr_ty;
458 arg_type_array[3] = i32_ty;
459 arg_type_array[4] = i8_ty;
461 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
463 llvm::FunctionType *CFSCWB_ty =
464 FunctionType::get(ns_str_ty, CFSCWB_arg_types,
false);
467 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(
m_module->getContext());
468 Constant *CFSCWB_addr_int =
469 ConstantInt::get(
m_intptr_ty, CFStringCreateWithBytes_addr,
false);
471 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)};
474 ConstantDataSequential *string_array =
nullptr;
477 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
479 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
480 Constant *bytes_arg = cstr ? cstr : Constant::getNullValue(i8_ptr_ty);
481 Constant *numBytes_arg = ConstantInt::get(
482 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0,
false);
483 int encoding_flags = 0;
484 switch (cstr ? string_array->getElementByteSize() : 1) {
486 encoding_flags = 0x08000100;
489 encoding_flags = 0x0100;
492 encoding_flags = 0x0c000100;
495 encoding_flags = 0x0600;
496 LLDB_LOG(log,
"Encountered an Objective-C constant string with unusual "
498 string_array->getElementByteSize());
500 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags,
false);
501 Constant *isExternal_arg =
502 ConstantInt::get(i8_ty, 0x0,
false);
504 Value *argument_array[5];
506 argument_array[0] = alloc_arg;
507 argument_array[1] = bytes_arg;
508 argument_array[2] = numBytes_arg;
509 argument_array[3] = encoding_arg;
510 argument_array[4] = isExternal_arg;
512 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
515 [
this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
516 return CallInst::Create(
518 "CFStringCreateWithBytes",
519 llvm::cast<Instruction>(
526 LLDB_LOG(log,
"Couldn't replace the NSString with the result of the call");
528 m_error_stream.Printf(
"error [IRForTarget internal]: Couldn't replace an "
529 "Objective-C constant string with a dynamic "
535 ns_str->eraseFromParent();
543 ValueSymbolTable &value_symbol_table =
m_module->getValueSymbolTable();
545 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
546 llvm::StringRef value_name = value_symbol.first();
548 if (value_name.contains(
"_unnamed_cfstring_")) {
549 Value *nsstring_value = value_symbol.second;
551 GlobalVariable *nsstring_global =
552 dyn_cast<GlobalVariable>(nsstring_value);
554 if (!nsstring_global) {
555 LLDB_LOG(log,
"NSString variable is not a GlobalVariable");
557 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
558 "constant string is not a global variable\n");
563 if (!nsstring_global->hasInitializer()) {
564 LLDB_LOG(log,
"NSString variable does not have an initializer");
566 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
567 "constant string does not have an initializer\n");
572 ConstantStruct *nsstring_struct =
573 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
575 if (!nsstring_struct) {
577 "NSString variable's initializer is not a ConstantStruct");
579 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
580 "constant string is not a structure constant\n");
594 if (nsstring_struct->getNumOperands() != 4) {
597 "NSString variable's initializer structure has an "
598 "unexpected number of members. Should be 4, is {0}",
599 nsstring_struct->getNumOperands());
601 m_error_stream.Printf(
"Internal error [IRForTarget]: The struct for an "
602 "Objective-C constant string is not as "
608 Constant *nsstring_member = nsstring_struct->getOperand(2);
610 if (!nsstring_member) {
611 LLDB_LOG(log,
"NSString initializer's str element was empty");
613 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
614 "constant string does not have a string "
620 auto *cstr_global = dyn_cast<GlobalVariable>(nsstring_member);
623 "NSString initializer's str element is not a GlobalVariable");
626 "constant string initializer\n");
631 if (!cstr_global->hasInitializer()) {
632 LLDB_LOG(log,
"NSString initializer's str element does not have an "
635 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
636 "constant string's string initializer doesn't "
637 "point to initialized data\n");
672 ConstantDataArray *cstr_array =
673 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
676 LLDB_LOG(log,
"Found NSString constant {0}, which contains \"{1}\"",
677 value_name, cstr_array->getAsString());
679 LLDB_LOG(log,
"Found NSString constant {0}, which contains \"\"",
683 cstr_global =
nullptr;
686 LLDB_LOG(log,
"Error rewriting the constant string");
696 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
697 llvm::StringRef value_name = value_symbol.first();
699 if (value_name ==
"__CFConstantStringClassReference") {
700 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second);
704 "__CFConstantStringClassReference is not a global variable");
707 "CFConstantStringClassReference, but it is not a "
713 gv->eraseFromParent();
723 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
726 !global_variable || !global_variable->hasName() ||
727 !global_variable->getName().starts_with(
"OBJC_SELECTOR_REFERENCES_"));
734 LoadInst *load = dyn_cast<LoadInst>(selector_load);
753 GlobalVariable *_objc_selector_references_ =
754 dyn_cast<GlobalVariable>(load->getPointerOperand());
756 if (!_objc_selector_references_ ||
757 !_objc_selector_references_->hasInitializer())
760 Constant *osr_initializer = _objc_selector_references_->getInitializer();
761 if (!osr_initializer)
766 GlobalVariable *_objc_meth_var_name_ =
767 dyn_cast<GlobalVariable>(osr_initializer);
769 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
772 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
774 ConstantDataArray *omvn_initializer_array =
775 dyn_cast<ConstantDataArray>(omvn_initializer);
777 if (!omvn_initializer_array->isString())
780 std::string omvn_initializer_string =
781 std::string(omvn_initializer_array->getAsString());
783 LLDB_LOG(log,
"Found Objective-C selector reference \"{0}\"",
784 omvn_initializer_string);
791 bool missing_weak =
false;
798 LLDB_LOG(log,
"Found sel_registerName at {0}", sel_registerName_addr);
807 Type *sel_ptr_type = PointerType::getUnqual(
m_module->getContext());
811 type_array[0] = llvm::PointerType::getUnqual(
m_module->getContext());
813 ArrayRef<Type *> srN_arg_types(type_array, 1);
815 llvm::FunctionType *srN_type =
816 FunctionType::get(sel_ptr_type, srN_arg_types,
false);
819 PointerType *srN_ptr_ty = PointerType::getUnqual(
m_module->getContext());
820 Constant *srN_addr_int =
821 ConstantInt::get(
m_intptr_ty, sel_registerName_addr,
false);
823 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
828 "sel_registerName", selector_load->getIterator());
832 selector_load->replaceAllUsesWith(srN_call);
834 selector_load->eraseFromParent();
844 for (Instruction &inst : basic_block) {
845 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
847 selector_loads.push_back(&inst);
850 for (Instruction *inst : selector_loads) {
852 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't change a "
853 "static reference to an Objective-C selector to a "
854 "dynamic reference\n");
856 LLDB_LOG(log,
"Couldn't rewrite a reference to an Objective-C selector");
869 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
871 MDNode *alloc_md = alloc->getMetadata(
"clang.decl.ptr");
873 if (!alloc_md || !alloc_md->getNumOperands())
876 ConstantInt *constant_int =
877 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
884 uintptr_t ptr = constant_int->getZExtValue();
886 clang::VarDecl *decl =
reinterpret_cast<clang::VarDecl *
>(ptr);
889 m_decl_map->GetTypeSystem()->GetType(decl->getType()));
891 StringRef decl_name(decl->getName());
894 if (!
m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
895 result_decl_type,
false,
false))
898 GlobalVariable *persistent_global =
new GlobalVariable(
899 (*
m_module), alloc->getType(),
false,
900 GlobalValue::ExternalLinkage,
nullptr,
901 alloc->getName().str());
906 NamedMDNode *named_metadata =
907 m_module->getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
909 llvm::Metadata *values[2];
910 values[0] = ConstantAsMetadata::get(persistent_global);
911 values[1] = ConstantAsMetadata::get(constant_int);
913 ArrayRef<llvm::Metadata *> value_ref(values, 2);
915 MDNode *persistent_global_md = MDNode::get(
m_module->getContext(), value_ref);
916 named_metadata->addOperand(persistent_global_md);
921 LoadInst *persistent_load =
922 new LoadInst(persistent_global->getValueType(), persistent_global,
"",
923 alloc->getIterator());
928 alloc->replaceAllUsesWith(persistent_load);
929 alloc->eraseFromParent();
942 for (Instruction &inst : basic_block) {
944 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
945 llvm::StringRef alloc_name = alloc->getName();
947 if (alloc_name.starts_with(
"$") && !alloc_name.starts_with(
"$__lldb")) {
948 if (alloc_name.find_first_of(
"0123456789") == 1) {
949 LLDB_LOG(log,
"Rejecting a numeric persistent variable.");
951 m_error_stream.Printf(
"Error [IRForTarget]: Names starting with $0, "
952 "$1, ... are reserved for use as result "
958 pvar_allocs.push_back(alloc);
963 for (Instruction *inst : pvar_allocs) {
965 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't rewrite "
966 "the creation of a persistent variable\n");
968 LLDB_LOG(log,
"Couldn't rewrite the creation of a persistent variable");
983 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
984 switch (constant_expr->getOpcode()) {
987 case Instruction::GetElementPtr:
988 case Instruction::BitCast:
989 Value *s = constant_expr->getOperand(0);
993 }
else if (GlobalVariable *global_variable =
994 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
995 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
998 clang::NamedDecl *named_decl =
DeclForGlobal(global_variable);
1004 if (!global_variable->hasExternalLinkage())
1007 LLDB_LOG(log,
"Found global variable \"{0}\" without metadata",
1008 global_variable->getName());
1013 llvm::StringRef name(named_decl->getName());
1015 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1016 if (value_decl ==
nullptr)
1020 m_decl_map->GetTypeSystem()->GetType(value_decl->getType());
1022 const Type *value_type =
nullptr;
1024 if (name.starts_with(
"$")) {
1036 value_type = PointerType::getUnqual(global_variable->getContext());
1038 value_type = global_variable->getType();
1042 std::optional<uint64_t> value_size =
1043 llvm::expectedToOptional(compiler_type.
GetByteSize(target));
1046 std::optional<size_t> opt_alignment = compiler_type.
GetTypeBitAlign(target);
1052 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, "
1056 PrintType(value_type), *value_size, value_alignment);
1060 llvm_value_ptr, *value_size,
1062 }
else if (isa<llvm::Function>(llvm_value_ptr)) {
1063 LLDB_LOG(log,
"Function pointers aren't handled right now");
1081 LLDB_LOG(log,
"Symbol \"{0}\" had no address", name);
1086 LLDB_LOG(log,
"Found \"{0}\" at {1}", name, symbol_addr);
1088 Type *symbol_type = symbol->getType();
1090 Constant *symbol_addr_int = ConstantInt::get(
m_intptr_ty, symbol_addr,
false);
1092 Value *symbol_addr_ptr =
1093 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1098 symbol->replaceAllUsesWith(symbol_addr_ptr);
1108 for (
unsigned op_index = 0, num_ops = Old->arg_size();
1109 op_index < num_ops; ++op_index)
1112 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't rewrite "
1113 "one of the arguments of a function call.\n");
1124 GlobalVariable *global_variable =
1125 dyn_cast<GlobalVariable>(classlist_reference);
1127 if (!global_variable)
1130 Constant *initializer = global_variable->getInitializer();
1135 if (!initializer->hasName())
1138 StringRef name(initializer->getName());
1143 LLDB_LOG(log,
"Found reference to Objective-C class {0} ({1})", name,
1144 (
unsigned long long)class_ptr);
1149 if (global_variable->use_empty())
1152 SmallVector<LoadInst *, 2> load_instructions;
1154 for (llvm::User *u : global_variable->users()) {
1155 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1156 load_instructions.push_back(load_instruction);
1159 if (load_instructions.empty())
1162 Constant *class_addr = ConstantInt::get(
m_intptr_ty, (uint64_t)class_ptr);
1164 for (LoadInst *load_instruction : load_instructions) {
1165 Constant *class_bitcast =
1166 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1168 load_instruction->replaceAllUsesWith(class_bitcast);
1170 load_instruction->eraseFromParent();
1177 std::vector<CallInst *> calls_to_remove;
1179 for (Instruction &inst : basic_block) {
1180 CallInst *call = dyn_cast<CallInst>(&inst);
1186 bool remove =
false;
1188 llvm::Function *func = call->getCalledFunction();
1190 if (func && func->getName() ==
"__cxa_atexit")
1193 llvm::Value *val = call->getCalledOperand();
1195 if (val && val->getName() ==
"__cxa_atexit")
1199 calls_to_remove.push_back(call);
1202 for (CallInst *ci : calls_to_remove)
1203 ci->eraseFromParent();
1211 for (Instruction &inst : basic_block) {
1212 CallInst *call = dyn_cast<CallInst>(&inst);
1225 for (GlobalVariable &global_var :
m_module->globals()) {
1226 llvm::StringRef global_name = global_var.getName();
1228 LLDB_LOG(log,
"Examining {0}, DeclForGlobalValue returns {1}", global_name,
1231 if (global_name.starts_with(
"OBJC_IVAR")) {
1233 m_error_stream.Format(
"Error [IRForTarget]: Couldn't find Objective-C "
1234 "indirect ivar symbol {0}\n",
1239 }
else if (global_name.contains(
"OBJC_CLASSLIST_REFERENCES_$")) {
1241 m_error_stream.Printf(
"Error [IRForTarget]: Couldn't resolve the class "
1242 "for an Objective-C static method call\n");
1246 }
else if (global_name.contains(
"OBJC_CLASSLIST_SUP_REFS_$")) {
1248 m_error_stream.Printf(
"Error [IRForTarget]: Couldn't resolve the class "
1249 "for an Objective-C static method call\n");
1255 m_error_stream.Format(
"Internal error [IRForTarget]: Couldn't rewrite "
1256 "external variable {0}\n",
1268 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1277 Constant *zero(Constant::getNullValue(guard_load->getType()));
1278 guard_load->replaceAllUsesWith(zero);
1279 guard_load->eraseFromParent();
1283 guard_store->eraseFromParent();
1292 for (Instruction &inst : basic_block) {
1294 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1296 guard_loads.push_back(&inst);
1298 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1300 guard_stores.push_back(&inst);
1303 for (Instruction *inst : guard_loads)
1306 for (Instruction *inst : guard_stores)
1314 llvm::Function *llvm_function,
1318 SmallVector<User *, 16> users;
1322 for (llvm::User *u : old_constant->users())
1325 for (
size_t i = 0; i < users.size(); ++i) {
1326 User *user = users[i];
1328 if (Constant *constant = dyn_cast<Constant>(user)) {
1331 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1332 switch (constant_expr->getOpcode()) {
1334 error_stream.
Printf(
"error [IRForTarget internal]: Unhandled "
1335 "constant expression type: \"%s\"",
1338 case Instruction::BitCast: {
1340 [&value_maker, &entry_instruction_finder, old_constant,
1341 constant_expr](llvm::Function *function) -> llvm::Value * {
1345 if (constant_expr->getOperand(0) != old_constant)
1346 return constant_expr;
1348 return new BitCastInst(
1349 value_maker.
GetValue(function), constant_expr->getType(),
1351 llvm::cast<Instruction>(
1352 entry_instruction_finder.
GetValue(function))
1356 if (!
UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1357 entry_instruction_finder, error_stream))
1360 case Instruction::GetElementPtr: {
1366 [&value_maker, &entry_instruction_finder, old_constant,
1367 constant_expr](llvm::Function *function) -> llvm::Value * {
1368 auto *gep = cast<llvm::GEPOperator>(constant_expr);
1369 Value *ptr = gep->getPointerOperand();
1371 if (ptr == old_constant)
1372 ptr = value_maker.
GetValue(function);
1374 std::vector<Value *> index_vector;
1375 for (Value *operand : gep->indices()) {
1376 if (operand == old_constant)
1377 operand = value_maker.
GetValue(function);
1379 index_vector.push_back(operand);
1382 ArrayRef<Value *> indices(index_vector);
1384 return GetElementPtrInst::Create(
1385 gep->getSourceElementType(), ptr, indices,
"",
1386 llvm::cast<Instruction>(
1387 entry_instruction_finder.
GetValue(function))
1392 get_element_pointer_maker,
1393 entry_instruction_finder, error_stream))
1399 "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1404 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1405 if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1406 error_stream.
PutCString(
"error: Capturing non-local variables in "
1407 "expressions is unsupported.\n");
1410 inst->replaceUsesOfWith(
1411 old_constant, value_maker.
GetValue(inst->getParent()->getParent()));
1414 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1421 if (!isa<GlobalValue>(old_constant)) {
1422 old_constant->destroyConstant();
1436 LLDB_LOG(log,
"Element arrangement:");
1438 uint32_t num_elements;
1439 uint32_t element_index;
1444 if (!
m_decl_map->GetStructInfo(num_elements, size, alignment))
1447 Function::arg_iterator iter(llvm_function.arg_begin());
1449 if (iter == llvm_function.arg_end()) {
1450 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes no "
1451 "arguments (should take at least a struct pointer)");
1456 Argument *argument = &*iter;
1458 if (argument->getName() ==
"this") {
1461 if (iter == llvm_function.arg_end()) {
1462 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes only "
1463 "'this' argument (should take a struct pointer "
1470 }
else if (argument->getName() ==
"self") {
1473 if (iter == llvm_function.arg_end()) {
1474 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes only "
1475 "'self' argument (should take '_cmd' and a struct "
1481 if (iter->getName() !=
"_cmd") {
1482 m_error_stream.Format(
"Internal error [IRForTarget]: Wrapper takes '{0}' "
1483 "after 'self' argument (should take '_cmd')",
1491 if (iter == llvm_function.arg_end()) {
1492 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes only "
1493 "'self' and '_cmd' arguments (should take a struct "
1502 if (argument->getName() !=
"$__lldb_arg") {
1503 m_error_stream.Format(
"Internal error [IRForTarget]: Wrapper takes an "
1504 "argument named '{0}' instead of the struct pointer",
1505 argument->getName());
1512 BasicBlock &entry_block(llvm_function.getEntryBlock());
1513 Instruction *FirstEntryInstruction(&*entry_block.getFirstNonPHIOrDbg());
1515 if (!FirstEntryInstruction) {
1516 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't find the "
1517 "first instruction in the wrapper for use in "
1523 LLVMContext &context(
m_module->getContext());
1524 IntegerType *offset_type(Type::getInt32Ty(context));
1528 "Internal error [IRForTarget]: Couldn't produce an offset type");
1533 for (element_index = 0; element_index < num_elements; ++element_index) {
1534 const clang::NamedDecl *decl =
nullptr;
1535 Value *value =
nullptr;
1539 if (!
m_decl_map->GetStructElement(decl, value, offset, name,
1542 "Internal error [IRForTarget]: Structure information is incomplete");
1547 LLDB_LOG(log,
" \"{0}\" (\"{1}\") placed at {2}", name,
1548 decl->getNameAsString(), offset);
1554 [
this, name, offset_type, offset, argument,
1555 value](llvm::Function *function) -> llvm::Value * {
1562 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1565 Type *int8Ty = Type::getInt8Ty(function->getContext());
1566 ConstantInt *offset_int(
1567 ConstantInt::get(offset_type, offset,
true));
1568 GetElementPtrInst *get_element_ptr =
1569 GetElementPtrInst::Create(int8Ty, argument, offset_int,
"",
1570 entry_instruction->getIterator());
1574 new LoadInst(value->getType(), get_element_ptr,
"",
1575 entry_instruction->getIterator());
1579 return get_element_ptr;
1583 if (Constant *constant = dyn_cast<Constant>(value)) {
1588 }
else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1589 if (instruction->getParent()->getParent() != &llvm_function) {
1590 m_error_stream.PutCString(
"error: Capturing non-local variables in "
1591 "expressions is unsupported.\n");
1594 value->replaceAllUsesWith(
1595 body_result_maker.GetValue(instruction->getParent()->getParent()));
1597 LLDB_LOG(log,
"Unhandled non-constant type: \"{0}\"",
1602 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1603 var->eraseFromParent();
1607 LLDB_LOG(log,
"Total structure [align {0}, size {1}]", (int64_t)alignment,
1623 raw_string_ostream oss(s);
1627 LLDB_LOG(log,
"Module as passed in to IRForTarget: \n\"{0}\"", s);
1630 Function *
const main_function =
1637 m_error_stream.Format(
"Internal error [IRForTarget]: Couldn't find wrapper "
1638 "'{0}' in the module",
1644 if (main_function) {
1646 LLDB_LOG(log,
"Couldn't fix the linkage for the function");
1653 if (main_function) {
1655 LLDB_LOG(log,
"CreateResultVariable() failed");
1665 raw_string_ostream oss(s);
1669 LLDB_LOG(log,
"Module after creating the result variable: \n\"{0}\"", s);
1672 for (llvm::Function &function : *
m_module) {
1673 for (BasicBlock &bb : function) {
1675 LLDB_LOG(log,
"RemoveGuards() failed");
1683 LLDB_LOG(log,
"RewritePersistentAllocs() failed");
1692 LLDB_LOG(log,
"RemoveCXAAtExit() failed");
1703 LLDB_LOG(log,
"RewriteObjCConstStrings() failed");
1710 for (llvm::Function &function : *
m_module) {
1711 for (llvm::BasicBlock &bb : function) {
1713 LLDB_LOG(log,
"RewriteObjCSelectors() failed");
1723 for (llvm::Function &function : *
m_module) {
1724 for (BasicBlock &bb : function) {
1726 LLDB_LOG(log,
"ResolveCalls() failed");
1736 if (main_function) {
1738 LLDB_LOG(log,
"ResolveExternals() failed");
1746 LLDB_LOG(log,
"ReplaceVariables() failed");
1755 if (llvm::Error
error =
1758 "InsertPointerSigningFixups() failed: {0}");
1764 raw_string_ostream oss(s);
1768 LLDB_LOG(log,
"Module after preparing for execution: \n\"{0}\"", s);
static llvm::raw_ostream & error(Stream &strm)
static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol, bool check_ms_abi=true)
Returns true iff the mangled symbol is for a static guard variable.
static std::string PrintValue(const Value *value, bool truncate=false)
static void ExciseGuardStore(Instruction *guard_store)
static llvm::Value * FindEntryInstruction(llvm::Function *function)
static bool IsObjCSelectorRef(Value *value)
SmallVector< Instruction *, 2 > InstrList
static bool isGuardVariableRef(Value *V)
static std::string PrintType(const llvm::Type *type, bool truncate=false)
static std::string PrintValue(const Value *value, bool truncate=false)
static std::string PrintType(const Type *type, bool truncate=false)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOG_ERROR(log, error,...)
FunctionValueCache(Maker const &maker)
llvm::Value * GetValue(llvm::Function *function)
std::function< llvm::Value *(llvm::Function *)> Maker
FunctionValueMap m_values
lldb_private::ConstString m_func_name
The name of the function to translate.
IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Stream &error_stream, lldb_private::ExecutionPolicy execution_policy, const char *func_name="$__lldb_expr")
Constructor.
bool MaybeHandleVariable(llvm::Value *value)
A function-level pass to find all external variables and functions used in the IR.
bool FixFunctionLinkage(llvm::Function &llvm_function)
Ensures that the current function's linkage is set to external.
lldb_private::IRExecutionUnit & m_execution_unit
The execution unit containing the IR being created.
bool CreateResultVariable(llvm::Function &llvm_function)
The top-level pass implementation.
llvm::Module * m_module
The module being processed, or NULL if that has not been determined yet.
bool HandleSymbol(llvm::Value *symbol)
Handle a single externally-defined symbol.
bool RewriteObjCConstStrings()
The top-level pass implementation.
bool ResolveCalls(llvm::BasicBlock &basic_block)
Resolve variable references in calls to external functions.
bool m_result_is_pointer
True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::Synthesi...
bool RewriteObjCConstString(llvm::GlobalVariable *NSStr, llvm::GlobalVariable *CStr)
A module-level pass to find Objective-C constant strings and transform them to calls to CFStringCreat...
bool RemoveGuards(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::Stream & m_error_stream
The stream on which errors should be printed.
bool HandleObjCClass(llvm::Value *classlist_reference)
Handle a single externally-defined Objective-C class.
bool m_resolve_vars
True if external variable references and persistent variable references should be resolved.
static clang::NamedDecl * DeclForGlobal(const llvm::GlobalValue *global_val, llvm::Module *module)
A function-level pass to take the generated global value $__lldb_expr_result and make it into a persi...
lldb_private::TypeFromParser m_result_type
The type of the result variable.
llvm::FunctionCallee m_CFStringCreateWithBytes
The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type.
bool MaybeHandleCallArguments(llvm::CallInst *call_inst)
Handle all the arguments to a function call.
lldb_private::ExecutionPolicy m_policy
bool runOnModule(llvm::Module &llvm_module)
Run this IR transformer on a single module.
bool RewriteObjCSelectors(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::ConstString m_result_name
The name of the result variable ($0, $1, ...)
lldb_private::ClangExpressionDeclMap * m_decl_map
The DeclMap containing the Decls.
bool RemoveCXAAtExit(llvm::BasicBlock &basic_block)
Remove calls to __cxa_atexit, which should never be generated by expressions.
bool RewritePersistentAllocs(llvm::BasicBlock &basic_block)
The top-level pass implementation.
bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc)
A basic block-level pass to find all newly-declared persistent variables and register them with the C...
void TurnGuardLoadIntoZero(llvm::Instruction *guard_load)
A basic block-level pass to excise guard variables from the code.
FunctionValueCache m_entry_instruction_finder
const llvm::DataLayout * m_target_data
The target data for the module being processed, or nullptr if there is no module.
llvm::FunctionCallee m_sel_registerName
The address of the function sel_registerName, cast to the appropriate function pointer type.
llvm::IntegerType * m_intptr_ty
The type of an integer large enough to hold a pointer.
bool RewriteObjCSelector(llvm::Instruction *selector_load)
A basic block-level pass to find all Objective-C method calls and rewrite them to use sel_registerNam...
bool ResolveExternals(llvm::Function &llvm_function)
The top-level pass implementation.
bool ReplaceVariables(llvm::Function &llvm_function)
A function-level pass to make all external variable references point at the correct offsets from the ...
static bool UnfoldConstant(llvm::Constant *old_constant, llvm::Function *llvm_function, FunctionValueCache &value_maker, FunctionValueCache &entry_instruction_finder, lldb_private::Stream &error_stream)
UnfoldConstant operates on a constant [Old] which has just been replaced with a value [New].
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
std::optional< size_t > GetTypeBitAlign(ExecutionContextScope *exe_scope) const
A uniqued constant string class.
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
const char * GetData() const
A stream class that can stream formatted output to a file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
#define LLDB_INVALID_ADDRESS
Error InjectPointerSigningFixupCode(llvm::Module &M, ExecutionPolicy execution_policy)
TaggedASTType< 0 > TypeFromParser
ExecutionPolicy
Expression execution policies.
std::shared_ptr< lldb_private::Target > TargetSP
static clang::QualType GetQualType(const CompilerType &ct)