Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:00

0001 //===- llvm/Function.h - Class to represent a single function ---*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file contains the declaration of the Function class, which represents a
0010 // single function/procedure in LLVM.
0011 //
0012 // A function basically consists of a list of basic blocks, a list of arguments,
0013 // and a symbol table.
0014 //
0015 //===----------------------------------------------------------------------===//
0016 
0017 #ifndef LLVM_IR_FUNCTION_H
0018 #define LLVM_IR_FUNCTION_H
0019 
0020 #include "llvm/ADT/DenseSet.h"
0021 #include "llvm/ADT/StringRef.h"
0022 #include "llvm/ADT/Twine.h"
0023 #include "llvm/ADT/ilist_node.h"
0024 #include "llvm/ADT/iterator_range.h"
0025 #include "llvm/IR/Argument.h"
0026 #include "llvm/IR/Attributes.h"
0027 #include "llvm/IR/BasicBlock.h"
0028 #include "llvm/IR/CallingConv.h"
0029 #include "llvm/IR/DerivedTypes.h"
0030 #include "llvm/IR/GlobalObject.h"
0031 #include "llvm/IR/GlobalValue.h"
0032 #include "llvm/IR/OperandTraits.h"
0033 #include "llvm/IR/SymbolTableListTraits.h"
0034 #include "llvm/IR/Value.h"
0035 #include <cassert>
0036 #include <cstddef>
0037 #include <cstdint>
0038 #include <memory>
0039 #include <string>
0040 
0041 namespace llvm {
0042 
0043 namespace Intrinsic {
0044 typedef unsigned ID;
0045 }
0046 
0047 class AssemblyAnnotationWriter;
0048 class Constant;
0049 class ConstantRange;
0050 class DataLayout;
0051 struct DenormalMode;
0052 class DISubprogram;
0053 enum LibFunc : unsigned;
0054 class LLVMContext;
0055 class Module;
0056 class raw_ostream;
0057 class TargetLibraryInfoImpl;
0058 class Type;
0059 class User;
0060 class BranchProbabilityInfo;
0061 class BlockFrequencyInfo;
0062 
0063 class LLVM_ABI Function : public GlobalObject, public ilist_node<Function> {
0064 public:
0065   using BasicBlockListType = SymbolTableList<BasicBlock>;
0066 
0067   // BasicBlock iterators...
0068   using iterator = BasicBlockListType::iterator;
0069   using const_iterator = BasicBlockListType::const_iterator;
0070 
0071   using arg_iterator = Argument *;
0072   using const_arg_iterator = const Argument *;
0073 
0074 private:
0075   constexpr static HungOffOperandsAllocMarker AllocMarker{};
0076 
0077   // Important things that make up a function!
0078   BasicBlockListType BasicBlocks;         ///< The basic blocks
0079 
0080   // Basic blocks need to get their number when added to a function.
0081   friend void BasicBlock::setParent(Function *);
0082   unsigned NextBlockNum = 0;
0083   /// Epoch of block numbers. (Could be shrinked to uint8_t if required.)
0084   unsigned BlockNumEpoch = 0;
0085 
0086   mutable Argument *Arguments = nullptr;  ///< The formal arguments
0087   size_t NumArgs;
0088   std::unique_ptr<ValueSymbolTable>
0089       SymTab;                             ///< Symbol table of args/instructions
0090   AttributeList AttributeSets;            ///< Parameter attributes
0091 
0092   /*
0093    * Value::SubclassData
0094    *
0095    * bit 0      : HasLazyArguments
0096    * bit 1      : HasPrefixData
0097    * bit 2      : HasPrologueData
0098    * bit 3      : HasPersonalityFn
0099    * bits 4-13  : CallingConvention
0100    * bits 14    : HasGC
0101    * bits 15 : [reserved]
0102    */
0103 
0104   /// Bits from GlobalObject::GlobalObjectSubclassData.
0105   enum {
0106     /// Whether this function is materializable.
0107     IsMaterializableBit = 0,
0108   };
0109 
0110   friend class SymbolTableListTraits<Function>;
0111 
0112 public:
0113   /// Is this function using intrinsics to record the position of debugging
0114   /// information, or non-intrinsic records? See IsNewDbgInfoFormat in
0115   /// \ref BasicBlock.
0116   bool IsNewDbgInfoFormat;
0117 
0118   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
0119   /// built on demand, so that the list isn't allocated until the first client
0120   /// needs it.  The hasLazyArguments predicate returns true if the arg list
0121   /// hasn't been set up yet.
0122   bool hasLazyArguments() const {
0123     return getSubclassDataFromValue() & (1<<0);
0124   }
0125 
0126   /// \see BasicBlock::convertToNewDbgValues.
0127   void convertToNewDbgValues();
0128 
0129   /// \see BasicBlock::convertFromNewDbgValues.
0130   void convertFromNewDbgValues();
0131 
0132   void setIsNewDbgInfoFormat(bool NewVal);
0133   void setNewDbgInfoFormatFlag(bool NewVal);
0134 
0135 private:
0136   friend class TargetLibraryInfoImpl;
0137 
0138   static constexpr LibFunc UnknownLibFunc = LibFunc(-1);
0139 
0140   /// Cache for TLI::getLibFunc() result without prototype validation.
0141   /// UnknownLibFunc if uninitialized. NotLibFunc if definitely not lib func.
0142   /// Otherwise may be libfunc if prototype validation passes.
0143   mutable LibFunc LibFuncCache = UnknownLibFunc;
0144 
0145   void CheckLazyArguments() const {
0146     if (hasLazyArguments())
0147       BuildLazyArguments();
0148   }
0149 
0150   void BuildLazyArguments() const;
0151 
0152   void clearArguments();
0153 
0154   void deleteBodyImpl(bool ShouldDrop);
0155 
0156   /// Function ctor - If the (optional) Module argument is specified, the
0157   /// function is automatically inserted into the end of the function list for
0158   /// the module.
0159   ///
0160   Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
0161            const Twine &N = "", Module *M = nullptr);
0162 
0163 public:
0164   Function(const Function&) = delete;
0165   void operator=(const Function&) = delete;
0166   ~Function();
0167 
0168   // This is here to help easily convert from FunctionT * (Function * or
0169   // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling
0170   // FunctionT->getFunction().
0171   const Function &getFunction() const { return *this; }
0172 
0173   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
0174                           unsigned AddrSpace, const Twine &N = "",
0175                           Module *M = nullptr) {
0176     return new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M);
0177   }
0178 
0179   // TODO: remove this once all users have been updated to pass an AddrSpace
0180   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
0181                           const Twine &N = "", Module *M = nullptr) {
0182     return new (AllocMarker)
0183         Function(Ty, Linkage, static_cast<unsigned>(-1), N, M);
0184   }
0185 
0186   /// Creates a new function and attaches it to a module.
0187   ///
0188   /// Places the function in the program address space as specified
0189   /// by the module's data layout.
0190   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
0191                           const Twine &N, Module &M);
0192 
0193   /// Creates a function with some attributes recorded in llvm.module.flags
0194   /// and the LLVMContext applied.
0195   ///
0196   /// Use this when synthesizing new functions that need attributes that would
0197   /// have been set by command line options.
0198   ///
0199   /// This function should not be called from backends or the LTO pipeline. If
0200   /// it is called from one of those places, some default attributes will not be
0201   /// applied to the function.
0202   static Function *createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage,
0203                                          unsigned AddrSpace,
0204                                          const Twine &N = "",
0205                                          Module *M = nullptr);
0206 
0207   // Provide fast operand accessors.
0208   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
0209 
0210   /// Returns the number of non-debug IR instructions in this function.
0211   /// This is equivalent to the sum of the sizes of each basic block contained
0212   /// within this function.
0213   unsigned getInstructionCount() const;
0214 
0215   /// Returns the FunctionType for me.
0216   FunctionType *getFunctionType() const {
0217     return cast<FunctionType>(getValueType());
0218   }
0219 
0220   /// Returns the type of the ret val.
0221   Type *getReturnType() const { return getFunctionType()->getReturnType(); }
0222 
0223   /// getContext - Return a reference to the LLVMContext associated with this
0224   /// function.
0225   LLVMContext &getContext() const;
0226 
0227   /// Get the data layout of the module this function belongs to.
0228   ///
0229   /// Requires the function to have a parent module.
0230   const DataLayout &getDataLayout() const;
0231 
0232   /// isVarArg - Return true if this function takes a variable number of
0233   /// arguments.
0234   bool isVarArg() const { return getFunctionType()->isVarArg(); }
0235 
0236   bool isMaterializable() const {
0237     return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
0238   }
0239   void setIsMaterializable(bool V) {
0240     unsigned Mask = 1 << IsMaterializableBit;
0241     setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
0242                                 (V ? Mask : 0u));
0243   }
0244 
0245   /// getIntrinsicID - This method returns the ID number of the specified
0246   /// function, or Intrinsic::not_intrinsic if the function is not an
0247   /// intrinsic, or if the pointer is null.  This value is always defined to be
0248   /// zero to allow easy checking for whether a function is intrinsic or not.
0249   /// The particular intrinsic functions which correspond to this value are
0250   /// defined in llvm/Intrinsics.h.
0251   Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
0252 
0253   /// isIntrinsic - Returns true if the function's name starts with "llvm.".
0254   /// It's possible for this function to return true while getIntrinsicID()
0255   /// returns Intrinsic::not_intrinsic!
0256   bool isIntrinsic() const { return HasLLVMReservedName; }
0257 
0258   /// isTargetIntrinsic - Returns true if this function is an intrinsic and the
0259   /// intrinsic is specific to a certain target. If this is not an intrinsic
0260   /// or a generic intrinsic, false is returned.
0261   bool isTargetIntrinsic() const;
0262 
0263   /// Returns true if the function is one of the "Constrained Floating-Point
0264   /// Intrinsics". Returns false if not, and returns false when
0265   /// getIntrinsicID() returns Intrinsic::not_intrinsic.
0266   bool isConstrainedFPIntrinsic() const;
0267 
0268   /// Update internal caches that depend on the function name (such as the
0269   /// intrinsic ID and libcall cache).
0270   /// Note, this method does not need to be called directly, as it is called
0271   /// from Value::setName() whenever the name of this function changes.
0272   void updateAfterNameChange();
0273 
0274   /// getCallingConv()/setCallingConv(CC) - These method get and set the
0275   /// calling convention of this function.  The enum values for the known
0276   /// calling conventions are defined in CallingConv.h.
0277   CallingConv::ID getCallingConv() const {
0278     return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
0279                                         CallingConv::MaxID);
0280   }
0281   void setCallingConv(CallingConv::ID CC) {
0282     auto ID = static_cast<unsigned>(CC);
0283     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
0284     setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
0285   }
0286 
0287   enum ProfileCountType { PCT_Real, PCT_Synthetic };
0288 
0289   /// Class to represent profile counts.
0290   ///
0291   /// This class represents both real and synthetic profile counts.
0292   class ProfileCount {
0293   private:
0294     uint64_t Count = 0;
0295     ProfileCountType PCT = PCT_Real;
0296 
0297   public:
0298     ProfileCount(uint64_t Count, ProfileCountType PCT)
0299         : Count(Count), PCT(PCT) {}
0300     uint64_t getCount() const { return Count; }
0301     ProfileCountType getType() const { return PCT; }
0302     bool isSynthetic() const { return PCT == PCT_Synthetic; }
0303   };
0304 
0305   /// Set the entry count for this function.
0306   ///
0307   /// Entry count is the number of times this function was executed based on
0308   /// pgo data. \p Imports points to a set of GUIDs that needs to
0309   /// be imported by the function for sample PGO, to enable the same inlines as
0310   /// the profiled optimized binary.
0311   void setEntryCount(ProfileCount Count,
0312                      const DenseSet<GlobalValue::GUID> *Imports = nullptr);
0313 
0314   /// A convenience wrapper for setting entry count
0315   void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real,
0316                      const DenseSet<GlobalValue::GUID> *Imports = nullptr);
0317 
0318   /// Get the entry count for this function.
0319   ///
0320   /// Entry count is the number of times the function was executed.
0321   /// When AllowSynthetic is false, only pgo_data will be returned.
0322   std::optional<ProfileCount> getEntryCount(bool AllowSynthetic = false) const;
0323 
0324   /// Return true if the function is annotated with profile data.
0325   ///
0326   /// Presence of entry counts from a profile run implies the function has
0327   /// profile annotations. If IncludeSynthetic is false, only return true
0328   /// when the profile data is real.
0329   bool hasProfileData(bool IncludeSynthetic = false) const {
0330     return getEntryCount(IncludeSynthetic).has_value();
0331   }
0332 
0333   /// Returns the set of GUIDs that needs to be imported to the function for
0334   /// sample PGO, to enable the same inlines as the profiled optimized binary.
0335   DenseSet<GlobalValue::GUID> getImportGUIDs() const;
0336 
0337   /// Set the section prefix for this function.
0338   void setSectionPrefix(StringRef Prefix);
0339 
0340   /// Get the section prefix for this function.
0341   std::optional<StringRef> getSectionPrefix() const;
0342 
0343   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
0344   ///                             to use during code generation.
0345   bool hasGC() const {
0346     return getSubclassDataFromValue() & (1<<14);
0347   }
0348   const std::string &getGC() const;
0349   void setGC(std::string Str);
0350   void clearGC();
0351 
0352   /// Return the attribute list for this Function.
0353   AttributeList getAttributes() const { return AttributeSets; }
0354 
0355   /// Set the attribute list for this Function.
0356   void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; }
0357 
0358   // TODO: remove non-AtIndex versions of these methods.
0359   /// adds the attribute to the list of attributes.
0360   void addAttributeAtIndex(unsigned i, Attribute Attr);
0361 
0362   /// Add function attributes to this function.
0363   void addFnAttr(Attribute::AttrKind Kind);
0364 
0365   /// Add function attributes to this function.
0366   void addFnAttr(StringRef Kind, StringRef Val = StringRef());
0367 
0368   /// Add function attributes to this function.
0369   void addFnAttr(Attribute Attr);
0370 
0371   /// Add function attributes to this function.
0372   void addFnAttrs(const AttrBuilder &Attrs);
0373 
0374   /// Add return value attributes to this function.
0375   void addRetAttr(Attribute::AttrKind Kind);
0376 
0377   /// Add return value attributes to this function.
0378   void addRetAttr(Attribute Attr);
0379 
0380   /// Add return value attributes to this function.
0381   void addRetAttrs(const AttrBuilder &Attrs);
0382 
0383   /// adds the attribute to the list of attributes for the given arg.
0384   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
0385 
0386   /// adds the attribute to the list of attributes for the given arg.
0387   void addParamAttr(unsigned ArgNo, Attribute Attr);
0388 
0389   /// adds the attributes to the list of attributes for the given arg.
0390   void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs);
0391 
0392   /// removes the attribute from the list of attributes.
0393   void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind);
0394 
0395   /// removes the attribute from the list of attributes.
0396   void removeAttributeAtIndex(unsigned i, StringRef Kind);
0397 
0398   /// Remove function attributes from this function.
0399   void removeFnAttr(Attribute::AttrKind Kind);
0400 
0401   /// Remove function attribute from this function.
0402   void removeFnAttr(StringRef Kind);
0403 
0404   void removeFnAttrs(const AttributeMask &Attrs);
0405 
0406   /// removes the attribute from the return value list of attributes.
0407   void removeRetAttr(Attribute::AttrKind Kind);
0408 
0409   /// removes the attribute from the return value list of attributes.
0410   void removeRetAttr(StringRef Kind);
0411 
0412   /// removes the attributes from the return value list of attributes.
0413   void removeRetAttrs(const AttributeMask &Attrs);
0414 
0415   /// removes the attribute from the list of attributes.
0416   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
0417 
0418   /// removes the attribute from the list of attributes.
0419   void removeParamAttr(unsigned ArgNo, StringRef Kind);
0420 
0421   /// removes the attribute from the list of attributes.
0422   void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs);
0423 
0424   /// Return true if the function has the attribute.
0425   bool hasFnAttribute(Attribute::AttrKind Kind) const;
0426 
0427   /// Return true if the function has the attribute.
0428   bool hasFnAttribute(StringRef Kind) const;
0429 
0430   /// check if an attribute is in the list of attributes for the return value.
0431   bool hasRetAttribute(Attribute::AttrKind Kind) const;
0432 
0433   /// check if an attributes is in the list of attributes.
0434   bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
0435 
0436   /// Check if an attribute is in the list of attributes.
0437   bool hasParamAttribute(unsigned ArgNo, StringRef Kind) const;
0438 
0439   /// gets the attribute from the list of attributes.
0440   Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const;
0441 
0442   /// gets the attribute from the list of attributes.
0443   Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const;
0444 
0445   /// Check if attribute of the given kind is set at the given index.
0446   bool hasAttributeAtIndex(unsigned Idx, Attribute::AttrKind Kind) const;
0447 
0448   /// Return the attribute for the given attribute kind.
0449   Attribute getFnAttribute(Attribute::AttrKind Kind) const;
0450 
0451   /// Return the attribute for the given attribute kind.
0452   Attribute getFnAttribute(StringRef Kind) const;
0453 
0454   /// Return the attribute for the given attribute kind for the return value.
0455   Attribute getRetAttribute(Attribute::AttrKind Kind) const;
0456 
0457   /// For a string attribute \p Kind, parse attribute as an integer.
0458   ///
0459   /// \returns \p Default if attribute is not present.
0460   ///
0461   /// \returns \p Default if there is an error parsing the attribute integer,
0462   /// and error is emitted to the LLVMContext
0463   uint64_t getFnAttributeAsParsedInteger(StringRef Kind,
0464                                          uint64_t Default = 0) const;
0465 
0466   /// gets the specified attribute from the list of attributes.
0467   Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
0468 
0469   /// Return the stack alignment for the function.
0470   MaybeAlign getFnStackAlign() const {
0471     return AttributeSets.getFnStackAlignment();
0472   }
0473 
0474   /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
0475   bool hasStackProtectorFnAttr() const;
0476 
0477   /// adds the dereferenceable attribute to the list of attributes for
0478   /// the given arg.
0479   void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes);
0480 
0481   /// adds the dereferenceable_or_null attribute to the list of
0482   /// attributes for the given arg.
0483   void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes);
0484 
0485   /// adds the range attribute to the list of attributes for the return value.
0486   void addRangeRetAttr(const ConstantRange &CR);
0487 
0488   MaybeAlign getParamAlign(unsigned ArgNo) const {
0489     return AttributeSets.getParamAlignment(ArgNo);
0490   }
0491 
0492   MaybeAlign getParamStackAlign(unsigned ArgNo) const {
0493     return AttributeSets.getParamStackAlignment(ArgNo);
0494   }
0495 
0496   /// Extract the byval type for a parameter.
0497   Type *getParamByValType(unsigned ArgNo) const {
0498     return AttributeSets.getParamByValType(ArgNo);
0499   }
0500 
0501   /// Extract the sret type for a parameter.
0502   Type *getParamStructRetType(unsigned ArgNo) const {
0503     return AttributeSets.getParamStructRetType(ArgNo);
0504   }
0505 
0506   /// Extract the inalloca type for a parameter.
0507   Type *getParamInAllocaType(unsigned ArgNo) const {
0508     return AttributeSets.getParamInAllocaType(ArgNo);
0509   }
0510 
0511   /// Extract the byref type for a parameter.
0512   Type *getParamByRefType(unsigned ArgNo) const {
0513     return AttributeSets.getParamByRefType(ArgNo);
0514   }
0515 
0516   /// Extract the preallocated type for a parameter.
0517   Type *getParamPreallocatedType(unsigned ArgNo) const {
0518     return AttributeSets.getParamPreallocatedType(ArgNo);
0519   }
0520 
0521   /// Extract the number of dereferenceable bytes for a parameter.
0522   /// @param ArgNo Index of an argument, with 0 being the first function arg.
0523   uint64_t getParamDereferenceableBytes(unsigned ArgNo) const {
0524     return AttributeSets.getParamDereferenceableBytes(ArgNo);
0525   }
0526 
0527   /// Extract the number of dereferenceable_or_null bytes for a
0528   /// parameter.
0529   /// @param ArgNo AttributeList ArgNo, referring to an argument.
0530   uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const {
0531     return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo);
0532   }
0533 
0534   /// Extract the nofpclass attribute for a parameter.
0535   FPClassTest getParamNoFPClass(unsigned ArgNo) const {
0536     return AttributeSets.getParamNoFPClass(ArgNo);
0537   }
0538 
0539   /// Determine if the function is presplit coroutine.
0540   bool isPresplitCoroutine() const {
0541     return hasFnAttribute(Attribute::PresplitCoroutine);
0542   }
0543   void setPresplitCoroutine() { addFnAttr(Attribute::PresplitCoroutine); }
0544   void setSplittedCoroutine() { removeFnAttr(Attribute::PresplitCoroutine); }
0545 
0546   bool isCoroOnlyDestroyWhenComplete() const {
0547     return hasFnAttribute(Attribute::CoroDestroyOnlyWhenComplete);
0548   }
0549   void setCoroDestroyOnlyWhenComplete() {
0550     addFnAttr(Attribute::CoroDestroyOnlyWhenComplete);
0551   }
0552 
0553   MemoryEffects getMemoryEffects() const;
0554   void setMemoryEffects(MemoryEffects ME);
0555 
0556   /// Determine if the function does not access memory.
0557   bool doesNotAccessMemory() const;
0558   void setDoesNotAccessMemory();
0559 
0560   /// Determine if the function does not access or only reads memory.
0561   bool onlyReadsMemory() const;
0562   void setOnlyReadsMemory();
0563 
0564   /// Determine if the function does not access or only writes memory.
0565   bool onlyWritesMemory() const;
0566   void setOnlyWritesMemory();
0567 
0568   /// Determine if the call can access memmory only using pointers based
0569   /// on its arguments.
0570   bool onlyAccessesArgMemory() const;
0571   void setOnlyAccessesArgMemory();
0572 
0573   /// Determine if the function may only access memory that is
0574   ///  inaccessible from the IR.
0575   bool onlyAccessesInaccessibleMemory() const;
0576   void setOnlyAccessesInaccessibleMemory();
0577 
0578   /// Determine if the function may only access memory that is
0579   ///  either inaccessible from the IR or pointed to by its arguments.
0580   bool onlyAccessesInaccessibleMemOrArgMem() const;
0581   void setOnlyAccessesInaccessibleMemOrArgMem();
0582 
0583   /// Determine if the function cannot return.
0584   bool doesNotReturn() const {
0585     return hasFnAttribute(Attribute::NoReturn);
0586   }
0587   void setDoesNotReturn() {
0588     addFnAttr(Attribute::NoReturn);
0589   }
0590 
0591   /// Determine if the function should not perform indirect branch tracking.
0592   bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); }
0593 
0594   /// Determine if the function cannot unwind.
0595   bool doesNotThrow() const {
0596     return hasFnAttribute(Attribute::NoUnwind);
0597   }
0598   void setDoesNotThrow() {
0599     addFnAttr(Attribute::NoUnwind);
0600   }
0601 
0602   /// Determine if the call cannot be duplicated.
0603   bool cannotDuplicate() const {
0604     return hasFnAttribute(Attribute::NoDuplicate);
0605   }
0606   void setCannotDuplicate() {
0607     addFnAttr(Attribute::NoDuplicate);
0608   }
0609 
0610   /// Determine if the call is convergent.
0611   bool isConvergent() const {
0612     return hasFnAttribute(Attribute::Convergent);
0613   }
0614   void setConvergent() {
0615     addFnAttr(Attribute::Convergent);
0616   }
0617   void setNotConvergent() {
0618     removeFnAttr(Attribute::Convergent);
0619   }
0620 
0621   /// Determine if the call has sideeffects.
0622   bool isSpeculatable() const {
0623     return hasFnAttribute(Attribute::Speculatable);
0624   }
0625   void setSpeculatable() {
0626     addFnAttr(Attribute::Speculatable);
0627   }
0628 
0629   /// Determine if the call might deallocate memory.
0630   bool doesNotFreeMemory() const {
0631     return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree);
0632   }
0633   void setDoesNotFreeMemory() {
0634     addFnAttr(Attribute::NoFree);
0635   }
0636 
0637   /// Determine if the call can synchroize with other threads
0638   bool hasNoSync() const {
0639     return hasFnAttribute(Attribute::NoSync);
0640   }
0641   void setNoSync() {
0642     addFnAttr(Attribute::NoSync);
0643   }
0644 
0645   /// Determine if the function is known not to recurse, directly or
0646   /// indirectly.
0647   bool doesNotRecurse() const {
0648     return hasFnAttribute(Attribute::NoRecurse);
0649   }
0650   void setDoesNotRecurse() {
0651     addFnAttr(Attribute::NoRecurse);
0652   }
0653 
0654   /// Determine if the function is required to make forward progress.
0655   bool mustProgress() const {
0656     return hasFnAttribute(Attribute::MustProgress) ||
0657            hasFnAttribute(Attribute::WillReturn);
0658   }
0659   void setMustProgress() { addFnAttr(Attribute::MustProgress); }
0660 
0661   /// Determine if the function will return.
0662   bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); }
0663   void setWillReturn() { addFnAttr(Attribute::WillReturn); }
0664 
0665   /// Get what kind of unwind table entry to generate for this function.
0666   UWTableKind getUWTableKind() const {
0667     return AttributeSets.getUWTableKind();
0668   }
0669 
0670   /// True if the ABI mandates (or the user requested) that this
0671   /// function be in a unwind table.
0672   bool hasUWTable() const {
0673     return getUWTableKind() != UWTableKind::None;
0674   }
0675   void setUWTableKind(UWTableKind K) {
0676     if (K == UWTableKind::None)
0677       removeFnAttr(Attribute::UWTable);
0678     else
0679       addFnAttr(Attribute::getWithUWTableKind(getContext(), K));
0680   }
0681   /// True if this function needs an unwind table.
0682   bool needsUnwindTableEntry() const {
0683     return hasUWTable() || !doesNotThrow() || hasPersonalityFn();
0684   }
0685 
0686   /// Determine if the function returns a structure through first
0687   /// or second pointer argument.
0688   bool hasStructRetAttr() const {
0689     return AttributeSets.hasParamAttr(0, Attribute::StructRet) ||
0690            AttributeSets.hasParamAttr(1, Attribute::StructRet);
0691   }
0692 
0693   /// Determine if the parameter or return value is marked with NoAlias
0694   /// attribute.
0695   bool returnDoesNotAlias() const {
0696     return AttributeSets.hasRetAttr(Attribute::NoAlias);
0697   }
0698   void setReturnDoesNotAlias() { addRetAttr(Attribute::NoAlias); }
0699 
0700   /// Do not optimize this function (-O0).
0701   bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); }
0702 
0703   /// Optimize this function for minimum size (-Oz).
0704   bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); }
0705 
0706   /// Optimize this function for size (-Os) or minimum size (-Oz).
0707   bool hasOptSize() const {
0708     return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize();
0709   }
0710 
0711   /// Returns the denormal handling type for the default rounding mode of the
0712   /// function.
0713   DenormalMode getDenormalMode(const fltSemantics &FPType) const;
0714 
0715   /// Return the representational value of "denormal-fp-math". Code interested
0716   /// in the semantics of the function should use getDenormalMode instead.
0717   DenormalMode getDenormalModeRaw() const;
0718 
0719   /// Return the representational value of "denormal-fp-math-f32". Code
0720   /// interested in the semantics of the function should use getDenormalMode
0721   /// instead.
0722   DenormalMode getDenormalModeF32Raw() const;
0723 
0724   /// copyAttributesFrom - copy all additional attributes (those not needed to
0725   /// create a Function) from the Function Src to this one.
0726   void copyAttributesFrom(const Function *Src);
0727 
0728   /// deleteBody - This method deletes the body of the function, and converts
0729   /// the linkage to external.
0730   ///
0731   void deleteBody() {
0732     deleteBodyImpl(/*ShouldDrop=*/false);
0733     setLinkage(ExternalLinkage);
0734   }
0735 
0736   /// removeFromParent - This method unlinks 'this' from the containing module,
0737   /// but does not delete it.
0738   ///
0739   void removeFromParent();
0740 
0741   /// eraseFromParent - This method unlinks 'this' from the containing module
0742   /// and deletes it.
0743   ///
0744   void eraseFromParent();
0745 
0746   /// Steal arguments from another function.
0747   ///
0748   /// Drop this function's arguments and splice in the ones from \c Src.
0749   /// Requires that this has no function body.
0750   void stealArgumentListFrom(Function &Src);
0751 
0752   /// Insert \p BB in the basic block list at \p Position. \Returns an iterator
0753   /// to the newly inserted BB.
0754   Function::iterator insert(Function::iterator Position, BasicBlock *BB) {
0755     Function::iterator FIt = BasicBlocks.insert(Position, BB);
0756     BB->setIsNewDbgInfoFormat(IsNewDbgInfoFormat);
0757     return FIt;
0758   }
0759 
0760   /// Transfer all blocks from \p FromF to this function at \p ToIt.
0761   void splice(Function::iterator ToIt, Function *FromF) {
0762     splice(ToIt, FromF, FromF->begin(), FromF->end());
0763   }
0764 
0765   /// Transfer one BasicBlock from \p FromF at \p FromIt to this function
0766   /// at \p ToIt.
0767   void splice(Function::iterator ToIt, Function *FromF,
0768               Function::iterator FromIt) {
0769     auto FromItNext = std::next(FromIt);
0770     // Single-element splice is a noop if destination == source.
0771     if (ToIt == FromIt || ToIt == FromItNext)
0772       return;
0773     splice(ToIt, FromF, FromIt, FromItNext);
0774   }
0775 
0776   /// Transfer a range of basic blocks that belong to \p FromF from \p
0777   /// FromBeginIt to \p FromEndIt, to this function at \p ToIt.
0778   void splice(Function::iterator ToIt, Function *FromF,
0779               Function::iterator FromBeginIt,
0780               Function::iterator FromEndIt);
0781 
0782   /// Erases a range of BasicBlocks from \p FromIt to (not including) \p ToIt.
0783   /// \Returns \p ToIt.
0784   Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt);
0785 
0786 private:
0787   // These need access to the underlying BB list.
0788   friend void BasicBlock::removeFromParent();
0789   friend iplist<BasicBlock>::iterator BasicBlock::eraseFromParent();
0790   template <class BB_t, class BB_i_t, class BI_t, class II_t>
0791   friend class InstIterator;
0792   friend class llvm::SymbolTableListTraits<llvm::BasicBlock>;
0793   friend class llvm::ilist_node_with_parent<llvm::BasicBlock, llvm::Function>;
0794 
0795   /// Get the underlying elements of the Function... the basic block list is
0796   /// empty for external functions.
0797   ///
0798   /// This is deliberately private because we have implemented an adequate set
0799   /// of functions to modify the list, including Function::splice(),
0800   /// Function::erase(), Function::insert() etc.
0801   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
0802         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
0803 
0804   static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
0805     return &Function::BasicBlocks;
0806   }
0807 
0808 public:
0809   const BasicBlock       &getEntryBlock() const   { return front(); }
0810         BasicBlock       &getEntryBlock()         { return front(); }
0811 
0812   //===--------------------------------------------------------------------===//
0813   // Symbol Table Accessing functions...
0814 
0815   /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
0816   ///
0817   inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
0818   inline const ValueSymbolTable *getValueSymbolTable() const {
0819     return SymTab.get();
0820   }
0821 
0822   //===--------------------------------------------------------------------===//
0823   // Block number functions
0824 
0825   /// Return a value larger than the largest block number. Intended to allocate
0826   /// a vector that is sufficiently large to hold all blocks indexed by their
0827   /// number.
0828   unsigned getMaxBlockNumber() const { return NextBlockNum; }
0829 
0830   /// Renumber basic blocks into a dense value range starting from 0. Be aware
0831   /// that other data structures and analyses (e.g., DominatorTree) may depend
0832   /// on the value numbers and need to be updated or invalidated.
0833   void renumberBlocks();
0834 
0835   /// Return the "epoch" of current block numbers. This will return a different
0836   /// value after every renumbering. The intention is: if something (e.g., an
0837   /// analysis) uses block numbers, it also stores the number epoch and then
0838   /// can assert later on that the epoch didn't change (indicating that the
0839   /// numbering is still valid). If the epoch changed, blocks might have been
0840   /// assigned new numbers and previous uses of the numbers needs to be
0841   /// invalidated. This is solely intended as a debugging feature.
0842   unsigned getBlockNumberEpoch() const { return BlockNumEpoch; }
0843 
0844 private:
0845   /// Assert that all blocks have unique numbers within 0..NextBlockNum. This
0846   /// has O(n) runtime complexity.
0847   void validateBlockNumbers() const;
0848 
0849 public:
0850   //===--------------------------------------------------------------------===//
0851   // BasicBlock iterator forwarding functions
0852   //
0853   iterator                begin()       { return BasicBlocks.begin(); }
0854   const_iterator          begin() const { return BasicBlocks.begin(); }
0855   iterator                end  ()       { return BasicBlocks.end();   }
0856   const_iterator          end  () const { return BasicBlocks.end();   }
0857 
0858   size_t                   size() const { return BasicBlocks.size();  }
0859   bool                    empty() const { return BasicBlocks.empty(); }
0860   const BasicBlock       &front() const { return BasicBlocks.front(); }
0861         BasicBlock       &front()       { return BasicBlocks.front(); }
0862   const BasicBlock        &back() const { return BasicBlocks.back();  }
0863         BasicBlock        &back()       { return BasicBlocks.back();  }
0864 
0865 /// @name Function Argument Iteration
0866 /// @{
0867 
0868   arg_iterator arg_begin() {
0869     CheckLazyArguments();
0870     return Arguments;
0871   }
0872   const_arg_iterator arg_begin() const {
0873     CheckLazyArguments();
0874     return Arguments;
0875   }
0876 
0877   arg_iterator arg_end() {
0878     CheckLazyArguments();
0879     return Arguments + NumArgs;
0880   }
0881   const_arg_iterator arg_end() const {
0882     CheckLazyArguments();
0883     return Arguments + NumArgs;
0884   }
0885 
0886   Argument* getArg(unsigned i) const {
0887     assert (i < NumArgs && "getArg() out of range!");
0888     CheckLazyArguments();
0889     return Arguments + i;
0890   }
0891 
0892   iterator_range<arg_iterator> args() {
0893     return make_range(arg_begin(), arg_end());
0894   }
0895   iterator_range<const_arg_iterator> args() const {
0896     return make_range(arg_begin(), arg_end());
0897   }
0898 
0899 /// @}
0900 
0901   size_t arg_size() const { return NumArgs; }
0902   bool arg_empty() const { return arg_size() == 0; }
0903 
0904   /// Check whether this function has a personality function.
0905   bool hasPersonalityFn() const {
0906     return getSubclassDataFromValue() & (1<<3);
0907   }
0908 
0909   /// Get the personality function associated with this function.
0910   Constant *getPersonalityFn() const;
0911   void setPersonalityFn(Constant *Fn);
0912 
0913   /// Check whether this function has prefix data.
0914   bool hasPrefixData() const {
0915     return getSubclassDataFromValue() & (1<<1);
0916   }
0917 
0918   /// Get the prefix data associated with this function.
0919   Constant *getPrefixData() const;
0920   void setPrefixData(Constant *PrefixData);
0921 
0922   /// Check whether this function has prologue data.
0923   bool hasPrologueData() const {
0924     return getSubclassDataFromValue() & (1<<2);
0925   }
0926 
0927   /// Get the prologue data associated with this function.
0928   Constant *getPrologueData() const;
0929   void setPrologueData(Constant *PrologueData);
0930 
0931   /// Print the function to an output stream with an optional
0932   /// AssemblyAnnotationWriter.
0933   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
0934              bool ShouldPreserveUseListOrder = false,
0935              bool IsForDebug = false) const;
0936 
0937   /// viewCFG - This function is meant for use from the debugger.  You can just
0938   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
0939   /// program, displaying the CFG of the current function with the code for each
0940   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
0941   /// in your path.
0942   ///
0943   void viewCFG() const;
0944 
0945   /// viewCFG - This function is meant for use from the debugger. It works just
0946   /// like viewCFG(), but generates the dot file with the given file name.
0947   void viewCFG(const char *OutputFileName) const;
0948 
0949   /// Extended form to print edge weights.
0950   void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
0951                const BranchProbabilityInfo *BPI,
0952                const char *OutputFileName = nullptr) const;
0953 
0954   /// viewCFGOnly - This function is meant for use from the debugger.  It works
0955   /// just like viewCFG, but it does not include the contents of basic blocks
0956   /// into the nodes, just the label.  If you are only interested in the CFG
0957   /// this can make the graph smaller.
0958   ///
0959   void viewCFGOnly() const;
0960 
0961   /// viewCFG - This function is meant for use from the debugger. It works just
0962   /// like viewCFGOnly(), but generates the dot file with the given file name.
0963   void viewCFGOnly(const char *OutputFileName) const;
0964 
0965   /// Extended form to print edge weights.
0966   void viewCFGOnly(const BlockFrequencyInfo *BFI,
0967                    const BranchProbabilityInfo *BPI) const;
0968 
0969   /// Methods for support type inquiry through isa, cast, and dyn_cast:
0970   static bool classof(const Value *V) {
0971     return V->getValueID() == Value::FunctionVal;
0972   }
0973 
0974   /// dropAllReferences() - This method causes all the subinstructions to "let
0975   /// go" of all references that they are maintaining.  This allows one to
0976   /// 'delete' a whole module at a time, even though there may be circular
0977   /// references... first all references are dropped, and all use counts go to
0978   /// zero.  Then everything is deleted for real.  Note that no operations are
0979   /// valid on an object that has "dropped all references", except operator
0980   /// delete.
0981   ///
0982   /// Since no other object in the module can have references into the body of a
0983   /// function, dropping all references deletes the entire body of the function,
0984   /// including any contained basic blocks.
0985   ///
0986   void dropAllReferences() {
0987     deleteBodyImpl(/*ShouldDrop=*/true);
0988   }
0989 
0990   /// hasAddressTaken - returns true if there are any uses of this function
0991   /// other than direct calls or invokes to it, or blockaddress expressions.
0992   /// Optionally passes back an offending user for diagnostic purposes,
0993   /// ignores callback uses, assume like pointer annotation calls, references in
0994   /// llvm.used and llvm.compiler.used variables, operand bundle
0995   /// "clang.arc.attachedcall", and direct calls with a different call site
0996   /// signature (the function is implicitly casted).
0997   bool hasAddressTaken(const User ** = nullptr, bool IgnoreCallbackUses = false,
0998                        bool IgnoreAssumeLikeCalls = true,
0999                        bool IngoreLLVMUsed = false,
1000                        bool IgnoreARCAttachedCall = false,
1001                        bool IgnoreCastedDirectCall = false) const;
1002 
1003   /// isDefTriviallyDead - Return true if it is trivially safe to remove
1004   /// this function definition from the module (because it isn't externally
1005   /// visible, does not have its address taken, and has no callers).  To make
1006   /// this more accurate, call removeDeadConstantUsers first.
1007   bool isDefTriviallyDead() const;
1008 
1009   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1010   /// setjmp or other function that gcc recognizes as "returning twice".
1011   bool callsFunctionThatReturnsTwice() const;
1012 
1013   /// Set the attached subprogram.
1014   ///
1015   /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
1016   void setSubprogram(DISubprogram *SP);
1017 
1018   /// Get the attached subprogram.
1019   ///
1020   /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
1021   /// to \a DISubprogram.
1022   DISubprogram *getSubprogram() const;
1023 
1024   /// Returns true if we should emit debug info for profiling.
1025   bool shouldEmitDebugInfoForProfiling() const;
1026 
1027   /// Check if null pointer dereferencing is considered undefined behavior for
1028   /// the function.
1029   /// Return value: false => null pointer dereference is undefined.
1030   /// Return value: true =>  null pointer dereference is not undefined.
1031   bool nullPointerIsDefined() const;
1032 
1033 private:
1034   void allocHungoffUselist();
1035   template<int Idx> void setHungoffOperand(Constant *C);
1036 
1037   /// Shadow Value::setValueSubclassData with a private forwarding method so
1038   /// that subclasses cannot accidentally use it.
1039   void setValueSubclassData(unsigned short D) {
1040     Value::setValueSubclassData(D);
1041   }
1042   void setValueSubclassDataBit(unsigned Bit, bool On);
1043 };
1044 
1045 /// Check whether null pointer dereferencing is considered undefined behavior
1046 /// for a given function or an address space.
1047 /// Null pointer access in non-zero address space is not considered undefined.
1048 /// Return value: false => null pointer dereference is undefined.
1049 /// Return value: true =>  null pointer dereference is not undefined.
1050 bool NullPointerIsDefined(const Function *F, unsigned AS = 0);
1051 
1052 template <> struct OperandTraits<Function> : public HungoffOperandTraits {};
1053 
1054 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
1055 
1056 } // end namespace llvm
1057 
1058 #endif // LLVM_IR_FUNCTION_H