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*) {}
49 static ValueSymbolTable *getSymTab(Function *ItemParent);
51 mutable ilist_half_node<Argument> Sentinel;
54 class Function : public GlobalObject, public ilist_node<Function> {
56 typedef iplist<Argument> ArgumentListType;
57 typedef iplist<BasicBlock> BasicBlockListType;
59 // BasicBlock iterators...
60 typedef BasicBlockListType::iterator iterator;
61 typedef BasicBlockListType::const_iterator const_iterator;
63 typedef ArgumentListType::iterator arg_iterator;
64 typedef ArgumentListType::const_iterator const_arg_iterator;
67 // Important things that make up a function!
68 BasicBlockListType BasicBlocks; ///< The basic blocks
69 mutable ArgumentListType ArgumentList; ///< The formal arguments
70 ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
71 AttributeSet AttributeSets; ///< Parameter attributes
77 * bit 0 : HasLazyArguments
78 * bit 1 : HasPrefixData
79 * bit 2 : HasPrologueData
80 * bit 3-6: CallingConvention
83 /// Bits from GlobalObject::GlobalObjectSubclassData.
85 /// Whether this function is materializable.
86 IsMaterializableBit = 1 << 0,
87 HasMetadataHashEntryBit = 1 << 1
89 void setGlobalObjectBit(unsigned Mask, bool Value) {
90 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
94 friend class SymbolTableListTraits<Function, Module>;
96 void setParent(Module *parent);
98 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
99 /// built on demand, so that the list isn't allocated until the first client
100 /// needs it. The hasLazyArguments predicate returns true if the arg list
101 /// hasn't been set up yet.
102 bool hasLazyArguments() const {
103 return getSubclassDataFromValue() & (1<<0);
105 void CheckLazyArguments() const {
106 if (hasLazyArguments())
107 BuildLazyArguments();
109 void BuildLazyArguments() const;
111 Function(const Function&) = delete;
112 void operator=(const Function&) = delete;
114 /// Function ctor - If the (optional) Module argument is specified, the
115 /// function is automatically inserted into the end of the function list for
118 Function(FunctionType *Ty, LinkageTypes Linkage,
119 const Twine &N = "", Module *M = nullptr);
122 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
123 const Twine &N = "", Module *M = nullptr) {
124 return new(1) Function(Ty, Linkage, N, M);
127 ~Function() override;
129 /// \brief Provide fast operand accessors
130 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
132 /// \brief Get the personality function associated with this function.
133 bool hasPersonalityFn() const { return getNumOperands() != 0; }
134 Constant *getPersonalityFn() const {
135 assert(hasPersonalityFn());
136 return cast<Constant>(Op<0>());
138 void setPersonalityFn(Constant *C);
140 Type *getReturnType() const; // Return the type of the ret val
141 FunctionType *getFunctionType() const; // Return the FunctionType for me
143 /// getContext - Return a reference to the LLVMContext associated with this
145 LLVMContext &getContext() const;
147 /// isVarArg - Return true if this function takes a variable number of
149 bool isVarArg() const;
151 bool isMaterializable() const;
152 void setIsMaterializable(bool V);
154 /// getIntrinsicID - This method returns the ID number of the specified
155 /// function, or Intrinsic::not_intrinsic if the function is not an
156 /// intrinsic, or if the pointer is null. This value is always defined to be
157 /// zero to allow easy checking for whether a function is intrinsic or not.
158 /// The particular intrinsic functions which correspond to this value are
159 /// defined in llvm/Intrinsics.h.
160 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
161 bool isIntrinsic() const { return getName().startswith("llvm."); }
163 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
164 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
165 /// if the name of this function does not match an intrinsic in that header.
166 /// Note, this method does not need to be called directly, as it is called
167 /// from Value::setName() whenever the name of this function changes.
168 void recalculateIntrinsicID();
170 /// getCallingConv()/setCallingConv(CC) - These method get and set the
171 /// calling convention of this function. The enum values for the known
172 /// calling conventions are defined in CallingConv.h.
173 CallingConv::ID getCallingConv() const {
174 return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
176 void setCallingConv(CallingConv::ID CC) {
177 setValueSubclassData((getSubclassDataFromValue() & 7) |
178 (static_cast<unsigned>(CC) << 3));
181 /// @brief Return the attribute list for this Function.
182 AttributeSet getAttributes() const { return AttributeSets; }
184 /// @brief Set the attribute list for this Function.
185 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
187 /// @brief Add function attributes to this function.
188 void addFnAttr(Attribute::AttrKind N) {
189 setAttributes(AttributeSets.addAttribute(getContext(),
190 AttributeSet::FunctionIndex, N));
193 /// @brief Remove function attributes from this function.
194 void removeFnAttr(Attribute::AttrKind N) {
195 setAttributes(AttributeSets.removeAttribute(
196 getContext(), AttributeSet::FunctionIndex, N));
199 /// @brief Add function attributes to this function.
200 void addFnAttr(StringRef Kind) {
202 AttributeSets.addAttribute(getContext(),
203 AttributeSet::FunctionIndex, Kind));
205 void addFnAttr(StringRef Kind, StringRef Value) {
207 AttributeSets.addAttribute(getContext(),
208 AttributeSet::FunctionIndex, Kind, Value));
211 /// Set the entry count for this function.
212 void setEntryCount(uint64_t Count);
214 /// Get the entry count for this function.
215 Optional<uint64_t> getEntryCount() const;
217 /// @brief Return true if the function has the attribute.
218 bool hasFnAttribute(Attribute::AttrKind Kind) const {
219 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
221 bool hasFnAttribute(StringRef Kind) const {
222 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
225 /// @brief Return the attribute for the given attribute kind.
226 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
227 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
229 Attribute getFnAttribute(StringRef Kind) const {
230 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
233 /// \brief Return the stack alignment for the function.
234 unsigned getFnStackAlignment() const {
235 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
238 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
239 /// to use during code generation.
241 const char *getGC() const;
242 void setGC(const char *Str);
245 /// @brief adds the attribute to the list of attributes.
246 void addAttribute(unsigned i, Attribute::AttrKind attr);
248 /// @brief adds the attributes to the list of attributes.
249 void addAttributes(unsigned i, AttributeSet attrs);
251 /// @brief removes the attributes from the list of attributes.
252 void removeAttributes(unsigned i, AttributeSet attr);
254 /// @brief adds the dereferenceable attribute to the list of attributes.
255 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
257 /// @brief adds the dereferenceable_or_null attribute to the list of
259 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
261 /// @brief Extract the alignment for a call or parameter (0=unknown).
262 unsigned getParamAlignment(unsigned i) const {
263 return AttributeSets.getParamAlignment(i);
266 /// @brief Extract the number of dereferenceable bytes for a call or
267 /// parameter (0=unknown).
268 uint64_t getDereferenceableBytes(unsigned i) const {
269 return AttributeSets.getDereferenceableBytes(i);
272 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
273 /// parameter (0=unknown).
274 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
275 return AttributeSets.getDereferenceableOrNullBytes(i);
278 /// @brief Determine if the function does not access memory.
279 bool doesNotAccessMemory() const {
280 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
281 Attribute::ReadNone);
283 void setDoesNotAccessMemory() {
284 addFnAttr(Attribute::ReadNone);
287 /// @brief Determine if the function does not access or only reads memory.
288 bool onlyReadsMemory() const {
289 return doesNotAccessMemory() ||
290 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
291 Attribute::ReadOnly);
293 void setOnlyReadsMemory() {
294 addFnAttr(Attribute::ReadOnly);
297 /// @brief Determine if the call can access memmory only using pointers based
298 /// on its arguments.
299 bool onlyAccessesArgMemory() const {
300 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
301 Attribute::ArgMemOnly);
303 void setOnlyAccessesArgMemory() {
304 addFnAttr(Attribute::ArgMemOnly);
307 /// @brief Determine if the function cannot return.
308 bool doesNotReturn() const {
309 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
310 Attribute::NoReturn);
312 void setDoesNotReturn() {
313 addFnAttr(Attribute::NoReturn);
316 /// @brief Determine if the function cannot unwind.
317 bool doesNotThrow() const {
318 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
319 Attribute::NoUnwind);
321 void setDoesNotThrow() {
322 addFnAttr(Attribute::NoUnwind);
325 /// @brief Determine if the call cannot be duplicated.
326 bool cannotDuplicate() const {
327 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
328 Attribute::NoDuplicate);
330 void setCannotDuplicate() {
331 addFnAttr(Attribute::NoDuplicate);
334 /// @brief Determine if the call is convergent.
335 bool isConvergent() const {
336 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
337 Attribute::Convergent);
339 void setConvergent() {
340 addFnAttr(Attribute::Convergent);
344 /// @brief True if the ABI mandates (or the user requested) that this
345 /// function be in a unwind table.
346 bool hasUWTable() const {
347 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
350 void setHasUWTable() {
351 addFnAttr(Attribute::UWTable);
354 /// @brief True if this function needs an unwind table.
355 bool needsUnwindTableEntry() const {
356 return hasUWTable() || !doesNotThrow();
359 /// @brief Determine if the function returns a structure through first
360 /// pointer argument.
361 bool hasStructRetAttr() const {
362 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
363 AttributeSets.hasAttribute(2, Attribute::StructRet);
366 /// @brief Determine if the parameter does not alias other parameters.
367 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
368 bool doesNotAlias(unsigned n) const {
369 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
371 void setDoesNotAlias(unsigned n) {
372 addAttribute(n, Attribute::NoAlias);
375 /// @brief Determine if the parameter can be captured.
376 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
377 bool doesNotCapture(unsigned n) const {
378 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
380 void setDoesNotCapture(unsigned n) {
381 addAttribute(n, Attribute::NoCapture);
384 bool doesNotAccessMemory(unsigned n) const {
385 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
387 void setDoesNotAccessMemory(unsigned n) {
388 addAttribute(n, Attribute::ReadNone);
391 bool onlyReadsMemory(unsigned n) const {
392 return doesNotAccessMemory(n) ||
393 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
395 void setOnlyReadsMemory(unsigned n) {
396 addAttribute(n, Attribute::ReadOnly);
399 /// Optimize this function for minimum size (-Oz).
400 bool optForMinSize() const {
401 return hasFnAttribute(Attribute::MinSize);
404 /// Optimize this function for size (-Os) or minimum size (-Oz).
405 bool optForSize() const {
406 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
409 /// copyAttributesFrom - copy all additional attributes (those not needed to
410 /// create a Function) from the Function Src to this one.
411 void copyAttributesFrom(const GlobalValue *Src) override;
413 /// deleteBody - This method deletes the body of the function, and converts
414 /// the linkage to external.
418 setLinkage(ExternalLinkage);
421 /// removeFromParent - This method unlinks 'this' from the containing module,
422 /// but does not delete it.
424 void removeFromParent() override;
426 /// eraseFromParent - This method unlinks 'this' from the containing module
429 void eraseFromParent() override;
432 /// Get the underlying elements of the Function... the basic block list is
433 /// empty for external functions.
435 const ArgumentListType &getArgumentList() const {
436 CheckLazyArguments();
439 ArgumentListType &getArgumentList() {
440 CheckLazyArguments();
443 static iplist<Argument> Function::*getSublistAccess(Argument*) {
444 return &Function::ArgumentList;
447 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
448 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
449 static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
450 return &Function::BasicBlocks;
453 const BasicBlock &getEntryBlock() const { return front(); }
454 BasicBlock &getEntryBlock() { return front(); }
456 //===--------------------------------------------------------------------===//
457 // Symbol Table Accessing functions...
459 /// getSymbolTable() - Return the symbol table...
461 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
462 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
465 //===--------------------------------------------------------------------===//
466 // BasicBlock iterator forwarding functions
468 iterator begin() { return BasicBlocks.begin(); }
469 const_iterator begin() const { return BasicBlocks.begin(); }
470 iterator end () { return BasicBlocks.end(); }
471 const_iterator end () const { return BasicBlocks.end(); }
473 size_t size() const { return BasicBlocks.size(); }
474 bool empty() const { return BasicBlocks.empty(); }
475 const BasicBlock &front() const { return BasicBlocks.front(); }
476 BasicBlock &front() { return BasicBlocks.front(); }
477 const BasicBlock &back() const { return BasicBlocks.back(); }
478 BasicBlock &back() { return BasicBlocks.back(); }
480 /// @name Function Argument Iteration
483 arg_iterator arg_begin() {
484 CheckLazyArguments();
485 return ArgumentList.begin();
487 const_arg_iterator arg_begin() const {
488 CheckLazyArguments();
489 return ArgumentList.begin();
491 arg_iterator arg_end() {
492 CheckLazyArguments();
493 return ArgumentList.end();
495 const_arg_iterator arg_end() const {
496 CheckLazyArguments();
497 return ArgumentList.end();
500 iterator_range<arg_iterator> args() {
501 return iterator_range<arg_iterator>(arg_begin(), arg_end());
504 iterator_range<const_arg_iterator> args() const {
505 return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
510 size_t arg_size() const;
511 bool arg_empty() const;
513 bool hasPrefixData() const {
514 return getSubclassDataFromValue() & (1<<1);
517 Constant *getPrefixData() const;
518 void setPrefixData(Constant *PrefixData);
520 bool hasPrologueData() const {
521 return getSubclassDataFromValue() & (1<<2);
524 Constant *getPrologueData() const;
525 void setPrologueData(Constant *PrologueData);
527 /// viewCFG - This function is meant for use from the debugger. You can just
528 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
529 /// program, displaying the CFG of the current function with the code for each
530 /// basic block inside. This depends on there being a 'dot' and 'gv' program
533 void viewCFG() const;
535 /// viewCFGOnly - This function is meant for use from the debugger. It works
536 /// just like viewCFG, but it does not include the contents of basic blocks
537 /// into the nodes, just the label. If you are only interested in the CFG
538 /// this can make the graph smaller.
540 void viewCFGOnly() const;
542 /// Methods for support type inquiry through isa, cast, and dyn_cast:
543 static inline bool classof(const Value *V) {
544 return V->getValueID() == Value::FunctionVal;
547 /// dropAllReferences() - This method causes all the subinstructions to "let
548 /// go" of all references that they are maintaining. This allows one to
549 /// 'delete' a whole module at a time, even though there may be circular
550 /// references... first all references are dropped, and all use counts go to
551 /// zero. Then everything is deleted for real. Note that no operations are
552 /// valid on an object that has "dropped all references", except operator
555 /// Since no other object in the module can have references into the body of a
556 /// function, dropping all references deletes the entire body of the function,
557 /// including any contained basic blocks.
559 void dropAllReferences();
561 /// hasAddressTaken - returns true if there are any uses of this function
562 /// other than direct calls or invokes to it, or blockaddress expressions.
563 /// Optionally passes back an offending user for diagnostic purposes.
565 bool hasAddressTaken(const User** = nullptr) const;
567 /// isDefTriviallyDead - Return true if it is trivially safe to remove
568 /// this function definition from the module (because it isn't externally
569 /// visible, does not have its address taken, and has no callers). To make
570 /// this more accurate, call removeDeadConstantUsers first.
571 bool isDefTriviallyDead() const;
573 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
574 /// setjmp or other function that gcc recognizes as "returning twice".
575 bool callsFunctionThatReturnsTwice() const;
577 /// \brief Check if this has any metadata.
578 bool hasMetadata() const { return hasMetadataHashEntry(); }
580 /// \brief Get the current metadata attachment, if any.
582 /// Returns \c nullptr if such an attachment is missing.
584 MDNode *getMetadata(unsigned KindID) const;
585 MDNode *getMetadata(StringRef Kind) const;
588 /// \brief Set a particular kind of metadata attachment.
590 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
591 /// replacing it if it already exists.
593 void setMetadata(unsigned KindID, MDNode *MD);
594 void setMetadata(StringRef Kind, MDNode *MD);
597 /// \brief Get all current metadata attachments.
599 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
601 /// \brief Drop metadata not in the given list.
603 /// Drop all metadata from \c this not included in \c KnownIDs.
604 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
606 /// \brief Set the attached subprogram.
608 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
609 void setSubprogram(DISubprogram *SP);
611 /// \brief Get the attached subprogram.
613 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
614 /// to \a DISubprogram.
615 DISubprogram *getSubprogram() const;
618 // Shadow Value::setValueSubclassData with a private forwarding method so that
619 // subclasses cannot accidentally use it.
620 void setValueSubclassData(unsigned short D) {
621 Value::setValueSubclassData(D);
624 bool hasMetadataHashEntry() const {
625 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
627 void setHasMetadataHashEntry(bool HasEntry) {
628 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
631 void clearMetadata();
634 inline ValueSymbolTable *
635 ilist_traits<BasicBlock>::getSymTab(Function *F) {
636 return F ? &F->getValueSymbolTable() : nullptr;
639 inline ValueSymbolTable *
640 ilist_traits<Argument>::getSymTab(Function *F) {
641 return F ? &F->getValueSymbolTable() : nullptr;
645 struct OperandTraits<Function> : public OptionalOperandTraits<Function> {};
647 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
649 } // End llvm namespace