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/iterator_range.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/GlobalObject.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/Support/Compiler.h"
38 struct SymbolTableListSentinelTraits<Argument>
39 : public ilist_half_embedded_sentinel_traits<Argument> {};
41 class Function : public GlobalObject, public ilist_node<Function> {
43 typedef SymbolTableList<Argument> ArgumentListType;
44 typedef SymbolTableList<BasicBlock> BasicBlockListType;
46 // BasicBlock iterators...
47 typedef BasicBlockListType::iterator iterator;
48 typedef BasicBlockListType::const_iterator const_iterator;
50 typedef ArgumentListType::iterator arg_iterator;
51 typedef ArgumentListType::const_iterator const_arg_iterator;
54 // Important things that make up a function!
55 BasicBlockListType BasicBlocks; ///< The basic blocks
56 mutable ArgumentListType ArgumentList; ///< The formal arguments
57 ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
58 AttributeSet AttributeSets; ///< Parameter attributes
64 * bit 0 : HasLazyArguments
65 * bit 1 : HasPrefixData
66 * bit 2 : HasPrologueData
67 * bit 3 : HasPersonalityFn
68 * bits 4-13 : CallingConvention
69 * bits 14-15 : [reserved]
72 /// Bits from GlobalObject::GlobalObjectSubclassData.
74 /// Whether this function is materializable.
75 IsMaterializableBit = 1 << 0,
76 HasMetadataHashEntryBit = 1 << 1
78 void setGlobalObjectBit(unsigned Mask, bool Value) {
79 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
83 friend class SymbolTableListTraits<Function>;
85 void setParent(Module *parent);
87 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
88 /// built on demand, so that the list isn't allocated until the first client
89 /// needs it. The hasLazyArguments predicate returns true if the arg list
90 /// hasn't been set up yet.
91 bool hasLazyArguments() const {
92 return getSubclassDataFromValue() & (1<<0);
94 void CheckLazyArguments() const {
95 if (hasLazyArguments())
98 void BuildLazyArguments() const;
100 Function(const Function&) = delete;
101 void operator=(const Function&) = delete;
103 /// Function ctor - If the (optional) Module argument is specified, the
104 /// function is automatically inserted into the end of the function list for
107 Function(FunctionType *Ty, LinkageTypes Linkage,
108 const Twine &N = "", Module *M = nullptr);
111 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
112 const Twine &N = "", Module *M = nullptr) {
113 return new Function(Ty, Linkage, N, M);
116 ~Function() override;
118 /// \brief Provide fast operand accessors
119 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
121 Type *getReturnType() const; // Return the type of the ret val
122 FunctionType *getFunctionType() const; // Return the FunctionType for me
124 /// getContext - Return a reference to the LLVMContext associated with this
126 LLVMContext &getContext() const;
128 /// isVarArg - Return true if this function takes a variable number of
130 bool isVarArg() const;
132 bool isMaterializable() const;
133 void setIsMaterializable(bool V);
135 /// getIntrinsicID - This method returns the ID number of the specified
136 /// function, or Intrinsic::not_intrinsic if the function is not an
137 /// intrinsic, or if the pointer is null. This value is always defined to be
138 /// zero to allow easy checking for whether a function is intrinsic or not.
139 /// The particular intrinsic functions which correspond to this value are
140 /// defined in llvm/Intrinsics.h.
141 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
142 bool isIntrinsic() const { return getName().startswith("llvm."); }
144 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
145 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
146 /// if the name of this function does not match an intrinsic in that header.
147 /// Note, this method does not need to be called directly, as it is called
148 /// from Value::setName() whenever the name of this function changes.
149 void recalculateIntrinsicID();
151 /// getCallingConv()/setCallingConv(CC) - These method get and set the
152 /// calling convention of this function. The enum values for the known
153 /// calling conventions are defined in CallingConv.h.
154 CallingConv::ID getCallingConv() const {
155 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
158 void setCallingConv(CallingConv::ID CC) {
159 auto ID = static_cast<unsigned>(CC);
160 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
161 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
164 /// @brief Return the attribute list for this Function.
165 AttributeSet getAttributes() const { return AttributeSets; }
167 /// @brief Set the attribute list for this Function.
168 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
170 /// @brief Add function attributes to this function.
171 void addFnAttr(Attribute::AttrKind N) {
172 setAttributes(AttributeSets.addAttribute(getContext(),
173 AttributeSet::FunctionIndex, N));
176 /// @brief Remove function attributes from this function.
177 void removeFnAttr(Attribute::AttrKind N) {
178 setAttributes(AttributeSets.removeAttribute(
179 getContext(), AttributeSet::FunctionIndex, N));
182 /// @brief Add function attributes to this function.
183 void addFnAttr(StringRef Kind) {
185 AttributeSets.addAttribute(getContext(),
186 AttributeSet::FunctionIndex, Kind));
188 void addFnAttr(StringRef Kind, StringRef Value) {
190 AttributeSets.addAttribute(getContext(),
191 AttributeSet::FunctionIndex, Kind, Value));
194 /// Set the entry count for this function.
195 void setEntryCount(uint64_t Count);
197 /// Get the entry count for this function.
198 Optional<uint64_t> getEntryCount() const;
200 /// @brief Return true if the function has the attribute.
201 bool hasFnAttribute(Attribute::AttrKind Kind) const {
202 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
204 bool hasFnAttribute(StringRef Kind) const {
205 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
208 /// @brief Return the attribute for the given attribute kind.
209 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
210 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
212 Attribute getFnAttribute(StringRef Kind) const {
213 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
216 /// \brief Return the stack alignment for the function.
217 unsigned getFnStackAlignment() const {
218 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
221 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
222 /// to use during code generation.
224 const char *getGC() const;
225 void setGC(const char *Str);
228 /// @brief adds the attribute to the list of attributes.
229 void addAttribute(unsigned i, Attribute::AttrKind attr);
231 /// @brief adds the attributes to the list of attributes.
232 void addAttributes(unsigned i, AttributeSet attrs);
234 /// @brief removes the attributes from the list of attributes.
235 void removeAttributes(unsigned i, AttributeSet attr);
237 /// @brief adds the dereferenceable attribute to the list of attributes.
238 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
240 /// @brief adds the dereferenceable_or_null attribute to the list of
242 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
244 /// @brief Extract the alignment for a call or parameter (0=unknown).
245 unsigned getParamAlignment(unsigned i) const {
246 return AttributeSets.getParamAlignment(i);
249 /// @brief Extract the number of dereferenceable bytes for a call or
250 /// parameter (0=unknown).
251 uint64_t getDereferenceableBytes(unsigned i) const {
252 return AttributeSets.getDereferenceableBytes(i);
255 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
256 /// parameter (0=unknown).
257 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
258 return AttributeSets.getDereferenceableOrNullBytes(i);
261 /// @brief Determine if the function does not access memory.
262 bool doesNotAccessMemory() const {
263 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
264 Attribute::ReadNone);
266 void setDoesNotAccessMemory() {
267 addFnAttr(Attribute::ReadNone);
270 /// @brief Determine if the function does not access or only reads memory.
271 bool onlyReadsMemory() const {
272 return doesNotAccessMemory() ||
273 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
274 Attribute::ReadOnly);
276 void setOnlyReadsMemory() {
277 addFnAttr(Attribute::ReadOnly);
280 /// @brief Determine if the call can access memmory only using pointers based
281 /// on its arguments.
282 bool onlyAccessesArgMemory() const {
283 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
284 Attribute::ArgMemOnly);
286 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
288 /// @brief Determine if the function may only access memory that is
289 /// inaccessible from the IR.
290 bool onlyAccessesInaccessibleMemory() const {
291 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
292 Attribute::InaccessibleMemOnly);
294 void setOnlyAccessesInaccessibleMemory() {
295 addFnAttr(Attribute::InaccessibleMemOnly);
298 /// @brief Determine if the function may only access memory that is
299 // either inaccessible from the IR or pointed to by its arguments.
300 bool onlyAccessesInaccessibleMemOrArgMem() const {
301 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
302 Attribute::InaccessibleMemOrArgMemOnly);
304 void setOnlyAccessesInaccessibleMemOrArgMem() {
305 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
308 /// @brief Determine if the function cannot return.
309 bool doesNotReturn() const {
310 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
311 Attribute::NoReturn);
313 void setDoesNotReturn() {
314 addFnAttr(Attribute::NoReturn);
317 /// @brief Determine if the function cannot unwind.
318 bool doesNotThrow() const {
319 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
320 Attribute::NoUnwind);
322 void setDoesNotThrow() {
323 addFnAttr(Attribute::NoUnwind);
326 /// @brief Determine if the call cannot be duplicated.
327 bool cannotDuplicate() const {
328 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
329 Attribute::NoDuplicate);
331 void setCannotDuplicate() {
332 addFnAttr(Attribute::NoDuplicate);
335 /// @brief Determine if the call is convergent.
336 bool isConvergent() const {
337 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
338 Attribute::Convergent);
340 void setConvergent() {
341 addFnAttr(Attribute::Convergent);
344 /// Determine if the function is known not to recurse, directly or
346 bool doesNotRecurse() const {
347 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
348 Attribute::NoRecurse);
350 void setDoesNotRecurse() {
351 addFnAttr(Attribute::NoRecurse);
354 /// @brief True if the ABI mandates (or the user requested) that this
355 /// function be in a unwind table.
356 bool hasUWTable() const {
357 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
360 void setHasUWTable() {
361 addFnAttr(Attribute::UWTable);
364 /// @brief True if this function needs an unwind table.
365 bool needsUnwindTableEntry() const {
366 return hasUWTable() || !doesNotThrow();
369 /// @brief Determine if the function returns a structure through first
370 /// pointer argument.
371 bool hasStructRetAttr() const {
372 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
373 AttributeSets.hasAttribute(2, Attribute::StructRet);
376 /// @brief Determine if the parameter or return value is marked with NoAlias
378 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
379 bool doesNotAlias(unsigned n) const {
380 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
382 void setDoesNotAlias(unsigned n) {
383 addAttribute(n, Attribute::NoAlias);
386 /// @brief Determine if the parameter can be captured.
387 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
388 bool doesNotCapture(unsigned n) const {
389 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
391 void setDoesNotCapture(unsigned n) {
392 addAttribute(n, Attribute::NoCapture);
395 bool doesNotAccessMemory(unsigned n) const {
396 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
398 void setDoesNotAccessMemory(unsigned n) {
399 addAttribute(n, Attribute::ReadNone);
402 bool onlyReadsMemory(unsigned n) const {
403 return doesNotAccessMemory(n) ||
404 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
406 void setOnlyReadsMemory(unsigned n) {
407 addAttribute(n, Attribute::ReadOnly);
410 /// Optimize this function for minimum size (-Oz).
411 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); };
413 /// Optimize this function for size (-Os) or minimum size (-Oz).
414 bool optForSize() const {
415 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
418 /// copyAttributesFrom - copy all additional attributes (those not needed to
419 /// create a Function) from the Function Src to this one.
420 void copyAttributesFrom(const GlobalValue *Src) override;
422 /// deleteBody - This method deletes the body of the function, and converts
423 /// the linkage to external.
427 setLinkage(ExternalLinkage);
430 /// removeFromParent - This method unlinks 'this' from the containing module,
431 /// but does not delete it.
433 void removeFromParent() override;
435 /// eraseFromParent - This method unlinks 'this' from the containing module
438 void eraseFromParent() override;
440 /// Get the underlying elements of the Function... the basic block list is
441 /// empty for external functions.
443 const ArgumentListType &getArgumentList() const {
444 CheckLazyArguments();
447 ArgumentListType &getArgumentList() {
448 CheckLazyArguments();
451 static ArgumentListType Function::*getSublistAccess(Argument*) {
452 return &Function::ArgumentList;
455 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
456 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
457 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
458 return &Function::BasicBlocks;
461 const BasicBlock &getEntryBlock() const { return front(); }
462 BasicBlock &getEntryBlock() { return front(); }
464 //===--------------------------------------------------------------------===//
465 // Symbol Table Accessing functions...
467 /// getSymbolTable() - Return the symbol table...
469 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
470 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
472 //===--------------------------------------------------------------------===//
473 // BasicBlock iterator forwarding functions
475 iterator begin() { return BasicBlocks.begin(); }
476 const_iterator begin() const { return BasicBlocks.begin(); }
477 iterator end () { return BasicBlocks.end(); }
478 const_iterator end () const { return BasicBlocks.end(); }
480 size_t size() const { return BasicBlocks.size(); }
481 bool empty() const { return BasicBlocks.empty(); }
482 const BasicBlock &front() const { return BasicBlocks.front(); }
483 BasicBlock &front() { return BasicBlocks.front(); }
484 const BasicBlock &back() const { return BasicBlocks.back(); }
485 BasicBlock &back() { return BasicBlocks.back(); }
487 /// @name Function Argument Iteration
490 arg_iterator arg_begin() {
491 CheckLazyArguments();
492 return ArgumentList.begin();
494 const_arg_iterator arg_begin() const {
495 CheckLazyArguments();
496 return ArgumentList.begin();
498 arg_iterator arg_end() {
499 CheckLazyArguments();
500 return ArgumentList.end();
502 const_arg_iterator arg_end() const {
503 CheckLazyArguments();
504 return ArgumentList.end();
507 iterator_range<arg_iterator> args() {
508 return make_range(arg_begin(), arg_end());
511 iterator_range<const_arg_iterator> args() const {
512 return make_range(arg_begin(), arg_end());
517 size_t arg_size() const;
518 bool arg_empty() const;
520 /// \brief Check whether this function has a personality function.
521 bool hasPersonalityFn() const {
522 return getSubclassDataFromValue() & (1<<3);
525 /// \brief Get the personality function associated with this function.
526 Constant *getPersonalityFn() const;
527 void setPersonalityFn(Constant *Fn);
529 /// \brief Check whether this function has prefix data.
530 bool hasPrefixData() const {
531 return getSubclassDataFromValue() & (1<<1);
534 /// \brief Get the prefix data associated with this function.
535 Constant *getPrefixData() const;
536 void setPrefixData(Constant *PrefixData);
538 /// \brief Check whether this function has prologue data.
539 bool hasPrologueData() const {
540 return getSubclassDataFromValue() & (1<<2);
543 /// \brief Get the prologue data associated with this function.
544 Constant *getPrologueData() const;
545 void setPrologueData(Constant *PrologueData);
547 /// viewCFG - This function is meant for use from the debugger. You can just
548 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
549 /// program, displaying the CFG of the current function with the code for each
550 /// basic block inside. This depends on there being a 'dot' and 'gv' program
553 void viewCFG() const;
555 /// viewCFGOnly - This function is meant for use from the debugger. It works
556 /// just like viewCFG, but it does not include the contents of basic blocks
557 /// into the nodes, just the label. If you are only interested in the CFG
558 /// this can make the graph smaller.
560 void viewCFGOnly() const;
562 /// Methods for support type inquiry through isa, cast, and dyn_cast:
563 static inline bool classof(const Value *V) {
564 return V->getValueID() == Value::FunctionVal;
567 /// dropAllReferences() - This method causes all the subinstructions to "let
568 /// go" of all references that they are maintaining. This allows one to
569 /// 'delete' a whole module at a time, even though there may be circular
570 /// references... first all references are dropped, and all use counts go to
571 /// zero. Then everything is deleted for real. Note that no operations are
572 /// valid on an object that has "dropped all references", except operator
575 /// Since no other object in the module can have references into the body of a
576 /// function, dropping all references deletes the entire body of the function,
577 /// including any contained basic blocks.
579 void dropAllReferences();
581 /// hasAddressTaken - returns true if there are any uses of this function
582 /// other than direct calls or invokes to it, or blockaddress expressions.
583 /// Optionally passes back an offending user for diagnostic purposes.
585 bool hasAddressTaken(const User** = nullptr) const;
587 /// isDefTriviallyDead - Return true if it is trivially safe to remove
588 /// this function definition from the module (because it isn't externally
589 /// visible, does not have its address taken, and has no callers). To make
590 /// this more accurate, call removeDeadConstantUsers first.
591 bool isDefTriviallyDead() const;
593 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
594 /// setjmp or other function that gcc recognizes as "returning twice".
595 bool callsFunctionThatReturnsTwice() const;
597 /// \brief Check if this has any metadata.
598 bool hasMetadata() const { return hasMetadataHashEntry(); }
600 /// \brief Get the current metadata attachment, if any.
602 /// Returns \c nullptr if such an attachment is missing.
604 MDNode *getMetadata(unsigned KindID) const;
605 MDNode *getMetadata(StringRef Kind) const;
608 /// \brief Set a particular kind of metadata attachment.
610 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
611 /// replacing it if it already exists.
613 void setMetadata(unsigned KindID, MDNode *MD);
614 void setMetadata(StringRef Kind, MDNode *MD);
617 /// \brief Get all current metadata attachments.
619 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
621 /// \brief Drop metadata not in the given list.
623 /// Drop all metadata from \c this not included in \c KnownIDs.
624 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
626 /// \brief Set the attached subprogram.
628 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
629 void setSubprogram(DISubprogram *SP);
631 /// \brief Get the attached subprogram.
633 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
634 /// to \a DISubprogram.
635 DISubprogram *getSubprogram() const;
638 void allocHungoffUselist();
639 template<int Idx> void setHungoffOperand(Constant *C);
641 // Shadow Value::setValueSubclassData with a private forwarding method so that
642 // subclasses cannot accidentally use it.
643 void setValueSubclassData(unsigned short D) {
644 Value::setValueSubclassData(D);
646 void setValueSubclassDataBit(unsigned Bit, bool On);
648 bool hasMetadataHashEntry() const {
649 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
651 void setHasMetadataHashEntry(bool HasEntry) {
652 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
655 void clearMetadata();
659 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
661 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
663 } // End llvm namespace