LLVM API Documentation

Function.h
Go to the documentation of this file.
00001 //===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the declaration of the Function class, which represents a
00011 // single function/procedure in LLVM.
00012 //
00013 // A function basically consists of a list of basic blocks, a list of arguments,
00014 // and a symbol table.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #ifndef LLVM_IR_FUNCTION_H
00019 #define LLVM_IR_FUNCTION_H
00020 
00021 #include "llvm/ADT/iterator_range.h"
00022 #include "llvm/IR/Argument.h"
00023 #include "llvm/IR/Attributes.h"
00024 #include "llvm/IR/BasicBlock.h"
00025 #include "llvm/IR/CallingConv.h"
00026 #include "llvm/IR/GlobalObject.h"
00027 #include "llvm/Support/Compiler.h"
00028 
00029 namespace llvm {
00030 
00031 class FunctionType;
00032 class LLVMContext;
00033 
00034 // Traits for intrusive list of basic blocks...
00035 template<> struct ilist_traits<BasicBlock>
00036   : public SymbolTableListTraits<BasicBlock, Function> {
00037 
00038   // createSentinel is used to get hold of the node that marks the end of the
00039   // list... (same trick used here as in ilist_traits<Instruction>)
00040   BasicBlock *createSentinel() const {
00041     return static_cast<BasicBlock*>(&Sentinel);
00042   }
00043   static void destroySentinel(BasicBlock*) {}
00044 
00045   BasicBlock *provideInitialHead() const { return createSentinel(); }
00046   BasicBlock *ensureHead(BasicBlock*) const { return createSentinel(); }
00047   static void noteHead(BasicBlock*, BasicBlock*) {}
00048 
00049   static ValueSymbolTable *getSymTab(Function *ItemParent);
00050 private:
00051   mutable ilist_half_node<BasicBlock> Sentinel;
00052 };
00053 
00054 template<> struct ilist_traits<Argument>
00055   : public SymbolTableListTraits<Argument, Function> {
00056 
00057   Argument *createSentinel() const {
00058     return static_cast<Argument*>(&Sentinel);
00059   }
00060   static void destroySentinel(Argument*) {}
00061 
00062   Argument *provideInitialHead() const { return createSentinel(); }
00063   Argument *ensureHead(Argument*) const { return createSentinel(); }
00064   static void noteHead(Argument*, Argument*) {}
00065 
00066   static ValueSymbolTable *getSymTab(Function *ItemParent);
00067 private:
00068   mutable ilist_half_node<Argument> Sentinel;
00069 };
00070 
00071 class Function : public GlobalObject, public ilist_node<Function> {
00072 public:
00073   typedef iplist<Argument> ArgumentListType;
00074   typedef iplist<BasicBlock> BasicBlockListType;
00075 
00076   // BasicBlock iterators...
00077   typedef BasicBlockListType::iterator iterator;
00078   typedef BasicBlockListType::const_iterator const_iterator;
00079 
00080   typedef ArgumentListType::iterator arg_iterator;
00081   typedef ArgumentListType::const_iterator const_arg_iterator;
00082 
00083 private:
00084   // Important things that make up a function!
00085   BasicBlockListType  BasicBlocks;        ///< The basic blocks
00086   mutable ArgumentListType ArgumentList;  ///< The formal arguments
00087   ValueSymbolTable *SymTab;               ///< Symbol table of args/instructions
00088   AttributeSet AttributeSets;             ///< Parameter attributes
00089 
00090   // HasLazyArguments is stored in Value::SubclassData.
00091   /*bool HasLazyArguments;*/
00092 
00093   // The Calling Convention is stored in Value::SubclassData.
00094   /*CallingConv::ID CallingConvention;*/
00095 
00096   friend class SymbolTableListTraits<Function, Module>;
00097 
00098   void setParent(Module *parent);
00099 
00100   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
00101   /// built on demand, so that the list isn't allocated until the first client
00102   /// needs it.  The hasLazyArguments predicate returns true if the arg list
00103   /// hasn't been set up yet.
00104   bool hasLazyArguments() const {
00105     return getSubclassDataFromValue() & 1;
00106   }
00107   void CheckLazyArguments() const {
00108     if (hasLazyArguments())
00109       BuildLazyArguments();
00110   }
00111   void BuildLazyArguments() const;
00112 
00113   Function(const Function&) LLVM_DELETED_FUNCTION;
00114   void operator=(const Function&) LLVM_DELETED_FUNCTION;
00115 
00116   /// Do the actual lookup of an intrinsic ID when the query could not be
00117   /// answered from the cache.
00118   unsigned lookupIntrinsicID() const LLVM_READONLY;
00119 
00120   /// Function ctor - If the (optional) Module argument is specified, the
00121   /// function is automatically inserted into the end of the function list for
00122   /// the module.
00123   ///
00124   Function(FunctionType *Ty, LinkageTypes Linkage,
00125            const Twine &N = "", Module *M = nullptr);
00126 
00127 public:
00128   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
00129                           const Twine &N = "", Module *M = nullptr) {
00130     return new(0) Function(Ty, Linkage, N, M);
00131   }
00132 
00133   ~Function();
00134 
00135   Type *getReturnType() const;           // Return the type of the ret val
00136   FunctionType *getFunctionType() const; // Return the FunctionType for me
00137 
00138   /// getContext - Return a pointer to the LLVMContext associated with this
00139   /// function, or NULL if this function is not bound to a context yet.
00140   LLVMContext &getContext() const;
00141 
00142   /// isVarArg - Return true if this function takes a variable number of
00143   /// arguments.
00144   bool isVarArg() const;
00145 
00146   bool isMaterializable() const;
00147   void setIsMaterializable(bool V);
00148 
00149   /// getIntrinsicID - This method returns the ID number of the specified
00150   /// function, or Intrinsic::not_intrinsic if the function is not an
00151   /// intrinsic, or if the pointer is null.  This value is always defined to be
00152   /// zero to allow easy checking for whether a function is intrinsic or not.
00153   /// The particular intrinsic functions which correspond to this value are
00154   /// defined in llvm/Intrinsics.h.  Results are cached in the LLVM context,
00155   /// subsequent requests for the same ID return results much faster from the
00156   /// cache.
00157   ///
00158   unsigned getIntrinsicID() const LLVM_READONLY;
00159   bool isIntrinsic() const { return getName().startswith("llvm."); }
00160 
00161   /// getCallingConv()/setCallingConv(CC) - These method get and set the
00162   /// calling convention of this function.  The enum values for the known
00163   /// calling conventions are defined in CallingConv.h.
00164   CallingConv::ID getCallingConv() const {
00165     return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 2);
00166   }
00167   void setCallingConv(CallingConv::ID CC) {
00168     setValueSubclassData((getSubclassDataFromValue() & 3) |
00169                          (static_cast<unsigned>(CC) << 2));
00170   }
00171 
00172   /// @brief Return the attribute list for this Function.
00173   AttributeSet getAttributes() const { return AttributeSets; }
00174 
00175   /// @brief Set the attribute list for this Function.
00176   void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
00177 
00178   /// @brief Add function attributes to this function.
00179   void addFnAttr(Attribute::AttrKind N) {
00180     setAttributes(AttributeSets.addAttribute(getContext(),
00181                                              AttributeSet::FunctionIndex, N));
00182   }
00183 
00184   /// @brief Remove function attributes from this function.
00185   void removeFnAttr(Attribute::AttrKind N) {
00186     setAttributes(AttributeSets.removeAttribute(
00187         getContext(), AttributeSet::FunctionIndex, N));
00188   }
00189 
00190   /// @brief Add function attributes to this function.
00191   void addFnAttr(StringRef Kind) {
00192     setAttributes(
00193       AttributeSets.addAttribute(getContext(),
00194                                  AttributeSet::FunctionIndex, Kind));
00195   }
00196   void addFnAttr(StringRef Kind, StringRef Value) {
00197     setAttributes(
00198       AttributeSets.addAttribute(getContext(),
00199                                  AttributeSet::FunctionIndex, Kind, Value));
00200   }
00201 
00202   /// @brief Return true if the function has the attribute.
00203   bool hasFnAttribute(Attribute::AttrKind Kind) const {
00204     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
00205   }
00206   bool hasFnAttribute(StringRef Kind) const {
00207     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
00208   }
00209 
00210   /// @brief Return the attribute for the given attribute kind.
00211   Attribute getFnAttribute(Attribute::AttrKind Kind) const {
00212     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
00213   }
00214   Attribute getFnAttribute(StringRef Kind) const {
00215     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
00216   }
00217 
00218   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
00219   ///                             to use during code generation.
00220   bool hasGC() const;
00221   const char *getGC() const;
00222   void setGC(const char *Str);
00223   void clearGC();
00224 
00225   /// @brief adds the attribute to the list of attributes.
00226   void addAttribute(unsigned i, Attribute::AttrKind attr);
00227 
00228   /// @brief adds the attributes to the list of attributes.
00229   void addAttributes(unsigned i, AttributeSet attrs);
00230 
00231   /// @brief removes the attributes from the list of attributes.
00232   void removeAttributes(unsigned i, AttributeSet attr);
00233 
00234   /// @brief Extract the alignment for a call or parameter (0=unknown).
00235   unsigned getParamAlignment(unsigned i) const {
00236     return AttributeSets.getParamAlignment(i);
00237   }
00238 
00239   /// @brief Extract the number of dereferenceable bytes for a call or
00240   /// parameter (0=unknown).
00241   uint64_t getDereferenceableBytes(unsigned i) const {
00242     return AttributeSets.getDereferenceableBytes(i);
00243   }
00244 
00245   /// @brief Determine if the function does not access memory.
00246   bool doesNotAccessMemory() const {
00247     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00248                                       Attribute::ReadNone);
00249   }
00250   void setDoesNotAccessMemory() {
00251     addFnAttr(Attribute::ReadNone);
00252   }
00253 
00254   /// @brief Determine if the function does not access or only reads memory.
00255   bool onlyReadsMemory() const {
00256     return doesNotAccessMemory() ||
00257       AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00258                                  Attribute::ReadOnly);
00259   }
00260   void setOnlyReadsMemory() {
00261     addFnAttr(Attribute::ReadOnly);
00262   }
00263 
00264   /// @brief Determine if the function cannot return.
00265   bool doesNotReturn() const {
00266     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00267                                       Attribute::NoReturn);
00268   }
00269   void setDoesNotReturn() {
00270     addFnAttr(Attribute::NoReturn);
00271   }
00272 
00273   /// @brief Determine if the function cannot unwind.
00274   bool doesNotThrow() const {
00275     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00276                                       Attribute::NoUnwind);
00277   }
00278   void setDoesNotThrow() {
00279     addFnAttr(Attribute::NoUnwind);
00280   }
00281 
00282   /// @brief Determine if the call cannot be duplicated.
00283   bool cannotDuplicate() const {
00284     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00285                                       Attribute::NoDuplicate);
00286   }
00287   void setCannotDuplicate() {
00288     addFnAttr(Attribute::NoDuplicate);
00289   }
00290 
00291   /// @brief True if the ABI mandates (or the user requested) that this
00292   /// function be in a unwind table.
00293   bool hasUWTable() const {
00294     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00295                                       Attribute::UWTable);
00296   }
00297   void setHasUWTable() {
00298     addFnAttr(Attribute::UWTable);
00299   }
00300 
00301   /// @brief True if this function needs an unwind table.
00302   bool needsUnwindTableEntry() const {
00303     return hasUWTable() || !doesNotThrow();
00304   }
00305 
00306   /// @brief Determine if the function returns a structure through first
00307   /// pointer argument.
00308   bool hasStructRetAttr() const {
00309     return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
00310            AttributeSets.hasAttribute(2, Attribute::StructRet);
00311   }
00312 
00313   /// @brief Determine if the parameter does not alias other parameters.
00314   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
00315   bool doesNotAlias(unsigned n) const {
00316     return AttributeSets.hasAttribute(n, Attribute::NoAlias);
00317   }
00318   void setDoesNotAlias(unsigned n) {
00319     addAttribute(n, Attribute::NoAlias);
00320   }
00321 
00322   /// @brief Determine if the parameter can be captured.
00323   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
00324   bool doesNotCapture(unsigned n) const {
00325     return AttributeSets.hasAttribute(n, Attribute::NoCapture);
00326   }
00327   void setDoesNotCapture(unsigned n) {
00328     addAttribute(n, Attribute::NoCapture);
00329   }
00330 
00331   bool doesNotAccessMemory(unsigned n) const {
00332     return AttributeSets.hasAttribute(n, Attribute::ReadNone);
00333   }
00334   void setDoesNotAccessMemory(unsigned n) {
00335     addAttribute(n, Attribute::ReadNone);
00336   }
00337 
00338   bool onlyReadsMemory(unsigned n) const {
00339     return doesNotAccessMemory(n) ||
00340       AttributeSets.hasAttribute(n, Attribute::ReadOnly);
00341   }
00342   void setOnlyReadsMemory(unsigned n) {
00343     addAttribute(n, Attribute::ReadOnly);
00344   }
00345 
00346   /// copyAttributesFrom - copy all additional attributes (those not needed to
00347   /// create a Function) from the Function Src to this one.
00348   void copyAttributesFrom(const GlobalValue *Src) override;
00349 
00350   /// deleteBody - This method deletes the body of the function, and converts
00351   /// the linkage to external.
00352   ///
00353   void deleteBody() {
00354     dropAllReferences();
00355     setLinkage(ExternalLinkage);
00356   }
00357 
00358   /// removeFromParent - This method unlinks 'this' from the containing module,
00359   /// but does not delete it.
00360   ///
00361   void removeFromParent() override;
00362 
00363   /// eraseFromParent - This method unlinks 'this' from the containing module
00364   /// and deletes it.
00365   ///
00366   void eraseFromParent() override;
00367 
00368 
00369   /// Get the underlying elements of the Function... the basic block list is
00370   /// empty for external functions.
00371   ///
00372   const ArgumentListType &getArgumentList() const {
00373     CheckLazyArguments();
00374     return ArgumentList;
00375   }
00376   ArgumentListType &getArgumentList() {
00377     CheckLazyArguments();
00378     return ArgumentList;
00379   }
00380   static iplist<Argument> Function::*getSublistAccess(Argument*) {
00381     return &Function::ArgumentList;
00382   }
00383 
00384   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
00385         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
00386   static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
00387     return &Function::BasicBlocks;
00388   }
00389 
00390   const BasicBlock       &getEntryBlock() const   { return front(); }
00391         BasicBlock       &getEntryBlock()         { return front(); }
00392 
00393   //===--------------------------------------------------------------------===//
00394   // Symbol Table Accessing functions...
00395 
00396   /// getSymbolTable() - Return the symbol table...
00397   ///
00398   inline       ValueSymbolTable &getValueSymbolTable()       { return *SymTab; }
00399   inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
00400 
00401 
00402   //===--------------------------------------------------------------------===//
00403   // BasicBlock iterator forwarding functions
00404   //
00405   iterator                begin()       { return BasicBlocks.begin(); }
00406   const_iterator          begin() const { return BasicBlocks.begin(); }
00407   iterator                end  ()       { return BasicBlocks.end();   }
00408   const_iterator          end  () const { return BasicBlocks.end();   }
00409 
00410   size_t                   size() const { return BasicBlocks.size();  }
00411   bool                    empty() const { return BasicBlocks.empty(); }
00412   const BasicBlock       &front() const { return BasicBlocks.front(); }
00413         BasicBlock       &front()       { return BasicBlocks.front(); }
00414   const BasicBlock        &back() const { return BasicBlocks.back();  }
00415         BasicBlock        &back()       { return BasicBlocks.back();  }
00416 
00417 /// @name Function Argument Iteration
00418 /// @{
00419 
00420   arg_iterator arg_begin() {
00421     CheckLazyArguments();
00422     return ArgumentList.begin();
00423   }
00424   const_arg_iterator arg_begin() const {
00425     CheckLazyArguments();
00426     return ArgumentList.begin();
00427   }
00428   arg_iterator arg_end() {
00429     CheckLazyArguments();
00430     return ArgumentList.end();
00431   }
00432   const_arg_iterator arg_end() const {
00433     CheckLazyArguments();
00434     return ArgumentList.end();
00435   }
00436 
00437   iterator_range<arg_iterator> args() {
00438     return iterator_range<arg_iterator>(arg_begin(), arg_end());
00439   }
00440 
00441   iterator_range<const_arg_iterator> args() const {
00442     return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
00443   }
00444 
00445 /// @}
00446 
00447   size_t arg_size() const;
00448   bool arg_empty() const;
00449 
00450   bool hasPrefixData() const {
00451     return getSubclassDataFromValue() & 2;
00452   }
00453 
00454   Constant *getPrefixData() const;
00455   void setPrefixData(Constant *PrefixData);
00456 
00457   /// viewCFG - This function is meant for use from the debugger.  You can just
00458   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
00459   /// program, displaying the CFG of the current function with the code for each
00460   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
00461   /// in your path.
00462   ///
00463   void viewCFG() const;
00464 
00465   /// viewCFGOnly - This function is meant for use from the debugger.  It works
00466   /// just like viewCFG, but it does not include the contents of basic blocks
00467   /// into the nodes, just the label.  If you are only interested in the CFG
00468   /// this can make the graph smaller.
00469   ///
00470   void viewCFGOnly() const;
00471 
00472   /// Methods for support type inquiry through isa, cast, and dyn_cast:
00473   static inline bool classof(const Value *V) {
00474     return V->getValueID() == Value::FunctionVal;
00475   }
00476 
00477   /// dropAllReferences() - This method causes all the subinstructions to "let
00478   /// go" of all references that they are maintaining.  This allows one to
00479   /// 'delete' a whole module at a time, even though there may be circular
00480   /// references... first all references are dropped, and all use counts go to
00481   /// zero.  Then everything is deleted for real.  Note that no operations are
00482   /// valid on an object that has "dropped all references", except operator
00483   /// delete.
00484   ///
00485   /// Since no other object in the module can have references into the body of a
00486   /// function, dropping all references deletes the entire body of the function,
00487   /// including any contained basic blocks.
00488   ///
00489   void dropAllReferences();
00490 
00491   /// hasAddressTaken - returns true if there are any uses of this function
00492   /// other than direct calls or invokes to it, or blockaddress expressions.
00493   /// Optionally passes back an offending user for diagnostic purposes.
00494   ///
00495   bool hasAddressTaken(const User** = nullptr) const;
00496 
00497   /// isDefTriviallyDead - Return true if it is trivially safe to remove
00498   /// this function definition from the module (because it isn't externally
00499   /// visible, does not have its address taken, and has no callers).  To make
00500   /// this more accurate, call removeDeadConstantUsers first.
00501   bool isDefTriviallyDead() const;
00502 
00503   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00504   /// setjmp or other function that gcc recognizes as "returning twice".
00505   bool callsFunctionThatReturnsTwice() const;
00506 
00507 private:
00508   // Shadow Value::setValueSubclassData with a private forwarding method so that
00509   // subclasses cannot accidentally use it.
00510   void setValueSubclassData(unsigned short D) {
00511     Value::setValueSubclassData(D);
00512   }
00513 };
00514 
00515 inline ValueSymbolTable *
00516 ilist_traits<BasicBlock>::getSymTab(Function *F) {
00517   return F ? &F->getValueSymbolTable() : nullptr;
00518 }
00519 
00520 inline ValueSymbolTable *
00521 ilist_traits<Argument>::getSymTab(Function *F) {
00522   return F ? &F->getValueSymbolTable() : nullptr;
00523 }
00524 
00525 } // End llvm namespace
00526 
00527 #endif