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