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