1 //===-- IRForTarget.cpp ---------------------------------------------------===//
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"
12 #include "ClangUtil.h"
14 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/Operator.h"
18 #include "llvm/IR/InstrTypes.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/LegacyPassManager.h"
22 #include "llvm/IR/Metadata.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/ValueSymbolTable.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/IPO.h"
28 #include "clang/AST/ASTContext.h"
30 #include "lldb/Core/dwarf.h"
31 #include "lldb/Expression/IRExecutionUnit.h"
32 #include "lldb/Expression/IRInterpreter.h"
33 #include "lldb/Symbol/CompilerType.h"
34 #include "lldb/Utility/ConstString.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/Endian.h"
37 #include "lldb/Utility/LLDBLog.h"
38 #include "lldb/Utility/Log.h"
39 #include "lldb/Utility/Scalar.h"
40 #include "lldb/Utility/StreamString.h"
46 using lldb_private::LLDBLog;
48 typedef SmallVector<Instruction *, 2> InstrList;
50 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker)
51 : m_maker(maker), m_values() {}
53 IRForTarget::FunctionValueCache::~FunctionValueCache() = default;
56 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) {
57 if (!m_values.count(function)) {
58 llvm::Value *ret = m_maker(function);
59 m_values[function] = ret;
62 return m_values[function];
65 static llvm::Value *FindEntryInstruction(llvm::Function *function) {
66 if (function->empty())
69 return function->getEntryBlock().getFirstNonPHIOrDbg();
72 IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
74 lldb_private::IRExecutionUnit &execution_unit,
75 lldb_private::Stream &error_stream,
76 const char *func_name)
77 : m_resolve_vars(resolve_vars), m_func_name(func_name),
78 m_decl_map(decl_map), m_error_stream(error_stream),
79 m_execution_unit(execution_unit),
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 bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) {
107 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
112 clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val,
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);
150 clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) {
151 return DeclForGlobal(global_val, m_module);
154 /// Returns true iff the mangled symbol is for a static guard variable.
155 static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol,
156 bool check_ms_abi = true) {
157 bool result = mangled_symbol.startswith("_ZGV"); // Itanium ABI guard variable
159 result |= mangled_symbol.endswith("@4IA"); // Microsoft ABI
163 bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
164 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
169 // Find the result variable. If it doesn't exist, we can give up right here.
171 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
173 llvm::StringRef result_name;
174 bool found_result = false;
176 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
177 result_name = value_symbol.first();
179 // Check if this is a guard variable. It seems this causes some hiccups
180 // on Windows, so let's only check for Itanium guard variables.
181 bool is_guard_var = isGuardVariableSymbol(result_name, /*MS ABI*/ false);
183 if (result_name.contains("$__lldb_expr_result_ptr") && !is_guard_var) {
185 m_result_is_pointer = true;
189 if (result_name.contains("$__lldb_expr_result") && !is_guard_var) {
191 m_result_is_pointer = false;
197 LLDB_LOG(log, "Couldn't find result variable");
202 LLDB_LOG(log, "Result name: \"{0}\"", result_name);
204 Value *result_value = m_module->getNamedValue(result_name);
207 LLDB_LOG(log, "Result variable had no data");
209 m_error_stream.Format("Internal error [IRForTarget]: Result variable's "
210 "name ({0}) exists, but not its definition\n",
216 LLDB_LOG(log, "Found result in the IR: \"{0}\"",
217 PrintValue(result_value, false));
219 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
221 if (!result_global) {
222 LLDB_LOG(log, "Result variable isn't a GlobalVariable");
224 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) "
225 "is defined, but is not a global variable\n",
231 clang::NamedDecl *result_decl = DeclForGlobal(result_global);
233 LLDB_LOG(log, "Result variable doesn't have a corresponding Decl");
235 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) "
236 "does not have a corresponding Clang entity\n",
243 std::string decl_desc_str;
244 raw_string_ostream decl_desc_stream(decl_desc_str);
245 result_decl->print(decl_desc_stream);
246 decl_desc_stream.flush();
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 "
263 // Get the next available result name from m_decl_map and create the
264 // persistent variable for it
266 // If the result is an Lvalue, it is emitted as a pointer; see
267 // ASTResultSynthesizer::SynthesizeBodyResult.
268 if (m_result_is_pointer) {
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();
280 m_result_type = lldb_private::TypeFromParser(
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);
286 m_result_type = lldb_private::TypeFromParser(
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",
298 m_result_type = lldb_private::TypeFromParser(
299 m_decl_map->GetTypeSystem()->GetType(result_var->getType()));
302 lldb::TargetSP target_sp(m_execution_unit.GetTarget());
303 std::optional<uint64_t> bit_size = m_result_type.GetBitSize(target_sp.get());
305 lldb_private::StreamString type_desc_stream;
306 m_result_type.DumpTypeDescription(&type_desc_stream);
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",
312 type_desc_stream.GetData());
317 lldb_private::StreamString type_desc_stream;
318 m_result_type.DumpTypeDescription(&type_desc_stream);
320 LLDB_LOG(log, "Result decl type: \"{0}\"", type_desc_stream.GetData());
323 m_result_name = lldb_private::ConstString("$RESULT_NAME");
325 LLDB_LOG(log, "Creating a new result global: \"{0}\" with size {1}",
327 m_result_type.GetByteSize(target_sp.get()).value_or(0));
329 // Construct a new result global and set up its metadata
331 GlobalVariable *new_result_global = new GlobalVariable(
332 (*m_module), result_global->getValueType(), false, /* not constant */
333 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
334 m_result_name.GetCString());
336 // It's too late in compilation to create a new VarDecl for this, but we
337 // don't need to. We point the metadata at the old VarDecl. This creates an
338 // odd anomaly: a variable with a Value whose name is something like $0 and a
339 // Decl whose name is $__lldb_expr_result. This condition is handled in
340 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
343 ConstantInt *new_constant_int =
344 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
345 reinterpret_cast<uintptr_t>(result_decl), false);
347 llvm::Metadata *values[2];
348 values[0] = ConstantAsMetadata::get(new_result_global);
349 values[1] = ConstantAsMetadata::get(new_constant_int);
351 ArrayRef<Metadata *> value_ref(values, 2);
353 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
354 NamedMDNode *named_metadata =
355 m_module->getNamedMetadata("clang.global.decl.ptrs");
356 named_metadata->addOperand(persistent_global_md);
358 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(result_global),
359 PrintValue(new_result_global));
361 if (result_global->use_empty()) {
362 // We need to synthesize a store for this variable, because otherwise
363 // there's nothing to put into its equivalent persistent variable.
365 BasicBlock &entry_block(llvm_function.getEntryBlock());
366 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
368 if (!first_entry_instruction)
371 if (!result_global->hasInitializer()) {
372 LLDB_LOG(log, "Couldn't find initializer for unused variable");
374 m_error_stream.Format("Internal error [IRForTarget]: Result variable "
375 "({0}) has no writes and no initializer\n",
381 Constant *initializer = result_global->getInitializer();
383 StoreInst *synthesized_store =
384 new StoreInst(initializer, new_result_global, first_entry_instruction);
386 LLDB_LOG(log, "Synthesized result store \"{0}\"\n",
387 PrintValue(synthesized_store));
389 result_global->replaceAllUsesWith(new_result_global);
392 if (!m_decl_map->AddPersistentVariable(
393 result_decl, m_result_name, m_result_type, true, m_result_is_pointer))
396 result_global->eraseFromParent();
401 bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str,
402 llvm::GlobalVariable *cstr) {
403 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
405 Type *ns_str_ty = ns_str->getType();
407 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
408 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
409 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
411 if (!m_CFStringCreateWithBytes) {
412 lldb::addr_t CFStringCreateWithBytes_addr;
414 static lldb_private::ConstString g_CFStringCreateWithBytes_str(
415 "CFStringCreateWithBytes");
417 bool missing_weak = false;
418 CFStringCreateWithBytes_addr =
419 m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str,
421 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS || missing_weak) {
422 LLDB_LOG(log, "Couldn't find CFStringCreateWithBytes in the target");
424 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
425 "constant string requires "
426 "CFStringCreateWithBytes\n");
431 LLDB_LOG(log, "Found CFStringCreateWithBytes at {0}",
432 CFStringCreateWithBytes_addr);
434 // Build the function type:
436 // CFStringRef CFStringCreateWithBytes (
437 // CFAllocatorRef alloc,
438 // const UInt8 *bytes,
440 // CFStringEncoding encoding,
441 // Boolean isExternalRepresentation
444 // We make the following substitutions:
446 // CFStringRef -> i8*
447 // CFAllocatorRef -> i8*
449 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
450 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
452 Type *arg_type_array[5];
454 arg_type_array[0] = i8_ptr_ty;
455 arg_type_array[1] = i8_ptr_ty;
456 arg_type_array[2] = m_intptr_ty;
457 arg_type_array[3] = i32_ty;
458 arg_type_array[4] = i8_ty;
460 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
462 llvm::FunctionType *CFSCWB_ty =
463 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
465 // Build the constant containing the pointer to the function
466 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
467 Constant *CFSCWB_addr_int =
468 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
469 m_CFStringCreateWithBytes = {
470 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)};
473 ConstantDataSequential *string_array = nullptr;
476 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
478 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
479 Constant *bytes_arg = cstr ? cstr : Constant::getNullValue(i8_ptr_ty);
480 Constant *numBytes_arg = ConstantInt::get(
481 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false);
482 int encoding_flags = 0;
483 switch (cstr ? string_array->getElementByteSize() : 1) {
485 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
488 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
491 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
494 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
495 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
497 string_array->getElementByteSize());
499 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
500 Constant *isExternal_arg =
501 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
503 Value *argument_array[5];
505 argument_array[0] = alloc_arg;
506 argument_array[1] = bytes_arg;
507 argument_array[2] = numBytes_arg;
508 argument_array[3] = encoding_arg;
509 argument_array[4] = isExternal_arg;
511 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
513 FunctionValueCache CFSCWB_Caller(
514 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
515 return CallInst::Create(
516 m_CFStringCreateWithBytes, CFSCWB_arguments,
517 "CFStringCreateWithBytes",
518 llvm::cast<Instruction>(
519 m_entry_instruction_finder.GetValue(function)));
522 if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder,
524 LLDB_LOG(log, "Couldn't replace the NSString with the result of the call");
526 m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an "
527 "Objective-C constant string with a dynamic "
533 ns_str->eraseFromParent();
538 bool IRForTarget::RewriteObjCConstStrings() {
539 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
541 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
543 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
544 llvm::StringRef value_name = value_symbol.first();
546 if (value_name.contains("_unnamed_cfstring_")) {
547 Value *nsstring_value = value_symbol.second;
549 GlobalVariable *nsstring_global =
550 dyn_cast<GlobalVariable>(nsstring_value);
552 if (!nsstring_global) {
553 LLDB_LOG(log, "NSString variable is not a GlobalVariable");
555 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
556 "constant string is not a global variable\n");
561 if (!nsstring_global->hasInitializer()) {
562 LLDB_LOG(log, "NSString variable does not have an initializer");
564 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
565 "constant string does not have an initializer\n");
570 ConstantStruct *nsstring_struct =
571 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
573 if (!nsstring_struct) {
575 "NSString variable's initializer is not a ConstantStruct");
577 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
578 "constant string is not a structure constant\n");
583 // We expect the following structure:
592 if (nsstring_struct->getNumOperands() != 4) {
595 "NSString variable's initializer structure has an "
596 "unexpected number of members. Should be 4, is {0}",
597 nsstring_struct->getNumOperands());
599 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
600 "Objective-C constant string is not as "
606 Constant *nsstring_member = nsstring_struct->getOperand(2);
608 if (!nsstring_member) {
609 LLDB_LOG(log, "NSString initializer's str element was empty");
611 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
612 "constant string does not have a string "
618 auto *cstr_global = dyn_cast<GlobalVariable>(nsstring_member);
621 "NSString initializer's str element is not a GlobalVariable");
623 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
624 "constant string initializer\n");
629 if (!cstr_global->hasInitializer()) {
630 LLDB_LOG(log, "NSString initializer's str element does not have an "
633 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
634 "constant string's string initializer doesn't "
635 "point to initialized data\n");
644 log->PutCString("NSString initializer's str element is not a
648 m_error_stream.Printf("Internal error [IRForTarget]: An
649 Objective-C constant string's string initializer doesn't point to an
655 if (!cstr_array->isCString())
658 log->PutCString("NSString initializer's str element is not a C
662 m_error_stream.Printf("Internal error [IRForTarget]: An
663 Objective-C constant string's string initializer doesn't point to a C
670 ConstantDataArray *cstr_array =
671 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
674 LLDB_LOG(log, "Found NSString constant {0}, which contains \"{1}\"",
675 value_name, cstr_array->getAsString());
677 LLDB_LOG(log, "Found NSString constant {0}, which contains \"\"",
681 cstr_global = nullptr;
683 if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
684 LLDB_LOG(log, "Error rewriting the constant string");
686 // We don't print an error message here because RewriteObjCConstString
687 // has done so for us.
694 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
695 llvm::StringRef value_name = value_symbol.first();
697 if (value_name == "__CFConstantStringClassReference") {
698 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second);
702 "__CFConstantStringClassReference is not a global variable");
704 m_error_stream.Printf("Internal error [IRForTarget]: Found a "
705 "CFConstantStringClassReference, but it is not a "
711 gv->eraseFromParent();
720 static bool IsObjCSelectorRef(Value *value) {
721 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
723 return !(!global_variable || !global_variable->hasName() ||
724 !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_"));
727 // This function does not report errors; its callers are responsible.
728 bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
729 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
731 LoadInst *load = dyn_cast<LoadInst>(selector_load);
736 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend
737 // gets represented as
739 // %sel = load ptr, ptr @OBJC_SELECTOR_REFERENCES_, align 8
740 // call i8 @objc_msgSend(ptr %obj, ptr %sel, ...)
742 // where %obj is the object pointer and %sel is the selector.
744 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
745 // @"\01L_OBJC_METH_VAR_NAME_".
746 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
748 // Find the pointer's initializer and get the string from its target.
750 GlobalVariable *_objc_selector_references_ =
751 dyn_cast<GlobalVariable>(load->getPointerOperand());
753 if (!_objc_selector_references_ ||
754 !_objc_selector_references_->hasInitializer())
757 Constant *osr_initializer = _objc_selector_references_->getInitializer();
758 if (!osr_initializer)
761 // Find the string's initializer (a ConstantArray) and get the string from it
763 GlobalVariable *_objc_meth_var_name_ =
764 dyn_cast<GlobalVariable>(osr_initializer);
766 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
769 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
771 ConstantDataArray *omvn_initializer_array =
772 dyn_cast<ConstantDataArray>(omvn_initializer);
774 if (!omvn_initializer_array->isString())
777 std::string omvn_initializer_string =
778 std::string(omvn_initializer_array->getAsString());
780 LLDB_LOG(log, "Found Objective-C selector reference \"{0}\"",
781 omvn_initializer_string);
783 // Construct a call to sel_registerName
785 if (!m_sel_registerName) {
786 lldb::addr_t sel_registerName_addr;
788 bool missing_weak = false;
789 static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
790 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str,
792 if (sel_registerName_addr == LLDB_INVALID_ADDRESS || missing_weak)
795 LLDB_LOG(log, "Found sel_registerName at {0}", sel_registerName_addr);
797 // Build the function type: struct objc_selector
798 // *sel_registerName(uint8_t*)
800 // The below code would be "more correct," but in actuality what's required
802 // Type *sel_type = StructType::get(m_module->getContext());
803 // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
804 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
808 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
810 ArrayRef<Type *> srN_arg_types(type_array, 1);
812 llvm::FunctionType *srN_type =
813 FunctionType::get(sel_ptr_type, srN_arg_types, false);
815 // Build the constant containing the pointer to the function
816 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
817 Constant *srN_addr_int =
818 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
819 m_sel_registerName = {srN_type,
820 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
824 CallInst::Create(m_sel_registerName, _objc_meth_var_name_,
825 "sel_registerName", selector_load);
827 // Replace the load with the call in all users
829 selector_load->replaceAllUsesWith(srN_call);
831 selector_load->eraseFromParent();
836 bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
837 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
839 InstrList selector_loads;
841 for (Instruction &inst : basic_block) {
842 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
843 if (IsObjCSelectorRef(load->getPointerOperand()))
844 selector_loads.push_back(&inst);
847 for (Instruction *inst : selector_loads) {
848 if (!RewriteObjCSelector(inst)) {
849 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a "
850 "static reference to an Objective-C selector to a "
851 "dynamic reference\n");
853 LLDB_LOG(log, "Couldn't rewrite a reference to an Objective-C selector");
862 // This function does not report errors; its callers are responsible.
863 bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
864 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
866 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
868 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
870 if (!alloc_md || !alloc_md->getNumOperands())
873 ConstantInt *constant_int =
874 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
879 // We attempt to register this as a new persistent variable with the DeclMap.
881 uintptr_t ptr = constant_int->getZExtValue();
883 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
885 lldb_private::TypeFromParser result_decl_type(
886 m_decl_map->GetTypeSystem()->GetType(decl->getType()));
888 StringRef decl_name(decl->getName());
889 lldb_private::ConstString persistent_variable_name(decl_name.data(),
891 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
892 result_decl_type, false, false))
895 GlobalVariable *persistent_global = new GlobalVariable(
896 (*m_module), alloc->getType(), false, /* not constant */
897 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
898 alloc->getName().str());
900 // What we're going to do here is make believe this was a regular old
901 // external variable. That means we need to make the metadata valid.
903 NamedMDNode *named_metadata =
904 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
906 llvm::Metadata *values[2];
907 values[0] = ConstantAsMetadata::get(persistent_global);
908 values[1] = ConstantAsMetadata::get(constant_int);
910 ArrayRef<llvm::Metadata *> value_ref(values, 2);
912 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
913 named_metadata->addOperand(persistent_global_md);
915 // Now, since the variable is a pointer variable, we will drop in a load of
916 // that pointer variable.
918 LoadInst *persistent_load = new LoadInst(persistent_global->getValueType(),
919 persistent_global, "", alloc);
921 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(alloc),
922 PrintValue(persistent_load));
924 alloc->replaceAllUsesWith(persistent_load);
925 alloc->eraseFromParent();
930 bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
934 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
936 InstrList pvar_allocs;
938 for (Instruction &inst : basic_block) {
940 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
941 llvm::StringRef alloc_name = alloc->getName();
943 if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) {
944 if (alloc_name.find_first_of("0123456789") == 1) {
945 LLDB_LOG(log, "Rejecting a numeric persistent variable.");
947 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
948 "$1, ... are reserved for use as result "
954 pvar_allocs.push_back(alloc);
959 for (Instruction *inst : pvar_allocs) {
960 if (!RewritePersistentAlloc(inst)) {
961 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
962 "the creation of a persistent variable\n");
964 LLDB_LOG(log, "Couldn't rewrite the creation of a persistent variable");
973 // This function does not report errors; its callers are responsible.
974 bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
975 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
977 LLDB_LOG(log, "MaybeHandleVariable ({0})", PrintValue(llvm_value_ptr));
979 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
980 switch (constant_expr->getOpcode()) {
983 case Instruction::GetElementPtr:
984 case Instruction::BitCast:
985 Value *s = constant_expr->getOperand(0);
986 if (!MaybeHandleVariable(s))
989 } else if (GlobalVariable *global_variable =
990 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
991 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
994 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
997 if (IsObjCSelectorRef(llvm_value_ptr))
1000 if (!global_variable->hasExternalLinkage())
1003 LLDB_LOG(log, "Found global variable \"{0}\" without metadata",
1004 global_variable->getName());
1009 llvm::StringRef name(named_decl->getName());
1011 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1012 if (value_decl == nullptr)
1015 lldb_private::CompilerType compiler_type =
1016 m_decl_map->GetTypeSystem()->GetType(value_decl->getType());
1018 const Type *value_type = nullptr;
1020 if (name.startswith("$")) {
1021 // The $__lldb_expr_result name indicates the return value has allocated
1022 // as a static variable. Per the comment at
1023 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1024 // variable need to be redirected to the result of dereferencing a
1025 // pointer that is passed in as one of the arguments.
1027 // Consequently, when reporting the size of the type, we report a pointer
1028 // type pointing to the type of $__lldb_expr_result, not the type itself.
1030 // We also do this for any user-declared persistent variables.
1031 compiler_type = compiler_type.GetPointerType();
1032 value_type = PointerType::get(global_variable->getType(), 0);
1034 value_type = global_variable->getType();
1037 auto *target = m_execution_unit.GetTarget().get();
1038 std::optional<uint64_t> value_size = compiler_type.GetByteSize(target);
1041 std::optional<size_t> opt_alignment = compiler_type.GetTypeBitAlign(target);
1044 lldb::offset_t value_alignment = (*opt_alignment + 7ull) / 8ull;
1047 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, "
1050 lldb_private::ClangUtil::GetQualType(compiler_type).getAsString(),
1051 PrintType(value_type), *value_size, value_alignment);
1054 m_decl_map->AddValueToStruct(named_decl, lldb_private::ConstString(name),
1055 llvm_value_ptr, *value_size,
1057 } else if (isa<llvm::Function>(llvm_value_ptr)) {
1058 LLDB_LOG(log, "Function pointers aren't handled right now");
1066 // This function does not report errors; its callers are responsible.
1067 bool IRForTarget::HandleSymbol(Value *symbol) {
1068 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1070 lldb_private::ConstString name(symbol->getName().str().c_str());
1072 lldb::addr_t symbol_addr =
1073 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1075 if (symbol_addr == LLDB_INVALID_ADDRESS) {
1076 LLDB_LOG(log, "Symbol \"{0}\" had no address", name);
1081 LLDB_LOG(log, "Found \"{0}\" at {1}", name, symbol_addr);
1083 Type *symbol_type = symbol->getType();
1085 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1087 Value *symbol_addr_ptr =
1088 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1090 LLDB_LOG(log, "Replacing {0} with {1}", PrintValue(symbol),
1091 PrintValue(symbol_addr_ptr));
1093 symbol->replaceAllUsesWith(symbol_addr_ptr);
1098 bool IRForTarget::MaybeHandleCallArguments(CallInst *Old) {
1099 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1101 LLDB_LOG(log, "MaybeHandleCallArguments({0})", PrintValue(Old));
1103 for (unsigned op_index = 0, num_ops = Old->arg_size();
1104 op_index < num_ops; ++op_index)
1105 // conservatively believe that this is a store
1106 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) {
1107 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1108 "one of the arguments of a function call.\n");
1116 bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1117 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1119 GlobalVariable *global_variable =
1120 dyn_cast<GlobalVariable>(classlist_reference);
1122 if (!global_variable)
1125 Constant *initializer = global_variable->getInitializer();
1130 if (!initializer->hasName())
1133 StringRef name(initializer->getName());
1134 lldb_private::ConstString name_cstr(name.str().c_str());
1135 lldb::addr_t class_ptr =
1136 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1138 LLDB_LOG(log, "Found reference to Objective-C class {0} ({1})", name,
1139 (unsigned long long)class_ptr);
1141 if (class_ptr == LLDB_INVALID_ADDRESS)
1144 if (global_variable->use_empty())
1147 SmallVector<LoadInst *, 2> load_instructions;
1149 for (llvm::User *u : global_variable->users()) {
1150 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1151 load_instructions.push_back(load_instruction);
1154 if (load_instructions.empty())
1157 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1159 for (LoadInst *load_instruction : load_instructions) {
1160 Constant *class_bitcast =
1161 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1163 load_instruction->replaceAllUsesWith(class_bitcast);
1165 load_instruction->eraseFromParent();
1171 bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1172 std::vector<CallInst *> calls_to_remove;
1174 for (Instruction &inst : basic_block) {
1175 CallInst *call = dyn_cast<CallInst>(&inst);
1177 // MaybeHandleCallArguments handles error reporting; we are silent here
1181 bool remove = false;
1183 llvm::Function *func = call->getCalledFunction();
1185 if (func && func->getName() == "__cxa_atexit")
1188 llvm::Value *val = call->getCalledOperand();
1190 if (val && val->getName() == "__cxa_atexit")
1194 calls_to_remove.push_back(call);
1197 for (CallInst *ci : calls_to_remove)
1198 ci->eraseFromParent();
1203 bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1204 // Prepare the current basic block for execution in the remote process
1206 for (Instruction &inst : basic_block) {
1207 CallInst *call = dyn_cast<CallInst>(&inst);
1209 // MaybeHandleCallArguments handles error reporting; we are silent here
1210 if (call && !MaybeHandleCallArguments(call))
1217 bool IRForTarget::ResolveExternals(Function &llvm_function) {
1218 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1220 for (GlobalVariable &global_var : m_module->globals()) {
1221 llvm::StringRef global_name = global_var.getName();
1223 LLDB_LOG(log, "Examining {0}, DeclForGlobalValue returns {1}", global_name,
1224 static_cast<void *>(DeclForGlobal(&global_var)));
1226 if (global_name.startswith("OBJC_IVAR")) {
1227 if (!HandleSymbol(&global_var)) {
1228 m_error_stream.Format("Error [IRForTarget]: Couldn't find Objective-C "
1229 "indirect ivar symbol {0}\n",
1234 } else if (global_name.contains("OBJC_CLASSLIST_REFERENCES_$")) {
1235 if (!HandleObjCClass(&global_var)) {
1236 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1237 "for an Objective-C static method call\n");
1241 } else if (global_name.contains("OBJC_CLASSLIST_SUP_REFS_$")) {
1242 if (!HandleObjCClass(&global_var)) {
1243 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1244 "for an Objective-C static method call\n");
1248 } else if (DeclForGlobal(&global_var)) {
1249 if (!MaybeHandleVariable(&global_var)) {
1250 m_error_stream.Format("Internal error [IRForTarget]: Couldn't rewrite "
1251 "external variable {0}\n",
1262 static bool isGuardVariableRef(Value *V) {
1263 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1265 if (!GV || !GV->hasName() || !isGuardVariableSymbol(GV->getName()))
1271 void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1272 Constant *zero(Constant::getNullValue(guard_load->getType()));
1273 guard_load->replaceAllUsesWith(zero);
1274 guard_load->eraseFromParent();
1277 static void ExciseGuardStore(Instruction *guard_store) {
1278 guard_store->eraseFromParent();
1281 bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1282 // Eliminate any reference to guard variables found.
1284 InstrList guard_loads;
1285 InstrList guard_stores;
1287 for (Instruction &inst : basic_block) {
1289 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1290 if (isGuardVariableRef(load->getPointerOperand()))
1291 guard_loads.push_back(&inst);
1293 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1294 if (isGuardVariableRef(store->getPointerOperand()))
1295 guard_stores.push_back(&inst);
1298 for (Instruction *inst : guard_loads)
1299 TurnGuardLoadIntoZero(inst);
1301 for (Instruction *inst : guard_stores)
1302 ExciseGuardStore(inst);
1307 // This function does not report errors; its callers are responsible.
1308 bool IRForTarget::UnfoldConstant(Constant *old_constant,
1309 llvm::Function *llvm_function,
1310 FunctionValueCache &value_maker,
1311 FunctionValueCache &entry_instruction_finder,
1312 lldb_private::Stream &error_stream) {
1313 SmallVector<User *, 16> users;
1315 // We do this because the use list might change, invalidating our iterator.
1316 // Much better to keep a work list ourselves.
1317 for (llvm::User *u : old_constant->users())
1320 for (size_t i = 0; i < users.size(); ++i) {
1321 User *user = users[i];
1323 if (Constant *constant = dyn_cast<Constant>(user)) {
1324 // synthesize a new non-constant equivalent of the constant
1326 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1327 switch (constant_expr->getOpcode()) {
1329 error_stream.Printf("error [IRForTarget internal]: Unhandled "
1330 "constant expression type: \"%s\"",
1331 PrintValue(constant_expr).c_str());
1333 case Instruction::BitCast: {
1334 FunctionValueCache bit_cast_maker(
1335 [&value_maker, &entry_instruction_finder, old_constant,
1336 constant_expr](llvm::Function *function) -> llvm::Value * {
1338 // OperandList[0] is value
1340 if (constant_expr->getOperand(0) != old_constant)
1341 return constant_expr;
1343 return new BitCastInst(
1344 value_maker.GetValue(function), constant_expr->getType(),
1345 "", llvm::cast<Instruction>(
1346 entry_instruction_finder.GetValue(function)));
1349 if (!UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1350 entry_instruction_finder, error_stream))
1353 case Instruction::GetElementPtr: {
1354 // GetElementPtrConstantExpr
1355 // OperandList[0] is base
1356 // OperandList[1]... are indices
1358 FunctionValueCache get_element_pointer_maker(
1359 [&value_maker, &entry_instruction_finder, old_constant,
1360 constant_expr](llvm::Function *function) -> llvm::Value * {
1361 auto *gep = cast<llvm::GEPOperator>(constant_expr);
1362 Value *ptr = gep->getPointerOperand();
1364 if (ptr == old_constant)
1365 ptr = value_maker.GetValue(function);
1367 std::vector<Value *> index_vector;
1368 for (Value *operand : gep->indices()) {
1369 if (operand == old_constant)
1370 operand = value_maker.GetValue(function);
1372 index_vector.push_back(operand);
1375 ArrayRef<Value *> indices(index_vector);
1377 return GetElementPtrInst::Create(
1378 gep->getSourceElementType(), ptr, indices, "",
1379 llvm::cast<Instruction>(
1380 entry_instruction_finder.GetValue(function)));
1383 if (!UnfoldConstant(constant_expr, llvm_function,
1384 get_element_pointer_maker,
1385 entry_instruction_finder, error_stream))
1390 error_stream.Printf(
1391 "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1392 PrintValue(constant).c_str());
1396 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1397 if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1398 error_stream.PutCString("error: Capturing non-local variables in "
1399 "expressions is unsupported.\n");
1402 inst->replaceUsesOfWith(
1403 old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1405 error_stream.Printf(
1406 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1407 PrintValue(user).c_str());
1413 if (!isa<GlobalValue>(old_constant)) {
1414 old_constant->destroyConstant();
1420 bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1421 if (!m_resolve_vars)
1424 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1426 m_decl_map->DoStructLayout();
1428 LLDB_LOG(log, "Element arrangement:");
1430 uint32_t num_elements;
1431 uint32_t element_index;
1434 lldb::offset_t alignment;
1436 if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1439 Function::arg_iterator iter(llvm_function.arg_begin());
1441 if (iter == llvm_function.arg_end()) {
1442 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no "
1443 "arguments (should take at least a struct pointer)");
1448 Argument *argument = &*iter;
1450 if (argument->getName().equals("this")) {
1453 if (iter == llvm_function.arg_end()) {
1454 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1455 "'this' argument (should take a struct pointer "
1462 } else if (argument->getName().equals("self")) {
1465 if (iter == llvm_function.arg_end()) {
1466 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1467 "'self' argument (should take '_cmd' and a struct "
1473 if (!iter->getName().equals("_cmd")) {
1474 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes '{0}' "
1475 "after 'self' argument (should take '_cmd')",
1483 if (iter == llvm_function.arg_end()) {
1484 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only "
1485 "'self' and '_cmd' arguments (should take a struct "
1494 if (!argument->getName().equals("$__lldb_arg")) {
1495 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes an "
1496 "argument named '{0}' instead of the struct pointer",
1497 argument->getName());
1502 LLDB_LOG(log, "Arg: \"{0}\"", PrintValue(argument));
1504 BasicBlock &entry_block(llvm_function.getEntryBlock());
1505 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1507 if (!FirstEntryInstruction) {
1508 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1509 "first instruction in the wrapper for use in "
1515 LLVMContext &context(m_module->getContext());
1516 IntegerType *offset_type(Type::getInt32Ty(context));
1519 m_error_stream.Printf(
1520 "Internal error [IRForTarget]: Couldn't produce an offset type");
1525 for (element_index = 0; element_index < num_elements; ++element_index) {
1526 const clang::NamedDecl *decl = nullptr;
1527 Value *value = nullptr;
1528 lldb::offset_t offset;
1529 lldb_private::ConstString name;
1531 if (!m_decl_map->GetStructElement(decl, value, offset, name,
1533 m_error_stream.Printf(
1534 "Internal error [IRForTarget]: Structure information is incomplete");
1539 LLDB_LOG(log, " \"{0}\" (\"{1}\") placed at {2}", name,
1540 decl->getNameAsString(), offset);
1543 LLDB_LOG(log, " Replacing [{0}]", PrintValue(value));
1545 FunctionValueCache body_result_maker(
1546 [this, name, offset_type, offset, argument,
1547 value](llvm::Function *function) -> llvm::Value * {
1548 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1549 // in cases where the result variable is an rvalue, we have to
1550 // synthesize a dereference of the appropriate structure entry in
1551 // order to produce the static variable that the AST thinks it is
1554 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1555 m_entry_instruction_finder.GetValue(function));
1557 Type *int8Ty = Type::getInt8Ty(function->getContext());
1558 ConstantInt *offset_int(
1559 ConstantInt::get(offset_type, offset, true));
1560 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(
1561 int8Ty, argument, offset_int, "", entry_instruction);
1563 if (name == m_result_name && !m_result_is_pointer) {
1564 LoadInst *load = new LoadInst(value->getType(), get_element_ptr,
1565 "", entry_instruction);
1569 return get_element_ptr;
1573 if (Constant *constant = dyn_cast<Constant>(value)) {
1574 if (!UnfoldConstant(constant, &llvm_function, body_result_maker,
1575 m_entry_instruction_finder, m_error_stream)) {
1578 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1579 if (instruction->getParent()->getParent() != &llvm_function) {
1580 m_error_stream.PutCString("error: Capturing non-local variables in "
1581 "expressions is unsupported.\n");
1584 value->replaceAllUsesWith(
1585 body_result_maker.GetValue(instruction->getParent()->getParent()));
1587 LLDB_LOG(log, "Unhandled non-constant type: \"{0}\"",
1592 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1593 var->eraseFromParent();
1597 LLDB_LOG(log, "Total structure [align {0}, size {1}]", (int64_t)alignment,
1603 bool IRForTarget::runOnModule(Module &llvm_module) {
1604 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1606 m_module = &llvm_module;
1607 m_target_data = std::make_unique<DataLayout>(m_module);
1608 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
1609 m_target_data->getPointerSizeInBits());
1613 raw_string_ostream oss(s);
1615 m_module->print(oss, nullptr);
1619 LLDB_LOG(log, "Module as passed in to IRForTarget: \n\"{0}\"", s);
1622 Function *const main_function =
1623 m_func_name.IsEmpty() ? nullptr
1624 : m_module->getFunction(m_func_name.GetStringRef());
1626 if (!m_func_name.IsEmpty() && !main_function) {
1627 LLDB_LOG(log, "Couldn't find \"{0}()\" in the module", m_func_name);
1629 m_error_stream.Format("Internal error [IRForTarget]: Couldn't find wrapper "
1630 "'{0}' in the module",
1636 if (main_function) {
1637 if (!FixFunctionLinkage(*main_function)) {
1638 LLDB_LOG(log, "Couldn't fix the linkage for the function");
1644 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
1646 m_reloc_placeholder = new llvm::GlobalVariable(
1647 (*m_module), int8_ty, false /* IsConstant */,
1648 GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty),
1649 "reloc_placeholder", nullptr /* InsertBefore */,
1650 GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */);
1652 ////////////////////////////////////////////////////////////
1653 // Replace $__lldb_expr_result with a persistent variable
1656 if (main_function) {
1657 if (!CreateResultVariable(*main_function)) {
1658 LLDB_LOG(log, "CreateResultVariable() failed");
1660 // CreateResultVariable() reports its own errors, so we don't do so here
1666 if (log && log->GetVerbose()) {
1668 raw_string_ostream oss(s);
1670 m_module->print(oss, nullptr);
1674 LLDB_LOG(log, "Module after creating the result variable: \n\"{0}\"", s);
1677 for (llvm::Function &function : *m_module) {
1678 for (BasicBlock &bb : function) {
1679 if (!RemoveGuards(bb)) {
1680 LLDB_LOG(log, "RemoveGuards() failed");
1682 // RemoveGuards() reports its own errors, so we don't do so here
1687 if (!RewritePersistentAllocs(bb)) {
1688 LLDB_LOG(log, "RewritePersistentAllocs() failed");
1690 // RewritePersistentAllocs() reports its own errors, so we don't do so
1696 if (!RemoveCXAAtExit(bb)) {
1697 LLDB_LOG(log, "RemoveCXAAtExit() failed");
1699 // RemoveCXAAtExit() reports its own errors, so we don't do so here
1706 ///////////////////////////////////////////////////////////////////////////////
1707 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
1710 if (!RewriteObjCConstStrings()) {
1711 LLDB_LOG(log, "RewriteObjCConstStrings() failed");
1713 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
1718 for (llvm::Function &function : *m_module) {
1719 for (llvm::BasicBlock &bb : function) {
1720 if (!RewriteObjCSelectors(bb)) {
1721 LLDB_LOG(log, "RewriteObjCSelectors() failed");
1723 // RewriteObjCSelectors() reports its own errors, so we don't do so
1731 for (llvm::Function &function : *m_module) {
1732 for (BasicBlock &bb : function) {
1733 if (!ResolveCalls(bb)) {
1734 LLDB_LOG(log, "ResolveCalls() failed");
1736 // ResolveCalls() reports its own errors, so we don't do so here
1743 ////////////////////////////////////////////////////////////////////////
1744 // Run function-level passes that only make sense on the main function
1747 if (main_function) {
1748 if (!ResolveExternals(*main_function)) {
1749 LLDB_LOG(log, "ResolveExternals() failed");
1751 // ResolveExternals() reports its own errors, so we don't do so here
1756 if (!ReplaceVariables(*main_function)) {
1757 LLDB_LOG(log, "ReplaceVariables() failed");
1759 // ReplaceVariables() reports its own errors, so we don't do so here
1765 if (log && log->GetVerbose()) {
1767 raw_string_ostream oss(s);
1769 m_module->print(oss, nullptr);
1773 LLDB_LOG(log, "Module after preparing for execution: \n\"{0}\"", s);