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"
37 template<> struct ilist_traits<Argument>
38 : public SymbolTableListTraits<Argument, Function> {
40 Argument *createSentinel() const {
41 return static_cast<Argument*>(&Sentinel);
43 static void destroySentinel(Argument*) {}
45 Argument *provideInitialHead() const { return createSentinel(); }
46 Argument *ensureHead(Argument*) const { return createSentinel(); }
47 static void noteHead(Argument*, Argument*) {}
50 mutable ilist_half_node<Argument> Sentinel;
53 class Function : public GlobalObject, public ilist_node<Function> {
55 typedef iplist<Argument> ArgumentListType;
56 typedef iplist<BasicBlock> BasicBlockListType;
58 // BasicBlock iterators...
59 typedef BasicBlockListType::iterator iterator;
60 typedef BasicBlockListType::const_iterator const_iterator;
62 typedef ArgumentListType::iterator arg_iterator;
63 typedef ArgumentListType::const_iterator const_arg_iterator;
66 // Important things that make up a function!
67 BasicBlockListType BasicBlocks; ///< The basic blocks
68 mutable ArgumentListType ArgumentList; ///< The formal arguments
69 ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
70 AttributeSet AttributeSets; ///< Parameter attributes
76 * bit 0 : HasLazyArguments
77 * bit 1 : HasPrefixData
78 * bit 2 : HasPrologueData
79 * bit 3-6: CallingConvention
82 /// Bits from GlobalObject::GlobalObjectSubclassData.
84 /// Whether this function is materializable.
85 IsMaterializableBit = 1 << 0,
86 HasMetadataHashEntryBit = 1 << 1
88 void setGlobalObjectBit(unsigned Mask, bool Value) {
89 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
93 friend class SymbolTableListTraits<Function, Module>;
95 void setParent(Module *parent);
97 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
98 /// built on demand, so that the list isn't allocated until the first client
99 /// needs it. The hasLazyArguments predicate returns true if the arg list
100 /// hasn't been set up yet.
101 bool hasLazyArguments() const {
102 return getSubclassDataFromValue() & (1<<0);
104 void CheckLazyArguments() const {
105 if (hasLazyArguments())
106 BuildLazyArguments();
108 void BuildLazyArguments() const;
110 Function(const Function&) = delete;
111 void operator=(const Function&) = delete;
113 /// Function ctor - If the (optional) Module argument is specified, the
114 /// function is automatically inserted into the end of the function list for
117 Function(FunctionType *Ty, LinkageTypes Linkage,
118 const Twine &N = "", Module *M = nullptr);
121 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
122 const Twine &N = "", Module *M = nullptr) {
123 return new(1) Function(Ty, Linkage, N, M);
126 ~Function() override;
128 /// \brief Provide fast operand accessors
129 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
131 /// \brief Get the personality function associated with this function.
132 bool hasPersonalityFn() const { return getNumOperands() != 0; }
133 Constant *getPersonalityFn() const {
134 assert(hasPersonalityFn());
135 return cast<Constant>(Op<0>());
137 void setPersonalityFn(Constant *C);
139 Type *getReturnType() const; // Return the type of the ret val
140 FunctionType *getFunctionType() const; // Return the FunctionType for me
142 /// getContext - Return a reference to the LLVMContext associated with this
144 LLVMContext &getContext() const;
146 /// isVarArg - Return true if this function takes a variable number of
148 bool isVarArg() const;
150 bool isMaterializable() const;
151 void setIsMaterializable(bool V);
153 /// getIntrinsicID - This method returns the ID number of the specified
154 /// function, or Intrinsic::not_intrinsic if the function is not an
155 /// intrinsic, or if the pointer is null. This value is always defined to be
156 /// zero to allow easy checking for whether a function is intrinsic or not.
157 /// The particular intrinsic functions which correspond to this value are
158 /// defined in llvm/Intrinsics.h.
159 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
160 bool isIntrinsic() const { return getName().startswith("llvm."); }
162 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
163 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
164 /// if the name of this function does not match an intrinsic in that header.
165 /// Note, this method does not need to be called directly, as it is called
166 /// from Value::setName() whenever the name of this function changes.
167 void recalculateIntrinsicID();
169 /// getCallingConv()/setCallingConv(CC) - These method get and set the
170 /// calling convention of this function. The enum values for the known
171 /// calling conventions are defined in CallingConv.h.
172 CallingConv::ID getCallingConv() const {
173 return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
175 void setCallingConv(CallingConv::ID CC) {
176 setValueSubclassData((getSubclassDataFromValue() & 7) |
177 (static_cast<unsigned>(CC) << 3));
180 /// @brief Return the attribute list for this Function.
181 AttributeSet getAttributes() const { return AttributeSets; }
183 /// @brief Set the attribute list for this Function.
184 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
186 /// @brief Add function attributes to this function.
187 void addFnAttr(Attribute::AttrKind N) {
188 setAttributes(AttributeSets.addAttribute(getContext(),
189 AttributeSet::FunctionIndex, N));
192 /// @brief Remove function attributes from this function.
193 void removeFnAttr(Attribute::AttrKind N) {
194 setAttributes(AttributeSets.removeAttribute(
195 getContext(), AttributeSet::FunctionIndex, N));
198 /// @brief Add function attributes to this function.
199 void addFnAttr(StringRef Kind) {
201 AttributeSets.addAttribute(getContext(),
202 AttributeSet::FunctionIndex, Kind));
204 void addFnAttr(StringRef Kind, StringRef Value) {
206 AttributeSets.addAttribute(getContext(),
207 AttributeSet::FunctionIndex, Kind, Value));
210 /// Set the entry count for this function.
211 void setEntryCount(uint64_t Count);
213 /// Get the entry count for this function.
214 Optional<uint64_t> getEntryCount() const;
216 /// @brief Return true if the function has the attribute.
217 bool hasFnAttribute(Attribute::AttrKind Kind) const {
218 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
220 bool hasFnAttribute(StringRef Kind) const {
221 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
224 /// @brief Return the attribute for the given attribute kind.
225 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
226 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
228 Attribute getFnAttribute(StringRef Kind) const {
229 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
232 /// \brief Return the stack alignment for the function.
233 unsigned getFnStackAlignment() const {
234 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
237 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
238 /// to use during code generation.
240 const char *getGC() const;
241 void setGC(const char *Str);
244 /// @brief adds the attribute to the list of attributes.
245 void addAttribute(unsigned i, Attribute::AttrKind attr);
247 /// @brief adds the attributes to the list of attributes.
248 void addAttributes(unsigned i, AttributeSet attrs);
250 /// @brief removes the attributes from the list of attributes.
251 void removeAttributes(unsigned i, AttributeSet attr);
253 /// @brief adds the dereferenceable attribute to the list of attributes.
254 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
256 /// @brief adds the dereferenceable_or_null attribute to the list of
258 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
260 /// @brief Extract the alignment for a call or parameter (0=unknown).
261 unsigned getParamAlignment(unsigned i) const {
262 return AttributeSets.getParamAlignment(i);
265 /// @brief Extract the number of dereferenceable bytes for a call or
266 /// parameter (0=unknown).
267 uint64_t getDereferenceableBytes(unsigned i) const {
268 return AttributeSets.getDereferenceableBytes(i);
271 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
272 /// parameter (0=unknown).
273 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
274 return AttributeSets.getDereferenceableOrNullBytes(i);
277 /// @brief Determine if the function does not access memory.
278 bool doesNotAccessMemory() const {
279 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
280 Attribute::ReadNone);
282 void setDoesNotAccessMemory() {
283 addFnAttr(Attribute::ReadNone);
286 /// @brief Determine if the function does not access or only reads memory.
287 bool onlyReadsMemory() const {
288 return doesNotAccessMemory() ||
289 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
290 Attribute::ReadOnly);
292 void setOnlyReadsMemory() {
293 addFnAttr(Attribute::ReadOnly);
296 /// @brief Determine if the call can access memmory only using pointers based
297 /// on its arguments.
298 bool onlyAccessesArgMemory() const {
299 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
300 Attribute::ArgMemOnly);
302 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
304 /// @brief Determine if the function cannot return.
305 bool doesNotReturn() const {
306 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
307 Attribute::NoReturn);
309 void setDoesNotReturn() {
310 addFnAttr(Attribute::NoReturn);
313 /// @brief Determine if the function cannot unwind.
314 bool doesNotThrow() const {
315 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
316 Attribute::NoUnwind);
318 void setDoesNotThrow() {
319 addFnAttr(Attribute::NoUnwind);
322 /// @brief Determine if the call cannot be duplicated.
323 bool cannotDuplicate() const {
324 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
325 Attribute::NoDuplicate);
327 void setCannotDuplicate() {
328 addFnAttr(Attribute::NoDuplicate);
331 /// @brief Determine if the call is convergent.
332 bool isConvergent() const {
333 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
334 Attribute::Convergent);
336 void setConvergent() {
337 addFnAttr(Attribute::Convergent);
341 /// @brief True if the ABI mandates (or the user requested) that this
342 /// function be in a unwind table.
343 bool hasUWTable() const {
344 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
347 void setHasUWTable() {
348 addFnAttr(Attribute::UWTable);
351 /// @brief True if this function needs an unwind table.
352 bool needsUnwindTableEntry() const {
353 return hasUWTable() || !doesNotThrow();
356 /// @brief Determine if the function returns a structure through first
357 /// pointer argument.
358 bool hasStructRetAttr() const {
359 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
360 AttributeSets.hasAttribute(2, Attribute::StructRet);
363 /// @brief Determine if the parameter does not alias other parameters.
364 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
365 bool doesNotAlias(unsigned n) const {
366 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
368 void setDoesNotAlias(unsigned n) {
369 addAttribute(n, Attribute::NoAlias);
372 /// @brief Determine if the parameter can be captured.
373 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
374 bool doesNotCapture(unsigned n) const {
375 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
377 void setDoesNotCapture(unsigned n) {
378 addAttribute(n, Attribute::NoCapture);
381 bool doesNotAccessMemory(unsigned n) const {
382 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
384 void setDoesNotAccessMemory(unsigned n) {
385 addAttribute(n, Attribute::ReadNone);
388 bool onlyReadsMemory(unsigned n) const {
389 return doesNotAccessMemory(n) ||
390 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
392 void setOnlyReadsMemory(unsigned n) {
393 addAttribute(n, Attribute::ReadOnly);
396 /// Optimize this function for minimum size (-Oz).
397 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); };
399 /// Optimize this function for size (-Os) or minimum size (-Oz).
400 bool optForSize() const {
401 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
404 /// copyAttributesFrom - copy all additional attributes (those not needed to
405 /// create a Function) from the Function Src to this one.
406 void copyAttributesFrom(const GlobalValue *Src) override;
408 /// deleteBody - This method deletes the body of the function, and converts
409 /// the linkage to external.
413 setLinkage(ExternalLinkage);
416 /// removeFromParent - This method unlinks 'this' from the containing module,
417 /// but does not delete it.
419 void removeFromParent() override;
421 /// eraseFromParent - This method unlinks 'this' from the containing module
424 void eraseFromParent() override;
426 /// Get the underlying elements of the Function... the basic block list is
427 /// empty for external functions.
429 const ArgumentListType &getArgumentList() const {
430 CheckLazyArguments();
433 ArgumentListType &getArgumentList() {
434 CheckLazyArguments();
437 static ArgumentListType Function::*getSublistAccess(Argument*) {
438 return &Function::ArgumentList;
441 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
442 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
443 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
444 return &Function::BasicBlocks;
447 const BasicBlock &getEntryBlock() const { return front(); }
448 BasicBlock &getEntryBlock() { return front(); }
450 //===--------------------------------------------------------------------===//
451 // Symbol Table Accessing functions...
453 /// getSymbolTable() - Return the symbol table...
455 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
456 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
458 //===--------------------------------------------------------------------===//
459 // BasicBlock iterator forwarding functions
461 iterator begin() { return BasicBlocks.begin(); }
462 const_iterator begin() const { return BasicBlocks.begin(); }
463 iterator end () { return BasicBlocks.end(); }
464 const_iterator end () const { return BasicBlocks.end(); }
466 size_t size() const { return BasicBlocks.size(); }
467 bool empty() const { return BasicBlocks.empty(); }
468 const BasicBlock &front() const { return BasicBlocks.front(); }
469 BasicBlock &front() { return BasicBlocks.front(); }
470 const BasicBlock &back() const { return BasicBlocks.back(); }
471 BasicBlock &back() { return BasicBlocks.back(); }
473 /// @name Function Argument Iteration
476 arg_iterator arg_begin() {
477 CheckLazyArguments();
478 return ArgumentList.begin();
480 const_arg_iterator arg_begin() const {
481 CheckLazyArguments();
482 return ArgumentList.begin();
484 arg_iterator arg_end() {
485 CheckLazyArguments();
486 return ArgumentList.end();
488 const_arg_iterator arg_end() const {
489 CheckLazyArguments();
490 return ArgumentList.end();
493 iterator_range<arg_iterator> args() {
494 return iterator_range<arg_iterator>(arg_begin(), arg_end());
497 iterator_range<const_arg_iterator> args() const {
498 return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
503 size_t arg_size() const;
504 bool arg_empty() const;
506 bool hasPrefixData() const {
507 return getSubclassDataFromValue() & (1<<1);
510 Constant *getPrefixData() const;
511 void setPrefixData(Constant *PrefixData);
513 bool hasPrologueData() const {
514 return getSubclassDataFromValue() & (1<<2);
517 Constant *getPrologueData() const;
518 void setPrologueData(Constant *PrologueData);
520 /// viewCFG - This function is meant for use from the debugger. You can just
521 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
522 /// program, displaying the CFG of the current function with the code for each
523 /// basic block inside. This depends on there being a 'dot' and 'gv' program
526 void viewCFG() const;
528 /// viewCFGOnly - This function is meant for use from the debugger. It works
529 /// just like viewCFG, but it does not include the contents of basic blocks
530 /// into the nodes, just the label. If you are only interested in the CFG
531 /// this can make the graph smaller.
533 void viewCFGOnly() const;
535 /// Methods for support type inquiry through isa, cast, and dyn_cast:
536 static inline bool classof(const Value *V) {
537 return V->getValueID() == Value::FunctionVal;
540 /// dropAllReferences() - This method causes all the subinstructions to "let
541 /// go" of all references that they are maintaining. This allows one to
542 /// 'delete' a whole module at a time, even though there may be circular
543 /// references... first all references are dropped, and all use counts go to
544 /// zero. Then everything is deleted for real. Note that no operations are
545 /// valid on an object that has "dropped all references", except operator
548 /// Since no other object in the module can have references into the body of a
549 /// function, dropping all references deletes the entire body of the function,
550 /// including any contained basic blocks.
552 void dropAllReferences();
554 /// hasAddressTaken - returns true if there are any uses of this function
555 /// other than direct calls or invokes to it, or blockaddress expressions.
556 /// Optionally passes back an offending user for diagnostic purposes.
558 bool hasAddressTaken(const User** = nullptr) const;
560 /// isDefTriviallyDead - Return true if it is trivially safe to remove
561 /// this function definition from the module (because it isn't externally
562 /// visible, does not have its address taken, and has no callers). To make
563 /// this more accurate, call removeDeadConstantUsers first.
564 bool isDefTriviallyDead() const;
566 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
567 /// setjmp or other function that gcc recognizes as "returning twice".
568 bool callsFunctionThatReturnsTwice() const;
570 /// \brief Check if this has any metadata.
571 bool hasMetadata() const { return hasMetadataHashEntry(); }
573 /// \brief Get the current metadata attachment, if any.
575 /// Returns \c nullptr if such an attachment is missing.
577 MDNode *getMetadata(unsigned KindID) const;
578 MDNode *getMetadata(StringRef Kind) const;
581 /// \brief Set a particular kind of metadata attachment.
583 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
584 /// replacing it if it already exists.
586 void setMetadata(unsigned KindID, MDNode *MD);
587 void setMetadata(StringRef Kind, MDNode *MD);
590 /// \brief Get all current metadata attachments.
592 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
594 /// \brief Drop metadata not in the given list.
596 /// Drop all metadata from \c this not included in \c KnownIDs.
597 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
599 /// \brief Set the attached subprogram.
601 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
602 void setSubprogram(DISubprogram *SP);
604 /// \brief Get the attached subprogram.
606 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
607 /// to \a DISubprogram.
608 DISubprogram *getSubprogram() const;
611 // Shadow Value::setValueSubclassData with a private forwarding method so that
612 // subclasses cannot accidentally use it.
613 void setValueSubclassData(unsigned short D) {
614 Value::setValueSubclassData(D);
617 bool hasMetadataHashEntry() const {
618 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
620 void setHasMetadataHashEntry(bool HasEntry) {
621 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
624 void clearMetadata();
628 struct OperandTraits<Function> : public OptionalOperandTraits<Function> {};
630 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
632 } // End llvm namespace