1 //===-- IRForTarget.h ---------------------------------------------*- C++
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_IRForTarget_h_
11 #define liblldb_IRForTarget_h_
13 #include "lldb/Symbol/TaggedASTType.h"
14 #include "lldb/Utility/ConstString.h"
15 #include "lldb/Utility/Status.h"
16 #include "lldb/Utility/Stream.h"
17 #include "lldb/Utility/StreamString.h"
18 #include "lldb/lldb-public.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/Pass.h"
40 namespace lldb_private {
41 class ClangExpressionDeclMap;
42 class IRExecutionUnit;
46 /// \class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h"
47 /// Transforms the IR for a function to run in the target
49 /// Once an expression has been parsed and converted to IR, it can run in two
50 /// contexts: interpreted by LLDB as a DWARF location expression, or compiled
51 /// by the JIT and inserted into the target process for execution.
53 /// IRForTarget makes the second possible, by applying a series of
54 /// transformations to the IR which make it relocatable. These
55 /// transformations are discussed in more detail next to their relevant
57 class IRForTarget : public llvm::ModulePass {
59 enum class LookupResult { Success, Fail, Ignore };
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.
68 /// \param[in] resolve_vars
69 /// True if the external variable references (including persistent
70 /// variables) should be resolved. If not, only external functions
73 /// \param[in] execution_policy
74 /// Determines whether an IR interpreter can be used to statically
75 /// evaluate the expression.
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.
82 /// \param[in] execution_unit
83 /// The holder for raw data associated with the expression.
85 /// \param[in] error_stream
86 /// If non-NULL, a stream on which errors can be printed.
88 /// \param[in] func_name
89 /// The name of the function to prepare for execution in the target.
90 IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars,
91 lldb_private::IRExecutionUnit &execution_unit,
92 lldb_private::Stream &error_stream,
93 const char *func_name = "$__lldb_expr");
96 ~IRForTarget() override;
98 /// Run this IR transformer on a single module
100 /// Implementation of the llvm::ModulePass::runOnModule() function.
102 /// \param[in] llvm_module
103 /// The module to run on. This module is searched for the function
104 /// $__lldb_expr, and that function is passed to the passes one by
107 /// \param[in] interpreter_error
108 /// An error. If the expression fails to be interpreted, this error
109 /// is set to a reason why.
112 /// True on success; false otherwise
113 bool runOnModule(llvm::Module &llvm_module) override;
117 /// Implementation of the llvm::ModulePass::assignPassManager() function.
118 void assignPassManager(llvm::PMStack &pass_mgr_stack,
119 llvm::PassManagerType pass_mgr_type =
120 llvm::PMT_ModulePassManager) override;
122 /// Returns PMT_ModulePassManager
124 /// Implementation of the llvm::ModulePass::getPotentialPassManagerType()
126 llvm::PassManagerType getPotentialPassManagerType() const override;
129 /// Ensures that the current function's linkage is set to external.
130 /// Otherwise the JIT may not return an address for it.
132 /// \param[in] llvm_function
133 /// The function whose linkage is to be fixed.
136 /// True on success; false otherwise.
137 bool FixFunctionLinkage(llvm::Function &llvm_function);
139 /// A module-level pass to replace all function pointers with their
140 /// integer equivalents.
142 /// The top-level pass implementation
144 /// \param[in] llvm_module
145 /// The module currently being processed.
147 /// \param[in] llvm_function
148 /// The function currently being processed.
151 /// True on success; false otherwise.
152 bool HasSideEffects(llvm::Function &llvm_function);
154 /// A function-level pass to check whether the function has side
157 /// Get the address of a function, and a location to put the complete Value
158 /// of the function if one is available.
160 /// \param[in] function
161 /// The function to find the location of.
164 /// The location of the function in the target.
167 /// The resolved name of the function (matters for intrinsics).
169 /// \param[out] value_ptr
170 /// A variable to put the function's completed Value* in, or NULL
171 /// if the Value* shouldn't be stored anywhere.
175 LookupResult GetFunctionAddress(llvm::Function *function, uint64_t &ptr,
176 lldb_private::ConstString &name,
177 llvm::Constant **&value_ptr);
179 /// A function-level pass to take the generated global value
180 /// $__lldb_expr_result and make it into a persistent variable. Also see
181 /// ASTResultSynthesizer.
183 /// Find the NamedDecl corresponding to a Value. This interface is exposed
184 /// for the IR interpreter.
186 /// \param[in] module
187 /// The module containing metadata to search
189 /// \param[in] global
190 /// The global entity to search for
193 /// The corresponding variable declaration
195 static clang::NamedDecl *DeclForGlobal(const llvm::GlobalValue *global_val,
196 llvm::Module *module);
199 clang::NamedDecl *DeclForGlobal(llvm::GlobalValue *global);
201 /// Set the constant result variable m_const_result to the provided
202 /// constant, assuming it can be evaluated. The result variable will be
203 /// reset to NULL later if the expression has side effects.
205 /// \param[in] initializer
206 /// The constant initializer for the variable.
209 /// The name of the result variable.
212 /// The Clang type of the result variable.
213 void MaybeSetConstantResult(llvm::Constant *initializer,
214 lldb_private::ConstString name,
215 lldb_private::TypeFromParser type);
217 /// If the IR represents a cast of a variable, set m_const_result to the
218 /// result of the cast. The result variable will be reset to
219 /// NULL latger if the expression has side effects.
222 /// The Clang type of the result variable.
223 void MaybeSetCastResult(lldb_private::TypeFromParser type);
225 /// The top-level pass implementation
227 /// \param[in] llvm_function
228 /// The function currently being processed.
231 /// True on success; false otherwise
232 bool CreateResultVariable(llvm::Function &llvm_function);
234 /// A module-level pass to find Objective-C constant strings and
235 /// transform them to calls to CFStringCreateWithBytes.
237 /// Rewrite a single Objective-C constant string.
240 /// The constant NSString to be transformed
243 /// The constant C string inside the NSString. This will be
244 /// passed as the bytes argument to CFStringCreateWithBytes.
247 /// True on success; false otherwise
248 bool RewriteObjCConstString(llvm::GlobalVariable *NSStr,
249 llvm::GlobalVariable *CStr);
251 /// The top-level pass implementation
254 /// True on success; false otherwise
255 bool RewriteObjCConstStrings();
257 /// A basic block-level pass to find all Objective-C method calls and
258 /// rewrite them to use sel_registerName instead of statically allocated
259 /// selectors. The reason is that the selectors are created on the
260 /// assumption that the Objective-C runtime will scan the appropriate
261 /// section and prepare them. This doesn't happen when code is copied into
262 /// the target, though, and there's no easy way to induce the runtime to
263 /// scan them. So instead we get our selectors from sel_registerName.
265 /// Replace a single selector reference
267 /// \param[in] selector_load
268 /// The load of the statically-allocated selector.
271 /// True on success; false otherwise
272 bool RewriteObjCSelector(llvm::Instruction *selector_load);
274 /// The top-level pass implementation
276 /// \param[in] basic_block
277 /// The basic block currently being processed.
280 /// True on success; false otherwise
281 bool RewriteObjCSelectors(llvm::BasicBlock &basic_block);
283 /// A basic block-level pass to find all Objective-C class references that
284 /// use the old-style Objective-C runtime and rewrite them to use
285 /// class_getClass instead of statically allocated class references.
287 /// Replace a single old-style class reference
289 /// \param[in] selector_load
290 /// The load of the statically-allocated selector.
293 /// True on success; false otherwise
294 bool RewriteObjCClassReference(llvm::Instruction *class_load);
296 /// The top-level pass implementation
298 /// \param[in] basic_block
299 /// The basic block currently being processed.
302 /// True on success; false otherwise
303 bool RewriteObjCClassReferences(llvm::BasicBlock &basic_block);
305 /// A basic block-level pass to find all newly-declared persistent
306 /// variables and register them with the ClangExprDeclMap. This allows them
307 /// to be materialized and dematerialized like normal external variables.
308 /// Before transformation, these persistent variables look like normal
309 /// locals, so they have an allocation. This pass excises these allocations
310 /// and makes references look like external references where they will be
311 /// resolved -- like all other external references -- by ResolveExternals().
313 /// Handle a single allocation of a persistent variable
315 /// \param[in] persistent_alloc
316 /// The allocation of the persistent variable.
319 /// True on success; false otherwise
320 bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc);
322 /// The top-level pass implementation
324 /// \param[in] basic_block
325 /// The basic block currently being processed.
326 bool RewritePersistentAllocs(llvm::BasicBlock &basic_block);
328 /// A function-level pass to find all external variables and functions
329 /// used in the IR. Each found external variable is added to the struct,
330 /// and each external function is resolved in place, its call replaced with
331 /// a call to a function pointer whose value is the address of the function
332 /// in the target process.
334 /// Write an initializer to a memory array of assumed sufficient size.
337 /// A pointer to the data to write to.
339 /// \param[in] initializer
340 /// The initializer itself.
343 /// True on success; false otherwise
344 bool MaterializeInitializer(uint8_t *data, llvm::Constant *initializer);
346 /// Move an internal variable into the static allocation section.
348 /// \param[in] global_variable
352 /// True on success; false otherwise
353 bool MaterializeInternalVariable(llvm::GlobalVariable *global_variable);
355 /// Handle a single externally-defined variable
361 /// True on success; false otherwise
362 bool MaybeHandleVariable(llvm::Value *value);
364 /// Handle a single externally-defined symbol
366 /// \param[in] symbol
370 /// True on success; false otherwise
371 bool HandleSymbol(llvm::Value *symbol);
373 /// Handle a single externally-defined Objective-C class
375 /// \param[in] classlist_reference
376 /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n"
377 /// where n (if present) is an index.
380 /// True on success; false otherwise
381 bool HandleObjCClass(llvm::Value *classlist_reference);
383 /// Handle all the arguments to a function call
386 /// The call instruction.
389 /// True on success; false otherwise
390 bool MaybeHandleCallArguments(llvm::CallInst *call_inst);
392 /// Resolve variable references in calls to external functions
394 /// \param[in] basic_block
395 /// The basic block currently being processed.
398 /// True on success; false otherwise
399 bool ResolveCalls(llvm::BasicBlock &basic_block);
401 /// Remove calls to __cxa_atexit, which should never be generated by
404 /// \param[in] call_inst
405 /// The call instruction.
408 /// True if the scan was successful; false if some operation
410 bool RemoveCXAAtExit(llvm::BasicBlock &basic_block);
412 /// The top-level pass implementation
414 /// \param[in] basic_block
415 /// The function currently being processed.
418 /// True on success; false otherwise
419 bool ResolveExternals(llvm::Function &llvm_function);
421 /// A basic block-level pass to excise guard variables from the code.
422 /// The result for the function is passed through Clang as a static
423 /// variable. Static variables normally have guard variables to ensure that
424 /// they are only initialized once.
426 /// Rewrite a load to a guard variable to return constant 0.
428 /// \param[in] guard_load
429 /// The load instruction to zero out.
430 void TurnGuardLoadIntoZero(llvm::Instruction *guard_load);
432 /// The top-level pass implementation
434 /// \param[in] basic_block
435 /// The basic block currently being processed.
438 /// True on success; false otherwise
439 bool RemoveGuards(llvm::BasicBlock &basic_block);
441 /// A function-level pass to make all external variable references
442 /// point at the correct offsets from the void* passed into the function.
443 /// ClangExpressionDeclMap::DoStructLayout() must be called beforehand, so
444 /// that the offsets are valid.
446 /// The top-level pass implementation
448 /// \param[in] llvm_function
449 /// The function currently being processed.
452 /// True on success; false otherwise
453 bool ReplaceVariables(llvm::Function &llvm_function);
456 bool m_resolve_vars; ///< True if external variable references and persistent
457 ///variable references should be resolved
458 lldb_private::ConstString
459 m_func_name; ///< The name of the function to translate
460 lldb_private::ConstString
461 m_result_name; ///< The name of the result variable ($0, $1, ...)
462 lldb_private::TypeFromParser
463 m_result_type; ///< The type of the result variable.
464 llvm::Module *m_module; ///< The module being processed, or NULL if that has
465 ///not been determined yet.
466 std::unique_ptr<llvm::DataLayout> m_target_data; ///< The target data for the
467 ///module being processed, or
468 ///NULL if there is no
470 lldb_private::ClangExpressionDeclMap
471 *m_decl_map; ///< The DeclMap containing the Decls
473 m_CFStringCreateWithBytes; ///< The address of the function
474 /// CFStringCreateWithBytes, cast to the
475 /// appropriate function pointer type
476 llvm::FunctionCallee m_sel_registerName; ///< The address of the function
477 /// sel_registerName, cast to the
478 /// appropriate function pointer type
479 llvm::FunctionCallee m_objc_getClass; ///< The address of the function
480 /// objc_getClass, cast to the
481 /// appropriate function pointer type
483 *m_intptr_ty; ///< The type of an integer large enough to hold a pointer.
485 &m_error_stream; ///< The stream on which errors should be printed
486 lldb_private::IRExecutionUnit &
487 m_execution_unit; ///< The execution unit containing the IR being created.
489 llvm::StoreInst *m_result_store; ///< If non-NULL, the store instruction that
490 ///writes to the result variable. If
491 /// m_has_side_effects is true, this is
493 bool m_result_is_pointer; ///< True if the function's result in the AST is a
494 ///pointer (see comments in
495 /// ASTResultSynthesizer::SynthesizeBodyResult)
497 llvm::GlobalVariable *m_reloc_placeholder; ///< A placeholder that will be
498 ///replaced by a pointer to the
500 /// location of the static allocation.
502 /// UnfoldConstant operates on a constant [Old] which has just been replaced
503 /// with a value [New]. We assume that new_value has been properly placed
504 /// early in the function, in front of the first instruction in the entry
505 /// basic block [FirstEntryInstruction].
507 /// UnfoldConstant reads through the uses of Old and replaces Old in those
508 /// uses with New. Where those uses are constants, the function generates
509 /// new instructions to compute the result of the new, non-constant
510 /// expression and places them before FirstEntryInstruction. These
511 /// instructions replace the constant uses, so UnfoldConstant calls itself
512 /// recursively for those.
514 /// \param[in] llvm_function
515 /// The function currently being processed.
518 /// True on success; false otherwise
520 class FunctionValueCache {
522 typedef std::function<llvm::Value *(llvm::Function *)> Maker;
524 FunctionValueCache(Maker const &maker);
525 ~FunctionValueCache();
526 llvm::Value *GetValue(llvm::Function *function);
530 typedef std::map<llvm::Function *, llvm::Value *> FunctionValueMap;
531 FunctionValueMap m_values;
534 FunctionValueCache m_entry_instruction_finder;
536 static bool UnfoldConstant(llvm::Constant *old_constant,
537 llvm::Function *llvm_function,
538 FunctionValueCache &value_maker,
539 FunctionValueCache &entry_instruction_finder,
540 lldb_private::Stream &error_stream);
542 /// Construct a reference to m_reloc_placeholder with a given type and
543 /// offset. This typically happens after inserting data into
544 /// m_data_allocator.
547 /// The type of the value being loaded.
549 /// \param[in] offset
550 /// The offset of the value from the base of m_data_allocator.
553 /// The Constant for the reference, usually a ConstantExpr.
554 llvm::Constant *BuildRelocation(llvm::Type *type, uint64_t offset);
556 /// Commit the allocation in m_data_allocator and use its final location to
557 /// replace m_reloc_placeholder.
559 /// \param[in] module
560 /// The module that m_data_allocator resides in
563 /// True on success; false otherwise
564 bool CompleteDataAllocation();
567 #endif // liblldb_IRForTarget_h_