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/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/Argument.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/GlobalObject.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/OperandTraits.h"
31 #include "llvm/IR/SymbolTableListTraits.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Support/Compiler.h"
42 template <typename T> class Optional;
43 class AssemblyAnnotationWriter;
48 class Function : public GlobalObject, public ilist_node<Function> {
50 typedef SymbolTableList<Argument> ArgumentListType;
51 typedef SymbolTableList<BasicBlock> BasicBlockListType;
53 // BasicBlock iterators...
54 typedef BasicBlockListType::iterator iterator;
55 typedef BasicBlockListType::const_iterator const_iterator;
57 typedef ArgumentListType::iterator arg_iterator;
58 typedef ArgumentListType::const_iterator const_arg_iterator;
61 // Important things that make up a function!
62 BasicBlockListType BasicBlocks; ///< The basic blocks
63 mutable ArgumentListType ArgumentList; ///< The formal arguments
64 std::unique_ptr<ValueSymbolTable>
65 SymTab; ///< Symbol table of args/instructions
66 AttributeSet AttributeSets; ///< Parameter attributes
71 * bit 0 : HasLazyArguments
72 * bit 1 : HasPrefixData
73 * bit 2 : HasPrologueData
74 * bit 3 : HasPersonalityFn
75 * bits 4-13 : CallingConvention
77 * bits 15 : [reserved]
80 /// Bits from GlobalObject::GlobalObjectSubclassData.
82 /// Whether this function is materializable.
83 IsMaterializableBit = 0,
86 friend class SymbolTableListTraits<Function>;
88 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
89 /// built on demand, so that the list isn't allocated until the first client
90 /// needs it. The hasLazyArguments predicate returns true if the arg list
91 /// hasn't been set up yet.
93 bool hasLazyArguments() const {
94 return getSubclassDataFromValue() & (1<<0);
98 void CheckLazyArguments() const {
99 if (hasLazyArguments())
100 BuildLazyArguments();
103 void BuildLazyArguments() const;
105 /// Function ctor - If the (optional) Module argument is specified, the
106 /// function is automatically inserted into the end of the function list for
109 Function(FunctionType *Ty, LinkageTypes Linkage,
110 const Twine &N = "", Module *M = nullptr);
113 Function(const Function&) = delete;
114 void operator=(const Function&) = delete;
115 ~Function() override;
117 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
118 const Twine &N = "", Module *M = nullptr) {
119 return new Function(Ty, Linkage, N, M);
122 // Provide fast operand accessors.
123 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
124 /// Returns the type of the ret val.
125 Type *getReturnType() const;
126 /// Returns the FunctionType for me.
127 FunctionType *getFunctionType() const;
129 /// getContext - Return a reference to the LLVMContext associated with this
131 LLVMContext &getContext() const;
133 /// isVarArg - Return true if this function takes a variable number of
135 bool isVarArg() const;
137 bool isMaterializable() const;
138 void setIsMaterializable(bool V);
140 /// getIntrinsicID - This method returns the ID number of the specified
141 /// function, or Intrinsic::not_intrinsic if the function is not an
142 /// intrinsic, or if the pointer is null. This value is always defined to be
143 /// zero to allow easy checking for whether a function is intrinsic or not.
144 /// The particular intrinsic functions which correspond to this value are
145 /// defined in llvm/Intrinsics.h.
146 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
148 /// isIntrinsic - Returns true if the function's name starts with "llvm.".
149 /// It's possible for this function to return true while getIntrinsicID()
150 /// returns Intrinsic::not_intrinsic!
151 bool isIntrinsic() const { return HasLLVMReservedName; }
153 static Intrinsic::ID lookupIntrinsicID(StringRef Name);
155 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
156 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
157 /// if the name of this function does not match an intrinsic in that header.
158 /// Note, this method does not need to be called directly, as it is called
159 /// from Value::setName() whenever the name of this function changes.
160 void recalculateIntrinsicID();
162 /// getCallingConv()/setCallingConv(CC) - These method get and set the
163 /// calling convention of this function. The enum values for the known
164 /// calling conventions are defined in CallingConv.h.
165 CallingConv::ID getCallingConv() const {
166 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
169 void setCallingConv(CallingConv::ID CC) {
170 auto ID = static_cast<unsigned>(CC);
171 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
172 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
175 /// @brief Return the attribute list for this Function.
176 AttributeSet getAttributes() const { return AttributeSets; }
178 /// @brief Set the attribute list for this Function.
179 void setAttributes(AttributeSet Attrs) { AttributeSets = Attrs; }
181 /// @brief Add function attributes to this function.
182 void addFnAttr(Attribute::AttrKind Kind) {
183 addAttribute(AttributeSet::FunctionIndex, Kind);
186 /// @brief Add function attributes to this function.
187 void addFnAttr(StringRef Kind, StringRef Val = StringRef()) {
188 addAttribute(AttributeSet::FunctionIndex,
189 Attribute::get(getContext(), Kind, Val));
192 void addFnAttr(Attribute Attr) {
193 addAttribute(AttributeSet::FunctionIndex, Attr);
196 /// @brief Remove function attributes from this function.
197 void removeFnAttr(Attribute::AttrKind Kind) {
198 removeAttribute(AttributeSet::FunctionIndex, Kind);
201 /// @brief Remove function attribute from this function.
202 void removeFnAttr(StringRef Kind) {
203 setAttributes(AttributeSets.removeAttribute(
204 getContext(), AttributeSet::FunctionIndex, Kind));
207 /// \brief Set the entry count for this function.
209 /// Entry count is the number of times this function was executed based on
211 void setEntryCount(uint64_t Count);
213 /// \brief Get the entry count for this function.
215 /// Entry count is the number of times the function was executed based on
217 Optional<uint64_t> getEntryCount() const;
219 /// Set the section prefix for this function.
220 void setSectionPrefix(StringRef Prefix);
222 /// Get the section prefix for this function.
223 Optional<StringRef> getSectionPrefix() const;
225 /// @brief Return true if the function has the attribute.
226 bool hasFnAttribute(Attribute::AttrKind Kind) const {
227 return AttributeSets.hasFnAttribute(Kind);
229 bool hasFnAttribute(StringRef Kind) const {
230 return AttributeSets.hasFnAttribute(Kind);
233 /// @brief Return the attribute for the given attribute kind.
234 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
235 return getAttribute(AttributeSet::FunctionIndex, Kind);
237 Attribute getFnAttribute(StringRef Kind) const {
238 return getAttribute(AttributeSet::FunctionIndex, Kind);
241 /// \brief Return the stack alignment for the function.
242 unsigned getFnStackAlignment() const {
243 if (!hasFnAttribute(Attribute::StackAlignment))
245 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
248 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
249 /// to use during code generation.
251 return getSubclassDataFromValue() & (1<<14);
253 const std::string &getGC() const;
254 void setGC(std::string Str);
257 /// @brief adds the attribute to the list of attributes.
258 void addAttribute(unsigned i, Attribute::AttrKind Kind);
260 /// @brief adds the attribute to the list of attributes.
261 void addAttribute(unsigned i, Attribute Attr);
263 /// @brief adds the attributes to the list of attributes.
264 void addAttributes(unsigned i, AttributeSet Attrs);
266 /// @brief removes the attribute from the list of attributes.
267 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
269 /// @brief removes the attribute from the list of attributes.
270 void removeAttribute(unsigned i, StringRef Kind);
272 /// @brief removes the attributes from the list of attributes.
273 void removeAttributes(unsigned i, AttributeSet Attrs);
275 /// @brief check if an attributes is in the list of attributes.
276 bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const {
277 return getAttributes().hasAttribute(i, Kind);
280 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
281 return AttributeSets.getAttribute(i, Kind);
284 Attribute getAttribute(unsigned i, StringRef Kind) const {
285 return AttributeSets.getAttribute(i, Kind);
288 /// @brief adds the dereferenceable attribute to the list of attributes.
289 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
291 /// @brief adds the dereferenceable_or_null attribute to the list of
293 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
295 /// @brief Extract the alignment for a call or parameter (0=unknown).
296 unsigned getParamAlignment(unsigned i) const {
297 return AttributeSets.getParamAlignment(i);
300 /// @brief Extract the number of dereferenceable bytes for a call or
301 /// parameter (0=unknown).
302 uint64_t getDereferenceableBytes(unsigned i) const {
303 return AttributeSets.getDereferenceableBytes(i);
306 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
307 /// parameter (0=unknown).
308 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
309 return AttributeSets.getDereferenceableOrNullBytes(i);
312 /// @brief Determine if the function does not access memory.
313 bool doesNotAccessMemory() const {
314 return hasFnAttribute(Attribute::ReadNone);
316 void setDoesNotAccessMemory() {
317 addFnAttr(Attribute::ReadNone);
320 /// @brief Determine if the function does not access or only reads memory.
321 bool onlyReadsMemory() const {
322 return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly);
324 void setOnlyReadsMemory() {
325 addFnAttr(Attribute::ReadOnly);
328 /// @brief Determine if the function does not access or only writes memory.
329 bool doesNotReadMemory() const {
330 return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly);
332 void setDoesNotReadMemory() {
333 addFnAttr(Attribute::WriteOnly);
336 /// @brief Determine if the call can access memmory only using pointers based
337 /// on its arguments.
338 bool onlyAccessesArgMemory() const {
339 return hasFnAttribute(Attribute::ArgMemOnly);
341 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
343 /// @brief Determine if the function may only access memory that is
344 /// inaccessible from the IR.
345 bool onlyAccessesInaccessibleMemory() const {
346 return hasFnAttribute(Attribute::InaccessibleMemOnly);
348 void setOnlyAccessesInaccessibleMemory() {
349 addFnAttr(Attribute::InaccessibleMemOnly);
352 /// @brief Determine if the function may only access memory that is
353 /// either inaccessible from the IR or pointed to by its arguments.
354 bool onlyAccessesInaccessibleMemOrArgMem() const {
355 return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly);
357 void setOnlyAccessesInaccessibleMemOrArgMem() {
358 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
361 /// @brief Determine if the function cannot return.
362 bool doesNotReturn() const {
363 return hasFnAttribute(Attribute::NoReturn);
365 void setDoesNotReturn() {
366 addFnAttr(Attribute::NoReturn);
369 /// @brief Determine if the function cannot unwind.
370 bool doesNotThrow() const {
371 return hasFnAttribute(Attribute::NoUnwind);
373 void setDoesNotThrow() {
374 addFnAttr(Attribute::NoUnwind);
377 /// @brief Determine if the call cannot be duplicated.
378 bool cannotDuplicate() const {
379 return hasFnAttribute(Attribute::NoDuplicate);
381 void setCannotDuplicate() {
382 addFnAttr(Attribute::NoDuplicate);
385 /// @brief Determine if the call is convergent.
386 bool isConvergent() const {
387 return hasFnAttribute(Attribute::Convergent);
389 void setConvergent() {
390 addFnAttr(Attribute::Convergent);
392 void setNotConvergent() {
393 removeFnAttr(Attribute::Convergent);
396 /// Determine if the function is known not to recurse, directly or
398 bool doesNotRecurse() const {
399 return hasFnAttribute(Attribute::NoRecurse);
401 void setDoesNotRecurse() {
402 addFnAttr(Attribute::NoRecurse);
405 /// @brief True if the ABI mandates (or the user requested) that this
406 /// function be in a unwind table.
407 bool hasUWTable() const {
408 return hasFnAttribute(Attribute::UWTable);
410 void setHasUWTable() {
411 addFnAttr(Attribute::UWTable);
414 /// @brief True if this function needs an unwind table.
415 bool needsUnwindTableEntry() const {
416 return hasUWTable() || !doesNotThrow();
419 /// @brief Determine if the function returns a structure through first
420 /// pointer argument.
421 bool hasStructRetAttr() const {
422 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
423 AttributeSets.hasAttribute(2, Attribute::StructRet);
426 /// @brief Determine if the parameter or return value is marked with NoAlias
428 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
429 bool doesNotAlias(unsigned n) const {
430 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
432 void setDoesNotAlias(unsigned n) {
433 addAttribute(n, Attribute::NoAlias);
436 /// @brief Determine if the parameter can be captured.
437 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
438 bool doesNotCapture(unsigned n) const {
439 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
441 void setDoesNotCapture(unsigned n) {
442 addAttribute(n, Attribute::NoCapture);
445 bool doesNotAccessMemory(unsigned n) const {
446 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
448 void setDoesNotAccessMemory(unsigned n) {
449 addAttribute(n, Attribute::ReadNone);
452 bool onlyReadsMemory(unsigned n) const {
453 return doesNotAccessMemory(n) ||
454 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
456 void setOnlyReadsMemory(unsigned n) {
457 addAttribute(n, Attribute::ReadOnly);
460 /// Optimize this function for minimum size (-Oz).
461 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); }
463 /// Optimize this function for size (-Os) or minimum size (-Oz).
464 bool optForSize() const {
465 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
468 /// copyAttributesFrom - copy all additional attributes (those not needed to
469 /// create a Function) from the Function Src to this one.
470 void copyAttributesFrom(const GlobalValue *Src) override;
472 /// deleteBody - This method deletes the body of the function, and converts
473 /// the linkage to external.
477 setLinkage(ExternalLinkage);
480 /// removeFromParent - This method unlinks 'this' from the containing module,
481 /// but does not delete it.
483 void removeFromParent() override;
485 /// eraseFromParent - This method unlinks 'this' from the containing module
488 void eraseFromParent() override;
490 /// Steal arguments from another function.
492 /// Drop this function's arguments and splice in the ones from \c Src.
493 /// Requires that this has no function body.
494 void stealArgumentListFrom(Function &Src);
496 /// Get the underlying elements of the Function... the basic block list is
497 /// empty for external functions.
499 const ArgumentListType &getArgumentList() const {
500 CheckLazyArguments();
503 ArgumentListType &getArgumentList() {
504 CheckLazyArguments();
508 static ArgumentListType Function::*getSublistAccess(Argument*) {
509 return &Function::ArgumentList;
512 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
513 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
515 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
516 return &Function::BasicBlocks;
519 const BasicBlock &getEntryBlock() const { return front(); }
520 BasicBlock &getEntryBlock() { return front(); }
522 //===--------------------------------------------------------------------===//
523 // Symbol Table Accessing functions...
525 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
527 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
528 inline const ValueSymbolTable *getValueSymbolTable() const {
532 //===--------------------------------------------------------------------===//
533 // BasicBlock iterator forwarding functions
535 iterator begin() { return BasicBlocks.begin(); }
536 const_iterator begin() const { return BasicBlocks.begin(); }
537 iterator end () { return BasicBlocks.end(); }
538 const_iterator end () const { return BasicBlocks.end(); }
540 size_t size() const { return BasicBlocks.size(); }
541 bool empty() const { return BasicBlocks.empty(); }
542 const BasicBlock &front() const { return BasicBlocks.front(); }
543 BasicBlock &front() { return BasicBlocks.front(); }
544 const BasicBlock &back() const { return BasicBlocks.back(); }
545 BasicBlock &back() { return BasicBlocks.back(); }
547 /// @name Function Argument Iteration
550 arg_iterator arg_begin() {
551 CheckLazyArguments();
552 return ArgumentList.begin();
554 const_arg_iterator arg_begin() const {
555 CheckLazyArguments();
556 return ArgumentList.begin();
559 arg_iterator arg_end() {
560 CheckLazyArguments();
561 return ArgumentList.end();
563 const_arg_iterator arg_end() const {
564 CheckLazyArguments();
565 return ArgumentList.end();
568 iterator_range<arg_iterator> args() {
569 return make_range(arg_begin(), arg_end());
571 iterator_range<const_arg_iterator> args() const {
572 return make_range(arg_begin(), arg_end());
577 size_t arg_size() const;
578 bool arg_empty() const;
580 /// \brief Check whether this function has a personality function.
581 bool hasPersonalityFn() const {
582 return getSubclassDataFromValue() & (1<<3);
585 /// \brief Get the personality function associated with this function.
586 Constant *getPersonalityFn() const;
587 void setPersonalityFn(Constant *Fn);
589 /// \brief Check whether this function has prefix data.
590 bool hasPrefixData() const {
591 return getSubclassDataFromValue() & (1<<1);
594 /// \brief Get the prefix data associated with this function.
595 Constant *getPrefixData() const;
596 void setPrefixData(Constant *PrefixData);
598 /// \brief Check whether this function has prologue data.
599 bool hasPrologueData() const {
600 return getSubclassDataFromValue() & (1<<2);
603 /// \brief Get the prologue data associated with this function.
604 Constant *getPrologueData() const;
605 void setPrologueData(Constant *PrologueData);
607 /// Print the function to an output stream with an optional
608 /// AssemblyAnnotationWriter.
609 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
610 bool ShouldPreserveUseListOrder = false,
611 bool IsForDebug = false) const;
613 /// viewCFG - This function is meant for use from the debugger. You can just
614 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
615 /// program, displaying the CFG of the current function with the code for each
616 /// basic block inside. This depends on there being a 'dot' and 'gv' program
619 void viewCFG() const;
621 /// viewCFGOnly - This function is meant for use from the debugger. It works
622 /// just like viewCFG, but it does not include the contents of basic blocks
623 /// into the nodes, just the label. If you are only interested in the CFG
624 /// this can make the graph smaller.
626 void viewCFGOnly() const;
628 /// Methods for support type inquiry through isa, cast, and dyn_cast:
629 static inline bool classof(const Value *V) {
630 return V->getValueID() == Value::FunctionVal;
633 /// dropAllReferences() - This method causes all the subinstructions to "let
634 /// go" of all references that they are maintaining. This allows one to
635 /// 'delete' a whole module at a time, even though there may be circular
636 /// references... first all references are dropped, and all use counts go to
637 /// zero. Then everything is deleted for real. Note that no operations are
638 /// valid on an object that has "dropped all references", except operator
641 /// Since no other object in the module can have references into the body of a
642 /// function, dropping all references deletes the entire body of the function,
643 /// including any contained basic blocks.
645 void dropAllReferences();
647 /// hasAddressTaken - returns true if there are any uses of this function
648 /// other than direct calls or invokes to it, or blockaddress expressions.
649 /// Optionally passes back an offending user for diagnostic purposes.
651 bool hasAddressTaken(const User** = nullptr) const;
653 /// isDefTriviallyDead - Return true if it is trivially safe to remove
654 /// this function definition from the module (because it isn't externally
655 /// visible, does not have its address taken, and has no callers). To make
656 /// this more accurate, call removeDeadConstantUsers first.
657 bool isDefTriviallyDead() const;
659 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
660 /// setjmp or other function that gcc recognizes as "returning twice".
661 bool callsFunctionThatReturnsTwice() const;
663 /// \brief Set the attached subprogram.
665 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
666 void setSubprogram(DISubprogram *SP);
668 /// \brief Get the attached subprogram.
670 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
671 /// to \a DISubprogram.
672 DISubprogram *getSubprogram() const;
675 void allocHungoffUselist();
676 template<int Idx> void setHungoffOperand(Constant *C);
678 /// Shadow Value::setValueSubclassData with a private forwarding method so
679 /// that subclasses cannot accidentally use it.
680 void setValueSubclassData(unsigned short D) {
681 Value::setValueSubclassData(D);
683 void setValueSubclassDataBit(unsigned Bit, bool On);
687 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
689 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
691 } // end namespace llvm
693 #endif // LLVM_IR_FUNCTION_H