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