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