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 LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_IRFORTARGET_H
11 #define LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_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"
44 namespace lldb_private
{
45 class ClangExpressionDeclMap
;
46 class IRExecutionUnit
;
50 /// \class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h"
51 /// Transforms the IR for a function to run in the target
53 /// Once an expression has been parsed and converted to IR, it can run in two
54 /// contexts: interpreted by LLDB as a DWARF location expression, or compiled
55 /// by the JIT and inserted into the target process for execution.
57 /// IRForTarget makes the second possible, by applying a series of
58 /// transformations to the IR which make it relocatable. These
59 /// transformations are discussed in more detail next to their relevant
63 enum class LookupResult
{ Success
, Fail
, Ignore
};
67 /// \param[in] decl_map
68 /// The list of externally-referenced variables for the expression,
69 /// for use in looking up globals and allocating the argument
70 /// struct. See the documentation for ClangExpressionDeclMap.
72 /// \param[in] resolve_vars
73 /// True if the external variable references (including persistent
74 /// variables) should be resolved. If not, only external functions
77 /// \param[in] execution_unit
78 /// The holder for raw data associated with the expression.
80 /// \param[in] error_stream
81 /// If non-NULL, a stream on which errors can be printed.
83 /// \param[in] func_name
84 /// The name of the function to prepare for execution in the target.
85 IRForTarget(lldb_private::ClangExpressionDeclMap
*decl_map
, bool resolve_vars
,
86 lldb_private::IRExecutionUnit
&execution_unit
,
87 lldb_private::Stream
&error_stream
,
88 const char *func_name
= "$__lldb_expr");
90 /// Run this IR transformer on a single module
92 /// Implementation of the llvm::ModulePass::runOnModule() function.
94 /// \param[in] llvm_module
95 /// The module to run on. This module is searched for the function
96 /// $__lldb_expr, and that function is passed to the passes one by
100 /// True on success; false otherwise
101 bool runOnModule(llvm::Module
&llvm_module
);
104 /// Ensures that the current function's linkage is set to external.
105 /// Otherwise the JIT may not return an address for it.
107 /// \param[in] llvm_function
108 /// The function whose linkage is to be fixed.
111 /// True on success; false otherwise.
112 bool FixFunctionLinkage(llvm::Function
&llvm_function
);
114 /// A function-level pass to take the generated global value
115 /// $__lldb_expr_result and make it into a persistent variable. Also see
116 /// ASTResultSynthesizer.
118 /// Find the NamedDecl corresponding to a Value. This interface is exposed
119 /// for the IR interpreter.
121 /// \param[in] global_val
122 /// The global entity to search for
124 /// \param[in] module
125 /// The module containing metadata to search
128 /// The corresponding variable declaration
130 static clang::NamedDecl
*DeclForGlobal(const llvm::GlobalValue
*global_val
,
131 llvm::Module
*module
);
134 clang::NamedDecl
*DeclForGlobal(llvm::GlobalValue
*global
);
136 /// The top-level pass implementation
138 /// \param[in] llvm_function
139 /// The function currently being processed.
142 /// True on success; false otherwise
143 bool CreateResultVariable(llvm::Function
&llvm_function
);
145 /// A module-level pass to find Objective-C constant strings and
146 /// transform them to calls to CFStringCreateWithBytes.
148 /// Rewrite a single Objective-C constant string.
151 /// The constant NSString to be transformed
154 /// The constant C string inside the NSString. This will be
155 /// passed as the bytes argument to CFStringCreateWithBytes.
158 /// True on success; false otherwise
159 bool RewriteObjCConstString(llvm::GlobalVariable
*NSStr
,
160 llvm::GlobalVariable
*CStr
);
162 /// The top-level pass implementation
165 /// True on success; false otherwise
166 bool RewriteObjCConstStrings();
168 /// A basic block-level pass to find all Objective-C method calls and
169 /// rewrite them to use sel_registerName instead of statically allocated
170 /// selectors. The reason is that the selectors are created on the
171 /// assumption that the Objective-C runtime will scan the appropriate
172 /// section and prepare them. This doesn't happen when code is copied into
173 /// the target, though, and there's no easy way to induce the runtime to
174 /// scan them. So instead we get our selectors from sel_registerName.
176 /// Replace a single selector reference
178 /// \param[in] selector_load
179 /// The load of the statically-allocated selector.
182 /// True on success; false otherwise
183 bool RewriteObjCSelector(llvm::Instruction
*selector_load
);
185 /// The top-level pass implementation
187 /// \param[in] basic_block
188 /// The basic block currently being processed.
191 /// True on success; false otherwise
192 bool RewriteObjCSelectors(llvm::BasicBlock
&basic_block
);
194 /// A basic block-level pass to find all newly-declared persistent
195 /// variables and register them with the ClangExprDeclMap. This allows them
196 /// to be materialized and dematerialized like normal external variables.
197 /// Before transformation, these persistent variables look like normal
198 /// locals, so they have an allocation. This pass excises these allocations
199 /// and makes references look like external references where they will be
200 /// resolved -- like all other external references -- by ResolveExternals().
202 /// Handle a single allocation of a persistent variable
204 /// \param[in] persistent_alloc
205 /// The allocation of the persistent variable.
208 /// True on success; false otherwise
209 bool RewritePersistentAlloc(llvm::Instruction
*persistent_alloc
);
211 /// The top-level pass implementation
213 /// \param[in] basic_block
214 /// The basic block currently being processed.
215 bool RewritePersistentAllocs(llvm::BasicBlock
&basic_block
);
217 /// A function-level pass to find all external variables and functions
218 /// used in the IR. Each found external variable is added to the struct,
219 /// and each external function is resolved in place, its call replaced with
220 /// a call to a function pointer whose value is the address of the function
221 /// in the target process.
223 /// Handle a single externally-defined variable
229 /// True on success; false otherwise
230 bool MaybeHandleVariable(llvm::Value
*value
);
232 /// Handle a single externally-defined symbol
234 /// \param[in] symbol
238 /// True on success; false otherwise
239 bool HandleSymbol(llvm::Value
*symbol
);
241 /// Handle a single externally-defined Objective-C class
243 /// \param[in] classlist_reference
244 /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n"
245 /// where n (if present) is an index.
248 /// True on success; false otherwise
249 bool HandleObjCClass(llvm::Value
*classlist_reference
);
251 /// Handle all the arguments to a function call
253 /// \param[in] call_inst
254 /// The call instruction.
257 /// True on success; false otherwise
258 bool MaybeHandleCallArguments(llvm::CallInst
*call_inst
);
260 /// Resolve variable references in calls to external functions
262 /// \param[in] basic_block
263 /// The basic block currently being processed.
266 /// True on success; false otherwise
267 bool ResolveCalls(llvm::BasicBlock
&basic_block
);
269 /// Remove calls to __cxa_atexit, which should never be generated by
272 /// \param[in] basic_block
273 /// The basic block currently being processed.
276 /// True if the scan was successful; false if some operation
278 bool RemoveCXAAtExit(llvm::BasicBlock
&basic_block
);
280 /// The top-level pass implementation
282 /// \param[in] llvm_function
283 /// The function currently being processed.
286 /// True on success; false otherwise
287 bool ResolveExternals(llvm::Function
&llvm_function
);
289 /// A basic block-level pass to excise guard variables from the code.
290 /// The result for the function is passed through Clang as a static
291 /// variable. Static variables normally have guard variables to ensure that
292 /// they are only initialized once.
294 /// Rewrite a load to a guard variable to return constant 0.
296 /// \param[in] guard_load
297 /// The load instruction to zero out.
298 void TurnGuardLoadIntoZero(llvm::Instruction
*guard_load
);
300 /// The top-level pass implementation
302 /// \param[in] basic_block
303 /// The basic block currently being processed.
306 /// True on success; false otherwise
307 bool RemoveGuards(llvm::BasicBlock
&basic_block
);
309 /// A function-level pass to make all external variable references
310 /// point at the correct offsets from the void* passed into the function.
311 /// ClangExpressionDeclMap::DoStructLayout() must be called beforehand, so
312 /// that the offsets are valid.
314 /// The top-level pass implementation
316 /// \param[in] llvm_function
317 /// The function currently being processed.
320 /// True on success; false otherwise
321 bool ReplaceVariables(llvm::Function
&llvm_function
);
323 /// True if external variable references and persistent variable references
324 /// should be resolved
326 /// The name of the function to translate
327 lldb_private::ConstString m_func_name
;
328 /// The name of the result variable ($0, $1, ...)
329 lldb_private::ConstString m_result_name
;
330 /// The type of the result variable.
331 lldb_private::TypeFromParser m_result_type
;
332 /// The module being processed, or NULL if that has not been determined yet.
333 llvm::Module
*m_module
= nullptr;
334 /// The target data for the module being processed, or NULL if there is no
336 std::unique_ptr
<llvm::DataLayout
> m_target_data
;
337 /// The DeclMap containing the Decls
338 lldb_private::ClangExpressionDeclMap
*m_decl_map
;
339 /// The address of the function CFStringCreateWithBytes, cast to the
340 /// appropriate function pointer type
341 llvm::FunctionCallee m_CFStringCreateWithBytes
;
342 /// The address of the function sel_registerName, cast to the appropriate
343 /// function pointer type.
344 llvm::FunctionCallee m_sel_registerName
;
345 /// The type of an integer large enough to hold a pointer.
346 llvm::IntegerType
*m_intptr_ty
= nullptr;
347 /// The stream on which errors should be printed.
348 lldb_private::Stream
&m_error_stream
;
349 /// The execution unit containing the IR being created.
350 lldb_private::IRExecutionUnit
&m_execution_unit
;
351 /// True if the function's result in the AST is a pointer (see comments in
352 /// ASTResultSynthesizer::SynthesizeBodyResult)
353 bool m_result_is_pointer
= false;
355 class FunctionValueCache
{
357 typedef std::function
<llvm::Value
*(llvm::Function
*)> Maker
;
359 FunctionValueCache(Maker
const &maker
);
360 ~FunctionValueCache();
361 llvm::Value
*GetValue(llvm::Function
*function
);
365 typedef std::map
<llvm::Function
*, llvm::Value
*> FunctionValueMap
;
366 FunctionValueMap m_values
;
369 FunctionValueCache m_entry_instruction_finder
;
371 /// UnfoldConstant operates on a constant [Old] which has just been replaced
372 /// with a value [New]. We assume that new_value has been properly placed
373 /// early in the function, in front of the first instruction in the entry
374 /// basic block [FirstEntryInstruction].
376 /// UnfoldConstant reads through the uses of Old and replaces Old in those
377 /// uses with New. Where those uses are constants, the function generates
378 /// new instructions to compute the result of the new, non-constant
379 /// expression and places them before FirstEntryInstruction. These
380 /// instructions replace the constant uses, so UnfoldConstant calls itself
381 /// recursively for those.
384 /// True on success; false otherwise
385 static bool UnfoldConstant(llvm::Constant
*old_constant
,
386 llvm::Function
*llvm_function
,
387 FunctionValueCache
&value_maker
,
388 FunctionValueCache
&entry_instruction_finder
,
389 lldb_private::Stream
&error_stream
);
392 #endif // LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_IRFORTARGET_H