ClangExpressionDeclMap.h revision 293127
1//===-- ClangExpressionDeclMap.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_ClangExpressionDeclMap_h_
11#define liblldb_ClangExpressionDeclMap_h_
12
13// C Includes
14#include <signal.h>
15#include <stdint.h>
16
17// C++ Includes
18#include <vector>
19
20#include "ClangExpressionVariable.h"
21#include "ClangASTSource.h"
22
23// Other libraries and framework includes
24// Project includes
25#include "llvm/ADT/DenseMap.h"
26#include "clang/AST/Decl.h"
27#include "lldb/lldb-public.h"
28#include "lldb/Core/ClangForward.h"
29#include "lldb/Core/Value.h"
30#include "lldb/Expression/Materializer.h"
31#include "lldb/Symbol/TaggedASTType.h"
32#include "lldb/Symbol/SymbolContext.h"
33#include "lldb/Target/ExecutionContext.h"
34
35namespace lldb_private {
36
37//----------------------------------------------------------------------
38/// @class ClangExpressionDeclMap ClangExpressionDeclMap.h "lldb/Expression/ClangExpressionDeclMap.h"
39/// @brief Manages named entities that are defined in LLDB's debug information.
40///
41/// The Clang parser uses the ClangASTSource as an interface to request named
42/// entities from outside an expression.  The ClangASTSource reports back, listing
43/// all possible objects corresponding to a particular name.  But it in turn
44/// relies on ClangExpressionDeclMap, which performs several important functions.
45///
46/// First, it records what variables and functions were looked up and what Decls
47/// were returned for them.
48///
49/// Second, it constructs a struct on behalf of IRForTarget, recording which
50/// variables should be placed where and relaying this information back so that
51/// IRForTarget can generate context-independent code.
52///
53/// Third, it "materializes" this struct on behalf of the expression command,
54/// finding the current values of each variable and placing them into the
55/// struct so that it can be passed to the JITted version of the IR.
56///
57/// Fourth and finally, it "dematerializes" the struct after the JITted code has
58/// has executed, placing the new values back where it found the old ones.
59//----------------------------------------------------------------------
60class ClangExpressionDeclMap :
61    public ClangASTSource
62{
63public:
64    //------------------------------------------------------------------
65    /// Constructor
66    ///
67    /// Initializes class variables.
68    ///
69    /// @param[in] keep_result_in_memory
70    ///     If true, inhibits the normal deallocation of the memory for
71    ///     the result persistent variable, and instead marks the variable
72    ///     as persisting.
73    ///
74    /// @param[in] delegate
75    ///     If non-NULL, use this delegate to report result values.  This
76    ///     allows the client ClangUserExpression to report a result.
77    ///
78    /// @param[in] exe_ctx
79    ///     The execution context to use when parsing.
80    //------------------------------------------------------------------
81    ClangExpressionDeclMap (bool keep_result_in_memory,
82                            Materializer::PersistentVariableDelegate *result_delegate,
83                            ExecutionContext &exe_ctx);
84
85    //------------------------------------------------------------------
86    /// Destructor
87    //------------------------------------------------------------------
88    ~ClangExpressionDeclMap() override;
89
90    //------------------------------------------------------------------
91    /// Enable the state needed for parsing and IR transformation.
92    ///
93    /// @param[in] exe_ctx
94    ///     The execution context to use when finding types for variables.
95    ///     Also used to find a "scratch" AST context to store result types.
96    ///
97    /// @param[in] materializer
98    ///     If non-NULL, the materializer to populate with information about
99    ///     the variables to use
100    ///
101    /// @return
102    ///     True if parsing is possible; false if it is unsafe to continue.
103    //------------------------------------------------------------------
104    bool
105    WillParse (ExecutionContext &exe_ctx,
106               Materializer *materializer);
107
108    void
109    InstallCodeGenerator (clang::ASTConsumer *code_gen);
110
111    //------------------------------------------------------------------
112    /// [Used by ClangExpressionParser] For each variable that had an unknown
113    ///     type at the beginning of parsing, determine its final type now.
114    ///
115    /// @return
116    ///     True on success; false otherwise.
117    //------------------------------------------------------------------
118    bool
119    ResolveUnknownTypes();
120
121    //------------------------------------------------------------------
122    /// Disable the state needed for parsing and IR transformation.
123    //------------------------------------------------------------------
124    void
125    DidParse ();
126
127    //------------------------------------------------------------------
128    /// [Used by IRForTarget] Add a variable to the list of persistent
129    ///     variables for the process.
130    ///
131    /// @param[in] decl
132    ///     The Clang declaration for the persistent variable, used for
133    ///     lookup during parsing.
134    ///
135    /// @param[in] name
136    ///     The name of the persistent variable, usually $something.
137    ///
138    /// @param[in] type
139    ///     The type of the variable, in the Clang parser's context.
140    ///
141    /// @return
142    ///     True on success; false otherwise.
143    //------------------------------------------------------------------
144    bool
145    AddPersistentVariable (const clang::NamedDecl *decl,
146                           const ConstString &name,
147                           TypeFromParser type,
148                           bool is_result,
149                           bool is_lvalue);
150
151    //------------------------------------------------------------------
152    /// [Used by IRForTarget] Add a variable to the struct that needs to
153    ///     be materialized each time the expression runs.
154    ///
155    /// @param[in] decl
156    ///     The Clang declaration for the variable.
157    ///
158    /// @param[in] name
159    ///     The name of the variable.
160    ///
161    /// @param[in] value
162    ///     The LLVM IR value for this variable.
163    ///
164    /// @param[in] size
165    ///     The size of the variable in bytes.
166    ///
167    /// @param[in] alignment
168    ///     The required alignment of the variable in bytes.
169    ///
170    /// @return
171    ///     True on success; false otherwise.
172    //------------------------------------------------------------------
173    bool
174    AddValueToStruct (const clang::NamedDecl *decl,
175                      const ConstString &name,
176                      llvm::Value *value,
177                      size_t size,
178                      lldb::offset_t alignment);
179
180    //------------------------------------------------------------------
181    /// [Used by IRForTarget] Finalize the struct, laying out the position
182    /// of each object in it.
183    ///
184    /// @return
185    ///     True on success; false otherwise.
186    //------------------------------------------------------------------
187    bool
188    DoStructLayout ();
189
190    //------------------------------------------------------------------
191    /// [Used by IRForTarget] Get general information about the laid-out
192    /// struct after DoStructLayout() has been called.
193    ///
194    /// @param[out] num_elements
195    ///     The number of elements in the struct.
196    ///
197    /// @param[out] size
198    ///     The size of the struct, in bytes.
199    ///
200    /// @param[out] alignment
201    ///     The alignment of the struct, in bytes.
202    ///
203    /// @return
204    ///     True if the information could be retrieved; false otherwise.
205    //------------------------------------------------------------------
206    bool
207    GetStructInfo (uint32_t &num_elements,
208                   size_t &size,
209                   lldb::offset_t &alignment);
210
211    //------------------------------------------------------------------
212    /// [Used by IRForTarget] Get specific information about one field
213    /// of the laid-out struct after DoStructLayout() has been called.
214    ///
215    /// @param[out] decl
216    ///     The parsed Decl for the field, as generated by ClangASTSource
217    ///     on ClangExpressionDeclMap's behalf.  In the case of the result
218    ///     value, this will have the name $__lldb_result even if the
219    ///     result value ends up having the name $1.  This is an
220    ///     implementation detail of IRForTarget.
221    ///
222    /// @param[out] value
223    ///     The IR value for the field (usually a GlobalVariable).  In
224    ///     the case of the result value, this will have the correct
225    ///     name ($1, for instance).  This is an implementation detail
226    ///     of IRForTarget.
227    ///
228    /// @param[out] offset
229    ///     The offset of the field from the beginning of the struct.
230    ///     As long as the struct is aligned according to its required
231    ///     alignment, this offset will align the field correctly.
232    ///
233    /// @param[out] name
234    ///     The name of the field as used in materialization.
235    ///
236    /// @param[in] index
237    ///     The index of the field about which information is requested.
238    ///
239    /// @return
240    ///     True if the information could be retrieved; false otherwise.
241    //------------------------------------------------------------------
242    bool
243    GetStructElement (const clang::NamedDecl *&decl,
244                      llvm::Value *&value,
245                      lldb::offset_t &offset,
246                      ConstString &name,
247                      uint32_t index);
248
249    //------------------------------------------------------------------
250    /// [Used by IRForTarget] Get information about a function given its
251    /// Decl.
252    ///
253    /// @param[in] decl
254    ///     The parsed Decl for the Function, as generated by ClangASTSource
255    ///     on ClangExpressionDeclMap's behalf.
256    ///
257    /// @param[out] ptr
258    ///     The absolute address of the function in the target.
259    ///
260    /// @return
261    ///     True if the information could be retrieved; false otherwise.
262    //------------------------------------------------------------------
263    bool
264    GetFunctionInfo (const clang::NamedDecl *decl,
265                     uint64_t &ptr);
266
267    //------------------------------------------------------------------
268    /// [Used by IRForTarget] Get the address of a function given nothing
269    /// but its name.  Some functions are needed but didn't get Decls made
270    /// during parsing -- specifically, sel_registerName is never called
271    /// in the generated IR but we need to call it nonetheless.
272    ///
273    /// @param[in] name
274    ///     The name of the function.
275    ///
276    /// @param[out] ptr
277    ///     The absolute address of the function in the target.
278    ///
279    /// @return
280    ///     True if the address could be retrieved; false otherwise.
281    //------------------------------------------------------------------
282    bool
283    GetFunctionAddress (const ConstString &name,
284                        uint64_t &ptr);
285
286    //------------------------------------------------------------------
287    /// [Used by IRForTarget] Get the address of a symbol given nothing
288    /// but its name.
289    ///
290    /// @param[in] target
291    ///     The target to find the symbol in.  If not provided,
292    ///     then the current parsing context's Target.
293    ///
294    /// @param[in] process
295    ///     The process to use.  For Objective-C symbols, the process's
296    ///     Objective-C language runtime may be queried if the process
297    ///     is non-NULL.
298    ///
299    /// @param[in] name
300    ///     The name of the symbol.
301    ///
302    /// @param[in] module
303    ///     The module to limit the search to. This can be NULL
304    ///
305    /// @return
306    ///     Valid load address for the symbol
307    //------------------------------------------------------------------
308    lldb::addr_t
309    GetSymbolAddress (Target &target,
310                      Process *process,
311                      const ConstString &name,
312                      lldb::SymbolType symbol_type,
313                      Module *module = NULL);
314
315    lldb::addr_t
316    GetSymbolAddress (const ConstString &name,
317                      lldb::SymbolType symbol_type);
318
319    //------------------------------------------------------------------
320    /// [Used by IRInterpreter] Get basic target information.
321    ///
322    /// @param[out] byte_order
323    ///     The byte order of the target.
324    ///
325    /// @param[out] address_byte_size
326    ///     The size of a pointer in bytes.
327    ///
328    /// @return
329    ///     True if the information could be determined; false
330    ///     otherwise.
331    //------------------------------------------------------------------
332    struct TargetInfo
333    {
334        lldb::ByteOrder byte_order;
335        size_t address_byte_size;
336
337        TargetInfo() :
338            byte_order(lldb::eByteOrderInvalid),
339            address_byte_size(0)
340        {
341        }
342
343        bool IsValid()
344        {
345            return (byte_order != lldb::eByteOrderInvalid &&
346                    address_byte_size != 0);
347        }
348    };
349    TargetInfo GetTargetInfo();
350
351    //------------------------------------------------------------------
352    /// [Used by ClangASTSource] Find all entities matching a given name,
353    /// using a NameSearchContext to make Decls for them.
354    ///
355    /// @param[in] context
356    ///     The NameSearchContext that can construct Decls for this name.
357    ///
358    /// @return
359    ///     True on success; false otherwise.
360    //------------------------------------------------------------------
361    void
362    FindExternalVisibleDecls(NameSearchContext &context) override;
363
364    //------------------------------------------------------------------
365    /// Find all entities matching a given name in a given module/namespace,
366    /// using a NameSearchContext to make Decls for them.
367    ///
368    /// @param[in] context
369    ///     The NameSearchContext that can construct Decls for this name.
370    ///
371    /// @param[in] module
372    ///     If non-NULL, the module to query.
373    ///
374    /// @param[in] namespace_decl
375    ///     If valid and module is non-NULL, the parent namespace.
376    ///
377    /// @param[in] name
378    ///     The name as a plain C string.  The NameSearchContext contains
379    ///     a DeclarationName for the name so at first the name may seem
380    ///     redundant, but ClangExpressionDeclMap operates in RTTI land so
381    ///     it can't access DeclarationName.
382    ///
383    /// @param[in] current_id
384    ///     The ID for the current FindExternalVisibleDecls invocation,
385    ///     for logging purposes.
386    ///
387    /// @return
388    ///     True on success; false otherwise.
389    //------------------------------------------------------------------
390    void
391    FindExternalVisibleDecls (NameSearchContext &context,
392                              lldb::ModuleSP module,
393                              CompilerDeclContext &namespace_decl,
394                              unsigned int current_id);
395private:
396    ExpressionVariableList      m_found_entities;           ///< All entities that were looked up for the parser.
397    ExpressionVariableList      m_struct_members;           ///< All entities that need to be placed in the struct.
398    bool                        m_keep_result_in_memory;    ///< True if result persistent variables generated by this expression should stay in memory.
399    Materializer::PersistentVariableDelegate *m_result_delegate;  ///< If non-NULL, used to report expression results to ClangUserExpression.
400
401    //----------------------------------------------------------------------
402    /// The following values should not live beyond parsing
403    //----------------------------------------------------------------------
404    class ParserVars
405    {
406    public:
407        ParserVars(ClangExpressionDeclMap &decl_map) :
408            m_decl_map(decl_map)
409        {
410        }
411
412        Target *
413        GetTarget()
414        {
415            if (m_exe_ctx.GetTargetPtr())
416                return m_exe_ctx.GetTargetPtr();
417            else if (m_sym_ctx.target_sp)
418                m_sym_ctx.target_sp.get();
419            return NULL;
420        }
421
422        ExecutionContext            m_exe_ctx;                      ///< The execution context to use when parsing.
423        SymbolContext               m_sym_ctx;                      ///< The symbol context to use in finding variables and types.
424        ClangPersistentVariables   *m_persistent_vars = nullptr;    ///< The persistent variables for the process.
425        bool                        m_enable_lookups = false;       ///< Set to true during parsing if we have found the first "$__lldb" name.
426        TargetInfo                  m_target_info;                  ///< Basic information about the target.
427        Materializer               *m_materializer = nullptr;       ///< If non-NULL, the materializer to use when reporting used variables.
428        clang::ASTConsumer         *m_code_gen = nullptr;           ///< If non-NULL, a code generator that receives new top-level functions.
429    private:
430        ClangExpressionDeclMap     &m_decl_map;
431        DISALLOW_COPY_AND_ASSIGN (ParserVars);
432    };
433
434    std::unique_ptr<ParserVars> m_parser_vars;
435
436    //----------------------------------------------------------------------
437    /// Activate parser-specific variables
438    //----------------------------------------------------------------------
439    void
440    EnableParserVars()
441    {
442        if (!m_parser_vars.get())
443            m_parser_vars.reset(new ParserVars(*this));
444    }
445
446    //----------------------------------------------------------------------
447    /// Deallocate parser-specific variables
448    //----------------------------------------------------------------------
449    void
450    DisableParserVars()
451    {
452        m_parser_vars.reset();
453    }
454
455    //----------------------------------------------------------------------
456    /// The following values contain layout information for the materialized
457    /// struct, but are not specific to a single materialization
458    //----------------------------------------------------------------------
459    struct StructVars {
460        StructVars() :
461            m_struct_alignment(0),
462            m_struct_size(0),
463            m_struct_laid_out(false),
464            m_result_name(),
465            m_object_pointer_type(NULL, NULL)
466        {
467        }
468
469        lldb::offset_t              m_struct_alignment;         ///< The alignment of the struct in bytes.
470        size_t                      m_struct_size;              ///< The size of the struct in bytes.
471        bool                        m_struct_laid_out;          ///< True if the struct has been laid out and the layout is valid (that is, no new fields have been added since).
472        ConstString                 m_result_name;              ///< The name of the result variable ($1, for example)
473        TypeFromUser                m_object_pointer_type;      ///< The type of the "this" variable, if one exists
474    };
475
476    std::unique_ptr<StructVars> m_struct_vars;
477
478    //----------------------------------------------------------------------
479    /// Activate struct variables
480    //----------------------------------------------------------------------
481    void
482    EnableStructVars()
483    {
484        if (!m_struct_vars.get())
485            m_struct_vars.reset(new struct StructVars);
486    }
487
488    //----------------------------------------------------------------------
489    /// Deallocate struct variables
490    //----------------------------------------------------------------------
491    void
492    DisableStructVars()
493    {
494        m_struct_vars.reset();
495    }
496
497    //----------------------------------------------------------------------
498    /// Get this parser's ID for use in extracting parser- and JIT-specific
499    /// data from persistent variables.
500    //----------------------------------------------------------------------
501    uint64_t
502    GetParserID()
503    {
504        return (uint64_t)this;
505    }
506
507    //------------------------------------------------------------------
508    /// Given a target, find a data symbol that has the given name.
509    ///
510    /// @param[in] target
511    ///     The target to use as the basis for the search.
512    ///
513    /// @param[in] name
514    ///     The name as a plain C string.
515    ///
516    /// @param[in] module
517    ///     The module to limit the search to. This can be NULL
518    ///
519    /// @return
520    ///     The LLDB Symbol found, or NULL if none was found.
521    //------------------------------------------------------------------
522    const Symbol *
523    FindGlobalDataSymbol (Target &target,
524                          const ConstString &name,
525                          Module *module = NULL);
526
527    //------------------------------------------------------------------
528    /// Given a target, find a variable that matches the given name and
529    /// type.
530    ///
531    /// @param[in] target
532    ///     The target to use as a basis for finding the variable.
533    ///
534    /// @param[in] module
535    ///     If non-NULL, the module to search.
536    ///
537    /// @param[in] name
538    ///     The name as a plain C string.
539    ///
540    /// @param[in] namespace_decl
541    ///     If non-NULL and module is non-NULL, the parent namespace.
542    ///
543    /// @param[in] type
544    ///     The required type for the variable.  This function may be called
545    ///     during parsing, in which case we don't know its type; hence the
546    ///     default.
547    ///
548    /// @return
549    ///     The LLDB Variable found, or NULL if none was found.
550    //------------------------------------------------------------------
551    lldb::VariableSP
552    FindGlobalVariable (Target &target,
553                        lldb::ModuleSP &module,
554                        const ConstString &name,
555                        CompilerDeclContext *namespace_decl,
556                        TypeFromUser *type = NULL);
557
558    //------------------------------------------------------------------
559    /// Get the value of a variable in a given execution context and return
560    /// the associated Types if needed.
561    ///
562    /// @param[in] var
563    ///     The variable to evaluate.
564    ///
565    /// @param[out] var_location
566    ///     The variable location value to fill in
567    ///
568    /// @param[out] found_type
569    ///     The type of the found value, as it was found in the user process.
570    ///     This is only useful when the variable is being inspected on behalf
571    ///     of the parser, hence the default.
572    ///
573    /// @param[out] parser_type
574    ///     The type of the found value, as it was copied into the parser's
575    ///     AST context.  This is only useful when the variable is being
576    ///     inspected on behalf of the parser, hence the default.
577    ///
578    /// @param[in] decl
579    ///     The Decl to be looked up.
580    ///
581    /// @return
582    ///     Return true if the value was successfully filled in.
583    //------------------------------------------------------------------
584    bool
585    GetVariableValue (lldb::VariableSP &var,
586                      lldb_private::Value &var_location,
587                      TypeFromUser *found_type = NULL,
588                      TypeFromParser *parser_type = NULL);
589
590    //------------------------------------------------------------------
591    /// Use the NameSearchContext to generate a Decl for the given LLDB
592    /// Variable, and put it in the Tuple list.
593    ///
594    /// @param[in] context
595    ///     The NameSearchContext to use when constructing the Decl.
596    ///
597    /// @param[in] var
598    ///     The LLDB Variable that needs a Decl.
599    ///
600    /// @param[in] valobj
601    ///     The LLDB ValueObject for that variable.
602    //------------------------------------------------------------------
603    void
604    AddOneVariable (NameSearchContext &context,
605                    lldb::VariableSP var,
606                    lldb::ValueObjectSP valobj,
607                    unsigned int current_id);
608
609    //------------------------------------------------------------------
610    /// Use the NameSearchContext to generate a Decl for the given
611    /// persistent variable, and put it in the list of found entities.
612    ///
613    /// @param[in] context
614    ///     The NameSearchContext to use when constructing the Decl.
615    ///
616    /// @param[in] pvar
617    ///     The persistent variable that needs a Decl.
618    ///
619    /// @param[in] current_id
620    ///     The ID of the current invocation of FindExternalVisibleDecls
621    ///     for logging purposes.
622    //------------------------------------------------------------------
623    void
624    AddOneVariable (NameSearchContext &context,
625                    lldb::ExpressionVariableSP &pvar_sp,
626                    unsigned int current_id);
627
628    //------------------------------------------------------------------
629    /// Use the NameSearchContext to generate a Decl for the given LLDB
630    /// symbol (treated as a variable), and put it in the list of found
631    /// entities.
632    ///
633    /// @param[in] context
634    ///     The NameSearchContext to use when constructing the Decl.
635    ///
636    /// @param[in] var
637    ///     The LLDB Variable that needs a Decl.
638    //------------------------------------------------------------------
639    void
640    AddOneGenericVariable (NameSearchContext &context,
641                           const Symbol &symbol,
642                           unsigned int current_id);
643
644    //------------------------------------------------------------------
645    /// Use the NameSearchContext to generate a Decl for the given
646    /// function.  (Functions are not placed in the Tuple list.)  Can
647    /// handle both fully typed functions and generic functions.
648    ///
649    /// @param[in] context
650    ///     The NameSearchContext to use when constructing the Decl.
651    ///
652    /// @param[in] fun
653    ///     The Function that needs to be created.  If non-NULL, this is
654    ///     a fully-typed function.
655    ///
656    /// @param[in] sym
657    ///     The Symbol that corresponds to a function that needs to be
658    ///     created with generic type (unitptr_t foo(...)).
659    //------------------------------------------------------------------
660    void
661    AddOneFunction (NameSearchContext &context,
662                    Function *fun,
663                    Symbol *sym,
664                    unsigned int current_id);
665
666    //------------------------------------------------------------------
667    /// Use the NameSearchContext to generate a Decl for the given
668    /// register.
669    ///
670    /// @param[in] context
671    ///     The NameSearchContext to use when constructing the Decl.
672    ///
673    /// @param[in] reg_info
674    ///     The information corresponding to that register.
675    //------------------------------------------------------------------
676    void
677    AddOneRegister (NameSearchContext &context,
678                    const RegisterInfo *reg_info,
679                    unsigned int current_id);
680
681    //------------------------------------------------------------------
682    /// Use the NameSearchContext to generate a Decl for the given
683    /// type.  (Types are not placed in the Tuple list.)
684    ///
685    /// @param[in] context
686    ///     The NameSearchContext to use when constructing the Decl.
687    ///
688    /// @param[in] type
689    ///     The type that needs to be created.
690    //------------------------------------------------------------------
691    void
692    AddOneType (NameSearchContext &context,
693                TypeFromUser &type,
694                unsigned int current_id);
695
696    //------------------------------------------------------------------
697    /// Generate a Decl for "*this" and add a member function declaration
698    /// to it for the expression, then report it.
699    ///
700    /// @param[in] context
701    ///     The NameSearchContext to use when constructing the Decl.
702    ///
703    /// @param[in] type
704    ///     The type for *this.
705    //------------------------------------------------------------------
706    void
707    AddThisType(NameSearchContext &context,
708                TypeFromUser &type,
709                unsigned int current_id);
710};
711
712} // namespace lldb_private
713
714#endif // liblldb_ClangExpressionDeclMap_h_
715