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