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/Support/Compiler.h"
35 template<> struct ilist_traits<Argument>
36 : public SymbolTableListTraits<Argument, Function> {
38 Argument *createSentinel() const {
39 return static_cast<Argument*>(&Sentinel);
41 static void destroySentinel(Argument*) {}
43 Argument *provideInitialHead() const { return createSentinel(); }
44 Argument *ensureHead(Argument*) const { return createSentinel(); }
45 static void noteHead(Argument*, Argument*) {}
47 static ValueSymbolTable *getSymTab(Function *ItemParent);
49 mutable ilist_half_node<Argument> Sentinel;
52 class Function : public GlobalObject, public ilist_node<Function> {
54 typedef iplist<Argument> ArgumentListType;
55 typedef iplist<BasicBlock> BasicBlockListType;
57 // BasicBlock iterators...
58 typedef BasicBlockListType::iterator iterator;
59 typedef BasicBlockListType::const_iterator const_iterator;
61 typedef ArgumentListType::iterator arg_iterator;
62 typedef ArgumentListType::const_iterator const_arg_iterator;
65 // Important things that make up a function!
66 BasicBlockListType BasicBlocks; ///< The basic blocks
67 mutable ArgumentListType ArgumentList; ///< The formal arguments
68 ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
69 AttributeSet AttributeSets; ///< Parameter attributes
75 * bit 0 : HasLazyArguments
76 * bit 1 : HasPrefixData
77 * bit 2 : HasPrologueData
78 * bit 3-6: CallingConvention
81 /// Bits from GlobalObject::GlobalObjectSubclassData.
83 /// Whether this function is materializable.
84 IsMaterializableBit = 1 << 0,
85 HasMetadataHashEntryBit = 1 << 1
87 void setGlobalObjectBit(unsigned Mask, bool Value) {
88 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
92 friend class SymbolTableListTraits<Function, Module>;
94 void setParent(Module *parent);
96 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
97 /// built on demand, so that the list isn't allocated until the first client
98 /// needs it. The hasLazyArguments predicate returns true if the arg list
99 /// hasn't been set up yet.
100 bool hasLazyArguments() const {
101 return getSubclassDataFromValue() & (1<<0);
103 void CheckLazyArguments() const {
104 if (hasLazyArguments())
105 BuildLazyArguments();
107 void BuildLazyArguments() const;
109 Function(const Function&) = delete;
110 void operator=(const Function&) = delete;
112 /// Do the actual lookup of an intrinsic ID when the query could not be
113 /// answered from the cache.
114 unsigned lookupIntrinsicID() const LLVM_READONLY;
116 /// Function ctor - If the (optional) Module argument is specified, the
117 /// function is automatically inserted into the end of the function list for
120 Function(FunctionType *Ty, LinkageTypes Linkage,
121 const Twine &N = "", Module *M = nullptr);
124 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
125 const Twine &N = "", Module *M = nullptr) {
126 return new(0) Function(Ty, Linkage, N, M);
129 ~Function() override;
131 Type *getReturnType() const; // Return the type of the ret val
132 FunctionType *getFunctionType() const; // Return the FunctionType for me
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;
142 bool isMaterializable() const;
143 void setIsMaterializable(bool V);
145 /// getIntrinsicID - This method returns the ID number of the specified
146 /// function, or Intrinsic::not_intrinsic if the function is not an
147 /// intrinsic, or if the pointer is null. This value is always defined to be
148 /// zero to allow easy checking for whether a function is intrinsic or not.
149 /// The particular intrinsic functions which correspond to this value are
150 /// defined in llvm/Intrinsics.h. Results are cached in the LLVM context,
151 /// subsequent requests for the same ID return results much faster from the
154 unsigned getIntrinsicID() const LLVM_READONLY;
155 bool isIntrinsic() const { return getName().startswith("llvm."); }
157 /// getCallingConv()/setCallingConv(CC) - These method get and set the
158 /// calling convention of this function. The enum values for the known
159 /// calling conventions are defined in CallingConv.h.
160 CallingConv::ID getCallingConv() const {
161 return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
163 void setCallingConv(CallingConv::ID CC) {
164 setValueSubclassData((getSubclassDataFromValue() & 7) |
165 (static_cast<unsigned>(CC) << 3));
168 /// @brief Return the attribute list for this Function.
169 AttributeSet getAttributes() const { return AttributeSets; }
171 /// @brief Set the attribute list for this Function.
172 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
174 /// @brief Add function attributes to this function.
175 void addFnAttr(Attribute::AttrKind N) {
176 setAttributes(AttributeSets.addAttribute(getContext(),
177 AttributeSet::FunctionIndex, N));
180 /// @brief Remove function attributes from this function.
181 void removeFnAttr(Attribute::AttrKind N) {
182 setAttributes(AttributeSets.removeAttribute(
183 getContext(), AttributeSet::FunctionIndex, N));
186 /// @brief Add function attributes to this function.
187 void addFnAttr(StringRef Kind) {
189 AttributeSets.addAttribute(getContext(),
190 AttributeSet::FunctionIndex, Kind));
192 void addFnAttr(StringRef Kind, StringRef Value) {
194 AttributeSets.addAttribute(getContext(),
195 AttributeSet::FunctionIndex, Kind, Value));
198 /// Set the entry count for this function.
199 void setEntryCount(uint64_t Count);
201 /// Get the entry count for this function.
202 Optional<uint64_t> getEntryCount() const;
204 /// @brief Return true if the function has the attribute.
205 bool hasFnAttribute(Attribute::AttrKind Kind) const {
206 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
208 bool hasFnAttribute(StringRef Kind) const {
209 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
212 /// @brief Return the attribute for the given attribute kind.
213 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
214 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
216 Attribute getFnAttribute(StringRef Kind) const {
217 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
220 /// \brief Return the stack alignment for the function.
221 unsigned getFnStackAlignment() const {
222 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
225 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
226 /// to use during code generation.
228 const char *getGC() const;
229 void setGC(const char *Str);
232 /// @brief adds the attribute to the list of attributes.
233 void addAttribute(unsigned i, Attribute::AttrKind attr);
235 /// @brief adds the attributes to the list of attributes.
236 void addAttributes(unsigned i, AttributeSet attrs);
238 /// @brief removes the attributes from the list of attributes.
239 void removeAttributes(unsigned i, AttributeSet attr);
241 /// @brief adds the dereferenceable attribute to the list of attributes.
242 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
244 /// @brief adds the dereferenceable_or_null attribute to the list of
246 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
248 /// @brief Extract the alignment for a call or parameter (0=unknown).
249 unsigned getParamAlignment(unsigned i) const {
250 return AttributeSets.getParamAlignment(i);
253 /// @brief Extract the number of dereferenceable bytes for a call or
254 /// parameter (0=unknown).
255 uint64_t getDereferenceableBytes(unsigned i) const {
256 return AttributeSets.getDereferenceableBytes(i);
259 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
260 /// parameter (0=unknown).
261 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
262 return AttributeSets.getDereferenceableOrNullBytes(i);
265 /// @brief Determine if the function does not access memory.
266 bool doesNotAccessMemory() const {
267 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
268 Attribute::ReadNone);
270 void setDoesNotAccessMemory() {
271 addFnAttr(Attribute::ReadNone);
274 /// @brief Determine if the function does not access or only reads memory.
275 bool onlyReadsMemory() const {
276 return doesNotAccessMemory() ||
277 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
278 Attribute::ReadOnly);
280 void setOnlyReadsMemory() {
281 addFnAttr(Attribute::ReadOnly);
284 /// @brief Determine if the function cannot return.
285 bool doesNotReturn() const {
286 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
287 Attribute::NoReturn);
289 void setDoesNotReturn() {
290 addFnAttr(Attribute::NoReturn);
293 /// @brief Determine if the function cannot unwind.
294 bool doesNotThrow() const {
295 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
296 Attribute::NoUnwind);
298 void setDoesNotThrow() {
299 addFnAttr(Attribute::NoUnwind);
302 /// @brief Determine if the call cannot be duplicated.
303 bool cannotDuplicate() const {
304 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
305 Attribute::NoDuplicate);
307 void setCannotDuplicate() {
308 addFnAttr(Attribute::NoDuplicate);
311 /// @brief True if the ABI mandates (or the user requested) that this
312 /// function be in a unwind table.
313 bool hasUWTable() const {
314 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
317 void setHasUWTable() {
318 addFnAttr(Attribute::UWTable);
321 /// @brief True if this function needs an unwind table.
322 bool needsUnwindTableEntry() const {
323 return hasUWTable() || !doesNotThrow();
326 /// @brief Determine if the function returns a structure through first
327 /// pointer argument.
328 bool hasStructRetAttr() const {
329 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
330 AttributeSets.hasAttribute(2, Attribute::StructRet);
333 /// @brief Determine if the parameter does not alias other parameters.
334 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
335 bool doesNotAlias(unsigned n) const {
336 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
338 void setDoesNotAlias(unsigned n) {
339 addAttribute(n, Attribute::NoAlias);
342 /// @brief Determine if the parameter can be captured.
343 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
344 bool doesNotCapture(unsigned n) const {
345 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
347 void setDoesNotCapture(unsigned n) {
348 addAttribute(n, Attribute::NoCapture);
351 bool doesNotAccessMemory(unsigned n) const {
352 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
354 void setDoesNotAccessMemory(unsigned n) {
355 addAttribute(n, Attribute::ReadNone);
358 bool onlyReadsMemory(unsigned n) const {
359 return doesNotAccessMemory(n) ||
360 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
362 void setOnlyReadsMemory(unsigned n) {
363 addAttribute(n, Attribute::ReadOnly);
366 /// copyAttributesFrom - copy all additional attributes (those not needed to
367 /// create a Function) from the Function Src to this one.
368 void copyAttributesFrom(const GlobalValue *Src) override;
370 /// deleteBody - This method deletes the body of the function, and converts
371 /// the linkage to external.
375 setLinkage(ExternalLinkage);
378 /// removeFromParent - This method unlinks 'this' from the containing module,
379 /// but does not delete it.
381 void removeFromParent() override;
383 /// eraseFromParent - This method unlinks 'this' from the containing module
386 void eraseFromParent() override;
389 /// Get the underlying elements of the Function... the basic block list is
390 /// empty for external functions.
392 const ArgumentListType &getArgumentList() const {
393 CheckLazyArguments();
396 ArgumentListType &getArgumentList() {
397 CheckLazyArguments();
400 static iplist<Argument> Function::*getSublistAccess(Argument*) {
401 return &Function::ArgumentList;
404 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
405 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
406 static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
407 return &Function::BasicBlocks;
410 const BasicBlock &getEntryBlock() const { return front(); }
411 BasicBlock &getEntryBlock() { return front(); }
413 //===--------------------------------------------------------------------===//
414 // Symbol Table Accessing functions...
416 /// getSymbolTable() - Return the symbol table...
418 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
419 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
422 //===--------------------------------------------------------------------===//
423 // BasicBlock iterator forwarding functions
425 iterator begin() { return BasicBlocks.begin(); }
426 const_iterator begin() const { return BasicBlocks.begin(); }
427 iterator end () { return BasicBlocks.end(); }
428 const_iterator end () const { return BasicBlocks.end(); }
430 size_t size() const { return BasicBlocks.size(); }
431 bool empty() const { return BasicBlocks.empty(); }
432 const BasicBlock &front() const { return BasicBlocks.front(); }
433 BasicBlock &front() { return BasicBlocks.front(); }
434 const BasicBlock &back() const { return BasicBlocks.back(); }
435 BasicBlock &back() { return BasicBlocks.back(); }
437 /// @name Function Argument Iteration
440 arg_iterator arg_begin() {
441 CheckLazyArguments();
442 return ArgumentList.begin();
444 const_arg_iterator arg_begin() const {
445 CheckLazyArguments();
446 return ArgumentList.begin();
448 arg_iterator arg_end() {
449 CheckLazyArguments();
450 return ArgumentList.end();
452 const_arg_iterator arg_end() const {
453 CheckLazyArguments();
454 return ArgumentList.end();
457 iterator_range<arg_iterator> args() {
458 return iterator_range<arg_iterator>(arg_begin(), arg_end());
461 iterator_range<const_arg_iterator> args() const {
462 return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
467 size_t arg_size() const;
468 bool arg_empty() const;
470 bool hasPrefixData() const {
471 return getSubclassDataFromValue() & (1<<1);
474 Constant *getPrefixData() const;
475 void setPrefixData(Constant *PrefixData);
477 bool hasPrologueData() const {
478 return getSubclassDataFromValue() & (1<<2);
481 Constant *getPrologueData() const;
482 void setPrologueData(Constant *PrologueData);
484 /// Print the function to an output stream with an optional
485 /// AssemblyAnnotationWriter.
486 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr) const;
488 /// viewCFG - This function is meant for use from the debugger. You can just
489 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
490 /// program, displaying the CFG of the current function with the code for each
491 /// basic block inside. This depends on there being a 'dot' and 'gv' program
494 void viewCFG() const;
496 /// viewCFGOnly - This function is meant for use from the debugger. It works
497 /// just like viewCFG, but it does not include the contents of basic blocks
498 /// into the nodes, just the label. If you are only interested in the CFG
499 /// this can make the graph smaller.
501 void viewCFGOnly() const;
503 /// Methods for support type inquiry through isa, cast, and dyn_cast:
504 static inline bool classof(const Value *V) {
505 return V->getValueID() == Value::FunctionVal;
508 /// dropAllReferences() - This method causes all the subinstructions to "let
509 /// go" of all references that they are maintaining. This allows one to
510 /// 'delete' a whole module at a time, even though there may be circular
511 /// references... first all references are dropped, and all use counts go to
512 /// zero. Then everything is deleted for real. Note that no operations are
513 /// valid on an object that has "dropped all references", except operator
516 /// Since no other object in the module can have references into the body of a
517 /// function, dropping all references deletes the entire body of the function,
518 /// including any contained basic blocks.
520 void dropAllReferences();
522 /// hasAddressTaken - returns true if there are any uses of this function
523 /// other than direct calls or invokes to it, or blockaddress expressions.
524 /// Optionally passes back an offending user for diagnostic purposes.
526 bool hasAddressTaken(const User** = nullptr) const;
528 /// isDefTriviallyDead - Return true if it is trivially safe to remove
529 /// this function definition from the module (because it isn't externally
530 /// visible, does not have its address taken, and has no callers). To make
531 /// this more accurate, call removeDeadConstantUsers first.
532 bool isDefTriviallyDead() const;
534 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
535 /// setjmp or other function that gcc recognizes as "returning twice".
536 bool callsFunctionThatReturnsTwice() const;
538 /// \brief Check if this has any metadata.
539 bool hasMetadata() const { return hasMetadataHashEntry(); }
541 /// \brief Get the current metadata attachment, if any.
543 /// Returns \c nullptr if such an attachment is missing.
545 MDNode *getMetadata(unsigned KindID) const;
546 MDNode *getMetadata(StringRef Kind) const;
549 /// \brief Set a particular kind of metadata attachment.
551 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
552 /// replacing it if it already exists.
554 void setMetadata(unsigned KindID, MDNode *MD);
555 void setMetadata(StringRef Kind, MDNode *MD);
558 /// \brief Get all current metadata attachments.
560 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
562 /// \brief Drop metadata not in the given list.
564 /// Drop all metadata from \c this not included in \c KnownIDs.
565 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
568 // Shadow Value::setValueSubclassData with a private forwarding method so that
569 // subclasses cannot accidentally use it.
570 void setValueSubclassData(unsigned short D) {
571 Value::setValueSubclassData(D);
574 bool hasMetadataHashEntry() const {
575 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
577 void setHasMetadataHashEntry(bool HasEntry) {
578 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
581 void clearMetadata();
584 inline ValueSymbolTable *
585 ilist_traits<BasicBlock>::getSymTab(Function *F) {
586 return F ? &F->getValueSymbolTable() : nullptr;
589 inline ValueSymbolTable *
590 ilist_traits<Argument>::getSymTab(Function *F) {
591 return F ? &F->getValueSymbolTable() : nullptr;
594 /// \brief Overwrite attribute Kind in function F.
595 void overrideFunctionAttribute(StringRef Kind, StringRef Value, Function &F);
597 } // End llvm namespace