LLVM 24.0.0git
Function.cpp
Go to the documentation of this file.
1//===- Function.cpp - Implement the Global object classes -----------------===//
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 implements the Function class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Function.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/IR/Argument.h"
24#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constant.h"
28#include "llvm/IR/Constants.h"
30#include "llvm/IR/GlobalValue.h"
32#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/MDBuilder.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Use.h"
44#include "llvm/IR/User.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <cstring>
56#include <string>
57
58using namespace llvm;
59
60// Explicit instantiations of SymbolTableListTraits since some of the methods
61// are not in the public header file...
63
65 "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
66 cl::desc("Maximum size for the name of non-global values."));
67
69 validateBlockNumbers();
70
71 NextBlockNum = 0;
72 for (auto &BB : *this)
73 BB.Number = NextBlockNum++;
74 BlockNumEpoch++;
75}
76
77void Function::validateBlockNumbers() const {
78#ifndef NDEBUG
79 BitVector Numbers(NextBlockNum);
80 for (const auto &BB : *this) {
81 unsigned Num = BB.getNumber();
82 assert(Num < NextBlockNum && "out of range block number");
83 assert(!Numbers[Num] && "duplicate block numbers");
84 Numbers.set(Num);
85 }
86#endif
87}
88
90 for (auto &BB : *this) {
91 BB.convertToNewDbgValues();
92 }
93}
94
96 bool Modified = false;
97 for (auto &BB : *this) {
98 if (BB.convertFromNewDbgValues())
99 Modified = true;
100 }
101 return Modified;
102}
103
104//===----------------------------------------------------------------------===//
105// Argument Implementation
106//===----------------------------------------------------------------------===//
107
108Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
109 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
110 setName(Name);
111}
112
113void Argument::setParent(Function *parent) {
114 Parent = parent;
115}
116
117bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
118 if (!getType()->isPointerTy()) return false;
120 if (Attrs.hasAttribute(Attribute::NonNull) &&
121 (AllowUndefOrPoison || Attrs.hasAttribute(Attribute::NoUndef)))
122 return true;
123 else if (getDereferenceableBytes() > 0 &&
126 return true;
127 return false;
128}
129
130bool Argument::hasByValAttr() const {
131 if (!getType()->isPointerTy()) return false;
132 return hasAttribute(Attribute::ByVal);
133}
134
136 assert(getType()->isPointerTy() && "Only pointers have dead_on_return bytes");
137 return getParent()->getDeadOnReturnInfo(getArgNo());
138}
139
140bool Argument::hasByRefAttr() const {
141 if (!getType()->isPointerTy())
142 return false;
143 return hasAttribute(Attribute::ByRef);
144}
145
146bool Argument::hasSwiftSelfAttr() const {
147 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
148}
149
150bool Argument::hasSwiftErrorAttr() const {
151 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
152}
153
154bool Argument::hasInAllocaAttr() const {
155 if (!getType()->isPointerTy()) return false;
156 return hasAttribute(Attribute::InAlloca);
157}
158
160 if (!getType()->isPointerTy())
161 return false;
162 return hasAttribute(Attribute::Preallocated);
163}
164
166 if (!getType()->isPointerTy()) return false;
168 return Attrs.hasAttribute(Attribute::ByVal) ||
169 Attrs.hasAttribute(Attribute::InAlloca) ||
170 Attrs.hasAttribute(Attribute::Preallocated);
171}
172
174 if (!getType()->isPointerTy())
175 return false;
177 return Attrs.hasAttribute(Attribute::ByVal) ||
178 Attrs.hasAttribute(Attribute::StructRet) ||
179 Attrs.hasAttribute(Attribute::InAlloca) ||
180 Attrs.hasAttribute(Attribute::Preallocated) ||
181 Attrs.hasAttribute(Attribute::ByRef);
182}
183
184/// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
185/// parameter type.
186static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
187 // FIXME: All the type carrying attributes are mutually exclusive, so there
188 // should be a single query to get the stored type that handles any of them.
189 if (Type *ByValTy = ParamAttrs.getByValType())
190 return ByValTy;
191 if (Type *ByRefTy = ParamAttrs.getByRefType())
192 return ByRefTy;
193 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
194 return PreAllocTy;
195 if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
196 return InAllocaTy;
197 if (Type *SRetTy = ParamAttrs.getStructRetType())
198 return SRetTy;
199
200 return nullptr;
201}
202
204 if (Type *MemTy = getMemoryParamAllocType(getAttributes()))
205 return DL.getTypeAllocSize(MemTy);
206 return 0;
207}
208
211}
212
214 assert(getType()->isPointerTy() && "Only pointers have alignments");
215 return getParent()->getParamAlign(getArgNo());
216}
217
219 return getParent()->getParamStackAlign(getArgNo());
220}
221
222Type *Argument::getParamByValType() const {
223 assert(getType()->isPointerTy() && "Only pointers have byval types");
224 return getParent()->getParamByValType(getArgNo());
225}
226
228 assert(getType()->isPointerTy() && "Only pointers have sret types");
229 return getParent()->getParamStructRetType(getArgNo());
230}
231
232Type *Argument::getParamByRefType() const {
233 assert(getType()->isPointerTy() && "Only pointers have byref types");
234 return getParent()->getParamByRefType(getArgNo());
235}
236
237Type *Argument::getParamInAllocaType() const {
238 assert(getType()->isPointerTy() && "Only pointers have inalloca types");
239 return getParent()->getParamInAllocaType(getArgNo());
240}
241
244 "Only pointers have dereferenceable bytes");
245 return getParent()->getParamDereferenceableBytes(getArgNo());
246}
247
250 "Only pointers have dereferenceable bytes");
251 return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
252}
253
254FPClassTest Argument::getNoFPClass() const {
255 return getParent()->getParamNoFPClass(getArgNo());
256}
257
258std::optional<ConstantRange> Argument::getRange() const {
259 const Attribute RangeAttr = getAttribute(llvm::Attribute::Range);
260 if (RangeAttr.isValid())
261 return RangeAttr.getRange();
262 return std::nullopt;
263}
264
265bool Argument::hasNestAttr() const {
266 if (!getType()->isPointerTy()) return false;
267 return hasAttribute(Attribute::Nest);
268}
269
270bool Argument::hasNoAliasAttr() const {
271 if (!getType()->isPointerTy()) return false;
272 return hasAttribute(Attribute::NoAlias);
273}
274
275bool Argument::hasNoCaptureAttr() const {
276 if (!getType()->isPointerTy()) return false;
277 return capturesNothing(getAttributes().getCaptureInfo());
278}
279
280bool Argument::hasNoFreeAttr() const {
281 if (!getType()->isPointerTy()) return false;
282 return hasAttribute(Attribute::NoFree);
283}
284
285bool Argument::hasStructRetAttr() const {
286 if (!getType()->isPointerTy()) return false;
287 return hasAttribute(Attribute::StructRet);
288}
289
290bool Argument::hasInRegAttr() const {
291 return hasAttribute(Attribute::InReg);
292}
293
294bool Argument::hasReturnedAttr() const {
295 return hasAttribute(Attribute::Returned);
296}
297
298bool Argument::hasZExtAttr() const {
299 return hasAttribute(Attribute::ZExt);
300}
301
302bool Argument::hasSExtAttr() const {
303 return hasAttribute(Attribute::SExt);
304}
305
306bool Argument::onlyReadsMemory() const {
308 return Attrs.hasAttribute(Attribute::ReadOnly) ||
309 Attrs.hasAttribute(Attribute::ReadNone);
310}
311
312void Argument::addAttrs(AttrBuilder &B) {
313 AttributeList AL = getParent()->getAttributes();
314 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
315 getParent()->setAttributes(AL);
316}
317
319 getParent()->addParamAttr(getArgNo(), Kind);
320}
321
322void Argument::addAttr(Attribute Attr) {
323 getParent()->addParamAttr(getArgNo(), Attr);
324}
325
327 getParent()->removeParamAttr(getArgNo(), Kind);
328}
329
330void Argument::removeAttrs(const AttributeMask &AM) {
331 AttributeList AL = getParent()->getAttributes();
332 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);
333 getParent()->setAttributes(AL);
334}
335
337 return getParent()->hasParamAttribute(getArgNo(), Kind);
338}
339
340bool Argument::hasAttribute(StringRef Kind) const {
341 return getParent()->hasParamAttribute(getArgNo(), Kind);
342}
343
344Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
345 return getParent()->getParamAttribute(getArgNo(), Kind);
346}
347
349 return getParent()->getAttributes().getParamAttrs(getArgNo());
350}
351
352//===----------------------------------------------------------------------===//
353// Helper Methods in Function
354//===----------------------------------------------------------------------===//
355
357 return getType()->getContext();
358}
359
360const DataLayout &Function::getDataLayout() const {
361 return getParent()->getDataLayout();
362}
363
364unsigned Function::getInstructionCount() const {
365 unsigned NumInstrs = 0;
366 for (const BasicBlock &BB : BasicBlocks)
367 NumInstrs += BB.size();
368 return NumInstrs;
369}
370
372 const Twine &N, Module &M) {
373 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
374}
375
377 LinkageTypes Linkage,
378 unsigned AddrSpace, const Twine &N,
379 Module *M) {
380 auto *F = new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M);
381 AttrBuilder B(F->getContext());
382 UWTableKind UWTable = M->getUwtable();
383 if (UWTable != UWTableKind::None)
384 B.addUWTableAttr(UWTable);
385 switch (M->getFramePointer()) {
387 // 0 ("none") is the default.
388 break;
390 B.addAttribute("frame-pointer", "reserved");
391 break;
393 B.addAttribute("frame-pointer", "non-leaf");
394 break;
396 B.addAttribute("frame-pointer", "non-leaf-no-reserve");
397 break;
399 B.addAttribute("frame-pointer", "all");
400 break;
401 }
402 if (M->getModuleFlag("function_return_thunk_extern"))
403 B.addAttribute(Attribute::FnRetThunkExtern);
404 StringRef DefaultCPU = F->getContext().getDefaultTargetCPU();
405 if (!DefaultCPU.empty())
406 B.addAttribute("target-cpu", DefaultCPU);
407 StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures();
408 if (!DefaultFeatures.empty())
409 B.addAttribute("target-features", DefaultFeatures);
410
411 // Check if the module attribute is present and not zero.
412 auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool {
413 const auto *Attr =
414 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(ModAttr));
415 return Attr && !Attr->isZero();
416 };
417
418 auto AddAttributeIfSet = [&](const StringRef &ModAttr) {
419 if (isModuleAttributeSet(ModAttr))
420 B.addAttribute(ModAttr);
421 };
422
423 StringRef SignType = "none";
424 if (isModuleAttributeSet("sign-return-address"))
425 SignType = "non-leaf";
426 if (isModuleAttributeSet("sign-return-address-all"))
427 SignType = "all";
428 if (SignType != "none") {
429 B.addAttribute("sign-return-address", SignType);
430 B.addAttribute("sign-return-address-key",
431 isModuleAttributeSet("sign-return-address-with-bkey")
432 ? "b_key"
433 : "a_key");
434 }
435
436 if (auto Value = dyn_cast_if_present<MDString>(
437 M->getModuleFlag("sign-return-address-harden")))
438 B.addAttribute("sign-return-address-harden", Value->getString());
439 AddAttributeIfSet("branch-target-enforcement");
440 AddAttributeIfSet("branch-protection-pauth-lr");
441 AddAttributeIfSet("guarded-control-stack");
442 AddAttributeIfSet("ptrauth-returns");
443 AddAttributeIfSet("ptrauth-auth-traps");
444 AddAttributeIfSet("ptrauth-indirect-gotos");
445 AddAttributeIfSet("aarch64-jump-table-hardening");
446
447 F->addFnAttrs(B);
448 return F;
449}
450
452 getParent()->getFunctionList().remove(getIterator());
453}
454
456 getParent()->getFunctionList().erase(getIterator());
457}
458
460 Function::iterator FromBeginIt,
461 Function::iterator FromEndIt) {
462#ifdef EXPENSIVE_CHECKS
463 // Check that FromBeginIt is before FromEndIt.
464 auto FromFEnd = FromF->end();
465 for (auto It = FromBeginIt; It != FromEndIt; ++It)
466 assert(It != FromFEnd && "FromBeginIt not before FromEndIt!");
467#endif // EXPENSIVE_CHECKS
468 BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt);
469}
470
472 Function::iterator ToIt) {
473 return BasicBlocks.erase(FromIt, ToIt);
474}
475
476//===----------------------------------------------------------------------===//
477// Function Implementation
478//===----------------------------------------------------------------------===//
479
480static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
481 // If AS == -1 and we are passed a valid module pointer we place the function
482 // in the program address space. Otherwise we default to AS0.
483 if (AddrSpace == static_cast<unsigned>(-1))
484 return M ? M->getDataLayout().getProgramAddressSpace() : 0;
485 return AddrSpace;
486}
487
488Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
489 const Twine &name, Module *ParentModule)
490 : GlobalObject(Ty, Value::FunctionVal, AllocMarker, Linkage, name,
491 computeAddrSpace(AddrSpace, ParentModule)),
492 NumArgs(Ty->getNumParams()) {
493 assert(FunctionType::isValidReturnType(getReturnType()) &&
494 "invalid return type");
495 setGlobalObjectSubClassData(0);
496
497 // We only need a symbol table for a function if the context keeps value names
498 if (!getContext().shouldDiscardValueNames())
499 SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
500
501 // If the function has arguments, mark them as lazily built.
502 if (Ty->getNumParams())
503 setValueSubclassData(1); // Set the "has lazy arguments" bit.
504
505 if (ParentModule) {
506 ParentModule->getFunctionList().push_back(this);
507 }
508
509 HasLLVMReservedName = getName().starts_with("llvm.");
510 // Ensure intrinsics have the right parameter attributes.
511 // Note, the IntID field will have been set in Value::setName if this function
512 // name is a valid intrinsic ID.
513 if (IntID) {
514 // Don't set the attributes if the intrinsic signature is invalid. This
515 // case will either be auto-upgraded or fail verification.
516 SmallVector<Type *> OverloadTys;
517 if (!Intrinsic::isSignatureValid(IntID, Ty, OverloadTys))
518 return;
519
520 setAttributes(Intrinsic::getAttributes(getContext(), IntID, Ty));
521 }
522}
523
525 validateBlockNumbers();
526
527 dropAllReferences(); // After this it is safe to delete instructions.
528
529 // Delete all of the method arguments and unlink from symbol table...
530 if (Arguments)
531 clearArguments();
532
533 // Remove the function from the on-the-side GC table.
534 clearGC();
535}
536
537void Function::BuildLazyArguments() const {
538 // Create the arguments vector, all arguments start out unnamed.
539 auto *FT = getFunctionType();
540 if (NumArgs > 0) {
541 Arguments = std::allocator<Argument>().allocate(NumArgs);
542 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
543 Type *ArgTy = FT->getParamType(i);
544 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
545 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
546 }
547 }
548
549 // Clear the lazy arguments bit.
550 unsigned SDC = getSubclassDataFromValue();
551 SDC &= ~(1 << 0);
552 const_cast<Function*>(this)->setValueSubclassData(SDC);
553 assert(!hasLazyArguments());
554}
555
557 return MutableArrayRef<Argument>(Args, Count);
558}
559
562}
563
564void Function::clearArguments() {
565 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
566 A.setName("");
567 A.~Argument();
568 }
569 std::allocator<Argument>().deallocate(Arguments, NumArgs);
570 Arguments = nullptr;
571}
572
574 assert(isDeclaration() && "Expected no references to current arguments");
575
576 // Drop the current arguments, if any, and set the lazy argument bit.
577 if (!hasLazyArguments()) {
579 [](const Argument &A) { return A.use_empty(); }) &&
580 "Expected arguments to be unused in declaration");
581 clearArguments();
582 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
583 }
584
585 // Nothing to steal if Src has lazy arguments.
586 if (Src.hasLazyArguments())
587 return;
588
589 // Steal arguments from Src, and fix the lazy argument bits.
590 assert(arg_size() == Src.arg_size());
591 Arguments = Src.Arguments;
592 Src.Arguments = nullptr;
593 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
594 // FIXME: This does the work of transferNodesFromList inefficiently.
596 if (A.hasName())
597 Name = A.getName();
598 if (!Name.empty())
599 A.setName("");
600 A.setParent(this);
601 if (!Name.empty())
602 A.setName(Name);
603 }
604
605 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
606 assert(!hasLazyArguments());
607 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
608}
609
610void Function::deleteBodyImpl(bool ShouldDrop) {
611 setIsMaterializable(false);
612
613 for (BasicBlock &BB : *this)
615
616 // Delete all basic blocks. They are now unused, except possibly by
617 // blockaddresses, but BasicBlock's destructor takes care of those.
618 while (!BasicBlocks.empty())
619 BasicBlocks.begin()->eraseFromParent();
620
621 if (getNumOperands()) {
622 if (ShouldDrop) {
623 // Drop uses of any optional data (real or placeholder).
625 setNumHungOffUseOperands(0);
626 } else {
627 // The code needs to match Function::allocHungoffUselist().
629 Op<0>().set(CPN);
630 Op<1>().set(CPN);
631 Op<2>().set(CPN);
632 }
633 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
634 }
635
636 // Metadata is stored in a side-table.
637 clearMetadata();
638}
639
640void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
641 AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
642}
643
645 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
646}
647
649 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
650}
651
652void Function::addFnAttr(Attribute Attr) {
653 AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
654}
655
656void Function::addFnAttrs(const AttrBuilder &Attrs) {
657 AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
658}
659
661 AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
662}
663
664void Function::addRetAttr(Attribute Attr) {
665 AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);
666}
667
668void Function::addRetAttrs(const AttrBuilder &Attrs) {
669 AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);
670}
671
672void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
673 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
674}
675
676void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
677 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
678}
679
680void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
681 AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
682}
683
685 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
686}
687
688void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
689 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
690}
691
693 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
694}
695
697 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
698}
699
701 AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);
702}
703
705 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
706}
707
709 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
710}
711
712void Function::removeRetAttrs(const AttributeMask &Attrs) {
713 AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
714}
715
716void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
717 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
718}
719
720void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
721 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
722}
723
724void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
725 AttributeSets =
726 AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
727}
728
729void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
730 AttributeSets =
731 AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
732}
733
735 return AttributeSets.hasFnAttr(Kind);
736}
737
738bool Function::hasFnAttribute(StringRef Kind) const {
739 return AttributeSets.hasFnAttr(Kind);
740}
741
743 return AttributeSets.hasRetAttr(Kind);
744}
745
746bool Function::hasParamAttribute(unsigned ArgNo,
747 Attribute::AttrKind Kind) const {
748 return AttributeSets.hasParamAttr(ArgNo, Kind);
749}
750
751bool Function::hasParamAttribute(unsigned ArgNo, StringRef Kind) const {
752 return AttributeSets.hasParamAttr(ArgNo, Kind);
753}
754
755Attribute Function::getAttributeAtIndex(unsigned i,
756 Attribute::AttrKind Kind) const {
757 return AttributeSets.getAttributeAtIndex(i, Kind);
758}
759
760Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
761 return AttributeSets.getAttributeAtIndex(i, Kind);
762}
763
764bool Function::hasAttributeAtIndex(unsigned Idx,
765 Attribute::AttrKind Kind) const {
766 return AttributeSets.hasAttributeAtIndex(Idx, Kind);
767}
768
769Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
770 return AttributeSets.getFnAttr(Kind);
771}
772
773Attribute Function::getFnAttribute(StringRef Kind) const {
774 return AttributeSets.getFnAttr(Kind);
775}
776
778 return AttributeSets.getRetAttr(Kind);
779}
780
782 uint64_t Default) const {
783 Attribute A = getFnAttribute(Name);
785 if (A.isStringAttribute()) {
786 StringRef Str = A.getValueAsString();
787 if (Str.getAsInteger(0, Result))
788 getContext().emitError("cannot parse integer attribute " + Name);
789 }
790
791 return Result;
792}
793
794/// gets the specified attribute from the list of attributes.
795Attribute Function::getParamAttribute(unsigned ArgNo,
796 Attribute::AttrKind Kind) const {
797 return AttributeSets.getParamAttr(ArgNo, Kind);
798}
799
801 uint64_t Bytes) {
802 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
803 ArgNo, Bytes);
804}
805
807 AttributeSets = AttributeSets.addRangeRetAttr(getContext(), CR);
808}
809
811 Attribute Attr = getFnAttribute(Attribute::DenormalFPEnv);
812 if (!Attr.isValid())
814
815 DenormalFPEnv FPEnv = Attr.getDenormalFPEnv();
816 return &FPType == &APFloat::IEEEsingle() ? FPEnv.F32Mode : FPEnv.DefaultMode;
817}
818
820 Attribute Attr = getFnAttribute(Attribute::DenormalFPEnv);
821 return Attr.isValid() ? Attr.getDenormalFPEnv() : DenormalFPEnv::getDefault();
822}
823
824const std::string &Function::getGC() const {
825 assert(hasGC() && "Function has no collector");
826 return getContext().getGC(*this);
827}
828
829void Function::setGC(std::string Str) {
830 setValueSubclassDataBit(14, !Str.empty());
831 getContext().setGC(*this, std::move(Str));
832}
833
834void Function::clearGC() {
835 if (!hasGC())
836 return;
837 getContext().deleteGC(*this);
838 setValueSubclassDataBit(14, false);
839}
840
842 return hasFnAttribute(Attribute::StackProtect) ||
843 hasFnAttribute(Attribute::StackProtectStrong) ||
844 hasFnAttribute(Attribute::StackProtectReq);
845}
846
847/// Copy all additional attributes (those not needed to create a Function) from
848/// the Function Src to this one.
849void Function::copyAttributesFrom(const Function *Src) {
851 setCallingConv(Src->getCallingConv());
852 setAttributes(Src->getAttributes());
853 if (Src->hasGC())
854 setGC(Src->getGC());
855 else
856 clearGC();
857 if (Src->hasPersonalityFn())
858 setPersonalityFn(Src->getPersonalityFn());
859 if (Src->hasPrefixData())
860 setPrefixData(Src->getPrefixData());
861 if (Src->hasPrologueData())
862 setPrologueData(Src->getPrologueData());
863}
864
866 return getAttributes().getMemoryEffects();
867}
870}
871
872/// Determine if the function does not access memory.
874 return getMemoryEffects().doesNotAccessMemory();
875}
878}
879
880/// Determine if the function does not access or only reads memory.
881bool Function::onlyReadsMemory() const {
882 return getMemoryEffects().onlyReadsMemory();
883}
885 setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());
886}
887
888/// Determine if the function does not access or only writes memory.
889bool Function::onlyWritesMemory() const {
890 return getMemoryEffects().onlyWritesMemory();
891}
893 setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());
894}
895
896/// Determine if the call can access memory only using pointers based
897/// on its arguments.
899 return getMemoryEffects().onlyAccessesArgPointees();
900}
902 setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());
903}
904
905/// Determine if the function may only access memory that is
906/// inaccessible from the IR.
908 return getMemoryEffects().onlyAccessesInaccessibleMem();
909}
912}
913
914/// Determine if the function may only access memory that is
915/// either inaccessible from the IR or pointed to by its arguments.
917 return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();
918}
920 setMemoryEffects(getMemoryEffects() &
922}
923
924bool Function::isTargetIntrinsic() const {
925 return Intrinsic::isTargetIntrinsic(IntID);
926}
927
929 LibFuncCache = UnknownLibFunc;
931 if (!Name.starts_with("llvm.")) {
932 HasLLVMReservedName = false;
934 return;
935 }
936 HasLLVMReservedName = true;
937 IntID = Intrinsic::lookupIntrinsicID(Name);
938}
939
940/// hasAddressTaken - returns true if there are any uses of this function
941/// other than direct calls or invokes to it. Optionally ignores callback
942/// uses, assume like pointer annotation calls, and references in llvm.used
943/// and llvm.compiler.used variables.
944bool Function::hasAddressTaken(const User **PutOffender,
945 bool IgnoreCallbackUses,
946 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
947 bool IgnoreARCAttachedCall,
948 bool IgnoreCastedDirectCall) const {
949 for (const Use &U : uses()) {
950 const User *FU = U.getUser();
951 if (IgnoreCallbackUses) {
952 AbstractCallSite ACS(&U);
953 if (ACS && ACS.isCallbackCall())
954 continue;
955 }
956
957 const auto *Call = dyn_cast<CallBase>(FU);
958 if (!Call) {
959 if (IgnoreAssumeLikeCalls &&
961 all_of(FU->users(), [](const User *U) {
962 if (const auto *I = dyn_cast<IntrinsicInst>(U))
963 return I->isAssumeLikeIntrinsic();
964 return false;
965 })) {
966 continue;
967 }
968
969 if (IgnoreLLVMUsed && !FU->user_empty()) {
970 const User *FUU = FU;
972 FU->hasOneUse() && !FU->user_begin()->user_empty())
973 FUU = *FU->user_begin();
974 if (llvm::all_of(FUU->users(), [](const User *U) {
975 if (const auto *GV = dyn_cast<GlobalVariable>(U))
976 return GV->hasName() &&
977 (GV->getName() == "llvm.compiler.used" ||
978 GV->getName() == "llvm.used");
979 return false;
980 }))
981 continue;
982 }
983 if (PutOffender)
984 *PutOffender = FU;
985 return true;
986 }
987
988 if (IgnoreAssumeLikeCalls) {
989 if (const auto *I = dyn_cast<IntrinsicInst>(Call))
990 if (I->isAssumeLikeIntrinsic())
991 continue;
992 }
993
994 if (!Call->isCallee(&U) || (!IgnoreCastedDirectCall &&
995 Call->getFunctionType() != getFunctionType())) {
996 if (IgnoreARCAttachedCall &&
997 Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,
998 U.getOperandNo()))
999 continue;
1000
1001 if (PutOffender)
1002 *PutOffender = FU;
1003 return true;
1004 }
1005 }
1006 return false;
1007}
1008
1009bool Function::isDefTriviallyDead() const {
1010 // Check the linkage
1011 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1012 !hasAvailableExternallyLinkage())
1013 return false;
1014
1015 return use_empty();
1016}
1017
1018/// callsFunctionThatReturnsTwice - Return true if the function has a call to
1019/// setjmp or other function that gcc recognizes as "returning twice".
1021 for (const Instruction &I : instructions(this))
1022 if (const auto *Call = dyn_cast<CallBase>(&I))
1023 if (Call->hasFnAttr(Attribute::ReturnsTwice))
1024 return true;
1025
1026 return false;
1027}
1028
1029Constant *Function::getPersonalityFn() const {
1030 assert(hasPersonalityFn() && getNumOperands());
1031 return cast<Constant>(Op<0>());
1032}
1033
1034void Function::setPersonalityFn(Constant *Fn) {
1035 setHungoffOperand<0>(Fn);
1036 setValueSubclassDataBit(3, Fn != nullptr);
1037}
1038
1039Constant *Function::getPrefixData() const {
1040 assert(hasPrefixData() && getNumOperands());
1041 return cast<Constant>(Op<1>());
1042}
1043
1044void Function::setPrefixData(Constant *PrefixData) {
1045 setHungoffOperand<1>(PrefixData);
1046 setValueSubclassDataBit(1, PrefixData != nullptr);
1047}
1048
1049Constant *Function::getPrologueData() const {
1050 assert(hasPrologueData() && getNumOperands());
1051 return cast<Constant>(Op<2>());
1052}
1053
1054void Function::setPrologueData(Constant *PrologueData) {
1055 setHungoffOperand<2>(PrologueData);
1056 setValueSubclassDataBit(2, PrologueData != nullptr);
1057}
1058
1059void Function::allocHungoffUselist() {
1060 // If we've already allocated a uselist, stop here.
1061 if (getNumOperands())
1062 return;
1063
1064 allocHungoffUses(3, /*IsPhi=*/ false);
1065 setNumHungOffUseOperands(3);
1066
1067 // Initialize the uselist with placeholder operands to allow traversal.
1069 Op<0>().set(CPN);
1070 Op<1>().set(CPN);
1071 Op<2>().set(CPN);
1072}
1073
1074template <int Idx>
1075void Function::setHungoffOperand(Constant *C) {
1076 if (C) {
1077 allocHungoffUselist();
1078 Op<Idx>().set(C);
1079 } else if (getNumOperands()) {
1081 }
1082}
1083
1084void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1085 assert(Bit < 16 && "SubclassData contains only 16 bits");
1086 if (On)
1087 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1088 else
1089 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1090}
1091
1093 const DenseSet<GlobalValue::GUID> *S) {
1094 auto ImportGUIDs = getImportGUIDs();
1095 if (S == nullptr && ImportGUIDs.size())
1096 S = &ImportGUIDs;
1097
1098 MDBuilder MDB(getContext());
1099 setMetadata(LLVMContext::MD_prof,
1100 MDB.createFunctionEntryCount(Count, false, S));
1101}
1102
1103std::optional<uint64_t> Function::getEntryCount() const {
1104 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1105 if (MD && MD->getOperand(0))
1106 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1107 if (MDS->getString() != MDProfLabels::FunctionEntryCount)
1108 return std::nullopt;
1111 // A value of -1 is used for SamplePGO when there were no samples.
1112 // Treat this the same as unknown.
1113 if (Count == static_cast<uint64_t>(-1))
1114 return std::nullopt;
1115 return Count;
1116 }
1117 return std::nullopt;
1118}
1119
1122 if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1123 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1124 if (MDS->getString() == MDProfLabels::FunctionEntryCount)
1125 for (unsigned i = 2; i < MD->getNumOperands(); i++)
1127 ->getValue()
1128 .getZExtValue());
1129 return R;
1130}
1131
1132bool Function::nullPointerIsDefined() const {
1133 return hasFnAttribute(Attribute::NullPointerIsValid);
1134}
1135
1136unsigned Function::getVScaleValue() const {
1137 Attribute Attr = getFnAttribute(Attribute::VScaleRange);
1138 if (!Attr.isValid())
1139 return 0;
1140
1141 unsigned VScale = Attr.getVScaleRangeMin();
1142 if (VScale && VScale == Attr.getVScaleRangeMax())
1143 return VScale;
1144
1145 return 0;
1146}
1147
1148bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1149 if (F && F->nullPointerIsDefined())
1150 return true;
1151
1152 if (AS != 0)
1153 return true;
1154
1155 return false;
1156}
1157
1159 switch (CC) {
1160 case CallingConv::C:
1161 case CallingConv::Fast:
1162 case CallingConv::Cold:
1163 case CallingConv::GHC:
1164 case CallingConv::HiPE:
1168 case CallingConv::Swift:
1170 case CallingConv::Tail:
1185 case CallingConv::Win64:
1193 return true;
1198 return false;
1216 case CallingConv::GRAAL:
1233 return true;
1234 default:
1235 return false;
1236 }
1237
1238 llvm_unreachable("covered callingconv switch");
1239}
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Lower Kernel Arguments
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static bool setMemoryEffects(Function &F, MemoryEffects ME)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:217
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
This file defines the DenseSet and SmallDenseSet classes.
@ Default
Module.h This file contains the declarations for the Module class.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
This file contains the declarations for profiling metadata utility functions.
static StringRef getName(Value *V)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
static Type * getMemoryParamAllocType(AttributeSet ParamAttrs)
For a byval, sret, inalloca, or preallocated parameter, get the in-memory parameter type.
Definition Function.cpp:186
static cl::opt< int > NonGlobalValueMaxNameSize("non-global-value-max-name-size", cl::Hidden, cl::init(1024), cl::desc("Maximum size for the name of non-global values."))
static MutableArrayRef< Argument > makeArgArray(Argument *Args, size_t Count)
Definition Function.cpp:556
static unsigned computeAddrSpace(unsigned AddrSpace, Module *M)
Definition Function.cpp:480
This file defines the SmallString class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI Type * getParamByRefType() const
If this is a byref argument, return its type.
Definition Function.cpp:232
LLVM_ABI DeadOnReturnInfo getDeadOnReturnInfo() const
Returns information on the memory marked dead_on_return for the argument.
Definition Function.cpp:135
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Definition Function.cpp:344
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Definition Function.cpp:270
LLVM_ABI bool hasNonNullAttr(bool AllowUndefOrPoison=true) const
Return true if this argument has the nonnull attribute.
Definition Function.cpp:117
LLVM_ABI bool hasByRefAttr() const
Return true if this argument has the byref attribute.
Definition Function.cpp:140
LLVM_ABI uint64_t getDereferenceableOrNullBytes() const
If this argument has the dereferenceable_or_null attribute, return the number of bytes known to be de...
Definition Function.cpp:248
LLVM_ABI void addAttr(Attribute::AttrKind Kind)
Definition Function.cpp:318
LLVM_ABI Argument(Type *Ty, const Twine &Name="", Function *F=nullptr, unsigned ArgNo=0)
Argument constructor.
Definition Function.cpp:108
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Definition Function.cpp:306
LLVM_ABI bool hasPointeeInMemoryValueAttr() const
Return true if this argument has the byval, sret, inalloca, preallocated, or byref attribute.
Definition Function.cpp:173
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:336
LLVM_ABI bool hasReturnedAttr() const
Return true if this argument has the returned attribute.
Definition Function.cpp:294
LLVM_ABI Type * getParamStructRetType() const
If this is an sret argument, return its type.
Definition Function.cpp:227
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
Definition Function.cpp:290
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
Definition Function.cpp:130
LLVM_ABI bool hasPreallocatedAttr() const
Return true if this argument has the preallocated attribute.
Definition Function.cpp:159
LLVM_ABI bool hasSExtAttr() const
Return true if this argument has the sext attribute.
Definition Function.cpp:302
LLVM_ABI void removeAttr(Attribute::AttrKind Kind)
Remove attributes from an argument.
Definition Function.cpp:326
LLVM_ABI uint64_t getPassPointeeByValueCopySize(const DataLayout &DL) const
If this argument satisfies has hasPassPointeeByValueAttr, return the in-memory ABI size copied to the...
Definition Function.cpp:203
LLVM_ABI void removeAttrs(const AttributeMask &AM)
Definition Function.cpp:330
LLVM_ABI Type * getPointeeInMemoryValueType() const
If hasPointeeInMemoryValueAttr returns true, the in-memory ABI type is returned.
Definition Function.cpp:209
LLVM_ABI bool hasInAllocaAttr() const
Return true if this argument has the inalloca attribute.
Definition Function.cpp:154
LLVM_ABI bool hasSwiftErrorAttr() const
Return true if this argument has the swifterror attribute.
Definition Function.cpp:150
LLVM_ABI FPClassTest getNoFPClass() const
If this argument has nofpclass attribute, return the mask representing disallowed floating-point valu...
Definition Function.cpp:254
LLVM_ABI void addAttrs(AttrBuilder &B)
Add attributes to an argument.
Definition Function.cpp:312
LLVM_ABI bool hasNoFreeAttr() const
Return true if this argument has the nofree attribute.
Definition Function.cpp:280
LLVM_ABI bool hasSwiftSelfAttr() const
Return true if this argument has the swiftself attribute.
Definition Function.cpp:146
LLVM_ABI Type * getParamInAllocaType() const
If this is an inalloca argument, return its type.
Definition Function.cpp:237
LLVM_ABI bool hasZExtAttr() const
Return true if this argument has the zext attribute.
Definition Function.cpp:298
LLVM_ABI Type * getParamByValType() const
If this is a byval argument, return its type.
Definition Function.cpp:222
LLVM_ABI bool hasNestAttr() const
Return true if this argument has the nest attribute.
Definition Function.cpp:265
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
Definition Function.cpp:213
LLVM_ABI std::optional< ConstantRange > getRange() const
If this argument has a range attribute, return the value range of the argument.
Definition Function.cpp:258
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition Function.cpp:285
LLVM_ABI AttributeSet getAttributes() const
Definition Function.cpp:348
LLVM_ABI bool hasPassPointeeByValueCopyAttr() const
Return true if this argument has the byval, inalloca, or preallocated attribute.
Definition Function.cpp:165
LLVM_ABI MaybeAlign getParamStackAlign() const
Definition Function.cpp:218
LLVM_ABI bool hasNoCaptureAttr() const
Return true if this argument has the nocapture attribute.
Definition Function.cpp:275
LLVM_ABI uint64_t getDereferenceableBytes() const
If this argument has the dereferenceable attribute, return the number of bytes known to be dereferenc...
Definition Function.cpp:242
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
LLVM_ABI Type * getInAllocaType() const
LLVM_ABI Type * getByValType() const
LLVM_ABI Type * getStructRetType() const
LLVM_ABI Type * getPreallocatedType() const
LLVM_ABI Type * getByRefType() const
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
static LLVM_ABI Attribute getWithMemoryEffects(LLVMContext &Context, MemoryEffects ME)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:452
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:644
unsigned getVScaleValue() const
Return the value for vscale based on the vscale_range attribute or 0 when unknown.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs)
adds the attributes to the list of attributes for the given arg.
Definition Function.cpp:680
void removeRetAttr(Attribute::AttrKind Kind)
removes the attribute from the return value list of attributes.
Definition Function.cpp:704
void addRetAttrs(const AttrBuilder &Attrs)
Add return value attributes to this function.
Definition Function.cpp:668
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
bool onlyAccessesInaccessibleMemOrArgMem() const
Determine if the function may only access memory that is either inaccessible from the IR or pointed t...
Definition Function.cpp:916
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:746
BasicBlockListType::iterator iterator
Definition Function.h:70
bool hasAddressTaken(const User **=nullptr, bool IgnoreCallbackUses=false, bool IgnoreAssumeLikeCalls=true, bool IngoreLLVMUsed=false, bool IgnoreARCAttachedCall=false, bool IgnoreCastedDirectCall=false) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition Function.cpp:944
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
Definition Function.cpp:716
bool nullPointerIsDefined() const
Check if null pointer dereferencing is considered undefined behavior for the function.
bool convertFromNewDbgValues()
Definition Function.cpp:95
Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
gets the specified attribute from the list of attributes.
Definition Function.cpp:795
void setPrefixData(Constant *PrefixData)
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
Definition Function.cpp:841
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition Function.cpp:451
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:360
void addFnAttrs(const AttrBuilder &Attrs)
Add function attributes to this function.
Definition Function.cpp:656
void renumberBlocks()
Renumber basic blocks into a dense value range starting from 0.
Definition Function.cpp:68
void setDoesNotAccessMemory()
Definition Function.cpp:876
void setGC(std::string Str)
Definition Function.cpp:829
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:769
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:781
bool isConstrainedFPIntrinsic() const
Returns true if the function is one of the "Constrained Floating-PointIntrinsics".
Definition Function.cpp:560
void setOnlyAccessesArgMemory()
Definition Function.cpp:901
MemoryEffects getMemoryEffects() const
Definition Function.cpp:865
void setOnlyAccessesInaccessibleMemory()
Definition Function.cpp:910
void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs)
removes the attribute from the list of attributes.
Definition Function.cpp:724
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
Definition Function.cpp:746
bool hasAttributeAtIndex(unsigned Idx, Attribute::AttrKind Kind) const
Check if attribute of the given kind is set at the given index.
Definition Function.cpp:764
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition Function.cpp:376
void setOnlyReadsMemory()
Definition Function.cpp:884
bool isTargetIntrinsic() const
isTargetIntrinsic - Returns true if this function is an intrinsic and the intrinsic is specific to a ...
Definition Function.cpp:924
void removeFnAttrs(const AttributeMask &Attrs)
Definition Function.cpp:700
void addRetAttr(Attribute::AttrKind Kind)
Add return value attributes to this function.
Definition Function.cpp:660
DenormalFPEnv getDenormalFPEnv() const
Return the representational value of the denormal_fpenv attribute.
Definition Function.cpp:819
Constant * getPrologueData() const
Get the prologue data associated with this function.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setOnlyWritesMemory()
Definition Function.cpp:892
void setPersonalityFn(Constant *Fn)
DenseSet< GlobalValue::GUID > getImportGUIDs() const
Returns the set of GUIDs that needs to be imported to the function for sample PGO,...
void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
Definition Function.cpp:684
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:455
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
Definition Function.cpp:692
void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes)
adds the dereferenceable_or_null attribute to the list of attributes for the given arg.
Definition Function.cpp:800
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes for the return value.
Definition Function.cpp:806
void stealArgumentListFrom(Function &Src)
Steal arguments from another function.
Definition Function.cpp:573
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
const std::string & getGC() const
Definition Function.cpp:824
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:672
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:873
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition Function.cpp:810
void updateAfterNameChange()
Update internal caches that depend on the function name (such as the intrinsic ID and libcall cache).
Definition Function.cpp:928
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
bool hasRetAttribute(Attribute::AttrKind Kind) const
check if an attribute is in the list of attributes for the return value.
Definition Function.cpp:742
bool onlyWritesMemory() const
Determine if the function does not access or only writes memory.
Definition Function.cpp:889
bool onlyAccessesInaccessibleMemory() const
Determine if the function may only access memory that is inaccessible from the IR.
Definition Function.cpp:907
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:712
bool onlyAccessesArgMemory() const
Determine if the call can access memory only using pointers based on its arguments.
Definition Function.cpp:898
Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt)
Erases a range of BasicBlocks from FromIt to (not including) ToIt.
Definition Function.cpp:471
void setMemoryEffects(MemoryEffects ME)
Definition Function.cpp:868
Constant * getPrefixData() const
Get the prefix data associated with this function.
Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const
gets the attribute from the list of attributes.
Definition Function.cpp:755
iterator end()
Definition Function.h:840
void convertToNewDbgValues()
Definition Function.cpp:89
void setOnlyAccessesInaccessibleMemOrArgMem()
Definition Function.cpp:919
void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes)
adds the dereferenceable attribute to the list of attributes for the given arg.
Definition Function.cpp:729
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
Definition Function.cpp:364
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Definition Function.cpp:881
void addAttributeAtIndex(unsigned i, Attribute Attr)
adds the attribute to the list of attributes.
Definition Function.cpp:640
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:734
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:849
Attribute getRetAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind for the return value.
Definition Function.cpp:777
LLVM_ABI void copyAttributesFrom(const GlobalObject *Src)
Definition Globals.cpp:228
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
A single uniqued string.
Definition Metadata.h:733
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Definition Module.h:714
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
user_iterator user_begin()
Definition Value.h:404
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
iterator_range< user_iterator > users()
Definition Value.h:428
bool user_empty() const
Definition Value.h:391
void push_back(pointer val)
Definition ilist.h:250
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
LLVM_ABI LLVM_READNONE bool supportsNonVoidReturnType(CallingConv::ID CC)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ ARM64EC_Thunk_Native
Calling convention used in the ARM64EC ABI to implement calls between ARM64 code and thunks.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ M68k_INTR
Used for M68k interrupt routines.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ MSP430_BUILTIN
Used for special MSP430 rtlib functions which have an "optimized" convention using additional registe...
@ AVR_SIGNAL
Used for AVR signal routines.
@ HiPE
Used by the High-Performance Erlang Compiler (HiPE).
Definition CallingConv.h:53
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ RISCV_VLSCall_32
Calling convention used for RISC-V V-extension fixed vectors.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AVR_BUILTIN
Used for special AVR rtlib functions which have an "optimized" convention to preserve registers.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ ARM64EC_Thunk_X64
Calling convention used in the ARM64EC ABI to implement calls between x64 code and thunks.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
LLVM_ABI bool isConstrainedFPIntrinsic(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics".
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:694
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
constexpr double e
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:395
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
UWTableKind
Definition CodeGen.h:299
@ None
No unwind table requested.
Definition CodeGen.h:300
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
#define N
Represents the full denormal controls for a function, including the default mode and the f32 specific...
static constexpr DenormalFPEnv getDefault()
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDefault()
Return the assumed default mode for a function without denormal-fp-math.
static LLVM_ABI const char * FunctionEntryCount
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106