1 //===-- Function.h ----------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef liblldb_Function_h_
10 #define liblldb_Function_h_
11 
12 #include "lldb/Core/AddressRange.h"
13 #include "lldb/Core/Mangled.h"
14 #include "lldb/Expression/DWARFExpression.h"
15 #include "lldb/Symbol/Block.h"
16 #include "lldb/Symbol/Declaration.h"
17 #include "lldb/Utility/UserID.h"
18 #include "llvm/ADT/ArrayRef.h"
19 
20 namespace lldb_private {
21 
22 class ExecutionContext;
23 
24 /// \class FunctionInfo Function.h "lldb/Symbol/Function.h"
25 /// A class that contains generic function information.
26 ///
27 /// This provides generic function information that gets reused between inline
28 /// functions and function types.
29 class FunctionInfo {
30 public:
31   /// Construct with the function method name and optional declaration
32   /// information.
33   ///
34   /// \param[in] name
35   ///     A C string name for the method name for this function. This
36   ///     value should not be the mangled named, but the simple method
37   ///     name.
38   ///
39   /// \param[in] decl_ptr
40   ///     Optional declaration information that describes where the
41   ///     function was declared. This can be NULL.
42   FunctionInfo(const char *name, const Declaration *decl_ptr);
43 
44   /// Construct with the function method name and optional declaration
45   /// information.
46   ///
47   /// \param[in] name
48   ///     A name for the method name for this function. This value
49   ///     should not be the mangled named, but the simple method name.
50   ///
51   /// \param[in] decl_ptr
52   ///     Optional declaration information that describes where the
53   ///     function was declared. This can be NULL.
54   FunctionInfo(ConstString name, const Declaration *decl_ptr);
55 
56   /// Destructor.
57   ///
58   /// The destructor is virtual since classes inherit from this class.
59   virtual ~FunctionInfo();
60 
61   /// Compare two function information objects.
62   ///
63   /// First compares the method names, and if equal, then compares the
64   /// declaration information.
65   ///
66   /// \param[in] lhs
67   ///     The Left Hand Side const FunctionInfo object reference.
68   ///
69   /// \param[in] rhs
70   ///     The Right Hand Side const FunctionInfo object reference.
71   ///
72   /// \return
73   ///     -1 if lhs < rhs
74   ///     0 if lhs == rhs
75   ///     1 if lhs > rhs
76   static int Compare(const FunctionInfo &lhs, const FunctionInfo &rhs);
77 
78   /// Dump a description of this object to a Stream.
79   ///
80   /// Dump a description of the contents of this object to the supplied stream
81   /// \a s.
82   ///
83   /// \param[in] s
84   ///     The stream to which to dump the object description.
85   void Dump(Stream *s, bool show_fullpaths) const;
86 
87   /// Get accessor for the declaration information.
88   ///
89   /// \return
90   ///     A reference to the declaration object.
91   Declaration &GetDeclaration();
92 
93   /// Get const accessor for the declaration information.
94   ///
95   /// \return
96   ///     A const reference to the declaration object.
97   const Declaration &GetDeclaration() const;
98 
99   /// Get accessor for the method name.
100   ///
101   /// \return
102   ///     A const reference to the method name object.
103   ConstString GetName() const;
104 
105   /// Get the memory cost of this object.
106   ///
107   /// \return
108   ///     The number of bytes that this object occupies in memory.
109   ///     The returned value does not include the bytes for any
110   ///     shared string values.
111   ///
112   /// \see ConstString::StaticMemorySize ()
113   virtual size_t MemorySize() const;
114 
115 protected:
116   // Member variables.
117   ConstString m_name;        ///< Function method name (not a mangled name).
118   Declaration m_declaration; ///< Information describing where this function
119                              ///information was defined.
120 };
121 
122 /// \class InlineFunctionInfo Function.h "lldb/Symbol/Function.h"
123 /// A class that describes information for an inlined function.
124 class InlineFunctionInfo : public FunctionInfo {
125 public:
126   /// Construct with the function method name, mangled name, and optional
127   /// declaration information.
128   ///
129   /// \param[in] name
130   ///     A C string name for the method name for this function. This
131   ///     value should not be the mangled named, but the simple method
132   ///     name.
133   ///
134   /// \param[in] mangled
135   ///     A C string name for the mangled name for this function. This
136   ///     value can be NULL if there is no mangled information.
137   ///
138   /// \param[in] decl_ptr
139   ///     Optional declaration information that describes where the
140   ///     function was declared. This can be NULL.
141   ///
142   /// \param[in] call_decl_ptr
143   ///     Optional calling location declaration information that
144   ///     describes from where this inlined function was called.
145   InlineFunctionInfo(const char *name, llvm::StringRef mangled,
146                      const Declaration *decl_ptr,
147                      const Declaration *call_decl_ptr);
148 
149   /// Construct with the function method name, mangled name, and optional
150   /// declaration information.
151   ///
152   /// \param[in] name
153   ///     A name for the method name for this function. This value
154   ///     should not be the mangled named, but the simple method name.
155   ///
156   /// \param[in] mangled
157   ///     A name for the mangled name for this function. This value
158   ///     can be empty if there is no mangled information.
159   ///
160   /// \param[in] decl_ptr
161   ///     Optional declaration information that describes where the
162   ///     function was declared. This can be NULL.
163   ///
164   /// \param[in] call_decl_ptr
165   ///     Optional calling location declaration information that
166   ///     describes from where this inlined function was called.
167   InlineFunctionInfo(ConstString name, const Mangled &mangled,
168                      const Declaration *decl_ptr,
169                      const Declaration *call_decl_ptr);
170 
171   /// Destructor.
172   ~InlineFunctionInfo() override;
173 
174   /// Compare two inlined function information objects.
175   ///
176   /// First compares the FunctionInfo objects, and if equal, compares the
177   /// mangled names.
178   ///
179   /// \param[in] lhs
180   ///     The Left Hand Side const InlineFunctionInfo object
181   ///     reference.
182   ///
183   /// \param[in] rhs
184   ///     The Right Hand Side const InlineFunctionInfo object
185   ///     reference.
186   ///
187   /// \return
188   ///     -1 if lhs < rhs
189   ///     0 if lhs == rhs
190   ///     1 if lhs > rhs
191   int Compare(const InlineFunctionInfo &lhs, const InlineFunctionInfo &rhs);
192 
193   /// Dump a description of this object to a Stream.
194   ///
195   /// Dump a description of the contents of this object to the supplied stream
196   /// \a s.
197   ///
198   /// \param[in] s
199   ///     The stream to which to dump the object description.
200   void Dump(Stream *s, bool show_fullpaths) const;
201 
202   void DumpStopContext(Stream *s, lldb::LanguageType language) const;
203 
204   ConstString GetName(lldb::LanguageType language) const;
205 
206   ConstString GetDisplayName(lldb::LanguageType language) const;
207 
208   /// Get accessor for the call site declaration information.
209   ///
210   /// \return
211   ///     A reference to the declaration object.
212   Declaration &GetCallSite();
213 
214   /// Get const accessor for the call site declaration information.
215   ///
216   /// \return
217   ///     A const reference to the declaration object.
218   const Declaration &GetCallSite() const;
219 
220   /// Get accessor for the mangled name object.
221   ///
222   /// \return
223   ///     A reference to the mangled name object.
224   Mangled &GetMangled();
225 
226   /// Get const accessor for the mangled name object.
227   ///
228   /// \return
229   ///     A const reference to the mangled name object.
230   const Mangled &GetMangled() const;
231 
232   /// Get the memory cost of this object.
233   ///
234   /// \return
235   ///     The number of bytes that this object occupies in memory.
236   ///     The returned value does not include the bytes for any
237   ///     shared string values.
238   ///
239   /// \see ConstString::StaticMemorySize ()
240   size_t MemorySize() const override;
241 
242 private:
243   // Member variables.
244   Mangled m_mangled; ///< Mangled inlined function name (can be empty if there
245                      ///is no mangled information).
246   Declaration m_call_decl;
247 };
248 
249 class Function;
250 
251 /// \class CallSiteParameter Function.h "lldb/Symbol/Function.h"
252 ///
253 /// Represent the locations of a parameter at a call site, both in the caller
254 /// and in the callee.
255 struct CallSiteParameter {
256   DWARFExpression LocationInCallee;
257   DWARFExpression LocationInCaller;
258 };
259 
260 /// A vector of \c CallSiteParameter.
261 using CallSiteParameterArray = llvm::SmallVector<CallSiteParameter, 0>;
262 
263 /// \class CallEdge Function.h "lldb/Symbol/Function.h"
264 ///
265 /// Represent a call made within a Function. This can be used to find a path
266 /// in the call graph between two functions, or to evaluate DW_OP_entry_value.
267 class CallEdge {
268 public:
269   virtual ~CallEdge() {}
270 
271   /// Get the callee's definition.
272   ///
273   /// Note that this might lazily invoke the DWARF parser. A register context
274   /// from the caller's activation is needed to find indirect call targets.
275   virtual Function *GetCallee(ModuleList &images,
276                               ExecutionContext &exe_ctx) = 0;
277 
278   /// Get the load PC address of the instruction which executes after the call
279   /// returns. Returns LLDB_INVALID_ADDRESS iff this is a tail call. \p caller
280   /// is the Function containing this call, and \p target is the Target which
281   /// made the call.
282   lldb::addr_t GetReturnPCAddress(Function &caller, Target &target) const;
283 
284   /// Like \ref GetReturnPCAddress, but returns an unslid function-local PC
285   /// offset.
286   lldb::addr_t GetUnresolvedReturnPCAddress() const { return return_pc; }
287 
288   /// Get the call site parameters available at this call edge.
289   llvm::ArrayRef<CallSiteParameter> GetCallSiteParameters() const {
290     return parameters;
291   }
292 
293 protected:
294   CallEdge(lldb::addr_t return_pc, CallSiteParameterArray &&parameters)
295       : return_pc(return_pc), parameters(std::move(parameters)) {}
296 
297   /// An invalid address if this is a tail call. Otherwise, the function-local
298   /// PC offset. Adding this PC offset to the function's base load address
299   /// gives the return PC for the call.
300   lldb::addr_t return_pc;
301 
302   CallSiteParameterArray parameters;
303 };
304 
305 /// A direct call site. Used to represent call sites where the address of the
306 /// callee is fixed (e.g. a function call in C in which the call target is not
307 /// a function pointer).
308 class DirectCallEdge : public CallEdge {
309 public:
310   /// Construct a call edge using a symbol name to identify the callee, and a
311   /// return PC within the calling function to identify a specific call site.
312   DirectCallEdge(const char *symbol_name, lldb::addr_t return_pc,
313                  CallSiteParameterArray &&parameters)
314       : CallEdge(return_pc, std::move(parameters)) {
315     lazy_callee.symbol_name = symbol_name;
316   }
317 
318   Function *GetCallee(ModuleList &images, ExecutionContext &exe_ctx) override;
319 
320 private:
321   void ParseSymbolFileAndResolve(ModuleList &images);
322 
323   // Used to describe a direct call.
324   //
325   // Either the callee's mangled name or its definition, discriminated by
326   // \ref resolved.
327   union {
328     const char *symbol_name;
329     Function *def;
330   } lazy_callee;
331 
332   /// Whether or not an attempt was made to find the callee's definition.
333   bool resolved = false;
334 };
335 
336 /// An indirect call site. Used to represent call sites where the address of
337 /// the callee is not fixed, e.g. a call to a C++ virtual function (where the
338 /// address is loaded out of a vtable), or a call to a function pointer in C.
339 class IndirectCallEdge : public CallEdge {
340 public:
341   /// Construct a call edge using a DWARFExpression to identify the callee, and
342   /// a return PC within the calling function to identify a specific call site.
343   IndirectCallEdge(DWARFExpression call_target, lldb::addr_t return_pc,
344                    CallSiteParameterArray &&parameters)
345       : CallEdge(return_pc, std::move(parameters)),
346         call_target(std::move(call_target)) {}
347 
348   Function *GetCallee(ModuleList &images, ExecutionContext &exe_ctx) override;
349 
350 private:
351   // Used to describe an indirect call.
352   //
353   // Specifies the location of the callee address in the calling frame.
354   DWARFExpression call_target;
355 };
356 
357 /// \class Function Function.h "lldb/Symbol/Function.h"
358 /// A class that describes a function.
359 ///
360 /// Functions belong to CompileUnit objects (Function::m_comp_unit), have
361 /// unique user IDs (Function::UserID), know how to reconstruct their symbol
362 /// context (Function::SymbolContextScope), have a specific function type
363 /// (Function::m_type_uid), have a simple method name (FunctionInfo::m_name),
364 /// be declared at a specific location (FunctionInfo::m_declaration), possibly
365 /// have mangled names (Function::m_mangled), an optional return type
366 /// (Function::m_type), and contains lexical blocks (Function::m_blocks).
367 ///
368 /// The function information is split into a few pieces:
369 ///     \li The concrete instance information
370 ///     \li The abstract information
371 ///
372 /// The abstract information is found in the function type (Type) that
373 /// describes a function information, return type and parameter types.
374 ///
375 /// The concrete information is the address range information and specific
376 /// locations for an instance of this function.
377 class Function : public UserID, public SymbolContextScope {
378 public:
379   /// Construct with a compile unit, function UID, function type UID, optional
380   /// mangled name, function type, and a section offset based address range.
381   ///
382   /// \param[in] comp_unit
383   ///     The compile unit to which this function belongs.
384   ///
385   /// \param[in] func_uid
386   ///     The UID for this function. This value is provided by the
387   ///     SymbolFile plug-in and can be any value that allows
388   ///     the plug-in to quickly find and parse more detailed
389   ///     information when and if more information is needed.
390   ///
391   /// \param[in] func_type_uid
392   ///     The type UID for the function Type to allow for lazy type
393   ///     parsing from the debug information.
394   ///
395   /// \param[in] mangled
396   ///     The optional mangled name for this function. If empty, there
397   ///     is no mangled information.
398   ///
399   /// \param[in] func_type
400   ///     The optional function type. If NULL, the function type will
401   ///     be parsed on demand when accessed using the
402   ///     Function::GetType() function by asking the SymbolFile
403   ///     plug-in to get the type for \a func_type_uid.
404   ///
405   /// \param[in] range
406   ///     The section offset based address for this function.
407   Function(CompileUnit *comp_unit, lldb::user_id_t func_uid,
408            lldb::user_id_t func_type_uid, const Mangled &mangled,
409            Type *func_type, const AddressRange &range);
410 
411   /// Destructor.
412   ~Function() override;
413 
414   /// \copydoc SymbolContextScope::CalculateSymbolContext(SymbolContext*)
415   ///
416   /// \see SymbolContextScope
417   void CalculateSymbolContext(SymbolContext *sc) override;
418 
419   lldb::ModuleSP CalculateSymbolContextModule() override;
420 
421   CompileUnit *CalculateSymbolContextCompileUnit() override;
422 
423   Function *CalculateSymbolContextFunction() override;
424 
425   const AddressRange &GetAddressRange() { return m_range; }
426 
427   lldb::LanguageType GetLanguage() const;
428   /// Find the file and line number of the source location of the start of the
429   /// function.  This will use the declaration if present and fall back on the
430   /// line table if that fails.  So there may NOT be a line table entry for
431   /// this source file/line combo.
432   ///
433   /// \param[out] source_file
434   ///     The source file.
435   ///
436   /// \param[out] line_no
437   ///     The line number.
438   void GetStartLineSourceInfo(FileSpec &source_file, uint32_t &line_no);
439 
440   /// Find the file and line number of the source location of the end of the
441   /// function.
442   ///
443   ///
444   /// \param[out] source_file
445   ///     The source file.
446   ///
447   /// \param[out] line_no
448   ///     The line number.
449   void GetEndLineSourceInfo(FileSpec &source_file, uint32_t &line_no);
450 
451   /// Get the outgoing call edges from this function, sorted by their return
452   /// PC addresses (in increasing order).
453   llvm::ArrayRef<std::unique_ptr<CallEdge>> GetCallEdges();
454 
455   /// Get the outgoing tail-calling edges from this function. If none exist,
456   /// return None.
457   llvm::ArrayRef<std::unique_ptr<CallEdge>> GetTailCallingEdges();
458 
459   /// Get the outgoing call edge from this function which has the given return
460   /// address \p return_pc, or return nullptr. Note that this will not return a
461   /// tail-calling edge.
462   CallEdge *GetCallEdgeForReturnAddress(lldb::addr_t return_pc, Target &target);
463 
464   /// Get accessor for the block list.
465   ///
466   /// \return
467   ///     The block list object that describes all lexical blocks
468   ///     in the function.
469   ///
470   /// \see BlockList
471   Block &GetBlock(bool can_create);
472 
473   /// Get accessor for the compile unit that owns this function.
474   ///
475   /// \return
476   ///     A compile unit object pointer.
477   CompileUnit *GetCompileUnit();
478 
479   /// Get const accessor for the compile unit that owns this function.
480   ///
481   /// \return
482   ///     A const compile unit object pointer.
483   const CompileUnit *GetCompileUnit() const;
484 
485   void GetDescription(Stream *s, lldb::DescriptionLevel level, Target *target);
486 
487   /// Get accessor for the frame base location.
488   ///
489   /// \return
490   ///     A location expression that describes the function frame
491   ///     base.
492   DWARFExpression &GetFrameBaseExpression() { return m_frame_base; }
493 
494   /// Get const accessor for the frame base location.
495   ///
496   /// \return
497   ///     A const compile unit object pointer.
498   const DWARFExpression &GetFrameBaseExpression() const { return m_frame_base; }
499 
500   ConstString GetName() const;
501 
502   ConstString GetNameNoArguments() const;
503 
504   ConstString GetDisplayName() const;
505 
506   const Mangled &GetMangled() const { return m_mangled; }
507 
508   /// Get the DeclContext for this function, if available.
509   ///
510   /// \return
511   ///     The DeclContext, or NULL if none exists.
512   CompilerDeclContext GetDeclContext();
513 
514   /// Get accessor for the type that describes the function return value type,
515   /// and parameter types.
516   ///
517   /// \return
518   ///     A type object pointer.
519   Type *GetType();
520 
521   /// Get const accessor for the type that describes the function return value
522   /// type, and parameter types.
523   ///
524   /// \return
525   ///     A const type object pointer.
526   const Type *GetType() const;
527 
528   CompilerType GetCompilerType();
529 
530   /// Get the size of the prologue instructions for this function.  The
531   /// "prologue" instructions include any instructions given line number 0
532   /// immediately following the prologue end.
533   ///
534   /// \return
535   ///     The size of the prologue.
536   uint32_t GetPrologueByteSize();
537 
538   /// Dump a description of this object to a Stream.
539   ///
540   /// Dump a description of the contents of this object to the supplied stream
541   /// \a s.
542   ///
543   /// \param[in] s
544   ///     The stream to which to dump the object description.
545   ///
546   /// \param[in] show_context
547   ///     If \b true, variables will dump their symbol context
548   ///     information.
549   void Dump(Stream *s, bool show_context) const;
550 
551   /// \copydoc SymbolContextScope::DumpSymbolContext(Stream*)
552   ///
553   /// \see SymbolContextScope
554   void DumpSymbolContext(Stream *s) override;
555 
556   /// Get the memory cost of this object.
557   ///
558   /// \return
559   ///     The number of bytes that this object occupies in memory.
560   ///     The returned value does not include the bytes for any
561   ///     shared string values.
562   ///
563   /// \see ConstString::StaticMemorySize ()
564   size_t MemorySize() const;
565 
566   /// Get whether compiler optimizations were enabled for this function
567   ///
568   /// The debug information may provide information about whether this
569   /// function was compiled with optimization or not.  In this case,
570   /// "optimized" means that the debug experience may be difficult for the
571   /// user to understand.  Variables may not be available when the developer
572   /// would expect them, stepping through the source lines in the function may
573   /// appear strange, etc.
574   ///
575   /// \return
576   ///     Returns 'true' if this function was compiled with
577   ///     optimization.  'false' indicates that either the optimization
578   ///     is unknown, or this function was built without optimization.
579   bool GetIsOptimized();
580 
581   /// Get whether this function represents a 'top-level' function
582   ///
583   /// The concept of a top-level function is language-specific, mostly meant
584   /// to represent the notion of scripting-style code that has global
585   /// visibility of the variables/symbols/functions/... defined within the
586   /// containing file/module
587   ///
588   /// If stopped in a top-level function, LLDB will expose global variables
589   /// as-if locals in the 'frame variable' command
590   ///
591   /// \return
592   ///     Returns 'true' if this function is a top-level function,
593   ///     'false' otherwise.
594   bool IsTopLevelFunction();
595 
596   lldb::DisassemblerSP GetInstructions(const ExecutionContext &exe_ctx,
597                                        const char *flavor,
598                                        bool prefer_file_cache);
599 
600   bool GetDisassembly(const ExecutionContext &exe_ctx, const char *flavor,
601                       bool prefer_file_cache, Stream &strm);
602 
603 protected:
604   enum {
605     flagsCalculatedPrologueSize =
606         (1 << 0) ///< Have we already tried to calculate the prologue size?
607   };
608 
609   // Member variables.
610   CompileUnit *m_comp_unit; ///< The compile unit that owns this function.
611   lldb::user_id_t
612       m_type_uid; ///< The user ID of for the prototype Type for this function.
613   Type *m_type; ///< The function prototype type for this function that include
614                 ///the function info (FunctionInfo), return type and parameters.
615   Mangled m_mangled; ///< The mangled function name if any, if empty, there is
616                      ///no mangled information.
617   Block m_block;     ///< All lexical blocks contained in this function.
618   AddressRange m_range; ///< The function address range that covers the widest
619                         ///range needed to contain all blocks
620   DWARFExpression m_frame_base; ///< The frame base expression for variables
621                                 ///that are relative to the frame pointer.
622   Flags m_flags;
623   uint32_t
624       m_prologue_byte_size; ///< Compute the prologue size once and cache it
625 
626   bool m_call_edges_resolved = false; ///< Whether call site info has been
627                                       ///  parsed.
628   std::vector<std::unique_ptr<CallEdge>> m_call_edges; ///< Outgoing call edges.
629 private:
630   DISALLOW_COPY_AND_ASSIGN(Function);
631 };
632 
633 } // namespace lldb_private
634 
635 #endif // liblldb_Function_h_
636