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 /// Function ctor - If the (optional) Module argument is specified, the
113 /// function is automatically inserted into the end of the function list for
116 Function(FunctionType *Ty, LinkageTypes Linkage,
117 const Twine &N = "", Module *M = nullptr);
120 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
121 const Twine &N = "", Module *M = nullptr) {
122 return new(0) Function(Ty, Linkage, N, M);
125 ~Function() override;
127 Type *getReturnType() const; // Return the type of the ret val
128 FunctionType *getFunctionType() const; // Return the FunctionType for me
130 /// getContext - Return a reference to the LLVMContext associated with this
132 LLVMContext &getContext() const;
134 /// isVarArg - Return true if this function takes a variable number of
136 bool isVarArg() const;
138 bool isMaterializable() const;
139 void setIsMaterializable(bool V);
141 /// getIntrinsicID - This method returns the ID number of the specified
142 /// function, or Intrinsic::not_intrinsic if the function is not an
143 /// intrinsic, or if the pointer is null. This value is always defined to be
144 /// zero to allow easy checking for whether a function is intrinsic or not.
145 /// The particular intrinsic functions which correspond to this value are
146 /// defined in llvm/Intrinsics.h. Results are cached in the LLVM context,
147 /// subsequent requests for the same ID return results much faster from the
150 unsigned getIntrinsicID() const LLVM_READONLY;
151 bool isIntrinsic() const { return getName().startswith("llvm."); }
153 /// getCallingConv()/setCallingConv(CC) - These method get and set the
154 /// calling convention of this function. The enum values for the known
155 /// calling conventions are defined in CallingConv.h.
156 CallingConv::ID getCallingConv() const {
157 return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
159 void setCallingConv(CallingConv::ID CC) {
160 setValueSubclassData((getSubclassDataFromValue() & 7) |
161 (static_cast<unsigned>(CC) << 3));
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 function cannot return.
281 bool doesNotReturn() const {
282 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
283 Attribute::NoReturn);
285 void setDoesNotReturn() {
286 addFnAttr(Attribute::NoReturn);
289 /// @brief Determine if the function cannot unwind.
290 bool doesNotThrow() const {
291 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
292 Attribute::NoUnwind);
294 void setDoesNotThrow() {
295 addFnAttr(Attribute::NoUnwind);
298 /// @brief Determine if the call cannot be duplicated.
299 bool cannotDuplicate() const {
300 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
301 Attribute::NoDuplicate);
303 void setCannotDuplicate() {
304 addFnAttr(Attribute::NoDuplicate);
307 /// @brief True if the ABI mandates (or the user requested) that this
308 /// function be in a unwind table.
309 bool hasUWTable() const {
310 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
313 void setHasUWTable() {
314 addFnAttr(Attribute::UWTable);
317 /// @brief True if this function needs an unwind table.
318 bool needsUnwindTableEntry() const {
319 return hasUWTable() || !doesNotThrow();
322 /// @brief Determine if the function returns a structure through first
323 /// pointer argument.
324 bool hasStructRetAttr() const {
325 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
326 AttributeSets.hasAttribute(2, Attribute::StructRet);
329 /// @brief Determine if the parameter does not alias other parameters.
330 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
331 bool doesNotAlias(unsigned n) const {
332 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
334 void setDoesNotAlias(unsigned n) {
335 addAttribute(n, Attribute::NoAlias);
338 /// @brief Determine if the parameter can be captured.
339 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
340 bool doesNotCapture(unsigned n) const {
341 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
343 void setDoesNotCapture(unsigned n) {
344 addAttribute(n, Attribute::NoCapture);
347 bool doesNotAccessMemory(unsigned n) const {
348 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
350 void setDoesNotAccessMemory(unsigned n) {
351 addAttribute(n, Attribute::ReadNone);
354 bool onlyReadsMemory(unsigned n) const {
355 return doesNotAccessMemory(n) ||
356 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
358 void setOnlyReadsMemory(unsigned n) {
359 addAttribute(n, Attribute::ReadOnly);
362 /// copyAttributesFrom - copy all additional attributes (those not needed to
363 /// create a Function) from the Function Src to this one.
364 void copyAttributesFrom(const GlobalValue *Src) override;
366 /// deleteBody - This method deletes the body of the function, and converts
367 /// the linkage to external.
371 setLinkage(ExternalLinkage);
374 /// removeFromParent - This method unlinks 'this' from the containing module,
375 /// but does not delete it.
377 void removeFromParent() override;
379 /// eraseFromParent - This method unlinks 'this' from the containing module
382 void eraseFromParent() override;
385 /// Get the underlying elements of the Function... the basic block list is
386 /// empty for external functions.
388 const ArgumentListType &getArgumentList() const {
389 CheckLazyArguments();
392 ArgumentListType &getArgumentList() {
393 CheckLazyArguments();
396 static iplist<Argument> Function::*getSublistAccess(Argument*) {
397 return &Function::ArgumentList;
400 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
401 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
402 static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
403 return &Function::BasicBlocks;
406 const BasicBlock &getEntryBlock() const { return front(); }
407 BasicBlock &getEntryBlock() { return front(); }
409 //===--------------------------------------------------------------------===//
410 // Symbol Table Accessing functions...
412 /// getSymbolTable() - Return the symbol table...
414 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
415 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
418 //===--------------------------------------------------------------------===//
419 // BasicBlock iterator forwarding functions
421 iterator begin() { return BasicBlocks.begin(); }
422 const_iterator begin() const { return BasicBlocks.begin(); }
423 iterator end () { return BasicBlocks.end(); }
424 const_iterator end () const { return BasicBlocks.end(); }
426 size_t size() const { return BasicBlocks.size(); }
427 bool empty() const { return BasicBlocks.empty(); }
428 const BasicBlock &front() const { return BasicBlocks.front(); }
429 BasicBlock &front() { return BasicBlocks.front(); }
430 const BasicBlock &back() const { return BasicBlocks.back(); }
431 BasicBlock &back() { return BasicBlocks.back(); }
433 /// @name Function Argument Iteration
436 arg_iterator arg_begin() {
437 CheckLazyArguments();
438 return ArgumentList.begin();
440 const_arg_iterator arg_begin() const {
441 CheckLazyArguments();
442 return ArgumentList.begin();
444 arg_iterator arg_end() {
445 CheckLazyArguments();
446 return ArgumentList.end();
448 const_arg_iterator arg_end() const {
449 CheckLazyArguments();
450 return ArgumentList.end();
453 iterator_range<arg_iterator> args() {
454 return iterator_range<arg_iterator>(arg_begin(), arg_end());
457 iterator_range<const_arg_iterator> args() const {
458 return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
463 size_t arg_size() const;
464 bool arg_empty() const;
466 bool hasPrefixData() const {
467 return getSubclassDataFromValue() & (1<<1);
470 Constant *getPrefixData() const;
471 void setPrefixData(Constant *PrefixData);
473 bool hasPrologueData() const {
474 return getSubclassDataFromValue() & (1<<2);
477 Constant *getPrologueData() const;
478 void setPrologueData(Constant *PrologueData);
480 /// Print the function to an output stream with an optional
481 /// AssemblyAnnotationWriter.
482 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr) const;
484 /// viewCFG - This function is meant for use from the debugger. You can just
485 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
486 /// program, displaying the CFG of the current function with the code for each
487 /// basic block inside. This depends on there being a 'dot' and 'gv' program
490 void viewCFG() const;
492 /// viewCFGOnly - This function is meant for use from the debugger. It works
493 /// just like viewCFG, but it does not include the contents of basic blocks
494 /// into the nodes, just the label. If you are only interested in the CFG
495 /// this can make the graph smaller.
497 void viewCFGOnly() const;
499 /// Methods for support type inquiry through isa, cast, and dyn_cast:
500 static inline bool classof(const Value *V) {
501 return V->getValueID() == Value::FunctionVal;
504 /// dropAllReferences() - This method causes all the subinstructions to "let
505 /// go" of all references that they are maintaining. This allows one to
506 /// 'delete' a whole module at a time, even though there may be circular
507 /// references... first all references are dropped, and all use counts go to
508 /// zero. Then everything is deleted for real. Note that no operations are
509 /// valid on an object that has "dropped all references", except operator
512 /// Since no other object in the module can have references into the body of a
513 /// function, dropping all references deletes the entire body of the function,
514 /// including any contained basic blocks.
516 void dropAllReferences();
518 /// hasAddressTaken - returns true if there are any uses of this function
519 /// other than direct calls or invokes to it, or blockaddress expressions.
520 /// Optionally passes back an offending user for diagnostic purposes.
522 bool hasAddressTaken(const User** = nullptr) const;
524 /// isDefTriviallyDead - Return true if it is trivially safe to remove
525 /// this function definition from the module (because it isn't externally
526 /// visible, does not have its address taken, and has no callers). To make
527 /// this more accurate, call removeDeadConstantUsers first.
528 bool isDefTriviallyDead() const;
530 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
531 /// setjmp or other function that gcc recognizes as "returning twice".
532 bool callsFunctionThatReturnsTwice() const;
534 /// \brief Check if this has any metadata.
535 bool hasMetadata() const { return hasMetadataHashEntry(); }
537 /// \brief Get the current metadata attachment, if any.
539 /// Returns \c nullptr if such an attachment is missing.
541 MDNode *getMetadata(unsigned KindID) const;
542 MDNode *getMetadata(StringRef Kind) const;
545 /// \brief Set a particular kind of metadata attachment.
547 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
548 /// replacing it if it already exists.
550 void setMetadata(unsigned KindID, MDNode *MD);
551 void setMetadata(StringRef Kind, MDNode *MD);
554 /// \brief Get all current metadata attachments.
556 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
558 /// \brief Drop metadata not in the given list.
560 /// Drop all metadata from \c this not included in \c KnownIDs.
561 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
564 // Shadow Value::setValueSubclassData with a private forwarding method so that
565 // subclasses cannot accidentally use it.
566 void setValueSubclassData(unsigned short D) {
567 Value::setValueSubclassData(D);
570 bool hasMetadataHashEntry() const {
571 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
573 void setHasMetadataHashEntry(bool HasEntry) {
574 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
577 void clearMetadata();
580 inline ValueSymbolTable *
581 ilist_traits<BasicBlock>::getSymTab(Function *F) {
582 return F ? &F->getValueSymbolTable() : nullptr;
585 inline ValueSymbolTable *
586 ilist_traits<Argument>::getSymTab(Function *F) {
587 return F ? &F->getValueSymbolTable() : nullptr;
590 /// \brief Overwrite attribute Kind in function F.
591 void overrideFunctionAttribute(StringRef Kind, StringRef Value, Function &F);
593 } // End llvm namespace