1 //===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "IRForTarget.h" 11 12 #include "ClangExpressionDeclMap.h" 13 14 #include "llvm/Support/raw_ostream.h" 15 #include "llvm/IR/Constants.h" 16 #include "llvm/IR/DataLayout.h" 17 #include "llvm/IR/InstrTypes.h" 18 #include "llvm/IR/Instructions.h" 19 #include "llvm/IR/Intrinsics.h" 20 #include "llvm/IR/Module.h" 21 #include "llvm/IR/LegacyPassManager.h" 22 #include "llvm/Transforms/IPO.h" 23 #include "llvm/IR/Metadata.h" 24 #include "llvm/IR/ValueSymbolTable.h" 25 26 #include "clang/AST/ASTContext.h" 27 28 #include "lldb/Core/dwarf.h" 29 #include "lldb/Core/ConstString.h" 30 #include "lldb/Core/DataBufferHeap.h" 31 #include "lldb/Core/Log.h" 32 #include "lldb/Core/Scalar.h" 33 #include "lldb/Core/StreamString.h" 34 #include "lldb/Expression/IRExecutionUnit.h" 35 #include "lldb/Expression/IRInterpreter.h" 36 #include "lldb/Host/Endian.h" 37 #include "lldb/Symbol/ClangASTContext.h" 38 #include "lldb/Symbol/CompilerType.h" 39 40 #include <map> 41 42 using namespace llvm; 43 44 static char ID; 45 46 IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) : 47 m_execution_unit(execution_unit), 48 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()), 49 m_allocation(LLDB_INVALID_ADDRESS) 50 { 51 } 52 53 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) : 54 m_maker(maker), 55 m_values() 56 { 57 } 58 59 IRForTarget::FunctionValueCache::~FunctionValueCache() 60 { 61 } 62 63 llvm::Value * 64 IRForTarget::FunctionValueCache::GetValue(llvm::Function *function) 65 { 66 if (!m_values.count(function)) 67 { 68 llvm::Value *ret = m_maker(function); 69 m_values[function] = ret; 70 return ret; 71 } 72 return m_values[function]; 73 } 74 75 lldb::addr_t 76 IRForTarget::StaticDataAllocator::Allocate() 77 { 78 lldb_private::Error err; 79 80 if (m_allocation != LLDB_INVALID_ADDRESS) 81 { 82 m_execution_unit.FreeNow(m_allocation); 83 m_allocation = LLDB_INVALID_ADDRESS; 84 } 85 86 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err); 87 88 return m_allocation; 89 } 90 91 lldb::TargetSP 92 IRForTarget::StaticDataAllocator::GetTarget() 93 { 94 return m_execution_unit.GetTarget(); 95 } 96 97 static llvm::Value * 98 FindEntryInstruction (llvm::Function *function) 99 { 100 if (function->empty()) 101 return NULL; 102 103 return function->getEntryBlock().getFirstNonPHIOrDbg(); 104 } 105 106 IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map, 107 bool resolve_vars, 108 lldb_private::IRExecutionUnit &execution_unit, 109 lldb_private::Stream *error_stream, 110 const char *func_name) : 111 ModulePass(ID), 112 m_resolve_vars(resolve_vars), 113 m_func_name(func_name), 114 m_module(NULL), 115 m_decl_map(decl_map), 116 m_data_allocator(execution_unit), 117 m_CFStringCreateWithBytes(NULL), 118 m_sel_registerName(NULL), 119 m_intptr_ty(NULL), 120 m_error_stream(error_stream), 121 m_result_store(NULL), 122 m_result_is_pointer(false), 123 m_reloc_placeholder(NULL), 124 m_entry_instruction_finder (FindEntryInstruction) 125 { 126 } 127 128 /* Handy utility functions used at several places in the code */ 129 130 static std::string 131 PrintValue(const Value *value, bool truncate = false) 132 { 133 std::string s; 134 if (value) 135 { 136 raw_string_ostream rso(s); 137 value->print(rso); 138 rso.flush(); 139 if (truncate) 140 s.resize(s.length() - 1); 141 } 142 return s; 143 } 144 145 static std::string 146 PrintType(const llvm::Type *type, bool truncate = false) 147 { 148 std::string s; 149 raw_string_ostream rso(s); 150 type->print(rso); 151 rso.flush(); 152 if (truncate) 153 s.resize(s.length() - 1); 154 return s; 155 } 156 157 IRForTarget::~IRForTarget() 158 { 159 } 160 161 bool 162 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) 163 { 164 llvm_function.setLinkage(GlobalValue::ExternalLinkage); 165 166 std::string name = llvm_function.getName().str(); 167 168 return true; 169 } 170 171 IRForTarget::LookupResult 172 IRForTarget::GetFunctionAddress (llvm::Function *fun, 173 uint64_t &fun_addr, 174 lldb_private::ConstString &name, 175 Constant **&value_ptr) 176 { 177 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 178 179 fun_addr = LLDB_INVALID_ADDRESS; 180 name.Clear(); 181 value_ptr = NULL; 182 183 if (fun->isIntrinsic()) 184 { 185 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID(); 186 187 switch (intrinsic_id) 188 { 189 default: 190 if (log) 191 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str()); 192 193 if (m_error_stream) 194 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str()); 195 196 return LookupResult::Fail; 197 case Intrinsic::memcpy: 198 { 199 static lldb_private::ConstString g_memcpy_str ("memcpy"); 200 name = g_memcpy_str; 201 } 202 break; 203 case Intrinsic::memset: 204 { 205 static lldb_private::ConstString g_memset_str ("memset"); 206 name = g_memset_str; 207 } 208 break; 209 case Intrinsic::dbg_declare: 210 case Intrinsic::dbg_value: 211 return LookupResult::Ignore; 212 } 213 214 if (log && name) 215 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString()); 216 } 217 else 218 { 219 name.SetCStringWithLength (fun->getName().data(), fun->getName().size()); 220 } 221 222 // Find the address of the function. 223 224 clang::NamedDecl *fun_decl = DeclForGlobal (fun); 225 226 if (fun_decl) 227 { 228 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr)) 229 { 230 std::vector<lldb_private::ConstString> alternates; 231 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr); 232 233 if (!found_it) 234 { 235 lldb_private::Mangled mangled_name(name); 236 if (m_error_stream) 237 { 238 if (mangled_name.GetMangledName()) 239 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n", 240 mangled_name.GetName(lldb::eLanguageTypeObjC_plus_plus).GetCString(), 241 mangled_name.GetMangledName().GetCString()); 242 else 243 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", 244 mangled_name.GetName(lldb::eLanguageTypeObjC_plus_plus).GetCString()); 245 } 246 return LookupResult::Fail; 247 } 248 } 249 } 250 else 251 { 252 if (!m_decl_map->GetFunctionAddress (name, fun_addr)) 253 { 254 if (log) 255 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString()); 256 257 if (m_error_stream) 258 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString()); 259 260 return LookupResult::Fail; 261 } 262 } 263 264 if (log) 265 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr); 266 267 return LookupResult::Success; 268 } 269 270 llvm::Constant * 271 IRForTarget::BuildFunctionPointer (llvm::Type *type, 272 uint64_t ptr) 273 { 274 PointerType *fun_ptr_ty = PointerType::getUnqual(type); 275 Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false); 276 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty); 277 } 278 279 void 280 IRForTarget::RegisterFunctionMetadata(LLVMContext &context, 281 llvm::Value *function_ptr, 282 const char *name) 283 { 284 for (llvm::User *user : function_ptr->users()) 285 { 286 if (Instruction *user_inst = dyn_cast<Instruction>(user)) 287 { 288 MDString* md_name = MDString::get(context, StringRef(name)); 289 290 MDNode *metadata = MDNode::get(context, md_name); 291 292 user_inst->setMetadata("lldb.call.realName", metadata); 293 } 294 else 295 { 296 RegisterFunctionMetadata (context, user, name); 297 } 298 } 299 } 300 301 bool 302 IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module) 303 { 304 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 305 306 for (llvm::Module::iterator fi = llvm_module.begin(); 307 fi != llvm_module.end(); 308 ++fi) 309 { 310 Function *fun = &*fi; 311 312 bool is_decl = fun->isDeclaration(); 313 314 if (log) 315 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str()); 316 317 if (!is_decl) 318 continue; 319 320 if (fun->use_empty()) 321 continue; // ignore 322 323 uint64_t addr = LLDB_INVALID_ADDRESS; 324 lldb_private::ConstString name; 325 Constant **value_ptr = NULL; 326 327 LookupResult result = GetFunctionAddress(fun, 328 addr, 329 name, 330 value_ptr); 331 332 switch (result) 333 { 334 case LookupResult::Fail: 335 return false; // GetFunctionAddress reports its own errors 336 337 case LookupResult::Ignore: 338 break; // Nothing to do 339 340 case LookupResult::Success: 341 { 342 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr); 343 344 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString()); 345 346 if (value_ptr) 347 *value_ptr = value; 348 349 // If we are replacing a function with the nobuiltin attribute, it may 350 // be called with the builtin attribute on call sites. Remove any such 351 // attributes since it's illegal to have a builtin call to something 352 // other than a nobuiltin function. 353 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 354 llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin); 355 356 for (auto u : fun->users()) { 357 if (auto call = dyn_cast<CallInst>(u)) { 358 call->removeAttribute(AttributeSet::FunctionIndex, builtin); 359 } 360 } 361 } 362 363 fun->replaceAllUsesWith(value); 364 } 365 break; 366 } 367 } 368 369 return true; 370 } 371 372 373 clang::NamedDecl * 374 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module) 375 { 376 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs"); 377 378 if (!named_metadata) 379 return NULL; 380 381 unsigned num_nodes = named_metadata->getNumOperands(); 382 unsigned node_index; 383 384 for (node_index = 0; 385 node_index < num_nodes; 386 ++node_index) 387 { 388 llvm::MDNode *metadata_node = dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index)); 389 if (!metadata_node) 390 return NULL; 391 392 if (metadata_node->getNumOperands() != 2) 393 continue; 394 395 if (mdconst::dyn_extract_or_null<GlobalValue>(metadata_node->getOperand(0)) != global_val) 396 continue; 397 398 ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1)); 399 400 if (!constant_int) 401 return NULL; 402 403 uintptr_t ptr = constant_int->getZExtValue(); 404 405 return reinterpret_cast<clang::NamedDecl *>(ptr); 406 } 407 408 return NULL; 409 } 410 411 clang::NamedDecl * 412 IRForTarget::DeclForGlobal (GlobalValue *global_val) 413 { 414 return DeclForGlobal(global_val, m_module); 415 } 416 417 bool 418 IRForTarget::CreateResultVariable (llvm::Function &llvm_function) 419 { 420 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 421 422 if (!m_resolve_vars) 423 return true; 424 425 // Find the result variable. If it doesn't exist, we can give up right here. 426 427 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable(); 428 429 std::string result_name_str; 430 const char *result_name = NULL; 431 432 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 433 vi != ve; 434 ++vi) 435 { 436 result_name_str = vi->first().str(); 437 const char *value_name = result_name_str.c_str(); 438 439 if (strstr(value_name, "$__lldb_expr_result_ptr") && 440 strncmp(value_name, "_ZGV", 4)) 441 { 442 result_name = value_name; 443 m_result_is_pointer = true; 444 break; 445 } 446 447 if (strstr(value_name, "$__lldb_expr_result") && 448 strncmp(value_name, "_ZGV", 4)) 449 { 450 result_name = value_name; 451 m_result_is_pointer = false; 452 break; 453 } 454 } 455 456 if (!result_name) 457 { 458 if (log) 459 log->PutCString("Couldn't find result variable"); 460 461 return true; 462 } 463 464 if (log) 465 log->Printf("Result name: \"%s\"", result_name); 466 467 Value *result_value = m_module->getNamedValue(result_name); 468 469 if (!result_value) 470 { 471 if (log) 472 log->PutCString("Result variable had no data"); 473 474 if (m_error_stream) 475 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name); 476 477 return false; 478 } 479 480 if (log) 481 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str()); 482 483 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value); 484 485 if (!result_global) 486 { 487 if (log) 488 log->PutCString("Result variable isn't a GlobalVariable"); 489 490 if (m_error_stream) 491 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name); 492 493 return false; 494 } 495 496 clang::NamedDecl *result_decl = DeclForGlobal (result_global); 497 if (!result_decl) 498 { 499 if (log) 500 log->PutCString("Result variable doesn't have a corresponding Decl"); 501 502 if (m_error_stream) 503 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name); 504 505 return false; 506 } 507 508 if (log) 509 { 510 std::string decl_desc_str; 511 raw_string_ostream decl_desc_stream(decl_desc_str); 512 result_decl->print(decl_desc_stream); 513 decl_desc_stream.flush(); 514 515 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str()); 516 } 517 518 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl); 519 if (!result_var) 520 { 521 if (log) 522 log->PutCString("Result variable Decl isn't a VarDecl"); 523 524 if (m_error_stream) 525 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name); 526 527 return false; 528 } 529 530 // Get the next available result name from m_decl_map and create the persistent 531 // variable for it 532 533 // If the result is an Lvalue, it is emitted as a pointer; see 534 // ASTResultSynthesizer::SynthesizeBodyResult. 535 if (m_result_is_pointer) 536 { 537 clang::QualType pointer_qual_type = result_var->getType(); 538 const clang::Type *pointer_type = pointer_qual_type.getTypePtr(); 539 540 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>(); 541 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>(); 542 543 if (pointer_pointertype) 544 { 545 clang::QualType element_qual_type = pointer_pointertype->getPointeeType(); 546 547 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(), 548 lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext())); 549 } 550 else if (pointer_objcobjpointertype) 551 { 552 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0); 553 554 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(), 555 lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext())); 556 } 557 else 558 { 559 if (log) 560 log->PutCString("Expected result to have pointer type, but it did not"); 561 562 if (m_error_stream) 563 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name); 564 565 return false; 566 } 567 } 568 else 569 { 570 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(), 571 lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext())); 572 } 573 574 575 lldb::TargetSP target_sp (m_data_allocator.GetTarget()); 576 lldb_private::ExecutionContext exe_ctx (target_sp, true); 577 if (m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope()) == 0) 578 { 579 lldb_private::StreamString type_desc_stream; 580 m_result_type.DumpTypeDescription(&type_desc_stream); 581 582 if (log) 583 log->Printf("Result type has size 0"); 584 585 if (m_error_stream) 586 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n", 587 type_desc_stream.GetData()); 588 return false; 589 } 590 591 if (log) 592 { 593 lldb_private::StreamString type_desc_stream; 594 m_result_type.DumpTypeDescription(&type_desc_stream); 595 596 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData()); 597 } 598 599 m_result_name = lldb_private::ConstString("$RESULT_NAME"); 600 601 if (log) 602 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64, 603 m_result_name.GetCString(), 604 m_result_type.GetByteSize(nullptr)); 605 606 // Construct a new result global and set up its metadata 607 608 GlobalVariable *new_result_global = new GlobalVariable((*m_module), 609 result_global->getType()->getElementType(), 610 false, /* not constant */ 611 GlobalValue::ExternalLinkage, 612 NULL, /* no initializer */ 613 m_result_name.GetCString ()); 614 615 // It's too late in compilation to create a new VarDecl for this, but we don't 616 // need to. We point the metadata at the old VarDecl. This creates an odd 617 // anomaly: a variable with a Value whose name is something like $0 and a 618 // Decl whose name is $__lldb_expr_result. This condition is handled in 619 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is 620 // fixed up. 621 622 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()), 623 reinterpret_cast<uint64_t>(result_decl), 624 false); 625 626 llvm::Metadata *values[2]; 627 values[0] = ConstantAsMetadata::get(new_result_global); 628 values[1] = ConstantAsMetadata::get(new_constant_int); 629 630 ArrayRef<Metadata *> value_ref(values, 2); 631 632 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 633 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs"); 634 named_metadata->addOperand(persistent_global_md); 635 636 if (log) 637 log->Printf("Replacing \"%s\" with \"%s\"", 638 PrintValue(result_global).c_str(), 639 PrintValue(new_result_global).c_str()); 640 641 if (result_global->use_empty()) 642 { 643 // We need to synthesize a store for this variable, because otherwise 644 // there's nothing to put into its equivalent persistent variable. 645 646 BasicBlock &entry_block(llvm_function.getEntryBlock()); 647 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); 648 649 if (!first_entry_instruction) 650 return false; 651 652 if (!result_global->hasInitializer()) 653 { 654 if (log) 655 log->Printf("Couldn't find initializer for unused variable"); 656 657 if (m_error_stream) 658 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name); 659 660 return false; 661 } 662 663 Constant *initializer = result_global->getInitializer(); 664 665 StoreInst *synthesized_store = new StoreInst(initializer, 666 new_result_global, 667 first_entry_instruction); 668 669 if (log) 670 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str()); 671 } 672 else 673 { 674 result_global->replaceAllUsesWith(new_result_global); 675 } 676 677 if (!m_decl_map->AddPersistentVariable(result_decl, 678 m_result_name, 679 m_result_type, 680 true, 681 m_result_is_pointer)) 682 return false; 683 684 result_global->eraseFromParent(); 685 686 return true; 687 } 688 689 bool 690 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str, 691 llvm::GlobalVariable *cstr) 692 { 693 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 694 695 Type *ns_str_ty = ns_str->getType(); 696 697 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 698 Type *i32_ty = Type::getInt32Ty(m_module->getContext()); 699 Type *i8_ty = Type::getInt8Ty(m_module->getContext()); 700 701 if (!m_CFStringCreateWithBytes) 702 { 703 lldb::addr_t CFStringCreateWithBytes_addr; 704 705 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes"); 706 707 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr)) 708 { 709 if (log) 710 log->PutCString("Couldn't find CFStringCreateWithBytes in the target"); 711 712 if (m_error_stream) 713 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n"); 714 715 return false; 716 } 717 718 if (log) 719 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr); 720 721 // Build the function type: 722 // 723 // CFStringRef CFStringCreateWithBytes ( 724 // CFAllocatorRef alloc, 725 // const UInt8 *bytes, 726 // CFIndex numBytes, 727 // CFStringEncoding encoding, 728 // Boolean isExternalRepresentation 729 // ); 730 // 731 // We make the following substitutions: 732 // 733 // CFStringRef -> i8* 734 // CFAllocatorRef -> i8* 735 // UInt8 * -> i8* 736 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now) 737 // CFStringEncoding -> i32 738 // Boolean -> i8 739 740 Type *arg_type_array[5]; 741 742 arg_type_array[0] = i8_ptr_ty; 743 arg_type_array[1] = i8_ptr_ty; 744 arg_type_array[2] = m_intptr_ty; 745 arg_type_array[3] = i32_ty; 746 arg_type_array[4] = i8_ty; 747 748 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5); 749 750 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false); 751 752 // Build the constant containing the pointer to the function 753 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); 754 Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false); 755 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); 756 } 757 758 ConstantDataSequential *string_array = NULL; 759 760 if (cstr) 761 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer()); 762 763 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); 764 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty); 765 Constant *numBytes_arg = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false); 766 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */ 767 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ 768 769 Value *argument_array[5]; 770 771 argument_array[0] = alloc_arg; 772 argument_array[1] = bytes_arg; 773 argument_array[2] = numBytes_arg; 774 argument_array[3] = encoding_arg; 775 argument_array[4] = isExternal_arg; 776 777 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5); 778 779 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * { 780 return CallInst::Create(m_CFStringCreateWithBytes, 781 CFSCWB_arguments, 782 "CFStringCreateWithBytes", 783 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function))); 784 }); 785 786 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder)) 787 { 788 if (log) 789 log->PutCString("Couldn't replace the NSString with the result of the call"); 790 791 if (m_error_stream) 792 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n"); 793 794 return false; 795 } 796 797 ns_str->eraseFromParent(); 798 799 return true; 800 } 801 802 bool 803 IRForTarget::RewriteObjCConstStrings() 804 { 805 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 806 807 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable(); 808 809 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 810 vi != ve; 811 ++vi) 812 { 813 std::string value_name = vi->first().str(); 814 const char *value_name_cstr = value_name.c_str(); 815 816 if (strstr(value_name_cstr, "_unnamed_cfstring_")) 817 { 818 Value *nsstring_value = vi->second; 819 820 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value); 821 822 if (!nsstring_global) 823 { 824 if (log) 825 log->PutCString("NSString variable is not a GlobalVariable"); 826 827 if (m_error_stream) 828 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n"); 829 830 return false; 831 } 832 833 if (!nsstring_global->hasInitializer()) 834 { 835 if (log) 836 log->PutCString("NSString variable does not have an initializer"); 837 838 if (m_error_stream) 839 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n"); 840 841 return false; 842 } 843 844 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer()); 845 846 if (!nsstring_struct) 847 { 848 if (log) 849 log->PutCString("NSString variable's initializer is not a ConstantStruct"); 850 851 if (m_error_stream) 852 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n"); 853 854 return false; 855 } 856 857 // We expect the following structure: 858 // 859 // struct { 860 // int *isa; 861 // int flags; 862 // char *str; 863 // long length; 864 // }; 865 866 if (nsstring_struct->getNumOperands() != 4) 867 { 868 if (log) 869 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands()); 870 871 if (m_error_stream) 872 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n"); 873 874 return false; 875 } 876 877 Constant *nsstring_member = nsstring_struct->getOperand(2); 878 879 if (!nsstring_member) 880 { 881 if (log) 882 log->PutCString("NSString initializer's str element was empty"); 883 884 if (m_error_stream) 885 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n"); 886 887 return false; 888 } 889 890 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member); 891 892 if (!nsstring_expr) 893 { 894 if (log) 895 log->PutCString("NSString initializer's str element is not a ConstantExpr"); 896 897 if (m_error_stream) 898 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n"); 899 900 return false; 901 } 902 903 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr) 904 { 905 if (log) 906 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName()); 907 908 if (m_error_stream) 909 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n"); 910 911 return false; 912 } 913 914 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 915 916 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 917 918 if (!cstr_global) 919 { 920 if (log) 921 log->PutCString("NSString initializer's str element is not a GlobalVariable"); 922 923 if (m_error_stream) 924 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n"); 925 926 return false; 927 } 928 929 if (!cstr_global->hasInitializer()) 930 { 931 if (log) 932 log->PutCString("NSString initializer's str element does not have an initializer"); 933 934 if (m_error_stream) 935 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n"); 936 937 return false; 938 } 939 940 /* 941 if (!cstr_array) 942 { 943 if (log) 944 log->PutCString("NSString initializer's str element is not a ConstantArray"); 945 946 if (m_error_stream) 947 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n"); 948 949 return false; 950 } 951 952 if (!cstr_array->isCString()) 953 { 954 if (log) 955 log->PutCString("NSString initializer's str element is not a C string array"); 956 957 if (m_error_stream) 958 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n"); 959 960 return false; 961 } 962 */ 963 964 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer()); 965 966 if (log) 967 { 968 if (cstr_array) 969 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str()); 970 else 971 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr); 972 } 973 974 if (!cstr_array) 975 cstr_global = NULL; 976 977 if (!RewriteObjCConstString(nsstring_global, cstr_global)) 978 { 979 if (log) 980 log->PutCString("Error rewriting the constant string"); 981 982 // We don't print an error message here because RewriteObjCConstString has done so for us. 983 984 return false; 985 } 986 } 987 } 988 989 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 990 vi != ve; 991 ++vi) 992 { 993 std::string value_name = vi->first().str(); 994 const char *value_name_cstr = value_name.c_str(); 995 996 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) 997 { 998 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second); 999 1000 if (!gv) 1001 { 1002 if (log) 1003 log->PutCString("__CFConstantStringClassReference is not a global variable"); 1004 1005 if (m_error_stream) 1006 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n"); 1007 1008 return false; 1009 } 1010 1011 gv->eraseFromParent(); 1012 1013 break; 1014 } 1015 } 1016 1017 return true; 1018 } 1019 1020 static bool IsObjCSelectorRef (Value *value) 1021 { 1022 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 1023 1024 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_")) 1025 return false; 1026 1027 return true; 1028 } 1029 1030 // This function does not report errors; its callers are responsible. 1031 bool 1032 IRForTarget::RewriteObjCSelector (Instruction* selector_load) 1033 { 1034 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1035 1036 LoadInst *load = dyn_cast<LoadInst>(selector_load); 1037 1038 if (!load) 1039 return false; 1040 1041 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as 1042 // 1043 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> 1044 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*> 1045 // 1046 // where %obj is the object pointer and %tmp is the selector. 1047 // 1048 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_". 1049 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string. 1050 1051 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target 1052 1053 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand()); 1054 1055 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer()) 1056 return false; 1057 1058 Constant *osr_initializer = _objc_selector_references_->getInitializer(); 1059 1060 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer); 1061 1062 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr) 1063 return false; 1064 1065 Value *osr_initializer_base = osr_initializer_expr->getOperand(0); 1066 1067 if (!osr_initializer_base) 1068 return false; 1069 1070 // Find the string's initializer (a ConstantArray) and get the string from it 1071 1072 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base); 1073 1074 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer()) 1075 return false; 1076 1077 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer(); 1078 1079 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer); 1080 1081 if (!omvn_initializer_array->isString()) 1082 return false; 1083 1084 std::string omvn_initializer_string = omvn_initializer_array->getAsString(); 1085 1086 if (log) 1087 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str()); 1088 1089 // Construct a call to sel_registerName 1090 1091 if (!m_sel_registerName) 1092 { 1093 lldb::addr_t sel_registerName_addr; 1094 1095 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName"); 1096 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr)) 1097 return false; 1098 1099 if (log) 1100 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr); 1101 1102 // Build the function type: struct objc_selector *sel_registerName(uint8_t*) 1103 1104 // The below code would be "more correct," but in actuality what's required is uint8_t* 1105 //Type *sel_type = StructType::get(m_module->getContext()); 1106 //Type *sel_ptr_type = PointerType::getUnqual(sel_type); 1107 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext()); 1108 1109 Type *type_array[1]; 1110 1111 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext()); 1112 1113 ArrayRef<Type *> srN_arg_types(type_array, 1); 1114 1115 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false); 1116 1117 // Build the constant containing the pointer to the function 1118 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); 1119 Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false); 1120 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty); 1121 } 1122 1123 Value *argument_array[1]; 1124 1125 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext())); 1126 1127 argument_array[0] = omvn_pointer; 1128 1129 ArrayRef<Value *> srN_arguments(argument_array, 1); 1130 1131 CallInst *srN_call = CallInst::Create(m_sel_registerName, 1132 srN_arguments, 1133 "sel_registerName", 1134 selector_load); 1135 1136 // Replace the load with the call in all users 1137 1138 selector_load->replaceAllUsesWith(srN_call); 1139 1140 selector_load->eraseFromParent(); 1141 1142 return true; 1143 } 1144 1145 bool 1146 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block) 1147 { 1148 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1149 1150 BasicBlock::iterator ii; 1151 1152 typedef SmallVector <Instruction*, 2> InstrList; 1153 typedef InstrList::iterator InstrIterator; 1154 1155 InstrList selector_loads; 1156 1157 for (ii = basic_block.begin(); 1158 ii != basic_block.end(); 1159 ++ii) 1160 { 1161 Instruction &inst = *ii; 1162 1163 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1164 if (IsObjCSelectorRef(load->getPointerOperand())) 1165 selector_loads.push_back(&inst); 1166 } 1167 1168 InstrIterator iter; 1169 1170 for (iter = selector_loads.begin(); 1171 iter != selector_loads.end(); 1172 ++iter) 1173 { 1174 if (!RewriteObjCSelector(*iter)) 1175 { 1176 if (m_error_stream) 1177 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n"); 1178 1179 if (log) 1180 log->PutCString("Couldn't rewrite a reference to an Objective-C selector"); 1181 1182 return false; 1183 } 1184 } 1185 1186 return true; 1187 } 1188 1189 // This function does not report errors; its callers are responsible. 1190 bool 1191 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc) 1192 { 1193 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1194 1195 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc); 1196 1197 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr"); 1198 1199 if (!alloc_md || !alloc_md->getNumOperands()) 1200 return false; 1201 1202 ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0)); 1203 1204 if (!constant_int) 1205 return false; 1206 1207 // We attempt to register this as a new persistent variable with the DeclMap. 1208 1209 uintptr_t ptr = constant_int->getZExtValue(); 1210 1211 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr); 1212 1213 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(), 1214 lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext())); 1215 1216 StringRef decl_name (decl->getName()); 1217 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size()); 1218 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false)) 1219 return false; 1220 1221 GlobalVariable *persistent_global = new GlobalVariable((*m_module), 1222 alloc->getType(), 1223 false, /* not constant */ 1224 GlobalValue::ExternalLinkage, 1225 NULL, /* no initializer */ 1226 alloc->getName().str().c_str()); 1227 1228 // What we're going to do here is make believe this was a regular old external 1229 // variable. That means we need to make the metadata valid. 1230 1231 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs"); 1232 1233 llvm::Metadata *values[2]; 1234 values[0] = ConstantAsMetadata::get(persistent_global); 1235 values[1] = ConstantAsMetadata::get(constant_int); 1236 1237 ArrayRef<llvm::Metadata *> value_ref(values, 2); 1238 1239 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 1240 named_metadata->addOperand(persistent_global_md); 1241 1242 // Now, since the variable is a pointer variable, we will drop in a load of that 1243 // pointer variable. 1244 1245 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc); 1246 1247 if (log) 1248 log->Printf("Replacing \"%s\" with \"%s\"", 1249 PrintValue(alloc).c_str(), 1250 PrintValue(persistent_load).c_str()); 1251 1252 alloc->replaceAllUsesWith(persistent_load); 1253 alloc->eraseFromParent(); 1254 1255 return true; 1256 } 1257 1258 bool 1259 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) 1260 { 1261 if (!m_resolve_vars) 1262 return true; 1263 1264 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1265 1266 BasicBlock::iterator ii; 1267 1268 typedef SmallVector <Instruction*, 2> InstrList; 1269 typedef InstrList::iterator InstrIterator; 1270 1271 InstrList pvar_allocs; 1272 1273 for (ii = basic_block.begin(); 1274 ii != basic_block.end(); 1275 ++ii) 1276 { 1277 Instruction &inst = *ii; 1278 1279 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) 1280 { 1281 llvm::StringRef alloc_name = alloc->getName(); 1282 1283 if (alloc_name.startswith("$") && 1284 !alloc_name.startswith("$__lldb")) 1285 { 1286 if (alloc_name.find_first_of("0123456789") == 1) 1287 { 1288 if (log) 1289 log->Printf("Rejecting a numeric persistent variable."); 1290 1291 if (m_error_stream) 1292 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n"); 1293 1294 return false; 1295 } 1296 1297 pvar_allocs.push_back(alloc); 1298 } 1299 } 1300 } 1301 1302 InstrIterator iter; 1303 1304 for (iter = pvar_allocs.begin(); 1305 iter != pvar_allocs.end(); 1306 ++iter) 1307 { 1308 if (!RewritePersistentAlloc(*iter)) 1309 { 1310 if (m_error_stream) 1311 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n"); 1312 1313 if (log) 1314 log->PutCString("Couldn't rewrite the creation of a persistent variable"); 1315 1316 return false; 1317 } 1318 } 1319 1320 return true; 1321 } 1322 1323 bool 1324 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer) 1325 { 1326 if (!initializer) 1327 return true; 1328 1329 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1330 1331 if (log && log->GetVerbose()) 1332 log->Printf(" MaterializeInitializer(%p, %s)", (void *)data, PrintValue(initializer).c_str()); 1333 1334 Type *initializer_type = initializer->getType(); 1335 1336 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) 1337 { 1338 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type)); 1339 return true; 1340 } 1341 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer)) 1342 { 1343 if (array_initializer->isString()) 1344 { 1345 std::string array_initializer_string = array_initializer->getAsString(); 1346 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type)); 1347 } 1348 else 1349 { 1350 ArrayType *array_initializer_type = array_initializer->getType(); 1351 Type *array_element_type = array_initializer_type->getElementType(); 1352 1353 size_t element_size = m_target_data->getTypeAllocSize(array_element_type); 1354 1355 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) 1356 { 1357 Value *operand_value = array_initializer->getOperand(i); 1358 Constant *operand_constant = dyn_cast<Constant>(operand_value); 1359 1360 if (!operand_constant) 1361 return false; 1362 1363 if (!MaterializeInitializer(data + (i * element_size), operand_constant)) 1364 return false; 1365 } 1366 } 1367 return true; 1368 } 1369 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer)) 1370 { 1371 StructType *struct_initializer_type = struct_initializer->getType(); 1372 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type); 1373 1374 for (unsigned i = 0; 1375 i < struct_initializer->getNumOperands(); 1376 ++i) 1377 { 1378 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i))) 1379 return false; 1380 } 1381 return true; 1382 } 1383 else if (isa<ConstantAggregateZero>(initializer)) 1384 { 1385 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type)); 1386 return true; 1387 } 1388 return false; 1389 } 1390 1391 bool 1392 IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable) 1393 { 1394 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage())) 1395 return false; 1396 1397 if (global_variable == m_reloc_placeholder) 1398 return true; 1399 1400 uint64_t offset = m_data_allocator.GetStream().GetSize(); 1401 1402 llvm::Type *variable_type = global_variable->getType(); 1403 1404 Constant *initializer = global_variable->getInitializer(); 1405 1406 llvm::Type *initializer_type = initializer->getType(); 1407 1408 size_t size = m_target_data->getTypeAllocSize(initializer_type); 1409 size_t align = m_target_data->getPrefTypeAlignment(initializer_type); 1410 1411 const size_t mask = (align - 1); 1412 uint64_t aligned_offset = (offset + mask) & ~mask; 1413 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0); 1414 offset = aligned_offset; 1415 1416 lldb_private::DataBufferHeap data(size, '\0'); 1417 1418 if (initializer) 1419 if (!MaterializeInitializer(data.GetBytes(), initializer)) 1420 return false; 1421 1422 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize()); 1423 1424 Constant *new_pointer = BuildRelocation(variable_type, offset); 1425 1426 global_variable->replaceAllUsesWith(new_pointer); 1427 1428 global_variable->eraseFromParent(); 1429 1430 return true; 1431 } 1432 1433 // This function does not report errors; its callers are responsible. 1434 bool 1435 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr) 1436 { 1437 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1438 1439 if (log) 1440 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str()); 1441 1442 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) 1443 { 1444 switch (constant_expr->getOpcode()) 1445 { 1446 default: 1447 break; 1448 case Instruction::GetElementPtr: 1449 case Instruction::BitCast: 1450 Value *s = constant_expr->getOperand(0); 1451 if (!MaybeHandleVariable(s)) 1452 return false; 1453 } 1454 } 1455 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr)) 1456 { 1457 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage())) 1458 return MaterializeInternalVariable(global_variable); 1459 1460 clang::NamedDecl *named_decl = DeclForGlobal(global_variable); 1461 1462 if (!named_decl) 1463 { 1464 if (IsObjCSelectorRef(llvm_value_ptr)) 1465 return true; 1466 1467 if (!global_variable->hasExternalLinkage()) 1468 return true; 1469 1470 if (log) 1471 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str()); 1472 1473 return false; 1474 } 1475 1476 std::string name (named_decl->getName().str()); 1477 1478 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl); 1479 if (value_decl == NULL) 1480 return false; 1481 1482 lldb_private::CompilerType compiler_type(&value_decl->getASTContext(), value_decl->getType()); 1483 1484 const Type *value_type = NULL; 1485 1486 if (name[0] == '$') 1487 { 1488 // The $__lldb_expr_result name indicates the return value has allocated as 1489 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, 1490 // accesses to this static variable need to be redirected to the result of dereferencing 1491 // a pointer that is passed in as one of the arguments. 1492 // 1493 // Consequently, when reporting the size of the type, we report a pointer type pointing 1494 // to the type of $__lldb_expr_result, not the type itself. 1495 // 1496 // We also do this for any user-declared persistent variables. 1497 compiler_type = compiler_type.GetPointerType(); 1498 value_type = PointerType::get(global_variable->getType(), 0); 1499 } 1500 else 1501 { 1502 value_type = global_variable->getType(); 1503 } 1504 1505 const uint64_t value_size = compiler_type.GetByteSize(nullptr); 1506 lldb::offset_t value_alignment = (compiler_type.GetTypeBitAlign() + 7ull) / 8ull; 1507 1508 if (log) 1509 { 1510 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRIu64 "]", 1511 name.c_str(), 1512 lldb_private::ClangASTContext::GetQualType(compiler_type).getAsString().c_str(), 1513 PrintType(value_type).c_str(), 1514 value_size, 1515 value_alignment); 1516 } 1517 1518 1519 if (named_decl && !m_decl_map->AddValueToStruct(named_decl, 1520 lldb_private::ConstString (name.c_str()), 1521 llvm_value_ptr, 1522 value_size, 1523 value_alignment)) 1524 { 1525 if (!global_variable->hasExternalLinkage()) 1526 return true; 1527 else if (HandleSymbol (global_variable)) 1528 return true; 1529 else 1530 return false; 1531 } 1532 } 1533 else if (dyn_cast<llvm::Function>(llvm_value_ptr)) 1534 { 1535 if (log) 1536 log->Printf("Function pointers aren't handled right now"); 1537 1538 return false; 1539 } 1540 1541 return true; 1542 } 1543 1544 // This function does not report errors; its callers are responsible. 1545 bool 1546 IRForTarget::HandleSymbol (Value *symbol) 1547 { 1548 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1549 1550 lldb_private::ConstString name(symbol->getName().str().c_str()); 1551 1552 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny); 1553 1554 if (symbol_addr == LLDB_INVALID_ADDRESS) 1555 { 1556 if (log) 1557 log->Printf ("Symbol \"%s\" had no address", name.GetCString()); 1558 1559 return false; 1560 } 1561 1562 if (log) 1563 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr); 1564 1565 Type *symbol_type = symbol->getType(); 1566 1567 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false); 1568 1569 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type); 1570 1571 if (log) 1572 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str()); 1573 1574 symbol->replaceAllUsesWith(symbol_addr_ptr); 1575 1576 return true; 1577 } 1578 1579 bool 1580 IRForTarget::MaybeHandleCallArguments (CallInst *Old) 1581 { 1582 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1583 1584 if (log) 1585 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str()); 1586 1587 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands(); 1588 op_index < num_ops; 1589 ++op_index) 1590 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store 1591 { 1592 if (m_error_stream) 1593 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n"); 1594 1595 return false; 1596 } 1597 1598 return true; 1599 } 1600 1601 bool 1602 IRForTarget::HandleObjCClass(Value *classlist_reference) 1603 { 1604 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1605 1606 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference); 1607 1608 if (!global_variable) 1609 return false; 1610 1611 Constant *initializer = global_variable->getInitializer(); 1612 1613 if (!initializer) 1614 return false; 1615 1616 if (!initializer->hasName()) 1617 return false; 1618 1619 StringRef name(initializer->getName()); 1620 lldb_private::ConstString name_cstr(name.str().c_str()); 1621 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass); 1622 1623 if (log) 1624 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr); 1625 1626 if (class_ptr == LLDB_INVALID_ADDRESS) 1627 return false; 1628 1629 if (global_variable->use_empty()) 1630 return false; 1631 1632 SmallVector<LoadInst *, 2> load_instructions; 1633 1634 for (llvm::User *u : global_variable->users()) 1635 { 1636 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u)) 1637 load_instructions.push_back(load_instruction); 1638 } 1639 1640 if (load_instructions.empty()) 1641 return false; 1642 1643 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr); 1644 1645 for (LoadInst *load_instruction : load_instructions) 1646 { 1647 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType()); 1648 1649 load_instruction->replaceAllUsesWith(class_bitcast); 1650 1651 load_instruction->eraseFromParent(); 1652 } 1653 1654 return true; 1655 } 1656 1657 bool 1658 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block) 1659 { 1660 BasicBlock::iterator ii; 1661 1662 std::vector<CallInst *> calls_to_remove; 1663 1664 for (ii = basic_block.begin(); 1665 ii != basic_block.end(); 1666 ++ii) 1667 { 1668 Instruction &inst = *ii; 1669 1670 CallInst *call = dyn_cast<CallInst>(&inst); 1671 1672 // MaybeHandleCallArguments handles error reporting; we are silent here 1673 if (!call) 1674 continue; 1675 1676 bool remove = false; 1677 1678 llvm::Function *func = call->getCalledFunction(); 1679 1680 if (func && func->getName() == "__cxa_atexit") 1681 remove = true; 1682 1683 llvm::Value *val = call->getCalledValue(); 1684 1685 if (val && val->getName() == "__cxa_atexit") 1686 remove = true; 1687 1688 if (remove) 1689 calls_to_remove.push_back(call); 1690 } 1691 1692 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end(); 1693 ci != ce; 1694 ++ci) 1695 { 1696 (*ci)->eraseFromParent(); 1697 } 1698 1699 return true; 1700 } 1701 1702 bool 1703 IRForTarget::ResolveCalls(BasicBlock &basic_block) 1704 { 1705 ///////////////////////////////////////////////////////////////////////// 1706 // Prepare the current basic block for execution in the remote process 1707 // 1708 1709 BasicBlock::iterator ii; 1710 1711 for (ii = basic_block.begin(); 1712 ii != basic_block.end(); 1713 ++ii) 1714 { 1715 Instruction &inst = *ii; 1716 1717 CallInst *call = dyn_cast<CallInst>(&inst); 1718 1719 // MaybeHandleCallArguments handles error reporting; we are silent here 1720 if (call && !MaybeHandleCallArguments(call)) 1721 return false; 1722 } 1723 1724 return true; 1725 } 1726 1727 bool 1728 IRForTarget::ResolveExternals (Function &llvm_function) 1729 { 1730 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1731 1732 for (GlobalVariable &global_var : m_module->globals()) 1733 { 1734 std::string global_name = global_var.getName().str(); 1735 1736 if (log) 1737 log->Printf("Examining %s, DeclForGlobalValue returns %p", 1738 global_name.c_str(), 1739 static_cast<void*>(DeclForGlobal(&global_var))); 1740 1741 if (global_name.find("OBJC_IVAR") == 0) 1742 { 1743 if (!HandleSymbol(&global_var)) 1744 { 1745 if (m_error_stream) 1746 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str()); 1747 1748 return false; 1749 } 1750 } 1751 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos) 1752 { 1753 if (!HandleObjCClass(&global_var)) 1754 { 1755 if (m_error_stream) 1756 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n"); 1757 1758 return false; 1759 } 1760 } 1761 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos) 1762 { 1763 if (!HandleObjCClass(&global_var)) 1764 { 1765 if (m_error_stream) 1766 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n"); 1767 1768 return false; 1769 } 1770 } 1771 else if (DeclForGlobal(&global_var)) 1772 { 1773 if (!MaybeHandleVariable (&global_var)) 1774 { 1775 if (m_error_stream) 1776 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str()); 1777 1778 return false; 1779 } 1780 } 1781 } 1782 1783 return true; 1784 } 1785 1786 bool 1787 IRForTarget::ReplaceStrings () 1788 { 1789 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1790 1791 typedef std::map <GlobalVariable *, size_t> OffsetsTy; 1792 1793 OffsetsTy offsets; 1794 1795 for (GlobalVariable &gv : m_module->globals()) 1796 { 1797 if (!gv.hasInitializer()) 1798 continue; 1799 1800 Constant *gc = gv.getInitializer(); 1801 1802 std::string str; 1803 1804 if (gc->isNullValue()) 1805 { 1806 Type *gc_type = gc->getType(); 1807 1808 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type); 1809 1810 if (!gc_array_type) 1811 continue; 1812 1813 Type *gc_element_type = gc_array_type->getElementType(); 1814 1815 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type); 1816 1817 if (gc_integer_type->getBitWidth() != 8) 1818 continue; 1819 1820 str = ""; 1821 } 1822 else 1823 { 1824 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc); 1825 1826 if (!gc_array) 1827 continue; 1828 1829 if (!gc_array->isCString()) 1830 continue; 1831 1832 if (log) 1833 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str()); 1834 1835 str = gc_array->getAsString(); 1836 } 1837 1838 offsets[&gv] = m_data_allocator.GetStream().GetSize(); 1839 1840 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1); 1841 } 1842 1843 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 1844 1845 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end(); 1846 oi != oe; 1847 ++oi) 1848 { 1849 GlobalVariable *gv = oi->first; 1850 size_t offset = oi->second; 1851 1852 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset); 1853 1854 if (log) 1855 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str()); 1856 1857 for (llvm::User *u : gv->users()) 1858 { 1859 if (log) 1860 log->Printf("Found use %s", PrintValue(u).c_str()); 1861 1862 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(u); 1863 StoreInst *store_inst = dyn_cast<StoreInst>(u); 1864 1865 if (const_expr) 1866 { 1867 if (const_expr->getOpcode() != Instruction::GetElementPtr) 1868 { 1869 if (log) 1870 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str()); 1871 1872 return false; 1873 } 1874 1875 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType()); 1876 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast); 1877 1878 const_expr->replaceAllUsesWith(new_gep); 1879 } 1880 else if (store_inst) 1881 { 1882 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType()); 1883 1884 store_inst->setOperand(0, bit_cast); 1885 } 1886 else 1887 { 1888 if (log) 1889 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str()); 1890 1891 return false; 1892 } 1893 } 1894 1895 gv->eraseFromParent(); 1896 } 1897 1898 return true; 1899 } 1900 1901 bool 1902 IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block) 1903 { 1904 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1905 1906 typedef SmallVector <Value*, 2> ConstantList; 1907 typedef SmallVector <llvm::Instruction*, 2> UserList; 1908 typedef ConstantList::iterator ConstantIterator; 1909 typedef UserList::iterator UserIterator; 1910 1911 ConstantList static_constants; 1912 UserList static_users; 1913 1914 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end(); 1915 ii != ie; 1916 ++ii) 1917 { 1918 llvm::Instruction &inst = *ii; 1919 1920 for (Value *operand_val : inst.operand_values()) 1921 { 1922 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val); 1923 1924 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/) 1925 { 1926 static_constants.push_back(operand_val); 1927 static_users.push_back(&*ii); 1928 } 1929 } 1930 } 1931 1932 ConstantIterator constant_iter; 1933 UserIterator user_iter; 1934 1935 for (constant_iter = static_constants.begin(), user_iter = static_users.begin(); 1936 constant_iter != static_constants.end(); 1937 ++constant_iter, ++user_iter) 1938 { 1939 Value *operand_val = *constant_iter; 1940 llvm::Instruction *inst = *user_iter; 1941 1942 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val); 1943 1944 if (operand_constant_fp) 1945 { 1946 Type *operand_type = operand_constant_fp->getType(); 1947 1948 APFloat operand_apfloat = operand_constant_fp->getValueAPF(); 1949 APInt operand_apint = operand_apfloat.bitcastToAPInt(); 1950 1951 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData(); 1952 size_t operand_data_size = operand_apint.getBitWidth() / 8; 1953 1954 if (log) 1955 { 1956 std::string s; 1957 raw_string_ostream ss(s); 1958 for (size_t index = 0; 1959 index < operand_data_size; 1960 ++index) 1961 { 1962 ss << (uint32_t)operand_raw_data[index]; 1963 ss << " "; 1964 } 1965 ss.flush(); 1966 1967 log->Printf("Found ConstantFP with size %" PRIu64 " and raw data %s", (uint64_t)operand_data_size, s.c_str()); 1968 } 1969 1970 lldb_private::DataBufferHeap data(operand_data_size, 0); 1971 1972 if (lldb_private::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder()) 1973 { 1974 uint8_t *data_bytes = data.GetBytes(); 1975 1976 for (size_t index = 0; 1977 index < operand_data_size; 1978 ++index) 1979 { 1980 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)]; 1981 } 1982 } 1983 else 1984 { 1985 memcpy(data.GetBytes(), operand_raw_data, operand_data_size); 1986 } 1987 1988 uint64_t offset = m_data_allocator.GetStream().GetSize(); 1989 1990 size_t align = m_target_data->getPrefTypeAlignment(operand_type); 1991 1992 const size_t mask = (align - 1); 1993 uint64_t aligned_offset = (offset + mask) & ~mask; 1994 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0); 1995 1996 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size); 1997 1998 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo(); 1999 2000 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset); 2001 2002 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst); 2003 2004 operand_constant_fp->replaceAllUsesWith(fp_load); 2005 } 2006 } 2007 2008 return true; 2009 } 2010 2011 static bool isGuardVariableRef(Value *V) 2012 { 2013 Constant *Old = NULL; 2014 2015 if (!(Old = dyn_cast<Constant>(V))) 2016 return false; 2017 2018 ConstantExpr *CE = NULL; 2019 2020 if ((CE = dyn_cast<ConstantExpr>(V))) 2021 { 2022 if (CE->getOpcode() != Instruction::BitCast) 2023 return false; 2024 2025 Old = CE->getOperand(0); 2026 } 2027 2028 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old); 2029 2030 if (!GV || !GV->hasName() || 2031 (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable 2032 !GV->getName().endswith("@4IA"))) // Microsoft ABI guard variable 2033 { 2034 return false; 2035 } 2036 2037 return true; 2038 } 2039 2040 void 2041 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load) 2042 { 2043 Constant *zero(Constant::getNullValue(guard_load->getType())); 2044 guard_load->replaceAllUsesWith(zero); 2045 guard_load->eraseFromParent(); 2046 } 2047 2048 static void ExciseGuardStore(Instruction* guard_store) 2049 { 2050 guard_store->eraseFromParent(); 2051 } 2052 2053 bool 2054 IRForTarget::RemoveGuards(BasicBlock &basic_block) 2055 { 2056 /////////////////////////////////////////////////////// 2057 // Eliminate any reference to guard variables found. 2058 // 2059 2060 BasicBlock::iterator ii; 2061 2062 typedef SmallVector <Instruction*, 2> InstrList; 2063 typedef InstrList::iterator InstrIterator; 2064 2065 InstrList guard_loads; 2066 InstrList guard_stores; 2067 2068 for (ii = basic_block.begin(); 2069 ii != basic_block.end(); 2070 ++ii) 2071 { 2072 Instruction &inst = *ii; 2073 2074 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 2075 if (isGuardVariableRef(load->getPointerOperand())) 2076 guard_loads.push_back(&inst); 2077 2078 if (StoreInst *store = dyn_cast<StoreInst>(&inst)) 2079 if (isGuardVariableRef(store->getPointerOperand())) 2080 guard_stores.push_back(&inst); 2081 } 2082 2083 InstrIterator iter; 2084 2085 for (iter = guard_loads.begin(); 2086 iter != guard_loads.end(); 2087 ++iter) 2088 TurnGuardLoadIntoZero(*iter); 2089 2090 for (iter = guard_stores.begin(); 2091 iter != guard_stores.end(); 2092 ++iter) 2093 ExciseGuardStore(*iter); 2094 2095 return true; 2096 } 2097 2098 // This function does not report errors; its callers are responsible. 2099 bool 2100 IRForTarget::UnfoldConstant(Constant *old_constant, 2101 FunctionValueCache &value_maker, 2102 FunctionValueCache &entry_instruction_finder) 2103 { 2104 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2105 2106 SmallVector<User*, 16> users; 2107 2108 // We do this because the use list might change, invalidating our iterator. 2109 // Much better to keep a work list ourselves. 2110 for (llvm::User *u : old_constant->users()) 2111 users.push_back(u); 2112 2113 for (size_t i = 0; 2114 i < users.size(); 2115 ++i) 2116 { 2117 User *user = users[i]; 2118 2119 if (Constant *constant = dyn_cast<Constant>(user)) 2120 { 2121 // synthesize a new non-constant equivalent of the constant 2122 2123 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) 2124 { 2125 switch (constant_expr->getOpcode()) 2126 { 2127 default: 2128 if (log) 2129 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str()); 2130 return false; 2131 case Instruction::BitCast: 2132 { 2133 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* { 2134 // UnaryExpr 2135 // OperandList[0] is value 2136 2137 if (constant_expr->getOperand(0) != old_constant) 2138 return constant_expr; 2139 2140 return new BitCastInst(value_maker.GetValue(function), 2141 constant_expr->getType(), 2142 "", 2143 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function))); 2144 }); 2145 2146 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder)) 2147 return false; 2148 } 2149 break; 2150 case Instruction::GetElementPtr: 2151 { 2152 // GetElementPtrConstantExpr 2153 // OperandList[0] is base 2154 // OperandList[1]... are indices 2155 2156 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* { 2157 Value *ptr = constant_expr->getOperand(0); 2158 2159 if (ptr == old_constant) 2160 ptr = value_maker.GetValue(function); 2161 2162 std::vector<Value*> index_vector; 2163 2164 unsigned operand_index; 2165 unsigned num_operands = constant_expr->getNumOperands(); 2166 2167 for (operand_index = 1; 2168 operand_index < num_operands; 2169 ++operand_index) 2170 { 2171 Value *operand = constant_expr->getOperand(operand_index); 2172 2173 if (operand == old_constant) 2174 operand = value_maker.GetValue(function); 2175 2176 index_vector.push_back(operand); 2177 } 2178 2179 ArrayRef <Value*> indices(index_vector); 2180 2181 return GetElementPtrInst::Create(nullptr, ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function))); 2182 }); 2183 2184 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder)) 2185 return false; 2186 } 2187 break; 2188 } 2189 } 2190 else 2191 { 2192 if (log) 2193 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str()); 2194 return false; 2195 } 2196 } 2197 else 2198 { 2199 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) 2200 { 2201 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent())); 2202 } 2203 else 2204 { 2205 if (log) 2206 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str()); 2207 return false; 2208 } 2209 } 2210 } 2211 2212 if (!isa<GlobalValue>(old_constant)) 2213 { 2214 old_constant->destroyConstant(); 2215 } 2216 2217 return true; 2218 } 2219 2220 bool 2221 IRForTarget::ReplaceVariables (Function &llvm_function) 2222 { 2223 if (!m_resolve_vars) 2224 return true; 2225 2226 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2227 2228 m_decl_map->DoStructLayout(); 2229 2230 if (log) 2231 log->Printf("Element arrangement:"); 2232 2233 uint32_t num_elements; 2234 uint32_t element_index; 2235 2236 size_t size; 2237 lldb::offset_t alignment; 2238 2239 if (!m_decl_map->GetStructInfo (num_elements, size, alignment)) 2240 return false; 2241 2242 Function::arg_iterator iter(llvm_function.getArgumentList().begin()); 2243 2244 if (iter == llvm_function.getArgumentList().end()) 2245 { 2246 if (m_error_stream) 2247 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)"); 2248 2249 return false; 2250 } 2251 2252 Argument *argument = &*iter; 2253 2254 if (argument->getName().equals("this")) 2255 { 2256 ++iter; 2257 2258 if (iter == llvm_function.getArgumentList().end()) 2259 { 2260 if (m_error_stream) 2261 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)"); 2262 2263 return false; 2264 } 2265 2266 argument = &*iter; 2267 } 2268 else if (argument->getName().equals("self")) 2269 { 2270 ++iter; 2271 2272 if (iter == llvm_function.getArgumentList().end()) 2273 { 2274 if (m_error_stream) 2275 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)"); 2276 2277 return false; 2278 } 2279 2280 if (!iter->getName().equals("_cmd")) 2281 { 2282 if (m_error_stream) 2283 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str()); 2284 2285 return false; 2286 } 2287 2288 ++iter; 2289 2290 if (iter == llvm_function.getArgumentList().end()) 2291 { 2292 if (m_error_stream) 2293 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)"); 2294 2295 return false; 2296 } 2297 2298 argument = &*iter; 2299 } 2300 2301 if (!argument->getName().equals("$__lldb_arg")) 2302 { 2303 if (m_error_stream) 2304 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str()); 2305 2306 return false; 2307 } 2308 2309 if (log) 2310 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str()); 2311 2312 BasicBlock &entry_block(llvm_function.getEntryBlock()); 2313 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); 2314 2315 if (!FirstEntryInstruction) 2316 { 2317 if (m_error_stream) 2318 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting"); 2319 2320 return false; 2321 } 2322 2323 LLVMContext &context(m_module->getContext()); 2324 IntegerType *offset_type(Type::getInt32Ty(context)); 2325 2326 if (!offset_type) 2327 { 2328 if (m_error_stream) 2329 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type"); 2330 2331 return false; 2332 } 2333 2334 for (element_index = 0; element_index < num_elements; ++element_index) 2335 { 2336 const clang::NamedDecl *decl = NULL; 2337 Value *value = NULL; 2338 lldb::offset_t offset; 2339 lldb_private::ConstString name; 2340 2341 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index)) 2342 { 2343 if (m_error_stream) 2344 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete"); 2345 2346 return false; 2347 } 2348 2349 if (log) 2350 log->Printf(" \"%s\" (\"%s\") placed at %" PRIu64, 2351 name.GetCString(), 2352 decl->getNameAsString().c_str(), 2353 offset); 2354 2355 if (value) 2356 { 2357 if (log) 2358 log->Printf(" Replacing [%s]", PrintValue(value).c_str()); 2359 2360 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * { 2361 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result 2362 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure 2363 // entry in order to produce the static variable that the AST thinks it is accessing. 2364 2365 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)); 2366 2367 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true)); 2368 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(nullptr, 2369 argument, 2370 offset_int, 2371 "", 2372 entry_instruction); 2373 2374 if (name == m_result_name && !m_result_is_pointer) 2375 { 2376 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, 2377 value->getType()->getPointerTo(), 2378 "", 2379 entry_instruction); 2380 2381 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction); 2382 2383 return load; 2384 } 2385 else 2386 { 2387 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction); 2388 2389 return bit_cast; 2390 } 2391 }); 2392 2393 if (Constant *constant = dyn_cast<Constant>(value)) 2394 { 2395 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder); 2396 } 2397 else if (Instruction *instruction = dyn_cast<Instruction>(value)) 2398 { 2399 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent())); 2400 } 2401 else 2402 { 2403 if (log) 2404 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str()); 2405 return false; 2406 } 2407 2408 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value)) 2409 var->eraseFromParent(); 2410 } 2411 } 2412 2413 if (log) 2414 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size); 2415 2416 return true; 2417 } 2418 2419 llvm::Constant * 2420 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset) 2421 { 2422 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset); 2423 2424 llvm::Constant *offset_array[1]; 2425 2426 offset_array[0] = offset_int; 2427 2428 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1); 2429 llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext()); 2430 llvm::Type *char_pointer_type = char_type->getPointerTo(); 2431 2432 llvm::Constant *reloc_placeholder_bitcast = ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type); 2433 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(char_type, reloc_placeholder_bitcast, offsets); 2434 llvm::Constant *reloc_bitcast = ConstantExpr::getBitCast(reloc_getelementptr, type); 2435 2436 return reloc_bitcast; 2437 } 2438 2439 bool 2440 IRForTarget::CompleteDataAllocation () 2441 { 2442 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2443 2444 if (!m_data_allocator.GetStream().GetSize()) 2445 return true; 2446 2447 lldb::addr_t allocation = m_data_allocator.Allocate(); 2448 2449 if (log) 2450 { 2451 if (allocation) 2452 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation); 2453 else 2454 log->Printf("Failed to allocate static data"); 2455 } 2456 2457 if (!allocation || allocation == LLDB_INVALID_ADDRESS) 2458 return false; 2459 2460 Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation); 2461 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext())); 2462 2463 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast); 2464 2465 m_reloc_placeholder->eraseFromParent(); 2466 2467 return true; 2468 } 2469 2470 bool 2471 IRForTarget::StripAllGVs (Module &llvm_module) 2472 { 2473 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2474 std::vector<GlobalVariable *> global_vars; 2475 std::set<GlobalVariable *>erased_vars; 2476 2477 bool erased = true; 2478 2479 while (erased) 2480 { 2481 erased = false; 2482 2483 for (GlobalVariable &global_var : llvm_module.globals()) 2484 { 2485 global_var.removeDeadConstantUsers(); 2486 2487 if (global_var.use_empty()) 2488 { 2489 if (log) 2490 log->Printf("Did remove %s", 2491 PrintValue(&global_var).c_str()); 2492 global_var.eraseFromParent(); 2493 erased = true; 2494 break; 2495 } 2496 } 2497 } 2498 2499 for (GlobalVariable &global_var : llvm_module.globals()) 2500 { 2501 GlobalValue::user_iterator ui = global_var.user_begin(); 2502 2503 if (log) 2504 log->Printf("Couldn't remove %s because of %s", 2505 PrintValue(&global_var).c_str(), 2506 PrintValue(*ui).c_str()); 2507 } 2508 2509 return true; 2510 } 2511 2512 bool 2513 IRForTarget::runOnModule (Module &llvm_module) 2514 { 2515 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2516 2517 m_module = &llvm_module; 2518 m_target_data.reset(new DataLayout(m_module)); 2519 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits()); 2520 2521 if (log) 2522 { 2523 std::string s; 2524 raw_string_ostream oss(s); 2525 2526 m_module->print(oss, NULL); 2527 2528 oss.flush(); 2529 2530 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str()); 2531 } 2532 2533 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str())); 2534 2535 if (!main_function) 2536 { 2537 if (log) 2538 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str()); 2539 2540 if (m_error_stream) 2541 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str()); 2542 2543 return false; 2544 } 2545 2546 if (!FixFunctionLinkage (*main_function)) 2547 { 2548 if (log) 2549 log->Printf("Couldn't fix the linkage for the function"); 2550 2551 return false; 2552 } 2553 2554 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext()); 2555 2556 m_reloc_placeholder = new llvm::GlobalVariable((*m_module), 2557 int8_ty, 2558 false /* IsConstant */, 2559 GlobalVariable::InternalLinkage, 2560 Constant::getNullValue(int8_ty), 2561 "reloc_placeholder", 2562 NULL /* InsertBefore */, 2563 GlobalVariable::NotThreadLocal /* ThreadLocal */, 2564 0 /* AddressSpace */); 2565 2566 //////////////////////////////////////////////////////////// 2567 // Replace $__lldb_expr_result with a persistent variable 2568 // 2569 2570 if (!CreateResultVariable(*main_function)) 2571 { 2572 if (log) 2573 log->Printf("CreateResultVariable() failed"); 2574 2575 // CreateResultVariable() reports its own errors, so we don't do so here 2576 2577 return false; 2578 } 2579 2580 if (log && log->GetVerbose()) 2581 { 2582 std::string s; 2583 raw_string_ostream oss(s); 2584 2585 m_module->print(oss, NULL); 2586 2587 oss.flush(); 2588 2589 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str()); 2590 } 2591 2592 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); 2593 fi != fe; 2594 ++fi) 2595 { 2596 llvm::Function *function = &*fi; 2597 2598 if (function->begin() == function->end()) 2599 continue; 2600 2601 Function::iterator bbi; 2602 2603 for (bbi = function->begin(); 2604 bbi != function->end(); 2605 ++bbi) 2606 { 2607 if (!RemoveGuards(*bbi)) 2608 { 2609 if (log) 2610 log->Printf("RemoveGuards() failed"); 2611 2612 // RemoveGuards() reports its own errors, so we don't do so here 2613 2614 return false; 2615 } 2616 2617 if (!RewritePersistentAllocs(*bbi)) 2618 { 2619 if (log) 2620 log->Printf("RewritePersistentAllocs() failed"); 2621 2622 // RewritePersistentAllocs() reports its own errors, so we don't do so here 2623 2624 return false; 2625 } 2626 2627 if (!RemoveCXAAtExit(*bbi)) 2628 { 2629 if (log) 2630 log->Printf("RemoveCXAAtExit() failed"); 2631 2632 // RemoveCXAAtExit() reports its own errors, so we don't do so here 2633 2634 return false; 2635 } 2636 } 2637 } 2638 2639 /////////////////////////////////////////////////////////////////////////////// 2640 // Fix all Objective-C constant strings to use NSStringWithCString:encoding: 2641 // 2642 2643 if (!RewriteObjCConstStrings()) 2644 { 2645 if (log) 2646 log->Printf("RewriteObjCConstStrings() failed"); 2647 2648 // RewriteObjCConstStrings() reports its own errors, so we don't do so here 2649 2650 return false; 2651 } 2652 2653 /////////////////////////////// 2654 // Resolve function pointers 2655 // 2656 2657 if (!ResolveFunctionPointers(llvm_module)) 2658 { 2659 if (log) 2660 log->Printf("ResolveFunctionPointers() failed"); 2661 2662 // ResolveFunctionPointers() reports its own errors, so we don't do so here 2663 2664 return false; 2665 } 2666 2667 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); 2668 fi != fe; 2669 ++fi) 2670 { 2671 llvm::Function *function = &*fi; 2672 2673 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end(); 2674 bbi != bbe; 2675 ++bbi) 2676 { 2677 if (!RewriteObjCSelectors(*bbi)) 2678 { 2679 if (log) 2680 log->Printf("RewriteObjCSelectors() failed"); 2681 2682 // RewriteObjCSelectors() reports its own errors, so we don't do so here 2683 2684 return false; 2685 } 2686 } 2687 } 2688 2689 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); 2690 fi != fe; 2691 ++fi) 2692 { 2693 llvm::Function *function = &*fi; 2694 2695 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end(); 2696 bbi != bbe; 2697 ++bbi) 2698 { 2699 if (!ResolveCalls(*bbi)) 2700 { 2701 if (log) 2702 log->Printf("ResolveCalls() failed"); 2703 2704 // ResolveCalls() reports its own errors, so we don't do so here 2705 2706 return false; 2707 } 2708 2709 if (!ReplaceStaticLiterals(*bbi)) 2710 { 2711 if (log) 2712 log->Printf("ReplaceStaticLiterals() failed"); 2713 2714 return false; 2715 } 2716 } 2717 } 2718 2719 //////////////////////////////////////////////////////////////////////// 2720 // Run function-level passes that only make sense on the main function 2721 // 2722 2723 if (!ResolveExternals(*main_function)) 2724 { 2725 if (log) 2726 log->Printf("ResolveExternals() failed"); 2727 2728 // ResolveExternals() reports its own errors, so we don't do so here 2729 2730 return false; 2731 } 2732 2733 if (!ReplaceVariables(*main_function)) 2734 { 2735 if (log) 2736 log->Printf("ReplaceVariables() failed"); 2737 2738 // ReplaceVariables() reports its own errors, so we don't do so here 2739 2740 return false; 2741 } 2742 2743 if (!ReplaceStrings()) 2744 { 2745 if (log) 2746 log->Printf("ReplaceStrings() failed"); 2747 2748 return false; 2749 } 2750 2751 if (!CompleteDataAllocation()) 2752 { 2753 if (log) 2754 log->Printf("CompleteDataAllocation() failed"); 2755 2756 return false; 2757 } 2758 2759 if (!StripAllGVs(llvm_module)) 2760 { 2761 if (log) 2762 log->Printf("StripAllGVs() failed"); 2763 } 2764 2765 if (log && log->GetVerbose()) 2766 { 2767 std::string s; 2768 raw_string_ostream oss(s); 2769 2770 m_module->print(oss, NULL); 2771 2772 oss.flush(); 2773 2774 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str()); 2775 } 2776 2777 return true; 2778 } 2779 2780 void 2781 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type) 2782 { 2783 } 2784 2785 PassManagerType 2786 IRForTarget::getPotentialPassManagerType() const 2787 { 2788 return PMT_ModulePassManager; 2789 } 2790