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