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