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