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