1 //===-- IRForTarget.cpp ---------------------------------------------------===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "IRForTarget.h" 10 11 #include "ClangExpressionDeclMap.h" 12 #include "ClangUtil.h" 13 14 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" 15 #include "llvm/IR/Constants.h" 16 #include "llvm/IR/DataLayout.h" 17 #include "llvm/IR/InstrTypes.h" 18 #include "llvm/IR/Instructions.h" 19 #include "llvm/IR/Intrinsics.h" 20 #include "llvm/IR/LegacyPassManager.h" 21 #include "llvm/IR/Metadata.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/IR/ValueSymbolTable.h" 24 #include "llvm/Support/raw_ostream.h" 25 #include "llvm/Transforms/IPO.h" 26 27 #include "clang/AST/ASTContext.h" 28 29 #include "lldb/Core/dwarf.h" 30 #include "lldb/Expression/IRExecutionUnit.h" 31 #include "lldb/Expression/IRInterpreter.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" 39 40 #include <map> 41 42 using namespace llvm; 43 44 static char ID; 45 46 typedef SmallVector<Instruction *, 2> InstrList; 47 48 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) 49 : m_maker(maker), m_values() {} 50 51 IRForTarget::FunctionValueCache::~FunctionValueCache() {} 52 53 llvm::Value * 54 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) { 55 if (!m_values.count(function)) { 56 llvm::Value *ret = m_maker(function); 57 m_values[function] = ret; 58 return ret; 59 } 60 return m_values[function]; 61 } 62 63 static llvm::Value *FindEntryInstruction(llvm::Function *function) { 64 if (function->empty()) 65 return nullptr; 66 67 return function->getEntryBlock().getFirstNonPHIOrDbg(); 68 } 69 70 IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, 71 bool resolve_vars, 72 lldb_private::IRExecutionUnit &execution_unit, 73 lldb_private::Stream &error_stream, 74 const char *func_name) 75 : ModulePass(ID), m_resolve_vars(resolve_vars), m_func_name(func_name), 76 m_module(nullptr), m_decl_map(decl_map), 77 m_CFStringCreateWithBytes(nullptr), m_sel_registerName(nullptr), 78 m_objc_getClass(nullptr), m_intptr_ty(nullptr), 79 m_error_stream(error_stream), m_execution_unit(execution_unit), 80 m_result_store(nullptr), m_result_is_pointer(false), 81 m_reloc_placeholder(nullptr), 82 m_entry_instruction_finder(FindEntryInstruction) {} 83 84 /* Handy utility functions used at several places in the code */ 85 86 static std::string PrintValue(const Value *value, bool truncate = false) { 87 std::string s; 88 if (value) { 89 raw_string_ostream rso(s); 90 value->print(rso); 91 rso.flush(); 92 if (truncate) 93 s.resize(s.length() - 1); 94 } 95 return s; 96 } 97 98 static std::string PrintType(const llvm::Type *type, bool truncate = false) { 99 std::string s; 100 raw_string_ostream rso(s); 101 type->print(rso); 102 rso.flush(); 103 if (truncate) 104 s.resize(s.length() - 1); 105 return s; 106 } 107 108 IRForTarget::~IRForTarget() {} 109 110 bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) { 111 llvm_function.setLinkage(GlobalValue::ExternalLinkage); 112 113 return true; 114 } 115 116 clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val, 117 Module *module) { 118 NamedMDNode *named_metadata = 119 module->getNamedMetadata("clang.global.decl.ptrs"); 120 121 if (!named_metadata) 122 return nullptr; 123 124 unsigned num_nodes = named_metadata->getNumOperands(); 125 unsigned node_index; 126 127 for (node_index = 0; node_index < num_nodes; ++node_index) { 128 llvm::MDNode *metadata_node = 129 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index)); 130 if (!metadata_node) 131 return nullptr; 132 133 if (metadata_node->getNumOperands() != 2) 134 continue; 135 136 if (mdconst::dyn_extract_or_null<GlobalValue>( 137 metadata_node->getOperand(0)) != global_val) 138 continue; 139 140 ConstantInt *constant_int = 141 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1)); 142 143 if (!constant_int) 144 return nullptr; 145 146 uintptr_t ptr = constant_int->getZExtValue(); 147 148 return reinterpret_cast<clang::NamedDecl *>(ptr); 149 } 150 151 return nullptr; 152 } 153 154 clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) { 155 return DeclForGlobal(global_val, m_module); 156 } 157 158 /// Returns true iff the mangled symbol is for a static guard variable. 159 static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol, 160 bool check_ms_abi = true) { 161 bool result = mangled_symbol.startswith("_ZGV"); // Itanium ABI guard variable 162 if (check_ms_abi) 163 result |= mangled_symbol.endswith("@4IA"); // Microsoft ABI 164 return result; 165 } 166 167 bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) { 168 lldb_private::Log *log( 169 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 170 171 if (!m_resolve_vars) 172 return true; 173 174 // Find the result variable. If it doesn't exist, we can give up right here. 175 176 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable(); 177 178 llvm::StringRef result_name; 179 bool found_result = false; 180 181 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) { 182 result_name = value_symbol.first(); 183 184 // Check if this is a guard variable. It seems this causes some hiccups 185 // on Windows, so let's only check for Itanium guard variables. 186 bool is_guard_var = isGuardVariableSymbol(result_name, /*MS ABI*/ false); 187 188 if (result_name.contains("$__lldb_expr_result_ptr") && !is_guard_var) { 189 found_result = true; 190 m_result_is_pointer = true; 191 break; 192 } 193 194 if (result_name.contains("$__lldb_expr_result") && !is_guard_var) { 195 found_result = true; 196 m_result_is_pointer = false; 197 break; 198 } 199 } 200 201 if (!found_result) { 202 LLDB_LOG(log, "Couldn't find result variable"); 203 204 return true; 205 } 206 207 LLDB_LOG(log, "Result name: \"{0}\"", result_name); 208 209 Value *result_value = m_module->getNamedValue(result_name); 210 211 if (!result_value) { 212 LLDB_LOG(log, "Result variable had no data"); 213 214 m_error_stream.Format("Internal error [IRForTarget]: Result variable's " 215 "name ({0}) exists, but not its definition\n", 216 result_name); 217 218 return false; 219 } 220 221 LLDB_LOG(log, "Found result in the IR: \"{0}\"", 222 PrintValue(result_value, false)); 223 224 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value); 225 226 if (!result_global) { 227 LLDB_LOG(log, "Result variable isn't a GlobalVariable"); 228 229 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) " 230 "is defined, but is not a global variable\n", 231 result_name); 232 233 return false; 234 } 235 236 clang::NamedDecl *result_decl = DeclForGlobal(result_global); 237 if (!result_decl) { 238 LLDB_LOG(log, "Result variable doesn't have a corresponding Decl"); 239 240 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) " 241 "does not have a corresponding Clang entity\n", 242 result_name); 243 244 return false; 245 } 246 247 if (log) { 248 std::string decl_desc_str; 249 raw_string_ostream decl_desc_stream(decl_desc_str); 250 result_decl->print(decl_desc_stream); 251 decl_desc_stream.flush(); 252 253 LLDB_LOG(log, "Found result decl: \"{0}\"", decl_desc_str); 254 } 255 256 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl); 257 if (!result_var) { 258 LLDB_LOG(log, "Result variable Decl isn't a VarDecl"); 259 260 m_error_stream.Format("Internal error [IRForTarget]: Result variable " 261 "({0})'s corresponding Clang entity isn't a " 262 "variable\n", 263 result_name); 264 265 return false; 266 } 267 268 // Get the next available result name from m_decl_map and create the 269 // persistent variable for it 270 271 // If the result is an Lvalue, it is emitted as a pointer; see 272 // ASTResultSynthesizer::SynthesizeBodyResult. 273 if (m_result_is_pointer) { 274 clang::QualType pointer_qual_type = result_var->getType(); 275 const clang::Type *pointer_type = pointer_qual_type.getTypePtr(); 276 277 const clang::PointerType *pointer_pointertype = 278 pointer_type->getAs<clang::PointerType>(); 279 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = 280 pointer_type->getAs<clang::ObjCObjectPointerType>(); 281 282 if (pointer_pointertype) { 283 clang::QualType element_qual_type = pointer_pointertype->getPointeeType(); 284 285 m_result_type = lldb_private::TypeFromParser( 286 m_decl_map->GetTypeSystem()->GetType(element_qual_type)); 287 } else if (pointer_objcobjpointertype) { 288 clang::QualType element_qual_type = 289 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0); 290 291 m_result_type = lldb_private::TypeFromParser( 292 m_decl_map->GetTypeSystem()->GetType(element_qual_type)); 293 } else { 294 LLDB_LOG(log, "Expected result to have pointer type, but it did not"); 295 296 m_error_stream.Format("Internal error [IRForTarget]: Lvalue result ({0}) " 297 "is not a pointer variable\n", 298 result_name); 299 300 return false; 301 } 302 } else { 303 m_result_type = lldb_private::TypeFromParser( 304 m_decl_map->GetTypeSystem()->GetType(result_var->getType())); 305 } 306 307 lldb::TargetSP target_sp(m_execution_unit.GetTarget()); 308 llvm::Optional<uint64_t> bit_size = m_result_type.GetBitSize(target_sp.get()); 309 if (!bit_size) { 310 lldb_private::StreamString type_desc_stream; 311 m_result_type.DumpTypeDescription(&type_desc_stream); 312 313 LLDB_LOG(log, "Result type has unknown size"); 314 315 m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' " 316 "couldn't be determined\n", 317 type_desc_stream.GetData()); 318 return false; 319 } 320 321 if (log) { 322 lldb_private::StreamString type_desc_stream; 323 m_result_type.DumpTypeDescription(&type_desc_stream); 324 325 LLDB_LOG(log, "Result decl type: \"{0}\"", type_desc_stream.GetData()); 326 } 327 328 m_result_name = lldb_private::ConstString("$RESULT_NAME"); 329 330 LLDB_LOG(log, "Creating a new result global: \"{0}\" with size {1}", 331 m_result_name, 332 m_result_type.GetByteSize(target_sp.get()).getValueOr(0)); 333 334 // Construct a new result global and set up its metadata 335 336 GlobalVariable *new_result_global = new GlobalVariable( 337 (*m_module), result_global->getType()->getElementType(), 338 false, /* not constant */ 339 GlobalValue::ExternalLinkage, nullptr, /* no initializer */ 340 m_result_name.GetCString()); 341 342 // It's too late in compilation to create a new VarDecl for this, but we 343 // don't need to. We point the metadata at the old VarDecl. This creates an 344 // odd anomaly: a variable with a Value whose name is something like $0 and a 345 // Decl whose name is $__lldb_expr_result. This condition is handled in 346 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is 347 // fixed up. 348 349 ConstantInt *new_constant_int = 350 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()), 351 reinterpret_cast<uintptr_t>(result_decl), false); 352 353 llvm::Metadata *values[2]; 354 values[0] = ConstantAsMetadata::get(new_result_global); 355 values[1] = ConstantAsMetadata::get(new_constant_int); 356 357 ArrayRef<Metadata *> value_ref(values, 2); 358 359 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 360 NamedMDNode *named_metadata = 361 m_module->getNamedMetadata("clang.global.decl.ptrs"); 362 named_metadata->addOperand(persistent_global_md); 363 364 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(result_global), 365 PrintValue(new_result_global)); 366 367 if (result_global->use_empty()) { 368 // We need to synthesize a store for this variable, because otherwise 369 // there's nothing to put into its equivalent persistent variable. 370 371 BasicBlock &entry_block(llvm_function.getEntryBlock()); 372 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); 373 374 if (!first_entry_instruction) 375 return false; 376 377 if (!result_global->hasInitializer()) { 378 LLDB_LOG(log, "Couldn't find initializer for unused variable"); 379 380 m_error_stream.Format("Internal error [IRForTarget]: Result variable " 381 "({0}) has no writes and no initializer\n", 382 result_name); 383 384 return false; 385 } 386 387 Constant *initializer = result_global->getInitializer(); 388 389 StoreInst *synthesized_store = 390 new StoreInst(initializer, new_result_global, first_entry_instruction); 391 392 LLDB_LOG(log, "Synthesized result store \"{0}\"\n", 393 PrintValue(synthesized_store)); 394 } else { 395 result_global->replaceAllUsesWith(new_result_global); 396 } 397 398 if (!m_decl_map->AddPersistentVariable( 399 result_decl, m_result_name, m_result_type, true, m_result_is_pointer)) 400 return false; 401 402 result_global->eraseFromParent(); 403 404 return true; 405 } 406 407 bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str, 408 llvm::GlobalVariable *cstr) { 409 lldb_private::Log *log( 410 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 411 412 Type *ns_str_ty = ns_str->getType(); 413 414 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 415 Type *i32_ty = Type::getInt32Ty(m_module->getContext()); 416 Type *i8_ty = Type::getInt8Ty(m_module->getContext()); 417 418 if (!m_CFStringCreateWithBytes) { 419 lldb::addr_t CFStringCreateWithBytes_addr; 420 421 static lldb_private::ConstString g_CFStringCreateWithBytes_str( 422 "CFStringCreateWithBytes"); 423 424 bool missing_weak = false; 425 CFStringCreateWithBytes_addr = 426 m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str, 427 missing_weak); 428 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS || missing_weak) { 429 LLDB_LOG(log, "Couldn't find CFStringCreateWithBytes in the target"); 430 431 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C " 432 "constant string requires " 433 "CFStringCreateWithBytes\n"); 434 435 return false; 436 } 437 438 LLDB_LOG(log, "Found CFStringCreateWithBytes at {0}", 439 CFStringCreateWithBytes_addr); 440 441 // Build the function type: 442 // 443 // CFStringRef CFStringCreateWithBytes ( 444 // CFAllocatorRef alloc, 445 // const UInt8 *bytes, 446 // CFIndex numBytes, 447 // CFStringEncoding encoding, 448 // Boolean isExternalRepresentation 449 // ); 450 // 451 // We make the following substitutions: 452 // 453 // CFStringRef -> i8* 454 // CFAllocatorRef -> i8* 455 // UInt8 * -> i8* 456 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its 457 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8 458 459 Type *arg_type_array[5]; 460 461 arg_type_array[0] = i8_ptr_ty; 462 arg_type_array[1] = i8_ptr_ty; 463 arg_type_array[2] = m_intptr_ty; 464 arg_type_array[3] = i32_ty; 465 arg_type_array[4] = i8_ty; 466 467 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5); 468 469 llvm::FunctionType *CFSCWB_ty = 470 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false); 471 472 // Build the constant containing the pointer to the function 473 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); 474 Constant *CFSCWB_addr_int = 475 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false); 476 m_CFStringCreateWithBytes = { 477 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)}; 478 } 479 480 ConstantDataSequential *string_array = nullptr; 481 482 if (cstr) 483 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer()); 484 485 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); 486 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) 487 : Constant::getNullValue(i8_ptr_ty); 488 Constant *numBytes_arg = ConstantInt::get( 489 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false); 490 int encoding_flags = 0; 491 switch (cstr ? string_array->getElementByteSize() : 1) { 492 case 1: 493 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */ 494 break; 495 case 2: 496 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */ 497 break; 498 case 4: 499 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */ 500 break; 501 default: 502 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */ 503 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual " 504 "element size {0}", 505 string_array->getElementByteSize()); 506 } 507 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false); 508 Constant *isExternal_arg = 509 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ 510 511 Value *argument_array[5]; 512 513 argument_array[0] = alloc_arg; 514 argument_array[1] = bytes_arg; 515 argument_array[2] = numBytes_arg; 516 argument_array[3] = encoding_arg; 517 argument_array[4] = isExternal_arg; 518 519 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5); 520 521 FunctionValueCache CFSCWB_Caller( 522 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * { 523 return CallInst::Create( 524 m_CFStringCreateWithBytes, CFSCWB_arguments, 525 "CFStringCreateWithBytes", 526 llvm::cast<Instruction>( 527 m_entry_instruction_finder.GetValue(function))); 528 }); 529 530 if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder, 531 m_error_stream)) { 532 LLDB_LOG(log, "Couldn't replace the NSString with the result of the call"); 533 534 m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an " 535 "Objective-C constant string with a dynamic " 536 "string\n"); 537 538 return false; 539 } 540 541 ns_str->eraseFromParent(); 542 543 return true; 544 } 545 546 bool IRForTarget::RewriteObjCConstStrings() { 547 lldb_private::Log *log( 548 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 549 550 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable(); 551 552 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) { 553 llvm::StringRef value_name = value_symbol.first(); 554 555 if (value_name.contains("_unnamed_cfstring_")) { 556 Value *nsstring_value = value_symbol.second; 557 558 GlobalVariable *nsstring_global = 559 dyn_cast<GlobalVariable>(nsstring_value); 560 561 if (!nsstring_global) { 562 LLDB_LOG(log, "NSString variable is not a GlobalVariable"); 563 564 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 565 "constant string is not a global variable\n"); 566 567 return false; 568 } 569 570 if (!nsstring_global->hasInitializer()) { 571 LLDB_LOG(log, "NSString variable does not have an initializer"); 572 573 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 574 "constant string does not have an initializer\n"); 575 576 return false; 577 } 578 579 ConstantStruct *nsstring_struct = 580 dyn_cast<ConstantStruct>(nsstring_global->getInitializer()); 581 582 if (!nsstring_struct) { 583 LLDB_LOG(log, 584 "NSString variable's initializer is not a ConstantStruct"); 585 586 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 587 "constant string is not a structure constant\n"); 588 589 return false; 590 } 591 592 // We expect the following structure: 593 // 594 // struct { 595 // int *isa; 596 // int flags; 597 // char *str; 598 // long length; 599 // }; 600 601 if (nsstring_struct->getNumOperands() != 4) { 602 603 LLDB_LOG(log, 604 "NSString variable's initializer structure has an " 605 "unexpected number of members. Should be 4, is {0}", 606 nsstring_struct->getNumOperands()); 607 608 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an " 609 "Objective-C constant string is not as " 610 "expected\n"); 611 612 return false; 613 } 614 615 Constant *nsstring_member = nsstring_struct->getOperand(2); 616 617 if (!nsstring_member) { 618 LLDB_LOG(log, "NSString initializer's str element was empty"); 619 620 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 621 "constant string does not have a string " 622 "initializer\n"); 623 624 return false; 625 } 626 627 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member); 628 629 if (!nsstring_expr) { 630 LLDB_LOG(log, 631 "NSString initializer's str element is not a ConstantExpr"); 632 633 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 634 "constant string's string initializer is not " 635 "constant\n"); 636 637 return false; 638 } 639 640 GlobalVariable *cstr_global = nullptr; 641 642 if (nsstring_expr->getOpcode() == Instruction::GetElementPtr) { 643 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 644 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 645 } else if (nsstring_expr->getOpcode() == Instruction::BitCast) { 646 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 647 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 648 } 649 650 if (!cstr_global) { 651 LLDB_LOG(log, 652 "NSString initializer's str element is not a GlobalVariable"); 653 654 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled" 655 "constant string initializer\n"); 656 657 return false; 658 } 659 660 if (!cstr_global->hasInitializer()) { 661 LLDB_LOG(log, "NSString initializer's str element does not have an " 662 "initializer"); 663 664 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 665 "constant string's string initializer doesn't " 666 "point to initialized data\n"); 667 668 return false; 669 } 670 671 /* 672 if (!cstr_array) 673 { 674 if (log) 675 log->PutCString("NSString initializer's str element is not a 676 ConstantArray"); 677 678 if (m_error_stream) 679 m_error_stream.Printf("Internal error [IRForTarget]: An 680 Objective-C constant string's string initializer doesn't point to an 681 array\n"); 682 683 return false; 684 } 685 686 if (!cstr_array->isCString()) 687 { 688 if (log) 689 log->PutCString("NSString initializer's str element is not a C 690 string array"); 691 692 if (m_error_stream) 693 m_error_stream.Printf("Internal error [IRForTarget]: An 694 Objective-C constant string's string initializer doesn't point to a C 695 string\n"); 696 697 return false; 698 } 699 */ 700 701 ConstantDataArray *cstr_array = 702 dyn_cast<ConstantDataArray>(cstr_global->getInitializer()); 703 704 if (cstr_array) 705 LLDB_LOG(log, "Found NSString constant {0}, which contains \"{1}\"", 706 value_name, cstr_array->getAsString()); 707 else 708 LLDB_LOG(log, "Found NSString constant {0}, which contains \"\"", 709 value_name); 710 711 if (!cstr_array) 712 cstr_global = nullptr; 713 714 if (!RewriteObjCConstString(nsstring_global, cstr_global)) { 715 LLDB_LOG(log, "Error rewriting the constant string"); 716 717 // We don't print an error message here because RewriteObjCConstString 718 // has done so for us. 719 720 return false; 721 } 722 } 723 } 724 725 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) { 726 llvm::StringRef value_name = value_symbol.first(); 727 728 if (value_name == "__CFConstantStringClassReference") { 729 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second); 730 731 if (!gv) { 732 LLDB_LOG(log, 733 "__CFConstantStringClassReference is not a global variable"); 734 735 m_error_stream.Printf("Internal error [IRForTarget]: Found a " 736 "CFConstantStringClassReference, but it is not a " 737 "global object\n"); 738 739 return false; 740 } 741 742 gv->eraseFromParent(); 743 744 break; 745 } 746 } 747 748 return true; 749 } 750 751 static bool IsObjCSelectorRef(Value *value) { 752 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 753 754 return !(!global_variable || !global_variable->hasName() || 755 !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_")); 756 } 757 758 // This function does not report errors; its callers are responsible. 759 bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) { 760 lldb_private::Log *log( 761 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 762 763 LoadInst *load = dyn_cast<LoadInst>(selector_load); 764 765 if (!load) 766 return false; 767 768 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend 769 // gets represented as 770 // 771 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> %call = call 772 // i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*> 773 // 774 // where %obj is the object pointer and %tmp is the selector. 775 // 776 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called 777 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_". 778 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string. 779 780 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) 781 // and get the string from its target 782 783 GlobalVariable *_objc_selector_references_ = 784 dyn_cast<GlobalVariable>(load->getPointerOperand()); 785 786 if (!_objc_selector_references_ || 787 !_objc_selector_references_->hasInitializer()) 788 return false; 789 790 Constant *osr_initializer = _objc_selector_references_->getInitializer(); 791 792 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer); 793 794 if (!osr_initializer_expr || 795 osr_initializer_expr->getOpcode() != Instruction::GetElementPtr) 796 return false; 797 798 Value *osr_initializer_base = osr_initializer_expr->getOperand(0); 799 800 if (!osr_initializer_base) 801 return false; 802 803 // Find the string's initializer (a ConstantArray) and get the string from it 804 805 GlobalVariable *_objc_meth_var_name_ = 806 dyn_cast<GlobalVariable>(osr_initializer_base); 807 808 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer()) 809 return false; 810 811 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer(); 812 813 ConstantDataArray *omvn_initializer_array = 814 dyn_cast<ConstantDataArray>(omvn_initializer); 815 816 if (!omvn_initializer_array->isString()) 817 return false; 818 819 std::string omvn_initializer_string = 820 std::string(omvn_initializer_array->getAsString()); 821 822 LLDB_LOG(log, "Found Objective-C selector reference \"{0}\"", 823 omvn_initializer_string); 824 825 // Construct a call to sel_registerName 826 827 if (!m_sel_registerName) { 828 lldb::addr_t sel_registerName_addr; 829 830 bool missing_weak = false; 831 static lldb_private::ConstString g_sel_registerName_str("sel_registerName"); 832 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str, 833 missing_weak); 834 if (sel_registerName_addr == LLDB_INVALID_ADDRESS || missing_weak) 835 return false; 836 837 LLDB_LOG(log, "Found sel_registerName at {0}", sel_registerName_addr); 838 839 // Build the function type: struct objc_selector 840 // *sel_registerName(uint8_t*) 841 842 // The below code would be "more correct," but in actuality what's required 843 // is uint8_t* 844 // Type *sel_type = StructType::get(m_module->getContext()); 845 // Type *sel_ptr_type = PointerType::getUnqual(sel_type); 846 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext()); 847 848 Type *type_array[1]; 849 850 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext()); 851 852 ArrayRef<Type *> srN_arg_types(type_array, 1); 853 854 llvm::FunctionType *srN_type = 855 FunctionType::get(sel_ptr_type, srN_arg_types, false); 856 857 // Build the constant containing the pointer to the function 858 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); 859 Constant *srN_addr_int = 860 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false); 861 m_sel_registerName = {srN_type, 862 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)}; 863 } 864 865 Value *argument_array[1]; 866 867 Constant *omvn_pointer = ConstantExpr::getBitCast( 868 _objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext())); 869 870 argument_array[0] = omvn_pointer; 871 872 ArrayRef<Value *> srN_arguments(argument_array, 1); 873 874 CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments, 875 "sel_registerName", selector_load); 876 877 // Replace the load with the call in all users 878 879 selector_load->replaceAllUsesWith(srN_call); 880 881 selector_load->eraseFromParent(); 882 883 return true; 884 } 885 886 bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) { 887 lldb_private::Log *log( 888 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 889 890 InstrList selector_loads; 891 892 for (Instruction &inst : basic_block) { 893 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 894 if (IsObjCSelectorRef(load->getPointerOperand())) 895 selector_loads.push_back(&inst); 896 } 897 898 for (Instruction *inst : selector_loads) { 899 if (!RewriteObjCSelector(inst)) { 900 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a " 901 "static reference to an Objective-C selector to a " 902 "dynamic reference\n"); 903 904 LLDB_LOG(log, "Couldn't rewrite a reference to an Objective-C selector"); 905 906 return false; 907 } 908 } 909 910 return true; 911 } 912 913 static bool IsObjCClassReference(Value *value) { 914 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 915 916 return !(!global_variable || !global_variable->hasName() || 917 !global_variable->getName().startswith("OBJC_CLASS_REFERENCES_")); 918 } 919 920 // This function does not report errors; its callers are responsible. 921 bool IRForTarget::RewriteObjCClassReference(Instruction *class_load) { 922 lldb_private::Log *log( 923 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 924 925 LoadInst *load = dyn_cast<LoadInst>(class_load); 926 927 if (!load) 928 return false; 929 930 // Unpack the class name from the reference. In LLVM IR, a reference to an 931 // Objective-C class gets represented as 932 // 933 // %tmp = load %struct._objc_class*, 934 // %struct._objc_class** @OBJC_CLASS_REFERENCES_, align 4 935 // 936 // @"OBJC_CLASS_REFERENCES_ is a bitcast of a character array called 937 // @OBJC_CLASS_NAME_. @OBJC_CLASS_NAME contains the string. 938 939 // Find the pointer's initializer (a ConstantExpr with opcode BitCast) and 940 // get the string from its target 941 942 GlobalVariable *_objc_class_references_ = 943 dyn_cast<GlobalVariable>(load->getPointerOperand()); 944 945 if (!_objc_class_references_ || 946 !_objc_class_references_->hasInitializer()) 947 return false; 948 949 Constant *ocr_initializer = _objc_class_references_->getInitializer(); 950 951 ConstantExpr *ocr_initializer_expr = dyn_cast<ConstantExpr>(ocr_initializer); 952 953 if (!ocr_initializer_expr || 954 ocr_initializer_expr->getOpcode() != Instruction::BitCast) 955 return false; 956 957 Value *ocr_initializer_base = ocr_initializer_expr->getOperand(0); 958 959 if (!ocr_initializer_base) 960 return false; 961 962 // Find the string's initializer (a ConstantArray) and get the string from it 963 964 GlobalVariable *_objc_class_name_ = 965 dyn_cast<GlobalVariable>(ocr_initializer_base); 966 967 if (!_objc_class_name_ || !_objc_class_name_->hasInitializer()) 968 return false; 969 970 Constant *ocn_initializer = _objc_class_name_->getInitializer(); 971 972 ConstantDataArray *ocn_initializer_array = 973 dyn_cast<ConstantDataArray>(ocn_initializer); 974 975 if (!ocn_initializer_array->isString()) 976 return false; 977 978 std::string ocn_initializer_string = 979 std::string(ocn_initializer_array->getAsString()); 980 981 LLDB_LOG(log, "Found Objective-C class reference \"{0}\"", 982 ocn_initializer_string); 983 984 // Construct a call to objc_getClass 985 986 if (!m_objc_getClass) { 987 lldb::addr_t objc_getClass_addr; 988 989 bool missing_weak = false; 990 static lldb_private::ConstString g_objc_getClass_str("objc_getClass"); 991 objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str, 992 missing_weak); 993 if (objc_getClass_addr == LLDB_INVALID_ADDRESS || missing_weak) 994 return false; 995 996 LLDB_LOG(log, "Found objc_getClass at {0}", objc_getClass_addr); 997 998 // Build the function type: %struct._objc_class *objc_getClass(i8*) 999 1000 Type *class_type = load->getType(); 1001 Type *type_array[1]; 1002 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext()); 1003 1004 ArrayRef<Type *> ogC_arg_types(type_array, 1); 1005 1006 llvm::FunctionType *ogC_type = 1007 FunctionType::get(class_type, ogC_arg_types, false); 1008 1009 // Build the constant containing the pointer to the function 1010 PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type); 1011 Constant *ogC_addr_int = 1012 ConstantInt::get(m_intptr_ty, objc_getClass_addr, false); 1013 m_objc_getClass = {ogC_type, 1014 ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty)}; 1015 } 1016 1017 Value *argument_array[1]; 1018 1019 Constant *ocn_pointer = ConstantExpr::getBitCast( 1020 _objc_class_name_, Type::getInt8PtrTy(m_module->getContext())); 1021 1022 argument_array[0] = ocn_pointer; 1023 1024 ArrayRef<Value *> ogC_arguments(argument_array, 1); 1025 1026 CallInst *ogC_call = CallInst::Create(m_objc_getClass, ogC_arguments, 1027 "objc_getClass", class_load); 1028 1029 // Replace the load with the call in all users 1030 1031 class_load->replaceAllUsesWith(ogC_call); 1032 1033 class_load->eraseFromParent(); 1034 1035 return true; 1036 } 1037 1038 bool IRForTarget::RewriteObjCClassReferences(BasicBlock &basic_block) { 1039 lldb_private::Log *log( 1040 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1041 1042 InstrList class_loads; 1043 1044 for (Instruction &inst : basic_block) { 1045 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1046 if (IsObjCClassReference(load->getPointerOperand())) 1047 class_loads.push_back(&inst); 1048 } 1049 1050 for (Instruction *inst : class_loads) { 1051 if (!RewriteObjCClassReference(inst)) { 1052 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a " 1053 "static reference to an Objective-C class to a " 1054 "dynamic reference\n"); 1055 1056 LLDB_LOG(log, "Couldn't rewrite a reference to an Objective-C class"); 1057 1058 return false; 1059 } 1060 } 1061 1062 return true; 1063 } 1064 1065 // This function does not report errors; its callers are responsible. 1066 bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) { 1067 lldb_private::Log *log( 1068 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1069 1070 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc); 1071 1072 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr"); 1073 1074 if (!alloc_md || !alloc_md->getNumOperands()) 1075 return false; 1076 1077 ConstantInt *constant_int = 1078 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0)); 1079 1080 if (!constant_int) 1081 return false; 1082 1083 // We attempt to register this as a new persistent variable with the DeclMap. 1084 1085 uintptr_t ptr = constant_int->getZExtValue(); 1086 1087 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr); 1088 1089 lldb_private::TypeFromParser result_decl_type( 1090 m_decl_map->GetTypeSystem()->GetType(decl->getType())); 1091 1092 StringRef decl_name(decl->getName()); 1093 lldb_private::ConstString persistent_variable_name(decl_name.data(), 1094 decl_name.size()); 1095 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, 1096 result_decl_type, false, false)) 1097 return false; 1098 1099 GlobalVariable *persistent_global = new GlobalVariable( 1100 (*m_module), alloc->getType(), false, /* not constant */ 1101 GlobalValue::ExternalLinkage, nullptr, /* no initializer */ 1102 alloc->getName().str()); 1103 1104 // What we're going to do here is make believe this was a regular old 1105 // external variable. That means we need to make the metadata valid. 1106 1107 NamedMDNode *named_metadata = 1108 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs"); 1109 1110 llvm::Metadata *values[2]; 1111 values[0] = ConstantAsMetadata::get(persistent_global); 1112 values[1] = ConstantAsMetadata::get(constant_int); 1113 1114 ArrayRef<llvm::Metadata *> value_ref(values, 2); 1115 1116 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 1117 named_metadata->addOperand(persistent_global_md); 1118 1119 // Now, since the variable is a pointer variable, we will drop in a load of 1120 // that pointer variable. 1121 1122 LoadInst *persistent_load = 1123 new LoadInst(persistent_global->getType()->getPointerElementType(), 1124 persistent_global, "", alloc); 1125 1126 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(alloc), 1127 PrintValue(persistent_load)); 1128 1129 alloc->replaceAllUsesWith(persistent_load); 1130 alloc->eraseFromParent(); 1131 1132 return true; 1133 } 1134 1135 bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) { 1136 if (!m_resolve_vars) 1137 return true; 1138 1139 lldb_private::Log *log( 1140 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1141 1142 InstrList pvar_allocs; 1143 1144 for (Instruction &inst : basic_block) { 1145 1146 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) { 1147 llvm::StringRef alloc_name = alloc->getName(); 1148 1149 if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) { 1150 if (alloc_name.find_first_of("0123456789") == 1) { 1151 LLDB_LOG(log, "Rejecting a numeric persistent variable."); 1152 1153 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, " 1154 "$1, ... are reserved for use as result " 1155 "names\n"); 1156 1157 return false; 1158 } 1159 1160 pvar_allocs.push_back(alloc); 1161 } 1162 } 1163 } 1164 1165 for (Instruction *inst : pvar_allocs) { 1166 if (!RewritePersistentAlloc(inst)) { 1167 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite " 1168 "the creation of a persistent variable\n"); 1169 1170 LLDB_LOG(log, "Couldn't rewrite the creation of a persistent variable"); 1171 1172 return false; 1173 } 1174 } 1175 1176 return true; 1177 } 1178 1179 // This function does not report errors; its callers are responsible. 1180 bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) { 1181 lldb_private::Log *log( 1182 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1183 1184 LLDB_LOG(log, "MaybeHandleVariable ({0})", PrintValue(llvm_value_ptr)); 1185 1186 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) { 1187 switch (constant_expr->getOpcode()) { 1188 default: 1189 break; 1190 case Instruction::GetElementPtr: 1191 case Instruction::BitCast: 1192 Value *s = constant_expr->getOperand(0); 1193 if (!MaybeHandleVariable(s)) 1194 return false; 1195 } 1196 } else if (GlobalVariable *global_variable = 1197 dyn_cast<GlobalVariable>(llvm_value_ptr)) { 1198 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage())) 1199 return true; 1200 1201 clang::NamedDecl *named_decl = DeclForGlobal(global_variable); 1202 1203 if (!named_decl) { 1204 if (IsObjCSelectorRef(llvm_value_ptr)) 1205 return true; 1206 1207 if (!global_variable->hasExternalLinkage()) 1208 return true; 1209 1210 LLDB_LOG(log, "Found global variable \"{0}\" without metadata", 1211 global_variable->getName()); 1212 1213 return false; 1214 } 1215 1216 llvm::StringRef name(named_decl->getName()); 1217 1218 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl); 1219 if (value_decl == nullptr) 1220 return false; 1221 1222 lldb_private::CompilerType compiler_type = 1223 m_decl_map->GetTypeSystem()->GetType(value_decl->getType()); 1224 1225 const Type *value_type = nullptr; 1226 1227 if (name.startswith("$")) { 1228 // The $__lldb_expr_result name indicates the return value has allocated 1229 // as a static variable. Per the comment at 1230 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static 1231 // variable need to be redirected to the result of dereferencing a 1232 // pointer that is passed in as one of the arguments. 1233 // 1234 // Consequently, when reporting the size of the type, we report a pointer 1235 // type pointing to the type of $__lldb_expr_result, not the type itself. 1236 // 1237 // We also do this for any user-declared persistent variables. 1238 compiler_type = compiler_type.GetPointerType(); 1239 value_type = PointerType::get(global_variable->getType(), 0); 1240 } else { 1241 value_type = global_variable->getType(); 1242 } 1243 1244 auto *target = m_execution_unit.GetTarget().get(); 1245 llvm::Optional<uint64_t> value_size = compiler_type.GetByteSize(target); 1246 if (!value_size) 1247 return false; 1248 llvm::Optional<size_t> opt_alignment = 1249 compiler_type.GetTypeBitAlign(target); 1250 if (!opt_alignment) 1251 return false; 1252 lldb::offset_t value_alignment = (*opt_alignment + 7ull) / 8ull; 1253 1254 LLDB_LOG(log, 1255 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, " 1256 "align {4}]", 1257 name, 1258 lldb_private::ClangUtil::GetQualType(compiler_type).getAsString(), 1259 PrintType(value_type), *value_size, value_alignment); 1260 1261 if (named_decl) 1262 m_decl_map->AddValueToStruct(named_decl, lldb_private::ConstString(name), 1263 llvm_value_ptr, *value_size, 1264 value_alignment); 1265 } else if (dyn_cast<llvm::Function>(llvm_value_ptr)) { 1266 LLDB_LOG(log, "Function pointers aren't handled right now"); 1267 1268 return false; 1269 } 1270 1271 return true; 1272 } 1273 1274 // This function does not report errors; its callers are responsible. 1275 bool IRForTarget::HandleSymbol(Value *symbol) { 1276 lldb_private::Log *log( 1277 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1278 1279 lldb_private::ConstString name(symbol->getName().str().c_str()); 1280 1281 lldb::addr_t symbol_addr = 1282 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny); 1283 1284 if (symbol_addr == LLDB_INVALID_ADDRESS) { 1285 LLDB_LOG(log, "Symbol \"{0}\" had no address", name); 1286 1287 return false; 1288 } 1289 1290 LLDB_LOG(log, "Found \"{0}\" at {1}", name, symbol_addr); 1291 1292 Type *symbol_type = symbol->getType(); 1293 1294 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false); 1295 1296 Value *symbol_addr_ptr = 1297 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type); 1298 1299 LLDB_LOG(log, "Replacing {0} with {1}", PrintValue(symbol), 1300 PrintValue(symbol_addr_ptr)); 1301 1302 symbol->replaceAllUsesWith(symbol_addr_ptr); 1303 1304 return true; 1305 } 1306 1307 bool IRForTarget::MaybeHandleCallArguments(CallInst *Old) { 1308 lldb_private::Log *log( 1309 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1310 1311 LLDB_LOG(log, "MaybeHandleCallArguments({0})", PrintValue(Old)); 1312 1313 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands(); 1314 op_index < num_ops; ++op_index) 1315 // conservatively believe that this is a store 1316 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) { 1317 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite " 1318 "one of the arguments of a function call.\n"); 1319 1320 return false; 1321 } 1322 1323 return true; 1324 } 1325 1326 bool IRForTarget::HandleObjCClass(Value *classlist_reference) { 1327 lldb_private::Log *log( 1328 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1329 1330 GlobalVariable *global_variable = 1331 dyn_cast<GlobalVariable>(classlist_reference); 1332 1333 if (!global_variable) 1334 return false; 1335 1336 Constant *initializer = global_variable->getInitializer(); 1337 1338 if (!initializer) 1339 return false; 1340 1341 if (!initializer->hasName()) 1342 return false; 1343 1344 StringRef name(initializer->getName()); 1345 lldb_private::ConstString name_cstr(name.str().c_str()); 1346 lldb::addr_t class_ptr = 1347 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass); 1348 1349 LLDB_LOG(log, "Found reference to Objective-C class {0} ({1})", name, 1350 (unsigned long long)class_ptr); 1351 1352 if (class_ptr == LLDB_INVALID_ADDRESS) 1353 return false; 1354 1355 if (global_variable->use_empty()) 1356 return false; 1357 1358 SmallVector<LoadInst *, 2> load_instructions; 1359 1360 for (llvm::User *u : global_variable->users()) { 1361 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u)) 1362 load_instructions.push_back(load_instruction); 1363 } 1364 1365 if (load_instructions.empty()) 1366 return false; 1367 1368 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr); 1369 1370 for (LoadInst *load_instruction : load_instructions) { 1371 Constant *class_bitcast = 1372 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType()); 1373 1374 load_instruction->replaceAllUsesWith(class_bitcast); 1375 1376 load_instruction->eraseFromParent(); 1377 } 1378 1379 return true; 1380 } 1381 1382 bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) { 1383 std::vector<CallInst *> calls_to_remove; 1384 1385 for (Instruction &inst : basic_block) { 1386 CallInst *call = dyn_cast<CallInst>(&inst); 1387 1388 // MaybeHandleCallArguments handles error reporting; we are silent here 1389 if (!call) 1390 continue; 1391 1392 bool remove = false; 1393 1394 llvm::Function *func = call->getCalledFunction(); 1395 1396 if (func && func->getName() == "__cxa_atexit") 1397 remove = true; 1398 1399 llvm::Value *val = call->getCalledOperand(); 1400 1401 if (val && val->getName() == "__cxa_atexit") 1402 remove = true; 1403 1404 if (remove) 1405 calls_to_remove.push_back(call); 1406 } 1407 1408 for (CallInst *ci : calls_to_remove) 1409 ci->eraseFromParent(); 1410 1411 return true; 1412 } 1413 1414 bool IRForTarget::ResolveCalls(BasicBlock &basic_block) { 1415 // Prepare the current basic block for execution in the remote process 1416 1417 for (Instruction &inst : basic_block) { 1418 CallInst *call = dyn_cast<CallInst>(&inst); 1419 1420 // MaybeHandleCallArguments handles error reporting; we are silent here 1421 if (call && !MaybeHandleCallArguments(call)) 1422 return false; 1423 } 1424 1425 return true; 1426 } 1427 1428 bool IRForTarget::ResolveExternals(Function &llvm_function) { 1429 lldb_private::Log *log( 1430 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1431 1432 for (GlobalVariable &global_var : m_module->globals()) { 1433 llvm::StringRef global_name = global_var.getName(); 1434 1435 LLDB_LOG(log, "Examining {0}, DeclForGlobalValue returns {1}", global_name, 1436 static_cast<void *>(DeclForGlobal(&global_var))); 1437 1438 if (global_name.startswith("OBJC_IVAR")) { 1439 if (!HandleSymbol(&global_var)) { 1440 m_error_stream.Format("Error [IRForTarget]: Couldn't find Objective-C " 1441 "indirect ivar symbol {0}\n", 1442 global_name); 1443 1444 return false; 1445 } 1446 } else if (global_name.contains("OBJC_CLASSLIST_REFERENCES_$")) { 1447 if (!HandleObjCClass(&global_var)) { 1448 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class " 1449 "for an Objective-C static method call\n"); 1450 1451 return false; 1452 } 1453 } else if (global_name.contains("OBJC_CLASSLIST_SUP_REFS_$")) { 1454 if (!HandleObjCClass(&global_var)) { 1455 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class " 1456 "for an Objective-C static method call\n"); 1457 1458 return false; 1459 } 1460 } else if (DeclForGlobal(&global_var)) { 1461 if (!MaybeHandleVariable(&global_var)) { 1462 m_error_stream.Format("Internal error [IRForTarget]: Couldn't rewrite " 1463 "external variable {0}\n", 1464 global_name); 1465 1466 return false; 1467 } 1468 } 1469 } 1470 1471 return true; 1472 } 1473 1474 static bool isGuardVariableRef(Value *V) { 1475 Constant *Old = dyn_cast<Constant>(V); 1476 1477 if (!Old) 1478 return false; 1479 1480 if (auto CE = dyn_cast<ConstantExpr>(V)) { 1481 if (CE->getOpcode() != Instruction::BitCast) 1482 return false; 1483 1484 Old = CE->getOperand(0); 1485 } 1486 1487 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old); 1488 1489 if (!GV || !GV->hasName() || !isGuardVariableSymbol(GV->getName())) 1490 return false; 1491 1492 return true; 1493 } 1494 1495 void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) { 1496 Constant *zero(Constant::getNullValue(guard_load->getType())); 1497 guard_load->replaceAllUsesWith(zero); 1498 guard_load->eraseFromParent(); 1499 } 1500 1501 static void ExciseGuardStore(Instruction *guard_store) { 1502 guard_store->eraseFromParent(); 1503 } 1504 1505 bool IRForTarget::RemoveGuards(BasicBlock &basic_block) { 1506 // Eliminate any reference to guard variables found. 1507 1508 InstrList guard_loads; 1509 InstrList guard_stores; 1510 1511 for (Instruction &inst : basic_block) { 1512 1513 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1514 if (isGuardVariableRef(load->getPointerOperand())) 1515 guard_loads.push_back(&inst); 1516 1517 if (StoreInst *store = dyn_cast<StoreInst>(&inst)) 1518 if (isGuardVariableRef(store->getPointerOperand())) 1519 guard_stores.push_back(&inst); 1520 } 1521 1522 for (Instruction *inst : guard_loads) 1523 TurnGuardLoadIntoZero(inst); 1524 1525 for (Instruction *inst : guard_stores) 1526 ExciseGuardStore(inst); 1527 1528 return true; 1529 } 1530 1531 // This function does not report errors; its callers are responsible. 1532 bool IRForTarget::UnfoldConstant(Constant *old_constant, 1533 llvm::Function *llvm_function, 1534 FunctionValueCache &value_maker, 1535 FunctionValueCache &entry_instruction_finder, 1536 lldb_private::Stream &error_stream) { 1537 SmallVector<User *, 16> users; 1538 1539 // We do this because the use list might change, invalidating our iterator. 1540 // Much better to keep a work list ourselves. 1541 for (llvm::User *u : old_constant->users()) 1542 users.push_back(u); 1543 1544 for (size_t i = 0; i < users.size(); ++i) { 1545 User *user = users[i]; 1546 1547 if (Constant *constant = dyn_cast<Constant>(user)) { 1548 // synthesize a new non-constant equivalent of the constant 1549 1550 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) { 1551 switch (constant_expr->getOpcode()) { 1552 default: 1553 error_stream.Printf("error [IRForTarget internal]: Unhandled " 1554 "constant expression type: \"%s\"", 1555 PrintValue(constant_expr).c_str()); 1556 return false; 1557 case Instruction::BitCast: { 1558 FunctionValueCache bit_cast_maker( 1559 [&value_maker, &entry_instruction_finder, old_constant, 1560 constant_expr](llvm::Function *function) -> llvm::Value * { 1561 // UnaryExpr 1562 // OperandList[0] is value 1563 1564 if (constant_expr->getOperand(0) != old_constant) 1565 return constant_expr; 1566 1567 return new BitCastInst( 1568 value_maker.GetValue(function), constant_expr->getType(), 1569 "", llvm::cast<Instruction>( 1570 entry_instruction_finder.GetValue(function))); 1571 }); 1572 1573 if (!UnfoldConstant(constant_expr, llvm_function, bit_cast_maker, 1574 entry_instruction_finder, error_stream)) 1575 return false; 1576 } break; 1577 case Instruction::GetElementPtr: { 1578 // GetElementPtrConstantExpr 1579 // OperandList[0] is base 1580 // OperandList[1]... are indices 1581 1582 FunctionValueCache get_element_pointer_maker( 1583 [&value_maker, &entry_instruction_finder, old_constant, 1584 constant_expr](llvm::Function *function) -> llvm::Value * { 1585 Value *ptr = constant_expr->getOperand(0); 1586 1587 if (ptr == old_constant) 1588 ptr = value_maker.GetValue(function); 1589 1590 std::vector<Value *> index_vector; 1591 1592 unsigned operand_index; 1593 unsigned num_operands = constant_expr->getNumOperands(); 1594 1595 for (operand_index = 1; operand_index < num_operands; 1596 ++operand_index) { 1597 Value *operand = constant_expr->getOperand(operand_index); 1598 1599 if (operand == old_constant) 1600 operand = value_maker.GetValue(function); 1601 1602 index_vector.push_back(operand); 1603 } 1604 1605 ArrayRef<Value *> indices(index_vector); 1606 1607 return GetElementPtrInst::Create( 1608 nullptr, ptr, indices, "", 1609 llvm::cast<Instruction>( 1610 entry_instruction_finder.GetValue(function))); 1611 }); 1612 1613 if (!UnfoldConstant(constant_expr, llvm_function, 1614 get_element_pointer_maker, 1615 entry_instruction_finder, error_stream)) 1616 return false; 1617 } break; 1618 } 1619 } else { 1620 error_stream.Printf( 1621 "error [IRForTarget internal]: Unhandled constant type: \"%s\"", 1622 PrintValue(constant).c_str()); 1623 return false; 1624 } 1625 } else { 1626 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) { 1627 if (llvm_function && inst->getParent()->getParent() != llvm_function) { 1628 error_stream.PutCString("error: Capturing non-local variables in " 1629 "expressions is unsupported.\n"); 1630 return false; 1631 } 1632 inst->replaceUsesOfWith( 1633 old_constant, value_maker.GetValue(inst->getParent()->getParent())); 1634 } else { 1635 error_stream.Printf( 1636 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"", 1637 PrintValue(user).c_str()); 1638 return false; 1639 } 1640 } 1641 } 1642 1643 if (!isa<GlobalValue>(old_constant)) { 1644 old_constant->destroyConstant(); 1645 } 1646 1647 return true; 1648 } 1649 1650 bool IRForTarget::ReplaceVariables(Function &llvm_function) { 1651 if (!m_resolve_vars) 1652 return true; 1653 1654 lldb_private::Log *log( 1655 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1656 1657 m_decl_map->DoStructLayout(); 1658 1659 LLDB_LOG(log, "Element arrangement:"); 1660 1661 uint32_t num_elements; 1662 uint32_t element_index; 1663 1664 size_t size; 1665 lldb::offset_t alignment; 1666 1667 if (!m_decl_map->GetStructInfo(num_elements, size, alignment)) 1668 return false; 1669 1670 Function::arg_iterator iter(llvm_function.arg_begin()); 1671 1672 if (iter == llvm_function.arg_end()) { 1673 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes no " 1674 "arguments (should take at least a struct pointer)"); 1675 1676 return false; 1677 } 1678 1679 Argument *argument = &*iter; 1680 1681 if (argument->getName().equals("this")) { 1682 ++iter; 1683 1684 if (iter == llvm_function.arg_end()) { 1685 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only " 1686 "'this' argument (should take a struct pointer " 1687 "too)"); 1688 1689 return false; 1690 } 1691 1692 argument = &*iter; 1693 } else if (argument->getName().equals("self")) { 1694 ++iter; 1695 1696 if (iter == llvm_function.arg_end()) { 1697 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only " 1698 "'self' argument (should take '_cmd' and a struct " 1699 "pointer too)"); 1700 1701 return false; 1702 } 1703 1704 if (!iter->getName().equals("_cmd")) { 1705 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes '{0}' " 1706 "after 'self' argument (should take '_cmd')", 1707 iter->getName()); 1708 1709 return false; 1710 } 1711 1712 ++iter; 1713 1714 if (iter == llvm_function.arg_end()) { 1715 m_error_stream.Printf("Internal error [IRForTarget]: Wrapper takes only " 1716 "'self' and '_cmd' arguments (should take a struct " 1717 "pointer too)"); 1718 1719 return false; 1720 } 1721 1722 argument = &*iter; 1723 } 1724 1725 if (!argument->getName().equals("$__lldb_arg")) { 1726 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes an " 1727 "argument named '{0}' instead of the struct pointer", 1728 argument->getName()); 1729 1730 return false; 1731 } 1732 1733 LLDB_LOG(log, "Arg: \"{0}\"", PrintValue(argument)); 1734 1735 BasicBlock &entry_block(llvm_function.getEntryBlock()); 1736 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); 1737 1738 if (!FirstEntryInstruction) { 1739 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the " 1740 "first instruction in the wrapper for use in " 1741 "rewriting"); 1742 1743 return false; 1744 } 1745 1746 LLVMContext &context(m_module->getContext()); 1747 IntegerType *offset_type(Type::getInt32Ty(context)); 1748 1749 if (!offset_type) { 1750 m_error_stream.Printf( 1751 "Internal error [IRForTarget]: Couldn't produce an offset type"); 1752 1753 return false; 1754 } 1755 1756 for (element_index = 0; element_index < num_elements; ++element_index) { 1757 const clang::NamedDecl *decl = nullptr; 1758 Value *value = nullptr; 1759 lldb::offset_t offset; 1760 lldb_private::ConstString name; 1761 1762 if (!m_decl_map->GetStructElement(decl, value, offset, name, 1763 element_index)) { 1764 m_error_stream.Printf( 1765 "Internal error [IRForTarget]: Structure information is incomplete"); 1766 1767 return false; 1768 } 1769 1770 LLDB_LOG(log, " \"{0}\" (\"{1}\") placed at {2}", name, 1771 decl->getNameAsString(), offset); 1772 1773 if (value) { 1774 LLDB_LOG(log, " Replacing [{0}]", PrintValue(value)); 1775 1776 FunctionValueCache body_result_maker( 1777 [this, name, offset_type, offset, argument, 1778 value](llvm::Function *function) -> llvm::Value * { 1779 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, 1780 // in cases where the result variable is an rvalue, we have to 1781 // synthesize a dereference of the appropriate structure entry in 1782 // order to produce the static variable that the AST thinks it is 1783 // accessing. 1784 1785 llvm::Instruction *entry_instruction = llvm::cast<Instruction>( 1786 m_entry_instruction_finder.GetValue(function)); 1787 1788 ConstantInt *offset_int( 1789 ConstantInt::get(offset_type, offset, true)); 1790 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create( 1791 nullptr, argument, offset_int, "", entry_instruction); 1792 1793 if (name == m_result_name && !m_result_is_pointer) { 1794 BitCastInst *bit_cast = new BitCastInst( 1795 get_element_ptr, value->getType()->getPointerTo(), "", 1796 entry_instruction); 1797 1798 LoadInst *load = 1799 new LoadInst(bit_cast->getType()->getPointerElementType(), 1800 bit_cast, "", entry_instruction); 1801 1802 return load; 1803 } else { 1804 BitCastInst *bit_cast = new BitCastInst( 1805 get_element_ptr, value->getType(), "", entry_instruction); 1806 1807 return bit_cast; 1808 } 1809 }); 1810 1811 if (Constant *constant = dyn_cast<Constant>(value)) { 1812 if (!UnfoldConstant(constant, &llvm_function, body_result_maker, 1813 m_entry_instruction_finder, m_error_stream)) { 1814 return false; 1815 } 1816 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) { 1817 if (instruction->getParent()->getParent() != &llvm_function) { 1818 m_error_stream.PutCString("error: Capturing non-local variables in " 1819 "expressions is unsupported.\n"); 1820 return false; 1821 } 1822 value->replaceAllUsesWith( 1823 body_result_maker.GetValue(instruction->getParent()->getParent())); 1824 } else { 1825 LLDB_LOG(log, "Unhandled non-constant type: \"{0}\"", 1826 PrintValue(value)); 1827 return false; 1828 } 1829 1830 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value)) 1831 var->eraseFromParent(); 1832 } 1833 } 1834 1835 LLDB_LOG(log, "Total structure [align {0}, size {1}]", (int64_t)alignment, 1836 (uint64_t)size); 1837 1838 return true; 1839 } 1840 1841 bool IRForTarget::runOnModule(Module &llvm_module) { 1842 lldb_private::Log *log( 1843 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1844 1845 m_module = &llvm_module; 1846 m_target_data = std::make_unique<DataLayout>(m_module); 1847 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), 1848 m_target_data->getPointerSizeInBits()); 1849 1850 if (log) { 1851 std::string s; 1852 raw_string_ostream oss(s); 1853 1854 m_module->print(oss, nullptr); 1855 1856 oss.flush(); 1857 1858 LLDB_LOG(log, "Module as passed in to IRForTarget: \n\"{0}\"", s); 1859 } 1860 1861 Function *const main_function = 1862 m_func_name.IsEmpty() ? nullptr 1863 : m_module->getFunction(m_func_name.GetStringRef()); 1864 1865 if (!m_func_name.IsEmpty() && !main_function) { 1866 LLDB_LOG(log, "Couldn't find \"{0}()\" in the module", m_func_name); 1867 1868 m_error_stream.Format("Internal error [IRForTarget]: Couldn't find wrapper " 1869 "'{0}' in the module", 1870 m_func_name); 1871 1872 return false; 1873 } 1874 1875 if (main_function) { 1876 if (!FixFunctionLinkage(*main_function)) { 1877 LLDB_LOG(log, "Couldn't fix the linkage for the function"); 1878 1879 return false; 1880 } 1881 } 1882 1883 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext()); 1884 1885 m_reloc_placeholder = new llvm::GlobalVariable( 1886 (*m_module), int8_ty, false /* IsConstant */, 1887 GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty), 1888 "reloc_placeholder", nullptr /* InsertBefore */, 1889 GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */); 1890 1891 //////////////////////////////////////////////////////////// 1892 // Replace $__lldb_expr_result with a persistent variable 1893 // 1894 1895 if (main_function) { 1896 if (!CreateResultVariable(*main_function)) { 1897 LLDB_LOG(log, "CreateResultVariable() failed"); 1898 1899 // CreateResultVariable() reports its own errors, so we don't do so here 1900 1901 return false; 1902 } 1903 } 1904 1905 if (log && log->GetVerbose()) { 1906 std::string s; 1907 raw_string_ostream oss(s); 1908 1909 m_module->print(oss, nullptr); 1910 1911 oss.flush(); 1912 1913 LLDB_LOG(log, "Module after creating the result variable: \n\"{0}\"", s); 1914 } 1915 1916 for (llvm::Function &function : *m_module) { 1917 for (BasicBlock &bb : function) { 1918 if (!RemoveGuards(bb)) { 1919 LLDB_LOG(log, "RemoveGuards() failed"); 1920 1921 // RemoveGuards() reports its own errors, so we don't do so here 1922 1923 return false; 1924 } 1925 1926 if (!RewritePersistentAllocs(bb)) { 1927 LLDB_LOG(log, "RewritePersistentAllocs() failed"); 1928 1929 // RewritePersistentAllocs() reports its own errors, so we don't do so 1930 // here 1931 1932 return false; 1933 } 1934 1935 if (!RemoveCXAAtExit(bb)) { 1936 LLDB_LOG(log, "RemoveCXAAtExit() failed"); 1937 1938 // RemoveCXAAtExit() reports its own errors, so we don't do so here 1939 1940 return false; 1941 } 1942 } 1943 } 1944 1945 /////////////////////////////////////////////////////////////////////////////// 1946 // Fix all Objective-C constant strings to use NSStringWithCString:encoding: 1947 // 1948 1949 if (!RewriteObjCConstStrings()) { 1950 LLDB_LOG(log, "RewriteObjCConstStrings() failed"); 1951 1952 // RewriteObjCConstStrings() reports its own errors, so we don't do so here 1953 1954 return false; 1955 } 1956 1957 for (llvm::Function &function : *m_module) { 1958 for (llvm::BasicBlock &bb : function) { 1959 if (!RewriteObjCSelectors(bb)) { 1960 LLDB_LOG(log, "RewriteObjCSelectors() failed"); 1961 1962 // RewriteObjCSelectors() reports its own errors, so we don't do so 1963 // here 1964 1965 return false; 1966 } 1967 1968 if (!RewriteObjCClassReferences(bb)) { 1969 LLDB_LOG(log, "RewriteObjCClassReferences() failed"); 1970 1971 // RewriteObjCClasses() reports its own errors, so we don't do so here 1972 1973 return false; 1974 } 1975 } 1976 } 1977 1978 for (llvm::Function &function : *m_module) { 1979 for (BasicBlock &bb : function) { 1980 if (!ResolveCalls(bb)) { 1981 LLDB_LOG(log, "ResolveCalls() failed"); 1982 1983 // ResolveCalls() reports its own errors, so we don't do so here 1984 1985 return false; 1986 } 1987 } 1988 } 1989 1990 //////////////////////////////////////////////////////////////////////// 1991 // Run function-level passes that only make sense on the main function 1992 // 1993 1994 if (main_function) { 1995 if (!ResolveExternals(*main_function)) { 1996 LLDB_LOG(log, "ResolveExternals() failed"); 1997 1998 // ResolveExternals() reports its own errors, so we don't do so here 1999 2000 return false; 2001 } 2002 2003 if (!ReplaceVariables(*main_function)) { 2004 LLDB_LOG(log, "ReplaceVariables() failed"); 2005 2006 // ReplaceVariables() reports its own errors, so we don't do so here 2007 2008 return false; 2009 } 2010 } 2011 2012 if (log && log->GetVerbose()) { 2013 std::string s; 2014 raw_string_ostream oss(s); 2015 2016 m_module->print(oss, nullptr); 2017 2018 oss.flush(); 2019 2020 LLDB_LOG(log, "Module after preparing for execution: \n\"{0}\"", s); 2021 } 2022 2023 return true; 2024 } 2025 2026 void IRForTarget::assignPassManager(PMStack &pass_mgr_stack, 2027 PassManagerType pass_mgr_type) {} 2028 2029 PassManagerType IRForTarget::getPotentialPassManagerType() const { 2030 return PMT_ModulePassManager; 2031 } 2032