1//===- llvm/Function.h - Class to represent a single function ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the declaration of the Function class, which represents a
10// single function/procedure in LLVM.
11//
12// A function basically consists of a list of basic blocks, a list of arguments,
13// and a symbol table.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_IR_FUNCTION_H
18#define LLVM_IR_FUNCTION_H
19
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/ADT/ilist_node.h"
24#include "llvm/ADT/iterator_range.h"
25#include "llvm/IR/Argument.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalObject.h"
31#include "llvm/IR/GlobalValue.h"
32#include "llvm/IR/OperandTraits.h"
33#include "llvm/IR/SymbolTableListTraits.h"
34#include "llvm/IR/Value.h"
35#include <cassert>
36#include <cstddef>
37#include <cstdint>
38#include <memory>
39#include <string>
40
41namespace llvm {
42
43namespace Intrinsic {
44typedef unsigned ID;
45}
46
47class AssemblyAnnotationWriter;
48class Constant;
49struct DenormalMode;
50class DISubprogram;
51enum LibFunc : unsigned;
52class LLVMContext;
53class Module;
54class raw_ostream;
55class TargetLibraryInfoImpl;
56class Type;
57class User;
58class BranchProbabilityInfo;
59class BlockFrequencyInfo;
60
61class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject,
62 public ilist_node<Function> {
63public:
64 using BasicBlockListType = SymbolTableList<BasicBlock>;
65
66 // BasicBlock iterators...
67 using iterator = BasicBlockListType::iterator;
68 using const_iterator = BasicBlockListType::const_iterator;
69
70 using arg_iterator = Argument *;
71 using const_arg_iterator = const Argument *;
72
73private:
74 // Important things that make up a function!
75 BasicBlockListType BasicBlocks; ///< The basic blocks
76 mutable Argument *Arguments = nullptr; ///< The formal arguments
77 size_t NumArgs;
78 std::unique_ptr<ValueSymbolTable>
79 SymTab; ///< Symbol table of args/instructions
80 AttributeList AttributeSets; ///< Parameter attributes
81
82 /*
83 * Value::SubclassData
84 *
85 * bit 0 : HasLazyArguments
86 * bit 1 : HasPrefixData
87 * bit 2 : HasPrologueData
88 * bit 3 : HasPersonalityFn
89 * bits 4-13 : CallingConvention
90 * bits 14 : HasGC
91 * bits 15 : [reserved]
92 */
93
94 /// Bits from GlobalObject::GlobalObjectSubclassData.
95 enum {
96 /// Whether this function is materializable.
97 IsMaterializableBit = 0,
98 };
99
100 friend class SymbolTableListTraits<Function>;
101
102public:
103 /// Is this function using intrinsics to record the position of debugging
104 /// information, or non-intrinsic records? See IsNewDbgInfoFormat in
105 /// \ref BasicBlock.
106 bool IsNewDbgInfoFormat;
107
108 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
109 /// built on demand, so that the list isn't allocated until the first client
110 /// needs it. The hasLazyArguments predicate returns true if the arg list
111 /// hasn't been set up yet.
112 bool hasLazyArguments() const {
113 return getSubclassDataFromValue() & (1<<0);
114 }
115
116 /// \see BasicBlock::convertToNewDbgValues.
117 void convertToNewDbgValues();
118
119 /// \see BasicBlock::convertFromNewDbgValues.
120 void convertFromNewDbgValues();
121
122 void setIsNewDbgInfoFormat(bool NewVal);
123 void setNewDbgInfoFormatFlag(bool NewVal);
124
125private:
126 friend class TargetLibraryInfoImpl;
127
128 static constexpr LibFunc UnknownLibFunc = LibFunc(-1);
129
130 /// Cache for TLI::getLibFunc() result without prototype validation.
131 /// UnknownLibFunc if uninitialized. NotLibFunc if definitely not lib func.
132 /// Otherwise may be libfunc if prototype validation passes.
133 mutable LibFunc LibFuncCache = UnknownLibFunc;
134
135 void CheckLazyArguments() const {
136 if (hasLazyArguments())
137 BuildLazyArguments();
138 }
139
140 void BuildLazyArguments() const;
141
142 void clearArguments();
143
144 void deleteBodyImpl(bool ShouldDrop);
145
146 /// Function ctor - If the (optional) Module argument is specified, the
147 /// function is automatically inserted into the end of the function list for
148 /// the module.
149 ///
150 Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
151 const Twine &N = "", Module *M = nullptr);
152
153public:
154 Function(const Function&) = delete;
155 void operator=(const Function&) = delete;
156 ~Function();
157
158 // This is here to help easily convert from FunctionT * (Function * or
159 // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling
160 // FunctionT->getFunction().
161 const Function &getFunction() const { return *this; }
162
163 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
164 unsigned AddrSpace, const Twine &N = "",
165 Module *M = nullptr) {
166 return new Function(Ty, Linkage, AddrSpace, N, M);
167 }
168
169 // TODO: remove this once all users have been updated to pass an AddrSpace
170 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
171 const Twine &N = "", Module *M = nullptr) {
172 return new Function(Ty, Linkage, static_cast<unsigned>(-1), N, M);
173 }
174
175 /// Creates a new function and attaches it to a module.
176 ///
177 /// Places the function in the program address space as specified
178 /// by the module's data layout.
179 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
180 const Twine &N, Module &M);
181
182 /// Creates a function with some attributes recorded in llvm.module.flags
183 /// applied.
184 ///
185 /// Use this when synthesizing new functions that need attributes that would
186 /// have been set by command line options.
187 static Function *createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage,
188 unsigned AddrSpace,
189 const Twine &N = "",
190 Module *M = nullptr);
191
192 // Provide fast operand accessors.
193 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
194
195 /// Returns the number of non-debug IR instructions in this function.
196 /// This is equivalent to the sum of the sizes of each basic block contained
197 /// within this function.
198 unsigned getInstructionCount() const;
199
200 /// Returns the FunctionType for me.
201 FunctionType *getFunctionType() const {
202 return cast<FunctionType>(Val: getValueType());
203 }
204
205 /// Returns the type of the ret val.
206 Type *getReturnType() const { return getFunctionType()->getReturnType(); }
207
208 /// getContext - Return a reference to the LLVMContext associated with this
209 /// function.
210 LLVMContext &getContext() const;
211
212 /// isVarArg - Return true if this function takes a variable number of
213 /// arguments.
214 bool isVarArg() const { return getFunctionType()->isVarArg(); }
215
216 bool isMaterializable() const {
217 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
218 }
219 void setIsMaterializable(bool V) {
220 unsigned Mask = 1 << IsMaterializableBit;
221 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
222 (V ? Mask : 0u));
223 }
224
225 /// getIntrinsicID - This method returns the ID number of the specified
226 /// function, or Intrinsic::not_intrinsic if the function is not an
227 /// intrinsic, or if the pointer is null. This value is always defined to be
228 /// zero to allow easy checking for whether a function is intrinsic or not.
229 /// The particular intrinsic functions which correspond to this value are
230 /// defined in llvm/Intrinsics.h.
231 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
232
233 /// isIntrinsic - Returns true if the function's name starts with "llvm.".
234 /// It's possible for this function to return true while getIntrinsicID()
235 /// returns Intrinsic::not_intrinsic!
236 bool isIntrinsic() const { return HasLLVMReservedName; }
237
238 /// isTargetIntrinsic - Returns true if IID is an intrinsic specific to a
239 /// certain target. If it is a generic intrinsic false is returned.
240 static bool isTargetIntrinsic(Intrinsic::ID IID);
241
242 /// isTargetIntrinsic - Returns true if this function is an intrinsic and the
243 /// intrinsic is specific to a certain target. If this is not an intrinsic
244 /// or a generic intrinsic, false is returned.
245 bool isTargetIntrinsic() const;
246
247 /// Returns true if the function is one of the "Constrained Floating-Point
248 /// Intrinsics". Returns false if not, and returns false when
249 /// getIntrinsicID() returns Intrinsic::not_intrinsic.
250 bool isConstrainedFPIntrinsic() const;
251
252 static Intrinsic::ID lookupIntrinsicID(StringRef Name);
253
254 /// Update internal caches that depend on the function name (such as the
255 /// intrinsic ID and libcall cache).
256 /// Note, this method does not need to be called directly, as it is called
257 /// from Value::setName() whenever the name of this function changes.
258 void updateAfterNameChange();
259
260 /// getCallingConv()/setCallingConv(CC) - These method get and set the
261 /// calling convention of this function. The enum values for the known
262 /// calling conventions are defined in CallingConv.h.
263 CallingConv::ID getCallingConv() const {
264 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
265 CallingConv::MaxID);
266 }
267 void setCallingConv(CallingConv::ID CC) {
268 auto ID = static_cast<unsigned>(CC);
269 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
270 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
271 }
272
273 enum ProfileCountType { PCT_Real, PCT_Synthetic };
274
275 /// Class to represent profile counts.
276 ///
277 /// This class represents both real and synthetic profile counts.
278 class ProfileCount {
279 private:
280 uint64_t Count = 0;
281 ProfileCountType PCT = PCT_Real;
282
283 public:
284 ProfileCount(uint64_t Count, ProfileCountType PCT)
285 : Count(Count), PCT(PCT) {}
286 uint64_t getCount() const { return Count; }
287 ProfileCountType getType() const { return PCT; }
288 bool isSynthetic() const { return PCT == PCT_Synthetic; }
289 };
290
291 /// Set the entry count for this function.
292 ///
293 /// Entry count is the number of times this function was executed based on
294 /// pgo data. \p Imports points to a set of GUIDs that needs to
295 /// be imported by the function for sample PGO, to enable the same inlines as
296 /// the profiled optimized binary.
297 void setEntryCount(ProfileCount Count,
298 const DenseSet<GlobalValue::GUID> *Imports = nullptr);
299
300 /// A convenience wrapper for setting entry count
301 void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real,
302 const DenseSet<GlobalValue::GUID> *Imports = nullptr);
303
304 /// Get the entry count for this function.
305 ///
306 /// Entry count is the number of times the function was executed.
307 /// When AllowSynthetic is false, only pgo_data will be returned.
308 std::optional<ProfileCount> getEntryCount(bool AllowSynthetic = false) const;
309
310 /// Return true if the function is annotated with profile data.
311 ///
312 /// Presence of entry counts from a profile run implies the function has
313 /// profile annotations. If IncludeSynthetic is false, only return true
314 /// when the profile data is real.
315 bool hasProfileData(bool IncludeSynthetic = false) const {
316 return getEntryCount(AllowSynthetic: IncludeSynthetic).has_value();
317 }
318
319 /// Returns the set of GUIDs that needs to be imported to the function for
320 /// sample PGO, to enable the same inlines as the profiled optimized binary.
321 DenseSet<GlobalValue::GUID> getImportGUIDs() const;
322
323 /// Set the section prefix for this function.
324 void setSectionPrefix(StringRef Prefix);
325
326 /// Get the section prefix for this function.
327 std::optional<StringRef> getSectionPrefix() const;
328
329 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
330 /// to use during code generation.
331 bool hasGC() const {
332 return getSubclassDataFromValue() & (1<<14);
333 }
334 const std::string &getGC() const;
335 void setGC(std::string Str);
336 void clearGC();
337
338 /// Return the attribute list for this Function.
339 AttributeList getAttributes() const { return AttributeSets; }
340
341 /// Set the attribute list for this Function.
342 void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; }
343
344 // TODO: remove non-AtIndex versions of these methods.
345 /// adds the attribute to the list of attributes.
346 void addAttributeAtIndex(unsigned i, Attribute Attr);
347
348 /// Add function attributes to this function.
349 void addFnAttr(Attribute::AttrKind Kind);
350
351 /// Add function attributes to this function.
352 void addFnAttr(StringRef Kind, StringRef Val = StringRef());
353
354 /// Add function attributes to this function.
355 void addFnAttr(Attribute Attr);
356
357 /// Add function attributes to this function.
358 void addFnAttrs(const AttrBuilder &Attrs);
359
360 /// Add return value attributes to this function.
361 void addRetAttr(Attribute::AttrKind Kind);
362
363 /// Add return value attributes to this function.
364 void addRetAttr(Attribute Attr);
365
366 /// Add return value attributes to this function.
367 void addRetAttrs(const AttrBuilder &Attrs);
368
369 /// adds the attribute to the list of attributes for the given arg.
370 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
371
372 /// adds the attribute to the list of attributes for the given arg.
373 void addParamAttr(unsigned ArgNo, Attribute Attr);
374
375 /// adds the attributes to the list of attributes for the given arg.
376 void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs);
377
378 /// removes the attribute from the list of attributes.
379 void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind);
380
381 /// removes the attribute from the list of attributes.
382 void removeAttributeAtIndex(unsigned i, StringRef Kind);
383
384 /// Remove function attributes from this function.
385 void removeFnAttr(Attribute::AttrKind Kind);
386
387 /// Remove function attribute from this function.
388 void removeFnAttr(StringRef Kind);
389
390 void removeFnAttrs(const AttributeMask &Attrs);
391
392 /// removes the attribute from the return value list of attributes.
393 void removeRetAttr(Attribute::AttrKind Kind);
394
395 /// removes the attribute from the return value list of attributes.
396 void removeRetAttr(StringRef Kind);
397
398 /// removes the attributes from the return value list of attributes.
399 void removeRetAttrs(const AttributeMask &Attrs);
400
401 /// removes the attribute from the list of attributes.
402 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
403
404 /// removes the attribute from the list of attributes.
405 void removeParamAttr(unsigned ArgNo, StringRef Kind);
406
407 /// removes the attribute from the list of attributes.
408 void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs);
409
410 /// Return true if the function has the attribute.
411 bool hasFnAttribute(Attribute::AttrKind Kind) const;
412
413 /// Return true if the function has the attribute.
414 bool hasFnAttribute(StringRef Kind) const;
415
416 /// check if an attribute is in the list of attributes for the return value.
417 bool hasRetAttribute(Attribute::AttrKind Kind) const;
418
419 /// check if an attributes is in the list of attributes.
420 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
421
422 /// gets the attribute from the list of attributes.
423 Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const;
424
425 /// gets the attribute from the list of attributes.
426 Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const;
427
428 /// Return the attribute for the given attribute kind.
429 Attribute getFnAttribute(Attribute::AttrKind Kind) const;
430
431 /// Return the attribute for the given attribute kind.
432 Attribute getFnAttribute(StringRef Kind) const;
433
434 /// Return the attribute for the given attribute kind for the return value.
435 Attribute getRetAttribute(Attribute::AttrKind Kind) const;
436
437 /// For a string attribute \p Kind, parse attribute as an integer.
438 ///
439 /// \returns \p Default if attribute is not present.
440 ///
441 /// \returns \p Default if there is an error parsing the attribute integer,
442 /// and error is emitted to the LLVMContext
443 uint64_t getFnAttributeAsParsedInteger(StringRef Kind,
444 uint64_t Default = 0) const;
445
446 /// gets the specified attribute from the list of attributes.
447 Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
448
449 /// Return the stack alignment for the function.
450 MaybeAlign getFnStackAlign() const {
451 return AttributeSets.getFnStackAlignment();
452 }
453
454 /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
455 bool hasStackProtectorFnAttr() const;
456
457 /// adds the dereferenceable attribute to the list of attributes for
458 /// the given arg.
459 void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes);
460
461 /// adds the dereferenceable_or_null attribute to the list of
462 /// attributes for the given arg.
463 void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes);
464
465 MaybeAlign getParamAlign(unsigned ArgNo) const {
466 return AttributeSets.getParamAlignment(ArgNo);
467 }
468
469 MaybeAlign getParamStackAlign(unsigned ArgNo) const {
470 return AttributeSets.getParamStackAlignment(ArgNo);
471 }
472
473 /// Extract the byval type for a parameter.
474 Type *getParamByValType(unsigned ArgNo) const {
475 return AttributeSets.getParamByValType(ArgNo);
476 }
477
478 /// Extract the sret type for a parameter.
479 Type *getParamStructRetType(unsigned ArgNo) const {
480 return AttributeSets.getParamStructRetType(ArgNo);
481 }
482
483 /// Extract the inalloca type for a parameter.
484 Type *getParamInAllocaType(unsigned ArgNo) const {
485 return AttributeSets.getParamInAllocaType(ArgNo);
486 }
487
488 /// Extract the byref type for a parameter.
489 Type *getParamByRefType(unsigned ArgNo) const {
490 return AttributeSets.getParamByRefType(ArgNo);
491 }
492
493 /// Extract the preallocated type for a parameter.
494 Type *getParamPreallocatedType(unsigned ArgNo) const {
495 return AttributeSets.getParamPreallocatedType(ArgNo);
496 }
497
498 /// Extract the number of dereferenceable bytes for a parameter.
499 /// @param ArgNo Index of an argument, with 0 being the first function arg.
500 uint64_t getParamDereferenceableBytes(unsigned ArgNo) const {
501 return AttributeSets.getParamDereferenceableBytes(Index: ArgNo);
502 }
503
504 /// Extract the number of dereferenceable_or_null bytes for a
505 /// parameter.
506 /// @param ArgNo AttributeList ArgNo, referring to an argument.
507 uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const {
508 return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo);
509 }
510
511 /// Extract the nofpclass attribute for a parameter.
512 FPClassTest getParamNoFPClass(unsigned ArgNo) const {
513 return AttributeSets.getParamNoFPClass(ArgNo);
514 }
515
516 /// Determine if the function is presplit coroutine.
517 bool isPresplitCoroutine() const {
518 return hasFnAttribute(Attribute::PresplitCoroutine);
519 }
520 void setPresplitCoroutine() { addFnAttr(Attribute::PresplitCoroutine); }
521 void setSplittedCoroutine() { removeFnAttr(Attribute::PresplitCoroutine); }
522
523 bool isCoroOnlyDestroyWhenComplete() const {
524 return hasFnAttribute(Attribute::CoroDestroyOnlyWhenComplete);
525 }
526 void setCoroDestroyOnlyWhenComplete() {
527 addFnAttr(Attribute::CoroDestroyOnlyWhenComplete);
528 }
529
530 MemoryEffects getMemoryEffects() const;
531 void setMemoryEffects(MemoryEffects ME);
532
533 /// Determine if the function does not access memory.
534 bool doesNotAccessMemory() const;
535 void setDoesNotAccessMemory();
536
537 /// Determine if the function does not access or only reads memory.
538 bool onlyReadsMemory() const;
539 void setOnlyReadsMemory();
540
541 /// Determine if the function does not access or only writes memory.
542 bool onlyWritesMemory() const;
543 void setOnlyWritesMemory();
544
545 /// Determine if the call can access memmory only using pointers based
546 /// on its arguments.
547 bool onlyAccessesArgMemory() const;
548 void setOnlyAccessesArgMemory();
549
550 /// Determine if the function may only access memory that is
551 /// inaccessible from the IR.
552 bool onlyAccessesInaccessibleMemory() const;
553 void setOnlyAccessesInaccessibleMemory();
554
555 /// Determine if the function may only access memory that is
556 /// either inaccessible from the IR or pointed to by its arguments.
557 bool onlyAccessesInaccessibleMemOrArgMem() const;
558 void setOnlyAccessesInaccessibleMemOrArgMem();
559
560 /// Determine if the function cannot return.
561 bool doesNotReturn() const {
562 return hasFnAttribute(Attribute::NoReturn);
563 }
564 void setDoesNotReturn() {
565 addFnAttr(Attribute::NoReturn);
566 }
567
568 /// Determine if the function should not perform indirect branch tracking.
569 bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); }
570
571 /// Determine if the function cannot unwind.
572 bool doesNotThrow() const {
573 return hasFnAttribute(Attribute::NoUnwind);
574 }
575 void setDoesNotThrow() {
576 addFnAttr(Attribute::NoUnwind);
577 }
578
579 /// Determine if the call cannot be duplicated.
580 bool cannotDuplicate() const {
581 return hasFnAttribute(Attribute::NoDuplicate);
582 }
583 void setCannotDuplicate() {
584 addFnAttr(Attribute::NoDuplicate);
585 }
586
587 /// Determine if the call is convergent.
588 bool isConvergent() const {
589 return hasFnAttribute(Attribute::Convergent);
590 }
591 void setConvergent() {
592 addFnAttr(Attribute::Convergent);
593 }
594 void setNotConvergent() {
595 removeFnAttr(Attribute::Convergent);
596 }
597
598 /// Determine if the call has sideeffects.
599 bool isSpeculatable() const {
600 return hasFnAttribute(Attribute::Speculatable);
601 }
602 void setSpeculatable() {
603 addFnAttr(Attribute::Speculatable);
604 }
605
606 /// Determine if the call might deallocate memory.
607 bool doesNotFreeMemory() const {
608 return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree);
609 }
610 void setDoesNotFreeMemory() {
611 addFnAttr(Attribute::NoFree);
612 }
613
614 /// Determine if the call can synchroize with other threads
615 bool hasNoSync() const {
616 return hasFnAttribute(Attribute::NoSync);
617 }
618 void setNoSync() {
619 addFnAttr(Attribute::NoSync);
620 }
621
622 /// Determine if the function is known not to recurse, directly or
623 /// indirectly.
624 bool doesNotRecurse() const {
625 return hasFnAttribute(Attribute::NoRecurse);
626 }
627 void setDoesNotRecurse() {
628 addFnAttr(Attribute::NoRecurse);
629 }
630
631 /// Determine if the function is required to make forward progress.
632 bool mustProgress() const {
633 return hasFnAttribute(Attribute::MustProgress) ||
634 hasFnAttribute(Attribute::WillReturn);
635 }
636 void setMustProgress() { addFnAttr(Attribute::MustProgress); }
637
638 /// Determine if the function will return.
639 bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); }
640 void setWillReturn() { addFnAttr(Attribute::WillReturn); }
641
642 /// Get what kind of unwind table entry to generate for this function.
643 UWTableKind getUWTableKind() const {
644 return AttributeSets.getUWTableKind();
645 }
646
647 /// True if the ABI mandates (or the user requested) that this
648 /// function be in a unwind table.
649 bool hasUWTable() const {
650 return getUWTableKind() != UWTableKind::None;
651 }
652 void setUWTableKind(UWTableKind K) {
653 addFnAttr(Attr: Attribute::getWithUWTableKind(Context&: getContext(), Kind: K));
654 }
655 /// True if this function needs an unwind table.
656 bool needsUnwindTableEntry() const {
657 return hasUWTable() || !doesNotThrow() || hasPersonalityFn();
658 }
659
660 /// Determine if the function returns a structure through first
661 /// or second pointer argument.
662 bool hasStructRetAttr() const {
663 return AttributeSets.hasParamAttr(0, Attribute::StructRet) ||
664 AttributeSets.hasParamAttr(1, Attribute::StructRet);
665 }
666
667 /// Determine if the parameter or return value is marked with NoAlias
668 /// attribute.
669 bool returnDoesNotAlias() const {
670 return AttributeSets.hasRetAttr(Attribute::NoAlias);
671 }
672 void setReturnDoesNotAlias() { addRetAttr(Attribute::NoAlias); }
673
674 /// Do not optimize this function (-O0).
675 bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); }
676
677 /// Optimize this function for minimum size (-Oz).
678 bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); }
679
680 /// Optimize this function for size (-Os) or minimum size (-Oz).
681 bool hasOptSize() const {
682 return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize();
683 }
684
685 /// Returns the denormal handling type for the default rounding mode of the
686 /// function.
687 DenormalMode getDenormalMode(const fltSemantics &FPType) const;
688
689 /// Return the representational value of "denormal-fp-math". Code interested
690 /// in the semantics of the function should use getDenormalMode instead.
691 DenormalMode getDenormalModeRaw() const;
692
693 /// Return the representational value of "denormal-fp-math-f32". Code
694 /// interested in the semantics of the function should use getDenormalMode
695 /// instead.
696 DenormalMode getDenormalModeF32Raw() const;
697
698 /// copyAttributesFrom - copy all additional attributes (those not needed to
699 /// create a Function) from the Function Src to this one.
700 void copyAttributesFrom(const Function *Src);
701
702 /// deleteBody - This method deletes the body of the function, and converts
703 /// the linkage to external.
704 ///
705 void deleteBody() {
706 deleteBodyImpl(/*ShouldDrop=*/ShouldDrop: false);
707 setLinkage(ExternalLinkage);
708 }
709
710 /// removeFromParent - This method unlinks 'this' from the containing module,
711 /// but does not delete it.
712 ///
713 void removeFromParent();
714
715 /// eraseFromParent - This method unlinks 'this' from the containing module
716 /// and deletes it.
717 ///
718 void eraseFromParent();
719
720 /// Steal arguments from another function.
721 ///
722 /// Drop this function's arguments and splice in the ones from \c Src.
723 /// Requires that this has no function body.
724 void stealArgumentListFrom(Function &Src);
725
726 /// Insert \p BB in the basic block list at \p Position. \Returns an iterator
727 /// to the newly inserted BB.
728 Function::iterator insert(Function::iterator Position, BasicBlock *BB) {
729 Function::iterator FIt = BasicBlocks.insert(where: Position, New: BB);
730 BB->setIsNewDbgInfoFormat(IsNewDbgInfoFormat);
731 return FIt;
732 }
733
734 /// Transfer all blocks from \p FromF to this function at \p ToIt.
735 void splice(Function::iterator ToIt, Function *FromF) {
736 splice(ToIt, FromF, FromBeginIt: FromF->begin(), FromEndIt: FromF->end());
737 }
738
739 /// Transfer one BasicBlock from \p FromF at \p FromIt to this function
740 /// at \p ToIt.
741 void splice(Function::iterator ToIt, Function *FromF,
742 Function::iterator FromIt) {
743 auto FromItNext = std::next(x: FromIt);
744 // Single-element splice is a noop if destination == source.
745 if (ToIt == FromIt || ToIt == FromItNext)
746 return;
747 splice(ToIt, FromF, FromBeginIt: FromIt, FromEndIt: FromItNext);
748 }
749
750 /// Transfer a range of basic blocks that belong to \p FromF from \p
751 /// FromBeginIt to \p FromEndIt, to this function at \p ToIt.
752 void splice(Function::iterator ToIt, Function *FromF,
753 Function::iterator FromBeginIt,
754 Function::iterator FromEndIt);
755
756 /// Erases a range of BasicBlocks from \p FromIt to (not including) \p ToIt.
757 /// \Returns \p ToIt.
758 Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt);
759
760private:
761 // These need access to the underlying BB list.
762 friend void BasicBlock::removeFromParent();
763 friend iplist<BasicBlock>::iterator BasicBlock::eraseFromParent();
764 template <class BB_t, class BB_i_t, class BI_t, class II_t>
765 friend class InstIterator;
766 friend class llvm::SymbolTableListTraits<llvm::BasicBlock>;
767 friend class llvm::ilist_node_with_parent<llvm::BasicBlock, llvm::Function>;
768
769 /// Get the underlying elements of the Function... the basic block list is
770 /// empty for external functions.
771 ///
772 /// This is deliberately private because we have implemented an adequate set
773 /// of functions to modify the list, including Function::splice(),
774 /// Function::erase(), Function::insert() etc.
775 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
776 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
777
778 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
779 return &Function::BasicBlocks;
780 }
781
782public:
783 const BasicBlock &getEntryBlock() const { return front(); }
784 BasicBlock &getEntryBlock() { return front(); }
785
786 //===--------------------------------------------------------------------===//
787 // Symbol Table Accessing functions...
788
789 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
790 ///
791 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
792 inline const ValueSymbolTable *getValueSymbolTable() const {
793 return SymTab.get();
794 }
795
796 //===--------------------------------------------------------------------===//
797 // BasicBlock iterator forwarding functions
798 //
799 iterator begin() { return BasicBlocks.begin(); }
800 const_iterator begin() const { return BasicBlocks.begin(); }
801 iterator end () { return BasicBlocks.end(); }
802 const_iterator end () const { return BasicBlocks.end(); }
803
804 size_t size() const { return BasicBlocks.size(); }
805 bool empty() const { return BasicBlocks.empty(); }
806 const BasicBlock &front() const { return BasicBlocks.front(); }
807 BasicBlock &front() { return BasicBlocks.front(); }
808 const BasicBlock &back() const { return BasicBlocks.back(); }
809 BasicBlock &back() { return BasicBlocks.back(); }
810
811/// @name Function Argument Iteration
812/// @{
813
814 arg_iterator arg_begin() {
815 CheckLazyArguments();
816 return Arguments;
817 }
818 const_arg_iterator arg_begin() const {
819 CheckLazyArguments();
820 return Arguments;
821 }
822
823 arg_iterator arg_end() {
824 CheckLazyArguments();
825 return Arguments + NumArgs;
826 }
827 const_arg_iterator arg_end() const {
828 CheckLazyArguments();
829 return Arguments + NumArgs;
830 }
831
832 Argument* getArg(unsigned i) const {
833 assert (i < NumArgs && "getArg() out of range!");
834 CheckLazyArguments();
835 return Arguments + i;
836 }
837
838 iterator_range<arg_iterator> args() {
839 return make_range(x: arg_begin(), y: arg_end());
840 }
841 iterator_range<const_arg_iterator> args() const {
842 return make_range(x: arg_begin(), y: arg_end());
843 }
844
845/// @}
846
847 size_t arg_size() const { return NumArgs; }
848 bool arg_empty() const { return arg_size() == 0; }
849
850 /// Check whether this function has a personality function.
851 bool hasPersonalityFn() const {
852 return getSubclassDataFromValue() & (1<<3);
853 }
854
855 /// Get the personality function associated with this function.
856 Constant *getPersonalityFn() const;
857 void setPersonalityFn(Constant *Fn);
858
859 /// Check whether this function has prefix data.
860 bool hasPrefixData() const {
861 return getSubclassDataFromValue() & (1<<1);
862 }
863
864 /// Get the prefix data associated with this function.
865 Constant *getPrefixData() const;
866 void setPrefixData(Constant *PrefixData);
867
868 /// Check whether this function has prologue data.
869 bool hasPrologueData() const {
870 return getSubclassDataFromValue() & (1<<2);
871 }
872
873 /// Get the prologue data associated with this function.
874 Constant *getPrologueData() const;
875 void setPrologueData(Constant *PrologueData);
876
877 /// Print the function to an output stream with an optional
878 /// AssemblyAnnotationWriter.
879 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
880 bool ShouldPreserveUseListOrder = false,
881 bool IsForDebug = false) const;
882
883 /// viewCFG - This function is meant for use from the debugger. You can just
884 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
885 /// program, displaying the CFG of the current function with the code for each
886 /// basic block inside. This depends on there being a 'dot' and 'gv' program
887 /// in your path.
888 ///
889 void viewCFG() const;
890
891 /// Extended form to print edge weights.
892 void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
893 const BranchProbabilityInfo *BPI) const;
894
895 /// viewCFGOnly - This function is meant for use from the debugger. It works
896 /// just like viewCFG, but it does not include the contents of basic blocks
897 /// into the nodes, just the label. If you are only interested in the CFG
898 /// this can make the graph smaller.
899 ///
900 void viewCFGOnly() const;
901
902 /// Extended form to print edge weights.
903 void viewCFGOnly(const BlockFrequencyInfo *BFI,
904 const BranchProbabilityInfo *BPI) const;
905
906 /// Methods for support type inquiry through isa, cast, and dyn_cast:
907 static bool classof(const Value *V) {
908 return V->getValueID() == Value::FunctionVal;
909 }
910
911 /// dropAllReferences() - This method causes all the subinstructions to "let
912 /// go" of all references that they are maintaining. This allows one to
913 /// 'delete' a whole module at a time, even though there may be circular
914 /// references... first all references are dropped, and all use counts go to
915 /// zero. Then everything is deleted for real. Note that no operations are
916 /// valid on an object that has "dropped all references", except operator
917 /// delete.
918 ///
919 /// Since no other object in the module can have references into the body of a
920 /// function, dropping all references deletes the entire body of the function,
921 /// including any contained basic blocks.
922 ///
923 void dropAllReferences() {
924 deleteBodyImpl(/*ShouldDrop=*/ShouldDrop: true);
925 }
926
927 /// hasAddressTaken - returns true if there are any uses of this function
928 /// other than direct calls or invokes to it, or blockaddress expressions.
929 /// Optionally passes back an offending user for diagnostic purposes,
930 /// ignores callback uses, assume like pointer annotation calls, references in
931 /// llvm.used and llvm.compiler.used variables, operand bundle
932 /// "clang.arc.attachedcall", and direct calls with a different call site
933 /// signature (the function is implicitly casted).
934 bool hasAddressTaken(const User ** = nullptr, bool IgnoreCallbackUses = false,
935 bool IgnoreAssumeLikeCalls = true,
936 bool IngoreLLVMUsed = false,
937 bool IgnoreARCAttachedCall = false,
938 bool IgnoreCastedDirectCall = false) const;
939
940 /// isDefTriviallyDead - Return true if it is trivially safe to remove
941 /// this function definition from the module (because it isn't externally
942 /// visible, does not have its address taken, and has no callers). To make
943 /// this more accurate, call removeDeadConstantUsers first.
944 bool isDefTriviallyDead() const;
945
946 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
947 /// setjmp or other function that gcc recognizes as "returning twice".
948 bool callsFunctionThatReturnsTwice() const;
949
950 /// Set the attached subprogram.
951 ///
952 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
953 void setSubprogram(DISubprogram *SP);
954
955 /// Get the attached subprogram.
956 ///
957 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
958 /// to \a DISubprogram.
959 DISubprogram *getSubprogram() const;
960
961 /// Returns true if we should emit debug info for profiling.
962 bool shouldEmitDebugInfoForProfiling() const;
963
964 /// Check if null pointer dereferencing is considered undefined behavior for
965 /// the function.
966 /// Return value: false => null pointer dereference is undefined.
967 /// Return value: true => null pointer dereference is not undefined.
968 bool nullPointerIsDefined() const;
969
970private:
971 void allocHungoffUselist();
972 template<int Idx> void setHungoffOperand(Constant *C);
973
974 /// Shadow Value::setValueSubclassData with a private forwarding method so
975 /// that subclasses cannot accidentally use it.
976 void setValueSubclassData(unsigned short D) {
977 Value::setValueSubclassData(D);
978 }
979 void setValueSubclassDataBit(unsigned Bit, bool On);
980};
981
982/// Check whether null pointer dereferencing is considered undefined behavior
983/// for a given function or an address space.
984/// Null pointer access in non-zero address space is not considered undefined.
985/// Return value: false => null pointer dereference is undefined.
986/// Return value: true => null pointer dereference is not undefined.
987bool NullPointerIsDefined(const Function *F, unsigned AS = 0);
988
989template <>
990struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
991
992DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
993
994} // end namespace llvm
995
996#endif // LLVM_IR_FUNCTION_H
997

source code of llvm/include/llvm/IR/Function.h