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