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