IRForTarget.h revision 0f0551e67d8ea8d63ace5456f7d42d951827b017
1//===-- IRForTarget.h ---------------------------------------------*- 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#ifndef liblldb_IRForTarget_h_ 11#define liblldb_IRForTarget_h_ 12 13#include "lldb/lldb-public.h" 14#include "lldb/Core/ConstString.h" 15#include "lldb/Core/Error.h" 16#include "lldb/Core/Stream.h" 17#include "lldb/Core/StreamString.h" 18#include "lldb/Symbol/TaggedASTType.h" 19#include "llvm/Pass.h" 20 21namespace llvm { 22 class BasicBlock; 23 class CallInst; 24 class Constant; 25 class ConstantInt; 26 class Function; 27 class GlobalValue; 28 class GlobalVariable; 29 class Instruction; 30 class Module; 31 class StoreInst; 32 class DataLayout; 33 class Type; 34 class Value; 35} 36 37namespace lldb_private { 38 class ClangExpressionDeclMap; 39 class IRExecutionUnit; 40 class IRMemoryMap; 41} 42 43//---------------------------------------------------------------------- 44/// @class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h" 45/// @brief Transforms the IR for a function to run in the target 46/// 47/// Once an expression has been parsed and converted to IR, it can run 48/// in two contexts: interpreted by LLDB as a DWARF location expression, 49/// or compiled by the JIT and inserted into the target process for 50/// execution. 51/// 52/// IRForTarget makes the second possible, by applying a series of 53/// transformations to the IR which make it relocatable. These 54/// transformations are discussed in more detail next to their relevant 55/// functions. 56//---------------------------------------------------------------------- 57class IRForTarget : public llvm::ModulePass 58{ 59public: 60 //------------------------------------------------------------------ 61 /// Constructor 62 /// 63 /// @param[in] decl_map 64 /// The list of externally-referenced variables for the expression, 65 /// for use in looking up globals and allocating the argument 66 /// struct. See the documentation for ClangExpressionDeclMap. 67 /// 68 /// @param[in] resolve_vars 69 /// True if the external variable references (including persistent 70 /// variables) should be resolved. If not, only external functions 71 /// are resolved. 72 /// 73 /// @param[in] execution_policy 74 /// Determines whether an IR interpreter can be used to statically 75 /// evaluate the expression. 76 /// 77 /// @param[in] const_result 78 /// This variable is populated with the statically-computed result 79 /// of the function, if it has no side-effects and the result can 80 /// be computed statically. 81 /// 82 /// @param[in] execution_unit 83 /// The holder for raw data associated with the expression. 84 /// 85 /// @param[in] error_stream 86 /// If non-NULL, a stream on which errors can be printed. 87 /// 88 /// @param[in] func_name 89 /// The name of the function to prepare for execution in the target. 90 //------------------------------------------------------------------ 91 IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, 92 bool resolve_vars, 93 lldb_private::IRExecutionUnit &execution_unit, 94 lldb_private::Stream *error_stream, 95 const char* func_name = "$__lldb_expr"); 96 97 //------------------------------------------------------------------ 98 /// Destructor 99 //------------------------------------------------------------------ 100 virtual ~IRForTarget(); 101 102 //------------------------------------------------------------------ 103 /// Run this IR transformer on a single module 104 /// 105 /// Implementation of the llvm::ModulePass::runOnModule() function. 106 /// 107 /// @param[in] llvm_module 108 /// The module to run on. This module is searched for the function 109 /// $__lldb_expr, and that function is passed to the passes one by 110 /// one. 111 /// 112 /// @param[in] interpreter_error 113 /// An error. If the expression fails to be interpreted, this error 114 /// is set to a reason why. 115 /// 116 /// @return 117 /// True on success; false otherwise 118 //------------------------------------------------------------------ 119 virtual bool 120 runOnModule (llvm::Module &llvm_module); 121 122 //------------------------------------------------------------------ 123 /// Interface stub 124 /// 125 /// Implementation of the llvm::ModulePass::assignPassManager() 126 /// function. 127 //------------------------------------------------------------------ 128 virtual void 129 assignPassManager (llvm::PMStack &pass_mgr_stack, 130 llvm::PassManagerType pass_mgr_type = llvm::PMT_ModulePassManager); 131 132 //------------------------------------------------------------------ 133 /// Returns PMT_ModulePassManager 134 /// 135 /// Implementation of the llvm::ModulePass::getPotentialPassManagerType() 136 /// function. 137 //------------------------------------------------------------------ 138 virtual llvm::PassManagerType 139 getPotentialPassManagerType() const; 140 141private: 142 //------------------------------------------------------------------ 143 /// Ensures that the current function's linkage is set to external. 144 /// Otherwise the JIT may not return an address for it. 145 /// 146 /// @param[in] llvm_function 147 /// The function whose linkage is to be fixed. 148 /// 149 /// @return 150 /// True on success; false otherwise. 151 //------------------------------------------------------------------ 152 bool 153 FixFunctionLinkage (llvm::Function &llvm_function); 154 155 //------------------------------------------------------------------ 156 /// A module-level pass to replace all function pointers with their 157 /// integer equivalents. 158 //------------------------------------------------------------------ 159 160 //------------------------------------------------------------------ 161 /// The top-level pass implementation 162 /// 163 /// @param[in] llvm_module 164 /// The module currently being processed. 165 /// 166 /// @param[in] llvm_function 167 /// The function currently being processed. 168 /// 169 /// @return 170 /// True on success; false otherwise. 171 //------------------------------------------------------------------ 172 bool 173 HasSideEffects (llvm::Function &llvm_function); 174 175 //------------------------------------------------------------------ 176 /// A function-level pass to check whether the function has side 177 /// effects. 178 //------------------------------------------------------------------ 179 180 //------------------------------------------------------------------ 181 /// Get the address of a fuction, and a location to put the complete 182 /// Value of the function if one is available. 183 /// 184 /// @param[in] function 185 /// The function to find the location of. 186 /// 187 /// @param[out] ptr 188 /// The location of the function in the target. 189 /// 190 /// @param[out] name 191 /// The resolved name of the function (matters for intrinsics). 192 /// 193 /// @param[out] value_ptr 194 /// A variable to put the function's completed Value* in, or NULL 195 /// if the Value* shouldn't be stored anywhere. 196 /// 197 /// @return 198 /// The pointer. 199 //------------------------------------------------------------------ 200 bool 201 GetFunctionAddress (llvm::Function *function, 202 uint64_t &ptr, 203 lldb_private::ConstString &name, 204 llvm::Constant **&value_ptr); 205 206 //------------------------------------------------------------------ 207 /// Build a function pointer given a type and a raw pointer. 208 /// 209 /// @param[in] type 210 /// The type of the function pointer to be built. 211 /// 212 /// @param[in] ptr 213 /// The value of the pointer. 214 /// 215 /// @return 216 /// The pointer. 217 //------------------------------------------------------------------ 218 llvm::Constant * 219 BuildFunctionPointer (llvm::Type *type, 220 uint64_t ptr); 221 222 void 223 RegisterFunctionMetadata (llvm::LLVMContext &context, 224 llvm::Value *function_ptr, 225 const char *name); 226 227 //------------------------------------------------------------------ 228 /// The top-level pass implementation 229 /// 230 /// @param[in] llvm_function 231 /// The function currently being processed. 232 /// 233 /// @return 234 /// True if the function has side effects (or if this cannot 235 /// be determined); false otherwise. 236 //------------------------------------------------------------------ 237 bool 238 ResolveFunctionPointers (llvm::Module &llvm_module, 239 llvm::Function &llvm_function); 240 241 //------------------------------------------------------------------ 242 /// A function-level pass to take the generated global value 243 /// $__lldb_expr_result and make it into a persistent variable. 244 /// Also see ASTResultSynthesizer. 245 //------------------------------------------------------------------ 246 247 //------------------------------------------------------------------ 248 /// Find the NamedDecl corresponding to a Value. This interface is 249 /// exposed for the IR interpreter. 250 /// 251 /// @param[in] module 252 /// The module containing metadata to search 253 /// 254 /// @param[in] global 255 /// The global entity to search for 256 /// 257 /// @return 258 /// The corresponding variable declaration 259 //------------------------------------------------------------------ 260public: 261 static clang::NamedDecl * 262 DeclForGlobal (const llvm::GlobalValue *global_val, llvm::Module *module); 263private: 264 clang::NamedDecl * 265 DeclForGlobal (llvm::GlobalValue *global); 266 267 //------------------------------------------------------------------ 268 /// Set the constant result variable m_const_result to the provided 269 /// constant, assuming it can be evaluated. The result variable 270 /// will be reset to NULL later if the expression has side effects. 271 /// 272 /// @param[in] initializer 273 /// The constant initializer for the variable. 274 /// 275 /// @param[in] name 276 /// The name of the result variable. 277 /// 278 /// @param[in] type 279 /// The Clang type of the result variable. 280 //------------------------------------------------------------------ 281 void 282 MaybeSetConstantResult (llvm::Constant *initializer, 283 const lldb_private::ConstString &name, 284 lldb_private::TypeFromParser type); 285 286 //------------------------------------------------------------------ 287 /// If the IR represents a cast of a variable, set m_const_result 288 /// to the result of the cast. The result variable will be reset to 289 /// NULL latger if the expression has side effects. 290 /// 291 /// @param[in] type 292 /// The Clang type of the result variable. 293 //------------------------------------------------------------------ 294 void 295 MaybeSetCastResult (lldb_private::TypeFromParser type); 296 297 //------------------------------------------------------------------ 298 /// The top-level pass implementation 299 /// 300 /// @param[in] llvm_function 301 /// The function currently being processed. 302 /// 303 /// @return 304 /// True on success; false otherwise 305 //------------------------------------------------------------------ 306 bool 307 CreateResultVariable (llvm::Function &llvm_function); 308 309 //------------------------------------------------------------------ 310 /// A function-level pass to find Objective-C constant strings and 311 /// transform them to calls to CFStringCreateWithBytes. 312 //------------------------------------------------------------------ 313 314 //------------------------------------------------------------------ 315 /// Rewrite a single Objective-C constant string. 316 /// 317 /// @param[in] NSStr 318 /// The constant NSString to be transformed 319 /// 320 /// @param[in] CStr 321 /// The constant C string inside the NSString. This will be 322 /// passed as the bytes argument to CFStringCreateWithBytes. 323 /// 324 /// @param[in] FirstEntryInstruction 325 /// An instruction early in the execution of the function. 326 /// When this function synthesizes a call to 327 /// CFStringCreateWithBytes, it places the call before this 328 /// instruction. The instruction should come before all 329 /// uses of the NSString. 330 /// 331 /// @return 332 /// True on success; false otherwise 333 //------------------------------------------------------------------ 334 bool 335 RewriteObjCConstString (llvm::GlobalVariable *NSStr, 336 llvm::GlobalVariable *CStr, 337 llvm::Instruction *FirstEntryInstruction); 338 339 //------------------------------------------------------------------ 340 /// The top-level pass implementation 341 /// 342 /// @param[in] llvm_function 343 /// The function currently being processed. 344 /// 345 /// @return 346 /// True on success; false otherwise 347 //------------------------------------------------------------------ 348 bool 349 RewriteObjCConstStrings (llvm::Function &llvm_function); 350 351 //------------------------------------------------------------------ 352 /// A basic block-level pass to find all Objective-C method calls and 353 /// rewrite them to use sel_registerName instead of statically allocated 354 /// selectors. The reason is that the selectors are created on the 355 /// assumption that the Objective-C runtime will scan the appropriate 356 /// section and prepare them. This doesn't happen when code is copied 357 /// into the target, though, and there's no easy way to induce the 358 /// runtime to scan them. So instead we get our selectors from 359 /// sel_registerName. 360 //------------------------------------------------------------------ 361 362 //------------------------------------------------------------------ 363 /// Replace a single selector reference 364 /// 365 /// @param[in] selector_load 366 /// The load of the statically-allocated selector. 367 /// 368 /// @return 369 /// True on success; false otherwise 370 //------------------------------------------------------------------ 371 bool 372 RewriteObjCSelector (llvm::Instruction* selector_load); 373 374 //------------------------------------------------------------------ 375 /// The top-level pass implementation 376 /// 377 /// @param[in] basic_block 378 /// The basic block currently being processed. 379 /// 380 /// @return 381 /// True on success; false otherwise 382 //------------------------------------------------------------------ 383 bool 384 RewriteObjCSelectors (llvm::BasicBlock &basic_block); 385 386 //------------------------------------------------------------------ 387 /// A basic block-level pass to find all newly-declared persistent 388 /// variables and register them with the ClangExprDeclMap. This 389 /// allows them to be materialized and dematerialized like normal 390 /// external variables. Before transformation, these persistent 391 /// variables look like normal locals, so they have an allocation. 392 /// This pass excises these allocations and makes references look 393 /// like external references where they will be resolved -- like all 394 /// other external references -- by ResolveExternals(). 395 //------------------------------------------------------------------ 396 397 //------------------------------------------------------------------ 398 /// Handle a single allocation of a persistent variable 399 /// 400 /// @param[in] persistent_alloc 401 /// The allocation of the persistent variable. 402 /// 403 /// @return 404 /// True on success; false otherwise 405 //------------------------------------------------------------------ 406 bool 407 RewritePersistentAlloc (llvm::Instruction *persistent_alloc); 408 409 //------------------------------------------------------------------ 410 /// The top-level pass implementation 411 /// 412 /// @param[in] basic_block 413 /// The basic block currently being processed. 414 //------------------------------------------------------------------ 415 bool 416 RewritePersistentAllocs (llvm::BasicBlock &basic_block); 417 418 //------------------------------------------------------------------ 419 /// A function-level pass to find all external variables and functions 420 /// used in the IR. Each found external variable is added to the 421 /// struct, and each external function is resolved in place, its call 422 /// replaced with a call to a function pointer whose value is the 423 /// address of the function in the target process. 424 //------------------------------------------------------------------ 425 426 //------------------------------------------------------------------ 427 /// Write an initializer to a memory array of assumed sufficient 428 /// size. 429 /// 430 /// @param[in] data 431 /// A pointer to the data to write to. 432 /// 433 /// @param[in] initializer 434 /// The initializer itself. 435 /// 436 /// @return 437 /// True on success; false otherwise 438 //------------------------------------------------------------------ 439 bool 440 MaterializeInitializer (uint8_t *data, llvm::Constant *initializer); 441 442 //------------------------------------------------------------------ 443 /// Move an internal variable into the static allocation section. 444 /// 445 /// @param[in] global_variable 446 /// The variable. 447 /// 448 /// @return 449 /// True on success; false otherwise 450 //------------------------------------------------------------------ 451 bool 452 MaterializeInternalVariable (llvm::GlobalVariable *global_variable); 453 454 //------------------------------------------------------------------ 455 /// Handle a single externally-defined variable 456 /// 457 /// @param[in] value 458 /// The variable. 459 /// 460 /// @return 461 /// True on success; false otherwise 462 //------------------------------------------------------------------ 463 bool 464 MaybeHandleVariable (llvm::Value *value); 465 466 //------------------------------------------------------------------ 467 /// Handle a single externally-defined symbol 468 /// 469 /// @param[in] symbol 470 /// The symbol. 471 /// 472 /// @return 473 /// True on success; false otherwise 474 //------------------------------------------------------------------ 475 bool 476 HandleSymbol (llvm::Value *symbol); 477 478 //------------------------------------------------------------------ 479 /// Handle a single externally-defined Objective-C class 480 /// 481 /// @param[in] classlist_reference 482 /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n" 483 /// where n (if present) is an index. 484 /// 485 /// @return 486 /// True on success; false otherwise 487 //------------------------------------------------------------------ 488 bool 489 HandleObjCClass(llvm::Value *classlist_reference); 490 491 //------------------------------------------------------------------ 492 /// Handle all the arguments to a function call 493 /// 494 /// @param[in] C 495 /// The call instruction. 496 /// 497 /// @return 498 /// True on success; false otherwise 499 //------------------------------------------------------------------ 500 bool 501 MaybeHandleCallArguments (llvm::CallInst *call_inst); 502 503 //------------------------------------------------------------------ 504 /// Resolve variable references in calls to external functions 505 /// 506 /// @param[in] basic_block 507 /// The basic block currently being processed. 508 /// 509 /// @return 510 /// True on success; false otherwise 511 //------------------------------------------------------------------ 512 bool 513 ResolveCalls (llvm::BasicBlock &basic_block); 514 515 //------------------------------------------------------------------ 516 /// Remove calls to __cxa_atexit, which should never be generated by 517 /// expressions. 518 /// 519 /// @param[in] call_inst 520 /// The call instruction. 521 /// 522 /// @return 523 /// True if the scan was successful; false if some operation 524 /// failed 525 //------------------------------------------------------------------ 526 bool 527 RemoveCXAAtExit (llvm::BasicBlock &basic_block); 528 529 //------------------------------------------------------------------ 530 /// The top-level pass implementation 531 /// 532 /// @param[in] basic_block 533 /// The function currently being processed. 534 /// 535 /// @return 536 /// True on success; false otherwise 537 //------------------------------------------------------------------ 538 bool 539 ResolveExternals (llvm::Function &llvm_function); 540 541 //------------------------------------------------------------------ 542 /// A basic block-level pass to excise guard variables from the code. 543 /// The result for the function is passed through Clang as a static 544 /// variable. Static variables normally have guard variables to 545 /// ensure that they are only initialized once. 546 //------------------------------------------------------------------ 547 548 //------------------------------------------------------------------ 549 /// Rewrite a load to a guard variable to return constant 0. 550 /// 551 /// @param[in] guard_load 552 /// The load instruction to zero out. 553 //------------------------------------------------------------------ 554 void 555 TurnGuardLoadIntoZero(llvm::Instruction* guard_load); 556 557 //------------------------------------------------------------------ 558 /// The top-level pass implementation 559 /// 560 /// @param[in] basic_block 561 /// The basic block currently being processed. 562 /// 563 /// @return 564 /// True on success; false otherwise 565 //------------------------------------------------------------------ 566 bool 567 RemoveGuards (llvm::BasicBlock &basic_block); 568 569 //------------------------------------------------------------------ 570 /// A module-level pass to allocate all string literals in a separate 571 /// allocation and redirect references to them. 572 //------------------------------------------------------------------ 573 574 //------------------------------------------------------------------ 575 /// The top-level pass implementation 576 /// 577 /// @return 578 /// True on success; false otherwise 579 //------------------------------------------------------------------ 580 bool 581 ReplaceStrings (); 582 583 //------------------------------------------------------------------ 584 /// A basick block-level pass to find all literals that will be 585 /// allocated as statics by the JIT (in contrast to the Strings, 586 /// which already are statics) and synthesize loads for them. 587 //------------------------------------------------------------------ 588 589 //------------------------------------------------------------------ 590 /// The top-level pass implementation 591 /// 592 /// @param[in] basic_block 593 /// The basic block currently being processed. 594 /// 595 /// @return 596 /// True on success; false otherwise 597 //------------------------------------------------------------------ 598 bool 599 ReplaceStaticLiterals (llvm::BasicBlock &basic_block); 600 601 //------------------------------------------------------------------ 602 /// A function-level pass to make all external variable references 603 /// point at the correct offsets from the void* passed into the 604 /// function. ClangExpressionDeclMap::DoStructLayout() must be called 605 /// beforehand, so that the offsets are valid. 606 //------------------------------------------------------------------ 607 608 //------------------------------------------------------------------ 609 /// The top-level pass implementation 610 /// 611 /// @param[in] llvm_function 612 /// The function currently being processed. 613 /// 614 /// @return 615 /// True on success; false otherwise 616 //------------------------------------------------------------------ 617 bool 618 ReplaceVariables (llvm::Function &llvm_function); 619 620 //------------------------------------------------------------------ 621 /// A module-level pass to remove all global variables from the 622 /// module since it no longer should export or import any symbols. 623 //------------------------------------------------------------------ 624 625 //------------------------------------------------------------------ 626 /// The top-level pass implementation 627 /// 628 /// @param[in] llvm_module 629 /// The module currently being processed. 630 /// 631 /// @return 632 /// True on success; false otherwise 633 //------------------------------------------------------------------ 634 bool 635 StripAllGVs (llvm::Module &llvm_module); 636 637 class StaticDataAllocator { 638 public: 639 StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit); 640 lldb_private::StreamString &GetStream() 641 { 642 return m_stream_string; 643 } 644 lldb::addr_t Allocate(); 645 private: 646 lldb_private::IRExecutionUnit &m_execution_unit; 647 lldb_private::StreamString m_stream_string; 648 lldb::addr_t m_allocation; 649 }; 650 651 /// Flags 652 bool m_resolve_vars; ///< True if external variable references and persistent variable references should be resolved 653 std::string m_func_name; ///< The name of the function to translate 654 lldb_private::ConstString m_result_name; ///< The name of the result variable ($0, $1, ...) 655 lldb_private::TypeFromParser m_result_type; ///< The type of the result variable. 656 llvm::Module *m_module; ///< The module being processed, or NULL if that has not been determined yet. 657 STD_UNIQUE_PTR(llvm::DataLayout) m_target_data; ///< The target data for the module being processed, or NULL if there is no module. 658 lldb_private::ClangExpressionDeclMap *m_decl_map; ///< The DeclMap containing the Decls 659 StaticDataAllocator m_data_allocator; ///< The allocator to use for constant strings 660 lldb_private::IRMemoryMap &m_memory_map; ///< The memory map to pass to the IR interpreter 661 llvm::Constant *m_CFStringCreateWithBytes; ///< The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type 662 llvm::Constant *m_sel_registerName; ///< The address of the function sel_registerName, cast to the appropriate function pointer type 663 lldb_private::Stream *m_error_stream; ///< If non-NULL, the stream on which errors should be printed 664 665 bool m_has_side_effects; ///< True if the function's result cannot be simply determined statically 666 llvm::StoreInst *m_result_store; ///< If non-NULL, the store instruction that writes to the result variable. If m_has_side_effects is true, this is NULL. 667 bool m_result_is_pointer; ///< True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::SynthesizeBodyResult) 668 669 llvm::GlobalVariable *m_reloc_placeholder; ///< A placeholder that will be replaced by a pointer to the final location of the static allocation. 670 671 //------------------------------------------------------------------ 672 /// UnfoldConstant operates on a constant [Old] which has just been 673 /// replaced with a value [New]. We assume that new_value has 674 /// been properly placed early in the function, in front of the 675 /// first instruction in the entry basic block 676 /// [FirstEntryInstruction]. 677 /// 678 /// UnfoldConstant reads through the uses of Old and replaces Old 679 /// in those uses with New. Where those uses are constants, the 680 /// function generates new instructions to compute the result of the 681 /// new, non-constant expression and places them before 682 /// FirstEntryInstruction. These instructions replace the constant 683 /// uses, so UnfoldConstant calls itself recursively for those. 684 /// 685 /// @param[in] llvm_function 686 /// The function currently being processed. 687 /// 688 /// @return 689 /// True on success; false otherwise 690 //------------------------------------------------------------------ 691 static bool 692 UnfoldConstant (llvm::Constant *old_constant, 693 llvm::Value *new_constant, 694 llvm::Instruction *first_entry_inst); 695 696 //------------------------------------------------------------------ 697 /// Construct a reference to m_reloc_placeholder with a given type 698 /// and offset. This typically happens after inserting data into 699 /// m_data_allocator. 700 /// 701 /// @param[in] type 702 /// The type of the value being loaded. 703 /// 704 /// @param[in] offset 705 /// The offset of the value from the base of m_data_allocator. 706 /// 707 /// @return 708 /// The Constant for the reference, usually a ConstantExpr. 709 //------------------------------------------------------------------ 710 llvm::Constant * 711 BuildRelocation(llvm::Type *type, 712 uint64_t offset); 713 714 //------------------------------------------------------------------ 715 /// Commit the allocation in m_data_allocator and use its final 716 /// location to replace m_reloc_placeholder. 717 /// 718 /// @param[in] module 719 /// The module that m_data_allocator resides in 720 /// 721 /// @return 722 /// True on success; false otherwise 723 //------------------------------------------------------------------ 724 bool 725 CompleteDataAllocation (); 726 727}; 728 729#endif 730