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