1 //===-- llvm/Function.h - Class to represent a single function --*- 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 // This file contains the declaration of the Function class, which represents a
11 // single function/procedure in LLVM.
12 //
13 // A function basically consists of a list of basic blocks, a list of arguments,
14 // and a symbol table.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_IR_FUNCTION_H
19 #define LLVM_IR_FUNCTION_H
20 
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/GlobalObject.h"
27 #include "llvm/Support/Compiler.h"
28 
29 namespace llvm {
30 
31 class FunctionType;
32 class LLVMContext;
33 
34 template<> struct ilist_traits<Argument>
35   : public SymbolTableListTraits<Argument, Function> {
36 
37   Argument *createSentinel() const {
38     return static_cast<Argument*>(&Sentinel);
39   }
40   static void destroySentinel(Argument*) {}
41 
42   Argument *provideInitialHead() const { return createSentinel(); }
43   Argument *ensureHead(Argument*) const { return createSentinel(); }
44   static void noteHead(Argument*, Argument*) {}
45 
46   static ValueSymbolTable *getSymTab(Function *ItemParent);
47 private:
48   mutable ilist_half_node<Argument> Sentinel;
49 };
50 
51 class Function : public GlobalObject, public ilist_node<Function> {
52 public:
53   typedef iplist<Argument> ArgumentListType;
54   typedef iplist<BasicBlock> BasicBlockListType;
55 
56   // BasicBlock iterators...
57   typedef BasicBlockListType::iterator iterator;
58   typedef BasicBlockListType::const_iterator const_iterator;
59 
60   typedef ArgumentListType::iterator arg_iterator;
61   typedef ArgumentListType::const_iterator const_arg_iterator;
62 
63 private:
64   // Important things that make up a function!
65   BasicBlockListType  BasicBlocks;        ///< The basic blocks
66   mutable ArgumentListType ArgumentList;  ///< The formal arguments
67   ValueSymbolTable *SymTab;               ///< Symbol table of args/instructions
68   AttributeSet AttributeSets;             ///< Parameter attributes
69   FunctionType *Ty;
70 
71   /*
72    * Value::SubclassData
73    *
74    * bit 0  : HasLazyArguments
75    * bit 1  : HasPrefixData
76    * bit 2  : HasPrologueData
77    * bit 3-6: CallingConvention
78    */
79 
80   friend class SymbolTableListTraits<Function, Module>;
81 
82   void setParent(Module *parent);
83 
84   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
85   /// built on demand, so that the list isn't allocated until the first client
86   /// needs it.  The hasLazyArguments predicate returns true if the arg list
87   /// hasn't been set up yet.
88   bool hasLazyArguments() const {
89     return getSubclassDataFromValue() & (1<<0);
90   }
91   void CheckLazyArguments() const {
92     if (hasLazyArguments())
93       BuildLazyArguments();
94   }
95   void BuildLazyArguments() const;
96 
97   Function(const Function&) = delete;
98   void operator=(const Function&) = delete;
99 
100   /// Do the actual lookup of an intrinsic ID when the query could not be
101   /// answered from the cache.
102   unsigned lookupIntrinsicID() const LLVM_READONLY;
103 
104   /// Function ctor - If the (optional) Module argument is specified, the
105   /// function is automatically inserted into the end of the function list for
106   /// the module.
107   ///
108   Function(FunctionType *Ty, LinkageTypes Linkage,
109            const Twine &N = "", Module *M = nullptr);
110 
111 public:
112   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
113                           const Twine &N = "", Module *M = nullptr) {
114     return new(0) Function(Ty, Linkage, N, M);
115   }
116 
117   ~Function() override;
118 
119   Type *getReturnType() const;           // Return the type of the ret val
120   FunctionType *getFunctionType() const; // Return the FunctionType for me
121 
122   /// getContext - Return a pointer to the LLVMContext associated with this
123   /// function, or NULL if this function is not bound to a context yet.
124   LLVMContext &getContext() const;
125 
126   /// isVarArg - Return true if this function takes a variable number of
127   /// arguments.
128   bool isVarArg() const;
129 
130   bool isMaterializable() const;
131   void setIsMaterializable(bool V);
132 
133   /// getIntrinsicID - This method returns the ID number of the specified
134   /// function, or Intrinsic::not_intrinsic if the function is not an
135   /// intrinsic, or if the pointer is null.  This value is always defined to be
136   /// zero to allow easy checking for whether a function is intrinsic or not.
137   /// The particular intrinsic functions which correspond to this value are
138   /// defined in llvm/Intrinsics.h.  Results are cached in the LLVM context,
139   /// subsequent requests for the same ID return results much faster from the
140   /// cache.
141   ///
142   unsigned getIntrinsicID() const LLVM_READONLY;
143   bool isIntrinsic() const { return getName().startswith("llvm."); }
144 
145   /// getCallingConv()/setCallingConv(CC) - These method get and set the
146   /// calling convention of this function.  The enum values for the known
147   /// calling conventions are defined in CallingConv.h.
148   CallingConv::ID getCallingConv() const {
149     return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
150   }
151   void setCallingConv(CallingConv::ID CC) {
152     setValueSubclassData((getSubclassDataFromValue() & 7) |
153                          (static_cast<unsigned>(CC) << 3));
154   }
155 
156   /// @brief Return the attribute list for this Function.
157   AttributeSet getAttributes() const { return AttributeSets; }
158 
159   /// @brief Set the attribute list for this Function.
160   void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
161 
162   /// @brief Add function attributes to this function.
163   void addFnAttr(Attribute::AttrKind N) {
164     setAttributes(AttributeSets.addAttribute(getContext(),
165                                              AttributeSet::FunctionIndex, N));
166   }
167 
168   /// @brief Remove function attributes from this function.
169   void removeFnAttr(Attribute::AttrKind N) {
170     setAttributes(AttributeSets.removeAttribute(
171         getContext(), AttributeSet::FunctionIndex, N));
172   }
173 
174   /// @brief Add function attributes to this function.
175   void addFnAttr(StringRef Kind) {
176     setAttributes(
177       AttributeSets.addAttribute(getContext(),
178                                  AttributeSet::FunctionIndex, Kind));
179   }
180   void addFnAttr(StringRef Kind, StringRef Value) {
181     setAttributes(
182       AttributeSets.addAttribute(getContext(),
183                                  AttributeSet::FunctionIndex, Kind, Value));
184   }
185 
186   /// @brief Return true if the function has the attribute.
187   bool hasFnAttribute(Attribute::AttrKind Kind) const {
188     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
189   }
190   bool hasFnAttribute(StringRef Kind) const {
191     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
192   }
193 
194   /// @brief Return the attribute for the given attribute kind.
195   Attribute getFnAttribute(Attribute::AttrKind Kind) const {
196     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
197   }
198   Attribute getFnAttribute(StringRef Kind) const {
199     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
200   }
201 
202   /// \brief Return the stack alignment for the function.
203   unsigned getFnStackAlignment() const {
204     return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
205   }
206 
207   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
208   ///                             to use during code generation.
209   bool hasGC() const;
210   const char *getGC() const;
211   void setGC(const char *Str);
212   void clearGC();
213 
214   /// @brief adds the attribute to the list of attributes.
215   void addAttribute(unsigned i, Attribute::AttrKind attr);
216 
217   /// @brief adds the attributes to the list of attributes.
218   void addAttributes(unsigned i, AttributeSet attrs);
219 
220   /// @brief removes the attributes from the list of attributes.
221   void removeAttributes(unsigned i, AttributeSet attr);
222 
223   /// @brief adds the dereferenceable attribute to the list of attributes.
224   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
225 
226   /// @brief adds the dereferenceable_or_null attribute to the list of
227   /// attributes.
228   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
229 
230   /// @brief Extract the alignment for a call or parameter (0=unknown).
231   unsigned getParamAlignment(unsigned i) const {
232     return AttributeSets.getParamAlignment(i);
233   }
234 
235   /// @brief Extract the number of dereferenceable bytes for a call or
236   /// parameter (0=unknown).
237   uint64_t getDereferenceableBytes(unsigned i) const {
238     return AttributeSets.getDereferenceableBytes(i);
239   }
240 
241   /// @brief Determine if the function does not access memory.
242   bool doesNotAccessMemory() const {
243     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
244                                       Attribute::ReadNone);
245   }
246   void setDoesNotAccessMemory() {
247     addFnAttr(Attribute::ReadNone);
248   }
249 
250   /// @brief Determine if the function does not access or only reads memory.
251   bool onlyReadsMemory() const {
252     return doesNotAccessMemory() ||
253       AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
254                                  Attribute::ReadOnly);
255   }
256   void setOnlyReadsMemory() {
257     addFnAttr(Attribute::ReadOnly);
258   }
259 
260   /// @brief Determine if the function cannot return.
261   bool doesNotReturn() const {
262     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
263                                       Attribute::NoReturn);
264   }
265   void setDoesNotReturn() {
266     addFnAttr(Attribute::NoReturn);
267   }
268 
269   /// @brief Determine if the function cannot unwind.
270   bool doesNotThrow() const {
271     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
272                                       Attribute::NoUnwind);
273   }
274   void setDoesNotThrow() {
275     addFnAttr(Attribute::NoUnwind);
276   }
277 
278   /// @brief Determine if the call cannot be duplicated.
279   bool cannotDuplicate() const {
280     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
281                                       Attribute::NoDuplicate);
282   }
283   void setCannotDuplicate() {
284     addFnAttr(Attribute::NoDuplicate);
285   }
286 
287   /// @brief True if the ABI mandates (or the user requested) that this
288   /// function be in a unwind table.
289   bool hasUWTable() const {
290     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
291                                       Attribute::UWTable);
292   }
293   void setHasUWTable() {
294     addFnAttr(Attribute::UWTable);
295   }
296 
297   /// @brief True if this function needs an unwind table.
298   bool needsUnwindTableEntry() const {
299     return hasUWTable() || !doesNotThrow();
300   }
301 
302   /// @brief Determine if the function returns a structure through first
303   /// pointer argument.
304   bool hasStructRetAttr() const {
305     return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
306            AttributeSets.hasAttribute(2, Attribute::StructRet);
307   }
308 
309   /// @brief Determine if the parameter does not alias other parameters.
310   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
311   bool doesNotAlias(unsigned n) const {
312     return AttributeSets.hasAttribute(n, Attribute::NoAlias);
313   }
314   void setDoesNotAlias(unsigned n) {
315     addAttribute(n, Attribute::NoAlias);
316   }
317 
318   /// @brief Determine if the parameter can be captured.
319   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
320   bool doesNotCapture(unsigned n) const {
321     return AttributeSets.hasAttribute(n, Attribute::NoCapture);
322   }
323   void setDoesNotCapture(unsigned n) {
324     addAttribute(n, Attribute::NoCapture);
325   }
326 
327   bool doesNotAccessMemory(unsigned n) const {
328     return AttributeSets.hasAttribute(n, Attribute::ReadNone);
329   }
330   void setDoesNotAccessMemory(unsigned n) {
331     addAttribute(n, Attribute::ReadNone);
332   }
333 
334   bool onlyReadsMemory(unsigned n) const {
335     return doesNotAccessMemory(n) ||
336       AttributeSets.hasAttribute(n, Attribute::ReadOnly);
337   }
338   void setOnlyReadsMemory(unsigned n) {
339     addAttribute(n, Attribute::ReadOnly);
340   }
341 
342   /// copyAttributesFrom - copy all additional attributes (those not needed to
343   /// create a Function) from the Function Src to this one.
344   void copyAttributesFrom(const GlobalValue *Src) override;
345 
346   /// deleteBody - This method deletes the body of the function, and converts
347   /// the linkage to external.
348   ///
349   void deleteBody() {
350     dropAllReferences();
351     setLinkage(ExternalLinkage);
352   }
353 
354   /// removeFromParent - This method unlinks 'this' from the containing module,
355   /// but does not delete it.
356   ///
357   void removeFromParent() override;
358 
359   /// eraseFromParent - This method unlinks 'this' from the containing module
360   /// and deletes it.
361   ///
362   void eraseFromParent() override;
363 
364 
365   /// Get the underlying elements of the Function... the basic block list is
366   /// empty for external functions.
367   ///
368   const ArgumentListType &getArgumentList() const {
369     CheckLazyArguments();
370     return ArgumentList;
371   }
372   ArgumentListType &getArgumentList() {
373     CheckLazyArguments();
374     return ArgumentList;
375   }
376   static iplist<Argument> Function::*getSublistAccess(Argument*) {
377     return &Function::ArgumentList;
378   }
379 
380   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
381         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
382   static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
383     return &Function::BasicBlocks;
384   }
385 
386   const BasicBlock       &getEntryBlock() const   { return front(); }
387         BasicBlock       &getEntryBlock()         { return front(); }
388 
389   //===--------------------------------------------------------------------===//
390   // Symbol Table Accessing functions...
391 
392   /// getSymbolTable() - Return the symbol table...
393   ///
394   inline       ValueSymbolTable &getValueSymbolTable()       { return *SymTab; }
395   inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
396 
397 
398   //===--------------------------------------------------------------------===//
399   // BasicBlock iterator forwarding functions
400   //
401   iterator                begin()       { return BasicBlocks.begin(); }
402   const_iterator          begin() const { return BasicBlocks.begin(); }
403   iterator                end  ()       { return BasicBlocks.end();   }
404   const_iterator          end  () const { return BasicBlocks.end();   }
405 
406   size_t                   size() const { return BasicBlocks.size();  }
407   bool                    empty() const { return BasicBlocks.empty(); }
408   const BasicBlock       &front() const { return BasicBlocks.front(); }
409         BasicBlock       &front()       { return BasicBlocks.front(); }
410   const BasicBlock        &back() const { return BasicBlocks.back();  }
411         BasicBlock        &back()       { return BasicBlocks.back();  }
412 
413 /// @name Function Argument Iteration
414 /// @{
415 
416   arg_iterator arg_begin() {
417     CheckLazyArguments();
418     return ArgumentList.begin();
419   }
420   const_arg_iterator arg_begin() const {
421     CheckLazyArguments();
422     return ArgumentList.begin();
423   }
424   arg_iterator arg_end() {
425     CheckLazyArguments();
426     return ArgumentList.end();
427   }
428   const_arg_iterator arg_end() const {
429     CheckLazyArguments();
430     return ArgumentList.end();
431   }
432 
433   iterator_range<arg_iterator> args() {
434     return iterator_range<arg_iterator>(arg_begin(), arg_end());
435   }
436 
437   iterator_range<const_arg_iterator> args() const {
438     return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
439   }
440 
441 /// @}
442 
443   size_t arg_size() const;
444   bool arg_empty() const;
445 
446   bool hasPrefixData() const {
447     return getSubclassDataFromValue() & (1<<1);
448   }
449 
450   Constant *getPrefixData() const;
451   void setPrefixData(Constant *PrefixData);
452 
453   bool hasPrologueData() const {
454     return getSubclassDataFromValue() & (1<<2);
455   }
456 
457   Constant *getPrologueData() const;
458   void setPrologueData(Constant *PrologueData);
459 
460   /// Print the function to an output stream with an optional
461   /// AssemblyAnnotationWriter.
462   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr) const;
463 
464   /// viewCFG - This function is meant for use from the debugger.  You can just
465   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
466   /// program, displaying the CFG of the current function with the code for each
467   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
468   /// in your path.
469   ///
470   void viewCFG() const;
471 
472   /// viewCFGOnly - This function is meant for use from the debugger.  It works
473   /// just like viewCFG, but it does not include the contents of basic blocks
474   /// into the nodes, just the label.  If you are only interested in the CFG
475   /// this can make the graph smaller.
476   ///
477   void viewCFGOnly() const;
478 
479   /// Methods for support type inquiry through isa, cast, and dyn_cast:
480   static inline bool classof(const Value *V) {
481     return V->getValueID() == Value::FunctionVal;
482   }
483 
484   /// dropAllReferences() - This method causes all the subinstructions to "let
485   /// go" of all references that they are maintaining.  This allows one to
486   /// 'delete' a whole module at a time, even though there may be circular
487   /// references... first all references are dropped, and all use counts go to
488   /// zero.  Then everything is deleted for real.  Note that no operations are
489   /// valid on an object that has "dropped all references", except operator
490   /// delete.
491   ///
492   /// Since no other object in the module can have references into the body of a
493   /// function, dropping all references deletes the entire body of the function,
494   /// including any contained basic blocks.
495   ///
496   void dropAllReferences();
497 
498   /// hasAddressTaken - returns true if there are any uses of this function
499   /// other than direct calls or invokes to it, or blockaddress expressions.
500   /// Optionally passes back an offending user for diagnostic purposes.
501   ///
502   bool hasAddressTaken(const User** = nullptr) const;
503 
504   /// isDefTriviallyDead - Return true if it is trivially safe to remove
505   /// this function definition from the module (because it isn't externally
506   /// visible, does not have its address taken, and has no callers).  To make
507   /// this more accurate, call removeDeadConstantUsers first.
508   bool isDefTriviallyDead() const;
509 
510   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
511   /// setjmp or other function that gcc recognizes as "returning twice".
512   bool callsFunctionThatReturnsTwice() const;
513 
514 private:
515   // Shadow Value::setValueSubclassData with a private forwarding method so that
516   // subclasses cannot accidentally use it.
517   void setValueSubclassData(unsigned short D) {
518     Value::setValueSubclassData(D);
519   }
520 };
521 
522 inline ValueSymbolTable *
523 ilist_traits<BasicBlock>::getSymTab(Function *F) {
524   return F ? &F->getValueSymbolTable() : nullptr;
525 }
526 
527 inline ValueSymbolTable *
528 ilist_traits<Argument>::getSymTab(Function *F) {
529   return F ? &F->getValueSymbolTable() : nullptr;
530 }
531 
532 } // End llvm namespace
533 
534 #endif
535