1 //===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the Function class, which represents a
11 // single function/procedure in LLVM.
13 // A function basically consists of a list of basic blocks, a list of arguments,
14 // and a symbol table.
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_IR_FUNCTION_H
19 #define LLVM_IR_FUNCTION_H
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/GlobalObject.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/OperandTraits.h"
32 #include "llvm/IR/SymbolTableListTraits.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/Support/Compiler.h"
43 template <typename T> class Optional;
44 class AssemblyAnnotationWriter;
49 class Function : public GlobalObject, public ilist_node<Function> {
51 typedef SymbolTableList<BasicBlock> BasicBlockListType;
53 // BasicBlock iterators...
54 typedef BasicBlockListType::iterator iterator;
55 typedef BasicBlockListType::const_iterator const_iterator;
57 typedef Argument *arg_iterator;
58 typedef const Argument *const_arg_iterator;
61 // Important things that make up a function!
62 BasicBlockListType BasicBlocks; ///< The basic blocks
63 mutable Argument *Arguments; ///< The formal arguments
65 std::unique_ptr<ValueSymbolTable>
66 SymTab; ///< Symbol table of args/instructions
67 AttributeList AttributeSets; ///< Parameter attributes
72 * bit 0 : HasLazyArguments
73 * bit 1 : HasPrefixData
74 * bit 2 : HasPrologueData
75 * bit 3 : HasPersonalityFn
76 * bits 4-13 : CallingConvention
78 * bits 15 : [reserved]
81 /// Bits from GlobalObject::GlobalObjectSubclassData.
83 /// Whether this function is materializable.
84 IsMaterializableBit = 0,
87 friend class SymbolTableListTraits<Function>;
89 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
90 /// built on demand, so that the list isn't allocated until the first client
91 /// needs it. The hasLazyArguments predicate returns true if the arg list
92 /// hasn't been set up yet.
94 bool hasLazyArguments() const {
95 return getSubclassDataFromValue() & (1<<0);
99 void CheckLazyArguments() const {
100 if (hasLazyArguments())
101 BuildLazyArguments();
104 void BuildLazyArguments() const;
106 void clearArguments();
108 /// Function ctor - If the (optional) Module argument is specified, the
109 /// function is automatically inserted into the end of the function list for
112 Function(FunctionType *Ty, LinkageTypes Linkage,
113 const Twine &N = "", Module *M = nullptr);
116 Function(const Function&) = delete;
117 void operator=(const Function&) = delete;
118 ~Function() override;
120 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
121 const Twine &N = "", Module *M = nullptr) {
122 return new Function(Ty, Linkage, N, M);
125 // Provide fast operand accessors.
126 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
127 /// Returns the FunctionType for me.
128 FunctionType *getFunctionType() const {
129 return cast<FunctionType>(getValueType());
131 /// Returns the type of the ret val.
132 Type *getReturnType() const { return getFunctionType()->getReturnType(); }
134 /// getContext - Return a reference to the LLVMContext associated with this
136 LLVMContext &getContext() const;
138 /// isVarArg - Return true if this function takes a variable number of
140 bool isVarArg() const { return getFunctionType()->isVarArg(); }
142 bool isMaterializable() const {
143 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
145 void setIsMaterializable(bool V) {
146 unsigned Mask = 1 << IsMaterializableBit;
147 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
151 /// getIntrinsicID - This method returns the ID number of the specified
152 /// function, or Intrinsic::not_intrinsic if the function is not an
153 /// intrinsic, or if the pointer is null. This value is always defined to be
154 /// zero to allow easy checking for whether a function is intrinsic or not.
155 /// The particular intrinsic functions which correspond to this value are
156 /// defined in llvm/Intrinsics.h.
157 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
159 /// isIntrinsic - Returns true if the function's name starts with "llvm.".
160 /// It's possible for this function to return true while getIntrinsicID()
161 /// returns Intrinsic::not_intrinsic!
162 bool isIntrinsic() const { return HasLLVMReservedName; }
164 static Intrinsic::ID lookupIntrinsicID(StringRef Name);
166 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
167 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
168 /// if the name of this function does not match an intrinsic in that header.
169 /// Note, this method does not need to be called directly, as it is called
170 /// from Value::setName() whenever the name of this function changes.
171 void recalculateIntrinsicID();
173 /// getCallingConv()/setCallingConv(CC) - These method get and set the
174 /// calling convention of this function. The enum values for the known
175 /// calling conventions are defined in CallingConv.h.
176 CallingConv::ID getCallingConv() const {
177 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
180 void setCallingConv(CallingConv::ID CC) {
181 auto ID = static_cast<unsigned>(CC);
182 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
183 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
186 /// @brief Return the attribute list for this Function.
187 AttributeList getAttributes() const { return AttributeSets; }
189 /// @brief Set the attribute list for this Function.
190 void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; }
192 /// @brief Add function attributes to this function.
193 void addFnAttr(Attribute::AttrKind Kind) {
194 addAttribute(AttributeList::FunctionIndex, Kind);
197 /// @brief Add function attributes to this function.
198 void addFnAttr(StringRef Kind, StringRef Val = StringRef()) {
199 addAttribute(AttributeList::FunctionIndex,
200 Attribute::get(getContext(), Kind, Val));
203 void addFnAttr(Attribute Attr) {
204 addAttribute(AttributeList::FunctionIndex, Attr);
207 /// @brief Remove function attributes from this function.
208 void removeFnAttr(Attribute::AttrKind Kind) {
209 removeAttribute(AttributeList::FunctionIndex, Kind);
212 /// @brief Remove function attribute from this function.
213 void removeFnAttr(StringRef Kind) {
214 setAttributes(AttributeSets.removeAttribute(
215 getContext(), AttributeList::FunctionIndex, Kind));
218 /// \brief Set the entry count for this function.
220 /// Entry count is the number of times this function was executed based on
221 /// pgo data. \p Imports points to a set of GUIDs that needs to be imported
222 /// by the function for sample PGO, to enable the same inlines as the
223 /// profiled optimized binary.
224 void setEntryCount(uint64_t Count,
225 const DenseSet<GlobalValue::GUID> *Imports = nullptr);
227 /// \brief Get the entry count for this function.
229 /// Entry count is the number of times the function was executed based on
231 Optional<uint64_t> getEntryCount() const;
233 /// Returns the set of GUIDs that needs to be imported to the function for
234 /// sample PGO, to enable the same inlines as the profiled optimized binary.
235 DenseSet<GlobalValue::GUID> getImportGUIDs() const;
237 /// Set the section prefix for this function.
238 void setSectionPrefix(StringRef Prefix);
240 /// Get the section prefix for this function.
241 Optional<StringRef> getSectionPrefix() const;
243 /// @brief Return true if the function has the attribute.
244 bool hasFnAttribute(Attribute::AttrKind Kind) const {
245 return AttributeSets.hasFnAttribute(Kind);
247 bool hasFnAttribute(StringRef Kind) const {
248 return AttributeSets.hasFnAttribute(Kind);
251 /// @brief Return the attribute for the given attribute kind.
252 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
253 return getAttribute(AttributeList::FunctionIndex, Kind);
255 Attribute getFnAttribute(StringRef Kind) const {
256 return getAttribute(AttributeList::FunctionIndex, Kind);
259 /// \brief Return the stack alignment for the function.
260 unsigned getFnStackAlignment() const {
261 if (!hasFnAttribute(Attribute::StackAlignment))
263 return AttributeSets.getStackAlignment(AttributeList::FunctionIndex);
266 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
267 /// to use during code generation.
269 return getSubclassDataFromValue() & (1<<14);
271 const std::string &getGC() const;
272 void setGC(std::string Str);
275 /// @brief adds the attribute to the list of attributes.
276 void addAttribute(unsigned i, Attribute::AttrKind Kind);
278 /// @brief adds the attribute to the list of attributes.
279 void addAttribute(unsigned i, Attribute Attr);
281 /// @brief adds the attributes to the list of attributes.
282 void addAttributes(unsigned i, AttributeList Attrs);
284 /// @brief removes the attribute from the list of attributes.
285 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
287 /// @brief removes the attribute from the list of attributes.
288 void removeAttribute(unsigned i, StringRef Kind);
290 /// @brief removes the attributes from the list of attributes.
291 void removeAttributes(unsigned i, AttributeList Attrs);
293 /// @brief check if an attributes is in the list of attributes.
294 bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const {
295 return getAttributes().hasAttribute(i, Kind);
298 /// @brief check if an attributes is in the list of attributes.
299 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const {
300 return getAttributes().hasParamAttribute(ArgNo, Kind);
303 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
304 return AttributeSets.getAttribute(i, Kind);
307 Attribute getAttribute(unsigned i, StringRef Kind) const {
308 return AttributeSets.getAttribute(i, Kind);
311 /// @brief adds the dereferenceable attribute to the list of attributes.
312 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
314 /// @brief adds the dereferenceable_or_null attribute to the list of
316 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
318 /// @brief Extract the alignment for a call or parameter (0=unknown).
319 unsigned getParamAlignment(unsigned i) const {
320 return AttributeSets.getParamAlignment(i);
323 /// @brief Extract the number of dereferenceable bytes for a call or
324 /// parameter (0=unknown).
325 uint64_t getDereferenceableBytes(unsigned i) const {
326 return AttributeSets.getDereferenceableBytes(i);
329 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
330 /// parameter (0=unknown).
331 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
332 return AttributeSets.getDereferenceableOrNullBytes(i);
335 /// @brief Determine if the function does not access memory.
336 bool doesNotAccessMemory() const {
337 return hasFnAttribute(Attribute::ReadNone);
339 void setDoesNotAccessMemory() {
340 addFnAttr(Attribute::ReadNone);
343 /// @brief Determine if the function does not access or only reads memory.
344 bool onlyReadsMemory() const {
345 return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly);
347 void setOnlyReadsMemory() {
348 addFnAttr(Attribute::ReadOnly);
351 /// @brief Determine if the function does not access or only writes memory.
352 bool doesNotReadMemory() const {
353 return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly);
355 void setDoesNotReadMemory() {
356 addFnAttr(Attribute::WriteOnly);
359 /// @brief Determine if the call can access memmory only using pointers based
360 /// on its arguments.
361 bool onlyAccessesArgMemory() const {
362 return hasFnAttribute(Attribute::ArgMemOnly);
364 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
366 /// @brief Determine if the function may only access memory that is
367 /// inaccessible from the IR.
368 bool onlyAccessesInaccessibleMemory() const {
369 return hasFnAttribute(Attribute::InaccessibleMemOnly);
371 void setOnlyAccessesInaccessibleMemory() {
372 addFnAttr(Attribute::InaccessibleMemOnly);
375 /// @brief Determine if the function may only access memory that is
376 /// either inaccessible from the IR or pointed to by its arguments.
377 bool onlyAccessesInaccessibleMemOrArgMem() const {
378 return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly);
380 void setOnlyAccessesInaccessibleMemOrArgMem() {
381 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
384 /// @brief Determine if the function cannot return.
385 bool doesNotReturn() const {
386 return hasFnAttribute(Attribute::NoReturn);
388 void setDoesNotReturn() {
389 addFnAttr(Attribute::NoReturn);
392 /// @brief Determine if the function cannot unwind.
393 bool doesNotThrow() const {
394 return hasFnAttribute(Attribute::NoUnwind);
396 void setDoesNotThrow() {
397 addFnAttr(Attribute::NoUnwind);
400 /// @brief Determine if the call cannot be duplicated.
401 bool cannotDuplicate() const {
402 return hasFnAttribute(Attribute::NoDuplicate);
404 void setCannotDuplicate() {
405 addFnAttr(Attribute::NoDuplicate);
408 /// @brief Determine if the call is convergent.
409 bool isConvergent() const {
410 return hasFnAttribute(Attribute::Convergent);
412 void setConvergent() {
413 addFnAttr(Attribute::Convergent);
415 void setNotConvergent() {
416 removeFnAttr(Attribute::Convergent);
419 /// Determine if the function is known not to recurse, directly or
421 bool doesNotRecurse() const {
422 return hasFnAttribute(Attribute::NoRecurse);
424 void setDoesNotRecurse() {
425 addFnAttr(Attribute::NoRecurse);
428 /// @brief True if the ABI mandates (or the user requested) that this
429 /// function be in a unwind table.
430 bool hasUWTable() const {
431 return hasFnAttribute(Attribute::UWTable);
433 void setHasUWTable() {
434 addFnAttr(Attribute::UWTable);
437 /// @brief True if this function needs an unwind table.
438 bool needsUnwindTableEntry() const {
439 return hasUWTable() || !doesNotThrow();
442 /// @brief Determine if the function returns a structure through first
443 /// pointer argument.
444 bool hasStructRetAttr() const {
445 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
446 AttributeSets.hasAttribute(2, Attribute::StructRet);
449 /// @brief Determine if the parameter or return value is marked with NoAlias
451 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
452 bool doesNotAlias(unsigned n) const {
453 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
455 void setDoesNotAlias(unsigned n) {
456 addAttribute(n, Attribute::NoAlias);
459 /// @brief Determine if the parameter can be captured.
460 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
461 bool doesNotCapture(unsigned n) const {
462 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
464 void setDoesNotCapture(unsigned n) {
465 addAttribute(n, Attribute::NoCapture);
468 bool doesNotAccessMemory(unsigned n) const {
469 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
471 void setDoesNotAccessMemory(unsigned n) {
472 addAttribute(n, Attribute::ReadNone);
475 bool onlyReadsMemory(unsigned n) const {
476 return doesNotAccessMemory(n) ||
477 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
479 void setOnlyReadsMemory(unsigned n) {
480 addAttribute(n, Attribute::ReadOnly);
483 /// Optimize this function for minimum size (-Oz).
484 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); }
486 /// Optimize this function for size (-Os) or minimum size (-Oz).
487 bool optForSize() const {
488 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
491 /// copyAttributesFrom - copy all additional attributes (those not needed to
492 /// create a Function) from the Function Src to this one.
493 void copyAttributesFrom(const GlobalValue *Src) override;
495 /// deleteBody - This method deletes the body of the function, and converts
496 /// the linkage to external.
500 setLinkage(ExternalLinkage);
503 /// removeFromParent - This method unlinks 'this' from the containing module,
504 /// but does not delete it.
506 void removeFromParent() override;
508 /// eraseFromParent - This method unlinks 'this' from the containing module
511 void eraseFromParent() override;
513 /// Steal arguments from another function.
515 /// Drop this function's arguments and splice in the ones from \c Src.
516 /// Requires that this has no function body.
517 void stealArgumentListFrom(Function &Src);
519 /// Get the underlying elements of the Function... the basic block list is
520 /// empty for external functions.
522 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
523 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
525 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
526 return &Function::BasicBlocks;
529 const BasicBlock &getEntryBlock() const { return front(); }
530 BasicBlock &getEntryBlock() { return front(); }
532 //===--------------------------------------------------------------------===//
533 // Symbol Table Accessing functions...
535 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
537 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
538 inline const ValueSymbolTable *getValueSymbolTable() const {
542 //===--------------------------------------------------------------------===//
543 // BasicBlock iterator forwarding functions
545 iterator begin() { return BasicBlocks.begin(); }
546 const_iterator begin() const { return BasicBlocks.begin(); }
547 iterator end () { return BasicBlocks.end(); }
548 const_iterator end () const { return BasicBlocks.end(); }
550 size_t size() const { return BasicBlocks.size(); }
551 bool empty() const { return BasicBlocks.empty(); }
552 const BasicBlock &front() const { return BasicBlocks.front(); }
553 BasicBlock &front() { return BasicBlocks.front(); }
554 const BasicBlock &back() const { return BasicBlocks.back(); }
555 BasicBlock &back() { return BasicBlocks.back(); }
557 /// @name Function Argument Iteration
560 arg_iterator arg_begin() {
561 CheckLazyArguments();
564 const_arg_iterator arg_begin() const {
565 CheckLazyArguments();
569 arg_iterator arg_end() {
570 CheckLazyArguments();
571 return Arguments + NumArgs;
573 const_arg_iterator arg_end() const {
574 CheckLazyArguments();
575 return Arguments + NumArgs;
578 iterator_range<arg_iterator> args() {
579 return make_range(arg_begin(), arg_end());
581 iterator_range<const_arg_iterator> args() const {
582 return make_range(arg_begin(), arg_end());
587 size_t arg_size() const { return NumArgs; }
588 bool arg_empty() const { return arg_size() == 0; }
590 /// \brief Check whether this function has a personality function.
591 bool hasPersonalityFn() const {
592 return getSubclassDataFromValue() & (1<<3);
595 /// \brief Get the personality function associated with this function.
596 Constant *getPersonalityFn() const;
597 void setPersonalityFn(Constant *Fn);
599 /// \brief Check whether this function has prefix data.
600 bool hasPrefixData() const {
601 return getSubclassDataFromValue() & (1<<1);
604 /// \brief Get the prefix data associated with this function.
605 Constant *getPrefixData() const;
606 void setPrefixData(Constant *PrefixData);
608 /// \brief Check whether this function has prologue data.
609 bool hasPrologueData() const {
610 return getSubclassDataFromValue() & (1<<2);
613 /// \brief Get the prologue data associated with this function.
614 Constant *getPrologueData() const;
615 void setPrologueData(Constant *PrologueData);
617 /// Print the function to an output stream with an optional
618 /// AssemblyAnnotationWriter.
619 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
620 bool ShouldPreserveUseListOrder = false,
621 bool IsForDebug = false) const;
623 /// viewCFG - This function is meant for use from the debugger. You can just
624 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
625 /// program, displaying the CFG of the current function with the code for each
626 /// basic block inside. This depends on there being a 'dot' and 'gv' program
629 void viewCFG() const;
631 /// viewCFGOnly - This function is meant for use from the debugger. It works
632 /// just like viewCFG, but it does not include the contents of basic blocks
633 /// into the nodes, just the label. If you are only interested in the CFG
634 /// this can make the graph smaller.
636 void viewCFGOnly() const;
638 /// Methods for support type inquiry through isa, cast, and dyn_cast:
639 static inline bool classof(const Value *V) {
640 return V->getValueID() == Value::FunctionVal;
643 /// dropAllReferences() - This method causes all the subinstructions to "let
644 /// go" of all references that they are maintaining. This allows one to
645 /// 'delete' a whole module at a time, even though there may be circular
646 /// references... first all references are dropped, and all use counts go to
647 /// zero. Then everything is deleted for real. Note that no operations are
648 /// valid on an object that has "dropped all references", except operator
651 /// Since no other object in the module can have references into the body of a
652 /// function, dropping all references deletes the entire body of the function,
653 /// including any contained basic blocks.
655 void dropAllReferences();
657 /// hasAddressTaken - returns true if there are any uses of this function
658 /// other than direct calls or invokes to it, or blockaddress expressions.
659 /// Optionally passes back an offending user for diagnostic purposes.
661 bool hasAddressTaken(const User** = nullptr) const;
663 /// isDefTriviallyDead - Return true if it is trivially safe to remove
664 /// this function definition from the module (because it isn't externally
665 /// visible, does not have its address taken, and has no callers). To make
666 /// this more accurate, call removeDeadConstantUsers first.
667 bool isDefTriviallyDead() const;
669 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
670 /// setjmp or other function that gcc recognizes as "returning twice".
671 bool callsFunctionThatReturnsTwice() const;
673 /// \brief Set the attached subprogram.
675 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
676 void setSubprogram(DISubprogram *SP);
678 /// \brief Get the attached subprogram.
680 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
681 /// to \a DISubprogram.
682 DISubprogram *getSubprogram() const;
684 /// Returns true if we should emit debug info for profiling.
685 bool isDebugInfoForProfiling() const;
688 void allocHungoffUselist();
689 template<int Idx> void setHungoffOperand(Constant *C);
691 /// Shadow Value::setValueSubclassData with a private forwarding method so
692 /// that subclasses cannot accidentally use it.
693 void setValueSubclassData(unsigned short D) {
694 Value::setValueSubclassData(D);
696 void setValueSubclassDataBit(unsigned Bit, bool On);
700 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
702 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
704 } // end namespace llvm
706 #endif // LLVM_IR_FUNCTION_H