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