LLVM 23.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;
60
61// Explicit instantiations of SymbolTableListTraits since some of the methods
62// are not in the public header file...
64
66 "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
67 cl::desc("Maximum size for the name of non-global values."));
68
70 validateBlockNumbers();
71
72 NextBlockNum = 0;
73 for (auto &BB : *this)
74 BB.Number = NextBlockNum++;
75 BlockNumEpoch++;
76}
77
78void Function::validateBlockNumbers() const {
79#ifndef NDEBUG
80 BitVector Numbers(NextBlockNum);
81 for (const auto &BB : *this) {
82 unsigned Num = BB.getNumber();
83 assert(Num < NextBlockNum && "out of range block number");
84 assert(!Numbers[Num] && "duplicate block numbers");
85 Numbers.set(Num);
86 }
87#endif
88}
89
91 for (auto &BB : *this) {
92 BB.convertToNewDbgValues();
93 }
94}
95
97 for (auto &BB : *this) {
98 BB.convertFromNewDbgValues();
99 }
100}
101
102//===----------------------------------------------------------------------===//
103// Argument Implementation
104//===----------------------------------------------------------------------===//
105
106Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
107 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
108 setName(Name);
109}
110
111void Argument::setParent(Function *parent) {
112 Parent = parent;
113}
114
115bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
116 if (!getType()->isPointerTy()) return false;
118 if (Attrs.hasAttribute(Attribute::NonNull) &&
119 (AllowUndefOrPoison || Attrs.hasAttribute(Attribute::NoUndef)))
120 return true;
121 else if (getDereferenceableBytes() > 0 &&
124 return true;
125 return false;
126}
127
128bool Argument::hasByValAttr() const {
129 if (!getType()->isPointerTy()) return false;
130 return hasAttribute(Attribute::ByVal);
131}
132
134 assert(getType()->isPointerTy() && "Only pointers have dead_on_return bytes");
135 return getParent()->getDeadOnReturnInfo(getArgNo());
136}
137
138bool Argument::hasByRefAttr() const {
139 if (!getType()->isPointerTy())
140 return false;
141 return hasAttribute(Attribute::ByRef);
142}
143
144bool Argument::hasSwiftSelfAttr() const {
145 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
146}
147
148bool Argument::hasSwiftErrorAttr() const {
149 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
150}
151
152bool Argument::hasInAllocaAttr() const {
153 if (!getType()->isPointerTy()) return false;
154 return hasAttribute(Attribute::InAlloca);
155}
156
158 if (!getType()->isPointerTy())
159 return false;
160 return hasAttribute(Attribute::Preallocated);
161}
162
164 if (!getType()->isPointerTy()) return false;
166 return Attrs.hasAttribute(Attribute::ByVal) ||
167 Attrs.hasAttribute(Attribute::InAlloca) ||
168 Attrs.hasAttribute(Attribute::Preallocated);
169}
170
172 if (!getType()->isPointerTy())
173 return false;
175 return Attrs.hasAttribute(Attribute::ByVal) ||
176 Attrs.hasAttribute(Attribute::StructRet) ||
177 Attrs.hasAttribute(Attribute::InAlloca) ||
178 Attrs.hasAttribute(Attribute::Preallocated) ||
179 Attrs.hasAttribute(Attribute::ByRef);
180}
181
182/// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
183/// parameter type.
184static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
185 // FIXME: All the type carrying attributes are mutually exclusive, so there
186 // should be a single query to get the stored type that handles any of them.
187 if (Type *ByValTy = ParamAttrs.getByValType())
188 return ByValTy;
189 if (Type *ByRefTy = ParamAttrs.getByRefType())
190 return ByRefTy;
191 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
192 return PreAllocTy;
193 if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
194 return InAllocaTy;
195 if (Type *SRetTy = ParamAttrs.getStructRetType())
196 return SRetTy;
197
198 return nullptr;
199}
200
202 if (Type *MemTy = getMemoryParamAllocType(getAttributes()))
203 return DL.getTypeAllocSize(MemTy);
204 return 0;
205}
206
209}
210
212 assert(getType()->isPointerTy() && "Only pointers have alignments");
213 return getParent()->getParamAlign(getArgNo());
214}
215
217 return getParent()->getParamStackAlign(getArgNo());
218}
219
220Type *Argument::getParamByValType() const {
221 assert(getType()->isPointerTy() && "Only pointers have byval types");
222 return getParent()->getParamByValType(getArgNo());
223}
224
226 assert(getType()->isPointerTy() && "Only pointers have sret types");
227 return getParent()->getParamStructRetType(getArgNo());
228}
229
230Type *Argument::getParamByRefType() const {
231 assert(getType()->isPointerTy() && "Only pointers have byref types");
232 return getParent()->getParamByRefType(getArgNo());
233}
234
235Type *Argument::getParamInAllocaType() const {
236 assert(getType()->isPointerTy() && "Only pointers have inalloca types");
237 return getParent()->getParamInAllocaType(getArgNo());
238}
239
242 "Only pointers have dereferenceable bytes");
243 return getParent()->getParamDereferenceableBytes(getArgNo());
244}
245
248 "Only pointers have dereferenceable bytes");
249 return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
250}
251
252FPClassTest Argument::getNoFPClass() const {
253 return getParent()->getParamNoFPClass(getArgNo());
254}
255
256std::optional<ConstantRange> Argument::getRange() const {
257 const Attribute RangeAttr = getAttribute(llvm::Attribute::Range);
258 if (RangeAttr.isValid())
259 return RangeAttr.getRange();
260 return std::nullopt;
261}
262
263bool Argument::hasNestAttr() const {
264 if (!getType()->isPointerTy()) return false;
265 return hasAttribute(Attribute::Nest);
266}
267
268bool Argument::hasNoAliasAttr() const {
269 if (!getType()->isPointerTy()) return false;
270 return hasAttribute(Attribute::NoAlias);
271}
272
273bool Argument::hasNoCaptureAttr() const {
274 if (!getType()->isPointerTy()) return false;
275 return capturesNothing(getAttributes().getCaptureInfo());
276}
277
278bool Argument::hasNoFreeAttr() const {
279 if (!getType()->isPointerTy()) return false;
280 return hasAttribute(Attribute::NoFree);
281}
282
283bool Argument::hasStructRetAttr() const {
284 if (!getType()->isPointerTy()) return false;
285 return hasAttribute(Attribute::StructRet);
286}
287
288bool Argument::hasInRegAttr() const {
289 return hasAttribute(Attribute::InReg);
290}
291
292bool Argument::hasReturnedAttr() const {
293 return hasAttribute(Attribute::Returned);
294}
295
296bool Argument::hasZExtAttr() const {
297 return hasAttribute(Attribute::ZExt);
298}
299
300bool Argument::hasSExtAttr() const {
301 return hasAttribute(Attribute::SExt);
302}
303
304bool Argument::onlyReadsMemory() const {
306 return Attrs.hasAttribute(Attribute::ReadOnly) ||
307 Attrs.hasAttribute(Attribute::ReadNone);
308}
309
310void Argument::addAttrs(AttrBuilder &B) {
311 AttributeList AL = getParent()->getAttributes();
312 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
313 getParent()->setAttributes(AL);
314}
315
317 getParent()->addParamAttr(getArgNo(), Kind);
318}
319
320void Argument::addAttr(Attribute Attr) {
321 getParent()->addParamAttr(getArgNo(), Attr);
322}
323
325 getParent()->removeParamAttr(getArgNo(), Kind);
326}
327
328void Argument::removeAttrs(const AttributeMask &AM) {
329 AttributeList AL = getParent()->getAttributes();
330 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);
331 getParent()->setAttributes(AL);
332}
333
335 return getParent()->hasParamAttribute(getArgNo(), Kind);
336}
337
338bool Argument::hasAttribute(StringRef Kind) const {
339 return getParent()->hasParamAttribute(getArgNo(), Kind);
340}
341
342Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
343 return getParent()->getParamAttribute(getArgNo(), Kind);
344}
345
347 return getParent()->getAttributes().getParamAttrs(getArgNo());
348}
349
350//===----------------------------------------------------------------------===//
351// Helper Methods in Function
352//===----------------------------------------------------------------------===//
353
355 return getType()->getContext();
356}
357
358const DataLayout &Function::getDataLayout() const {
359 return getParent()->getDataLayout();
360}
361
362unsigned Function::getInstructionCount() const {
363 unsigned NumInstrs = 0;
364 for (const BasicBlock &BB : BasicBlocks)
365 NumInstrs += BB.size();
366 return NumInstrs;
367}
368
370 const Twine &N, Module &M) {
371 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
372}
373
375 LinkageTypes Linkage,
376 unsigned AddrSpace, const Twine &N,
377 Module *M) {
378 auto *F = new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M);
379 AttrBuilder B(F->getContext());
380 UWTableKind UWTable = M->getUwtable();
381 if (UWTable != UWTableKind::None)
382 B.addUWTableAttr(UWTable);
383 switch (M->getFramePointer()) {
385 // 0 ("none") is the default.
386 break;
388 B.addAttribute("frame-pointer", "reserved");
389 break;
391 B.addAttribute("frame-pointer", "non-leaf");
392 break;
394 B.addAttribute("frame-pointer", "non-leaf-no-reserve");
395 break;
397 B.addAttribute("frame-pointer", "all");
398 break;
399 }
400 if (M->getModuleFlag("function_return_thunk_extern"))
401 B.addAttribute(Attribute::FnRetThunkExtern);
402 StringRef DefaultCPU = F->getContext().getDefaultTargetCPU();
403 if (!DefaultCPU.empty())
404 B.addAttribute("target-cpu", DefaultCPU);
405 StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures();
406 if (!DefaultFeatures.empty())
407 B.addAttribute("target-features", DefaultFeatures);
408
409 // Check if the module attribute is present and not zero.
410 auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool {
411 const auto *Attr =
412 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(ModAttr));
413 return Attr && !Attr->isZero();
414 };
415
416 auto AddAttributeIfSet = [&](const StringRef &ModAttr) {
417 if (isModuleAttributeSet(ModAttr))
418 B.addAttribute(ModAttr);
419 };
420
421 StringRef SignType = "none";
422 if (isModuleAttributeSet("sign-return-address"))
423 SignType = "non-leaf";
424 if (isModuleAttributeSet("sign-return-address-all"))
425 SignType = "all";
426 if (SignType != "none") {
427 B.addAttribute("sign-return-address", SignType);
428 B.addAttribute("sign-return-address-key",
429 isModuleAttributeSet("sign-return-address-with-bkey")
430 ? "b_key"
431 : "a_key");
432 }
433 AddAttributeIfSet("branch-target-enforcement");
434 AddAttributeIfSet("branch-protection-pauth-lr");
435 AddAttributeIfSet("guarded-control-stack");
436
437 F->addFnAttrs(B);
438 return F;
439}
440
442 getParent()->getFunctionList().remove(getIterator());
443}
444
446 getParent()->getFunctionList().erase(getIterator());
447}
448
450 Function::iterator FromBeginIt,
451 Function::iterator FromEndIt) {
452#ifdef EXPENSIVE_CHECKS
453 // Check that FromBeginIt is before FromEndIt.
454 auto FromFEnd = FromF->end();
455 for (auto It = FromBeginIt; It != FromEndIt; ++It)
456 assert(It != FromFEnd && "FromBeginIt not before FromEndIt!");
457#endif // EXPENSIVE_CHECKS
458 BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt);
459}
460
462 Function::iterator ToIt) {
463 return BasicBlocks.erase(FromIt, ToIt);
464}
465
466//===----------------------------------------------------------------------===//
467// Function Implementation
468//===----------------------------------------------------------------------===//
469
470static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
471 // If AS == -1 and we are passed a valid module pointer we place the function
472 // in the program address space. Otherwise we default to AS0.
473 if (AddrSpace == static_cast<unsigned>(-1))
474 return M ? M->getDataLayout().getProgramAddressSpace() : 0;
475 return AddrSpace;
476}
477
478Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
479 const Twine &name, Module *ParentModule)
480 : GlobalObject(Ty, Value::FunctionVal, AllocMarker, Linkage, name,
481 computeAddrSpace(AddrSpace, ParentModule)),
482 NumArgs(Ty->getNumParams()) {
483 assert(FunctionType::isValidReturnType(getReturnType()) &&
484 "invalid return type");
485 setGlobalObjectSubClassData(0);
486
487 // We only need a symbol table for a function if the context keeps value names
488 if (!getContext().shouldDiscardValueNames())
489 SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
490
491 // If the function has arguments, mark them as lazily built.
492 if (Ty->getNumParams())
493 setValueSubclassData(1); // Set the "has lazy arguments" bit.
494
495 if (ParentModule) {
496 ParentModule->getFunctionList().push_back(this);
497 }
498
499 HasLLVMReservedName = getName().starts_with("llvm.");
500 // Ensure intrinsics have the right parameter attributes.
501 // Note, the IntID field will have been set in Value::setName if this function
502 // name is a valid intrinsic ID.
503 if (IntID) {
504 // Don't set the attributes if the intrinsic signature is invalid. This
505 // case will either be auto-upgraded or fail verification.
506 SmallVector<Type *> OverloadTys;
507 if (!Intrinsic::isSignatureValid(IntID, Ty, OverloadTys))
508 return;
509
510 setAttributes(Intrinsic::getAttributes(getContext(), IntID, Ty));
511 }
512}
513
515 validateBlockNumbers();
516
517 dropAllReferences(); // After this it is safe to delete instructions.
518
519 // Delete all of the method arguments and unlink from symbol table...
520 if (Arguments)
521 clearArguments();
522
523 // Remove the function from the on-the-side GC table.
524 clearGC();
525}
526
527void Function::BuildLazyArguments() const {
528 // Create the arguments vector, all arguments start out unnamed.
529 auto *FT = getFunctionType();
530 if (NumArgs > 0) {
531 Arguments = std::allocator<Argument>().allocate(NumArgs);
532 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
533 Type *ArgTy = FT->getParamType(i);
534 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
535 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
536 }
537 }
538
539 // Clear the lazy arguments bit.
540 unsigned SDC = getSubclassDataFromValue();
541 SDC &= ~(1 << 0);
542 const_cast<Function*>(this)->setValueSubclassData(SDC);
543 assert(!hasLazyArguments());
544}
545
547 return MutableArrayRef<Argument>(Args, Count);
548}
549
552}
553
554void Function::clearArguments() {
555 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
556 A.setName("");
557 A.~Argument();
558 }
559 std::allocator<Argument>().deallocate(Arguments, NumArgs);
560 Arguments = nullptr;
561}
562
564 assert(isDeclaration() && "Expected no references to current arguments");
565
566 // Drop the current arguments, if any, and set the lazy argument bit.
567 if (!hasLazyArguments()) {
569 [](const Argument &A) { return A.use_empty(); }) &&
570 "Expected arguments to be unused in declaration");
571 clearArguments();
572 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
573 }
574
575 // Nothing to steal if Src has lazy arguments.
576 if (Src.hasLazyArguments())
577 return;
578
579 // Steal arguments from Src, and fix the lazy argument bits.
580 assert(arg_size() == Src.arg_size());
581 Arguments = Src.Arguments;
582 Src.Arguments = nullptr;
583 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
584 // FIXME: This does the work of transferNodesFromList inefficiently.
586 if (A.hasName())
587 Name = A.getName();
588 if (!Name.empty())
589 A.setName("");
590 A.setParent(this);
591 if (!Name.empty())
592 A.setName(Name);
593 }
594
595 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
596 assert(!hasLazyArguments());
597 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
598}
599
600void Function::deleteBodyImpl(bool ShouldDrop) {
601 setIsMaterializable(false);
602
603 for (BasicBlock &BB : *this)
605
606 // Delete all basic blocks. They are now unused, except possibly by
607 // blockaddresses, but BasicBlock's destructor takes care of those.
608 while (!BasicBlocks.empty())
609 BasicBlocks.begin()->eraseFromParent();
610
611 if (getNumOperands()) {
612 if (ShouldDrop) {
613 // Drop uses of any optional data (real or placeholder).
615 setNumHungOffUseOperands(0);
616 } else {
617 // The code needs to match Function::allocHungoffUselist().
619 Op<0>().set(CPN);
620 Op<1>().set(CPN);
621 Op<2>().set(CPN);
622 }
623 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
624 }
625
626 // Metadata is stored in a side-table.
627 clearMetadata();
628}
629
630void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
631 AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
632}
633
635 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
636}
637
639 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
640}
641
642void Function::addFnAttr(Attribute Attr) {
643 AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
644}
645
646void Function::addFnAttrs(const AttrBuilder &Attrs) {
647 AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
648}
649
651 AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
652}
653
654void Function::addRetAttr(Attribute Attr) {
655 AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);
656}
657
658void Function::addRetAttrs(const AttrBuilder &Attrs) {
659 AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);
660}
661
662void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
663 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
664}
665
666void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
667 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
668}
669
670void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
671 AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
672}
673
675 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
676}
677
678void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
679 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
680}
681
683 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
684}
685
687 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
688}
689
691 AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);
692}
693
695 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
696}
697
699 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
700}
701
702void Function::removeRetAttrs(const AttributeMask &Attrs) {
703 AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
704}
705
706void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
707 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
708}
709
710void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
711 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
712}
713
714void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
715 AttributeSets =
716 AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
717}
718
719void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
720 AttributeSets =
721 AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
722}
723
725 return AttributeSets.hasFnAttr(Kind);
726}
727
728bool Function::hasFnAttribute(StringRef Kind) const {
729 return AttributeSets.hasFnAttr(Kind);
730}
731
733 return AttributeSets.hasRetAttr(Kind);
734}
735
736bool Function::hasParamAttribute(unsigned ArgNo,
737 Attribute::AttrKind Kind) const {
738 return AttributeSets.hasParamAttr(ArgNo, Kind);
739}
740
741bool Function::hasParamAttribute(unsigned ArgNo, StringRef Kind) const {
742 return AttributeSets.hasParamAttr(ArgNo, Kind);
743}
744
745Attribute Function::getAttributeAtIndex(unsigned i,
746 Attribute::AttrKind Kind) const {
747 return AttributeSets.getAttributeAtIndex(i, Kind);
748}
749
750Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
751 return AttributeSets.getAttributeAtIndex(i, Kind);
752}
753
754bool Function::hasAttributeAtIndex(unsigned Idx,
755 Attribute::AttrKind Kind) const {
756 return AttributeSets.hasAttributeAtIndex(Idx, Kind);
757}
758
759Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
760 return AttributeSets.getFnAttr(Kind);
761}
762
763Attribute Function::getFnAttribute(StringRef Kind) const {
764 return AttributeSets.getFnAttr(Kind);
765}
766
768 return AttributeSets.getRetAttr(Kind);
769}
770
772 uint64_t Default) const {
773 Attribute A = getFnAttribute(Name);
775 if (A.isStringAttribute()) {
776 StringRef Str = A.getValueAsString();
777 if (Str.getAsInteger(0, Result))
778 getContext().emitError("cannot parse integer attribute " + Name);
779 }
780
781 return Result;
782}
783
784/// gets the specified attribute from the list of attributes.
785Attribute Function::getParamAttribute(unsigned ArgNo,
786 Attribute::AttrKind Kind) const {
787 return AttributeSets.getParamAttr(ArgNo, Kind);
788}
789
791 uint64_t Bytes) {
792 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
793 ArgNo, Bytes);
794}
795
797 AttributeSets = AttributeSets.addRangeRetAttr(getContext(), CR);
798}
799
801 Attribute Attr = getFnAttribute(Attribute::DenormalFPEnv);
802 if (!Attr.isValid())
804
805 DenormalFPEnv FPEnv = Attr.getDenormalFPEnv();
806 return &FPType == &APFloat::IEEEsingle() ? FPEnv.F32Mode : FPEnv.DefaultMode;
807}
808
810 Attribute Attr = getFnAttribute(Attribute::DenormalFPEnv);
811 return Attr.isValid() ? Attr.getDenormalFPEnv() : DenormalFPEnv::getDefault();
812}
813
814const std::string &Function::getGC() const {
815 assert(hasGC() && "Function has no collector");
816 return getContext().getGC(*this);
817}
818
819void Function::setGC(std::string Str) {
820 setValueSubclassDataBit(14, !Str.empty());
821 getContext().setGC(*this, std::move(Str));
822}
823
824void Function::clearGC() {
825 if (!hasGC())
826 return;
827 getContext().deleteGC(*this);
828 setValueSubclassDataBit(14, false);
829}
830
832 return hasFnAttribute(Attribute::StackProtect) ||
833 hasFnAttribute(Attribute::StackProtectStrong) ||
834 hasFnAttribute(Attribute::StackProtectReq);
835}
836
837/// Copy all additional attributes (those not needed to create a Function) from
838/// the Function Src to this one.
839void Function::copyAttributesFrom(const Function *Src) {
841 setCallingConv(Src->getCallingConv());
842 setAttributes(Src->getAttributes());
843 if (Src->hasGC())
844 setGC(Src->getGC());
845 else
846 clearGC();
847 if (Src->hasPersonalityFn())
848 setPersonalityFn(Src->getPersonalityFn());
849 if (Src->hasPrefixData())
850 setPrefixData(Src->getPrefixData());
851 if (Src->hasPrologueData())
852 setPrologueData(Src->getPrologueData());
853}
854
856 return getAttributes().getMemoryEffects();
857}
860}
861
862/// Determine if the function does not access memory.
864 return getMemoryEffects().doesNotAccessMemory();
865}
868}
869
870/// Determine if the function does not access or only reads memory.
871bool Function::onlyReadsMemory() const {
872 return getMemoryEffects().onlyReadsMemory();
873}
875 setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());
876}
877
878/// Determine if the function does not access or only writes memory.
879bool Function::onlyWritesMemory() const {
880 return getMemoryEffects().onlyWritesMemory();
881}
883 setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());
884}
885
886/// Determine if the call can access memory only using pointers based
887/// on its arguments.
889 return getMemoryEffects().onlyAccessesArgPointees();
890}
892 setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());
893}
894
895/// Determine if the function may only access memory that is
896/// inaccessible from the IR.
898 return getMemoryEffects().onlyAccessesInaccessibleMem();
899}
902}
903
904/// Determine if the function may only access memory that is
905/// either inaccessible from the IR or pointed to by its arguments.
907 return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();
908}
910 setMemoryEffects(getMemoryEffects() &
912}
913
914bool Function::isTargetIntrinsic() const {
915 return Intrinsic::isTargetIntrinsic(IntID);
916}
917
919 LibFuncCache = UnknownLibFunc;
921 if (!Name.starts_with("llvm.")) {
922 HasLLVMReservedName = false;
924 return;
925 }
926 HasLLVMReservedName = true;
927 IntID = Intrinsic::lookupIntrinsicID(Name);
928}
929
930/// hasAddressTaken - returns true if there are any uses of this function
931/// other than direct calls or invokes to it. Optionally ignores callback
932/// uses, assume like pointer annotation calls, and references in llvm.used
933/// and llvm.compiler.used variables.
934bool Function::hasAddressTaken(const User **PutOffender,
935 bool IgnoreCallbackUses,
936 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
937 bool IgnoreARCAttachedCall,
938 bool IgnoreCastedDirectCall) const {
939 for (const Use &U : uses()) {
940 const User *FU = U.getUser();
941 if (IgnoreCallbackUses) {
942 AbstractCallSite ACS(&U);
943 if (ACS && ACS.isCallbackCall())
944 continue;
945 }
946
947 const auto *Call = dyn_cast<CallBase>(FU);
948 if (!Call) {
949 if (IgnoreAssumeLikeCalls &&
951 all_of(FU->users(), [](const User *U) {
952 if (const auto *I = dyn_cast<IntrinsicInst>(U))
953 return I->isAssumeLikeIntrinsic();
954 return false;
955 })) {
956 continue;
957 }
958
959 if (IgnoreLLVMUsed && !FU->user_empty()) {
960 const User *FUU = FU;
962 FU->hasOneUse() && !FU->user_begin()->user_empty())
963 FUU = *FU->user_begin();
964 if (llvm::all_of(FUU->users(), [](const User *U) {
965 if (const auto *GV = dyn_cast<GlobalVariable>(U))
966 return GV->hasName() &&
967 (GV->getName() == "llvm.compiler.used" ||
968 GV->getName() == "llvm.used");
969 return false;
970 }))
971 continue;
972 }
973 if (PutOffender)
974 *PutOffender = FU;
975 return true;
976 }
977
978 if (IgnoreAssumeLikeCalls) {
979 if (const auto *I = dyn_cast<IntrinsicInst>(Call))
980 if (I->isAssumeLikeIntrinsic())
981 continue;
982 }
983
984 if (!Call->isCallee(&U) || (!IgnoreCastedDirectCall &&
985 Call->getFunctionType() != getFunctionType())) {
986 if (IgnoreARCAttachedCall &&
987 Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,
988 U.getOperandNo()))
989 continue;
990
991 if (PutOffender)
992 *PutOffender = FU;
993 return true;
994 }
995 }
996 return false;
997}
998
999bool Function::isDefTriviallyDead() const {
1000 // Check the linkage
1001 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1002 !hasAvailableExternallyLinkage())
1003 return false;
1004
1005 return use_empty();
1006}
1007
1008/// callsFunctionThatReturnsTwice - Return true if the function has a call to
1009/// setjmp or other function that gcc recognizes as "returning twice".
1011 for (const Instruction &I : instructions(this))
1012 if (const auto *Call = dyn_cast<CallBase>(&I))
1013 if (Call->hasFnAttr(Attribute::ReturnsTwice))
1014 return true;
1015
1016 return false;
1017}
1018
1019Constant *Function::getPersonalityFn() const {
1020 assert(hasPersonalityFn() && getNumOperands());
1021 return cast<Constant>(Op<0>());
1022}
1023
1024void Function::setPersonalityFn(Constant *Fn) {
1025 setHungoffOperand<0>(Fn);
1026 setValueSubclassDataBit(3, Fn != nullptr);
1027}
1028
1029Constant *Function::getPrefixData() const {
1030 assert(hasPrefixData() && getNumOperands());
1031 return cast<Constant>(Op<1>());
1032}
1033
1034void Function::setPrefixData(Constant *PrefixData) {
1035 setHungoffOperand<1>(PrefixData);
1036 setValueSubclassDataBit(1, PrefixData != nullptr);
1037}
1038
1039Constant *Function::getPrologueData() const {
1040 assert(hasPrologueData() && getNumOperands());
1041 return cast<Constant>(Op<2>());
1042}
1043
1044void Function::setPrologueData(Constant *PrologueData) {
1045 setHungoffOperand<2>(PrologueData);
1046 setValueSubclassDataBit(2, PrologueData != nullptr);
1047}
1048
1049void Function::allocHungoffUselist() {
1050 // If we've already allocated a uselist, stop here.
1051 if (getNumOperands())
1052 return;
1053
1054 allocHungoffUses(3, /*IsPhi=*/ false);
1055 setNumHungOffUseOperands(3);
1056
1057 // Initialize the uselist with placeholder operands to allow traversal.
1059 Op<0>().set(CPN);
1060 Op<1>().set(CPN);
1061 Op<2>().set(CPN);
1062}
1063
1064template <int Idx>
1065void Function::setHungoffOperand(Constant *C) {
1066 if (C) {
1067 allocHungoffUselist();
1068 Op<Idx>().set(C);
1069 } else if (getNumOperands()) {
1071 }
1072}
1073
1074void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1075 assert(Bit < 16 && "SubclassData contains only 16 bits");
1076 if (On)
1077 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1078 else
1079 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1080}
1081
1083 const DenseSet<GlobalValue::GUID> *S) {
1084#if !defined(NDEBUG)
1085 auto PrevCount = getEntryCount();
1086 assert(!PrevCount || PrevCount->getType() == Count.getType());
1087#endif
1088
1089 auto ImportGUIDs = getImportGUIDs();
1090 if (S == nullptr && ImportGUIDs.size())
1091 S = &ImportGUIDs;
1092
1093 MDBuilder MDB(getContext());
1094 setMetadata(
1095 LLVMContext::MD_prof,
1096 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1097}
1098
1100 const DenseSet<GlobalValue::GUID> *Imports) {
1101 setEntryCount(ProfileCount(Count, Type), Imports);
1102}
1103
1104std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {
1105 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1106 if (MD && MD->getOperand(0))
1107 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1108 if (MDS->getString() == MDProfLabels::FunctionEntryCount) {
1111 // A value of -1 is used for SamplePGO when there were no samples.
1112 // Treat this the same as unknown.
1113 if (Count == (uint64_t)-1)
1114 return std::nullopt;
1115 return ProfileCount(Count, PCT_Real);
1116 } else if (AllowSynthetic &&
1117 MDS->getString() ==
1121 return ProfileCount(Count, PCT_Synthetic);
1122 }
1123 }
1124 return std::nullopt;
1125}
1126
1129 if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1130 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1131 if (MDS->getString() == MDProfLabels::FunctionEntryCount)
1132 for (unsigned i = 2; i < MD->getNumOperands(); i++)
1134 ->getValue()
1135 .getZExtValue());
1136 return R;
1137}
1138
1139bool Function::nullPointerIsDefined() const {
1140 return hasFnAttribute(Attribute::NullPointerIsValid);
1141}
1142
1143unsigned Function::getVScaleValue() const {
1144 Attribute Attr = getFnAttribute(Attribute::VScaleRange);
1145 if (!Attr.isValid())
1146 return 0;
1147
1148 unsigned VScale = Attr.getVScaleRangeMin();
1149 if (VScale && VScale == Attr.getVScaleRangeMax())
1150 return VScale;
1151
1152 return 0;
1153}
1154
1155bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1156 if (F && F->nullPointerIsDefined())
1157 return true;
1158
1159 if (AS != 0)
1160 return true;
1161
1162 return false;
1163}
1164
1166 switch (CC) {
1167 case CallingConv::C:
1168 case CallingConv::Fast:
1169 case CallingConv::Cold:
1170 case CallingConv::GHC:
1171 case CallingConv::HiPE:
1175 case CallingConv::Swift:
1177 case CallingConv::Tail:
1192 case CallingConv::Win64:
1200 return true;
1205 return false;
1223 case CallingConv::GRAAL:
1240 return true;
1241 default:
1242 return false;
1243 }
1244
1245 llvm_unreachable("covered callingconv switch");
1246}
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
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)
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:184
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:546
static unsigned computeAddrSpace(unsigned AddrSpace, Module *M)
Definition Function.cpp:470
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:297
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1563
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:230
LLVM_ABI DeadOnReturnInfo getDeadOnReturnInfo() const
Returns information on the memory marked dead_on_return for the argument.
Definition Function.cpp:133
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Definition Function.cpp:342
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Definition Function.cpp:268
LLVM_ABI bool hasNonNullAttr(bool AllowUndefOrPoison=true) const
Return true if this argument has the nonnull attribute.
Definition Function.cpp:115
LLVM_ABI bool hasByRefAttr() const
Return true if this argument has the byref attribute.
Definition Function.cpp:138
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:246
LLVM_ABI void addAttr(Attribute::AttrKind Kind)
Definition Function.cpp:316
LLVM_ABI Argument(Type *Ty, const Twine &Name="", Function *F=nullptr, unsigned ArgNo=0)
Argument constructor.
Definition Function.cpp:106
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Definition Function.cpp:304
LLVM_ABI bool hasPointeeInMemoryValueAttr() const
Return true if this argument has the byval, sret, inalloca, preallocated, or byref attribute.
Definition Function.cpp:171
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:334
LLVM_ABI bool hasReturnedAttr() const
Return true if this argument has the returned attribute.
Definition Function.cpp:292
LLVM_ABI Type * getParamStructRetType() const
If this is an sret argument, return its type.
Definition Function.cpp:225
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
Definition Function.cpp:288
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
Definition Function.cpp:128
LLVM_ABI bool hasPreallocatedAttr() const
Return true if this argument has the preallocated attribute.
Definition Function.cpp:157
LLVM_ABI bool hasSExtAttr() const
Return true if this argument has the sext attribute.
Definition Function.cpp:300
LLVM_ABI void removeAttr(Attribute::AttrKind Kind)
Remove attributes from an argument.
Definition Function.cpp:324
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:201
LLVM_ABI void removeAttrs(const AttributeMask &AM)
Definition Function.cpp:328
LLVM_ABI Type * getPointeeInMemoryValueType() const
If hasPointeeInMemoryValueAttr returns true, the in-memory ABI type is returned.
Definition Function.cpp:207
LLVM_ABI bool hasInAllocaAttr() const
Return true if this argument has the inalloca attribute.
Definition Function.cpp:152
LLVM_ABI bool hasSwiftErrorAttr() const
Return true if this argument has the swifterror attribute.
Definition Function.cpp:148
LLVM_ABI FPClassTest getNoFPClass() const
If this argument has nofpclass attribute, return the mask representing disallowed floating-point valu...
Definition Function.cpp:252
LLVM_ABI void addAttrs(AttrBuilder &B)
Add attributes to an argument.
Definition Function.cpp:310
LLVM_ABI bool hasNoFreeAttr() const
Return true if this argument has the nofree attribute.
Definition Function.cpp:278
LLVM_ABI bool hasSwiftSelfAttr() const
Return true if this argument has the swiftself attribute.
Definition Function.cpp:144
LLVM_ABI Type * getParamInAllocaType() const
If this is an inalloca argument, return its type.
Definition Function.cpp:235
LLVM_ABI bool hasZExtAttr() const
Return true if this argument has the zext attribute.
Definition Function.cpp:296
LLVM_ABI Type * getParamByValType() const
If this is a byval argument, return its type.
Definition Function.cpp:220
LLVM_ABI bool hasNestAttr() const
Return true if this argument has the nest attribute.
Definition Function.cpp:263
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
Definition Function.cpp:211
LLVM_ABI std::optional< ConstantRange > getRange() const
If this argument has a range attribute, return the value range of the argument.
Definition Function.cpp:256
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition Function.cpp:283
LLVM_ABI AttributeSet getAttributes() const
Definition Function.cpp:346
LLVM_ABI bool hasPassPointeeByValueCopyAttr() const
Return true if this argument has the byval, inalloca, or preallocated attribute.
Definition Function.cpp:163
LLVM_ABI MaybeAlign getParamStackAlign() const
Definition Function.cpp:216
LLVM_ABI bool hasNoCaptureAttr() const
Return true if this argument has the nocapture attribute.
Definition Function.cpp:273
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:240
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:407
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:124
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:289
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:464
Class to represent profile counts.
Definition Function.h:299
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:634
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:168
void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs)
adds the attributes to the list of attributes for the given arg.
Definition Function.cpp:670
void removeRetAttr(Attribute::AttrKind Kind)
removes the attribute from the return value list of attributes.
Definition Function.cpp:694
void addRetAttrs(const AttrBuilder &Attrs)
Add return value attributes to this function.
Definition Function.cpp:658
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
Definition Function.cpp:999
bool onlyAccessesInaccessibleMemOrArgMem() const
Determine if the function may only access memory that is either inaccessible from the IR or pointed t...
Definition Function.cpp:906
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:761
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:934
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
Definition Function.cpp:706
bool nullPointerIsDefined() const
Check if null pointer dereferencing is considered undefined behavior for the function.
Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
gets the specified attribute from the list of attributes.
Definition Function.cpp:785
void setPrefixData(Constant *PrefixData)
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
Definition Function.cpp:831
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition Function.cpp:441
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:358
void addFnAttrs(const AttrBuilder &Attrs)
Add function attributes to this function.
Definition Function.cpp:646
void renumberBlocks()
Renumber basic blocks into a dense value range starting from 0.
Definition Function.cpp:69
void setDoesNotAccessMemory()
Definition Function.cpp:866
void setGC(std::string Str)
Definition Function.cpp:819
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:759
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:771
bool isConstrainedFPIntrinsic() const
Returns true if the function is one of the "Constrained Floating-PointIntrinsics".
Definition Function.cpp:550
void setOnlyAccessesArgMemory()
Definition Function.cpp:891
MemoryEffects getMemoryEffects() const
Definition Function.cpp:855
void setOnlyAccessesInaccessibleMemory()
Definition Function.cpp:900
void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs)
removes the attribute from the list of attributes.
Definition Function.cpp:714
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
Definition Function.cpp:736
bool hasAttributeAtIndex(unsigned Idx, Attribute::AttrKind Kind) const
Check if attribute of the given kind is set at the given index.
Definition Function.cpp:754
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:374
void setOnlyReadsMemory()
Definition Function.cpp:874
bool isTargetIntrinsic() const
isTargetIntrinsic - Returns true if this function is an intrinsic and the intrinsic is specific to a ...
Definition Function.cpp:914
void removeFnAttrs(const AttributeMask &Attrs)
Definition Function.cpp:690
void addRetAttr(Attribute::AttrKind Kind)
Add return value attributes to this function.
Definition Function.cpp:650
DenormalFPEnv getDenormalFPEnv() const
Return the representational value of the denormal_fpenv attribute.
Definition Function.cpp:809
Constant * getPrologueData() const
Get the prologue data associated with this function.
void convertFromNewDbgValues()
Definition Function.cpp:96
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setOnlyWritesMemory()
Definition Function.cpp:882
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:674
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:445
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
Definition Function.cpp:682
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:790
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes for the return value.
Definition Function.cpp:796
void stealArgumentListFrom(Function &Src)
Steal arguments from another function.
Definition Function.cpp:563
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:354
const std::string & getGC() const
Definition Function.cpp:814
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:662
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:863
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition Function.cpp:800
void updateAfterNameChange()
Update internal caches that depend on the function name (such as the intrinsic ID and libcall cache).
Definition Function.cpp:918
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:732
bool onlyWritesMemory() const
Determine if the function does not access or only writes memory.
Definition Function.cpp:879
std::optional< ProfileCount > getEntryCount(bool AllowSynthetic=false) const
Get the entry count for this function.
bool onlyAccessesInaccessibleMemory() const
Determine if the function may only access memory that is inaccessible from the IR.
Definition Function.cpp:897
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:702
bool onlyAccessesArgMemory() const
Determine if the call can access memory only using pointers based on its arguments.
Definition Function.cpp:888
Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt)
Erases a range of BasicBlocks from FromIt to (not including) ToIt.
Definition Function.cpp:461
void setMemoryEffects(MemoryEffects ME)
Definition Function.cpp:858
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:745
iterator end()
Definition Function.h:855
void convertToNewDbgValues()
Definition Function.cpp:90
void setOnlyAccessesInaccessibleMemOrArgMem()
Definition Function.cpp:909
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes)
adds the dereferenceable attribute to the list of attributes for the given arg.
Definition Function.cpp:719
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
Definition Function.cpp:362
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Definition Function.cpp:871
void addAttributeAtIndex(unsigned i, Attribute Attr)
adds the attribute to the list of attributes.
Definition Function.cpp:630
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:724
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:839
Attribute getRetAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind for the return value.
Definition Function.cpp:767
LLVM_ABI void copyAttributesFrom(const GlobalObject *Src)
Definition Globals.cpp:164
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1433
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1439
A single uniqued string.
Definition Metadata.h:722
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:598
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
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:402
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
iterator_range< user_iterator > users()
Definition Value.h:426
bool user_empty() const
Definition Value.h:389
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:683
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
constexpr double e
Context & getContext() const
Definition BasicBlock.h:99
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:1739
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:389
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
UWTableKind
Definition CodeGen.h:154
@ None
No unwind table requested.
Definition CodeGen.h:155
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:377
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
Function::ProfileCount ProfileCount
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
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 * SyntheticFunctionEntryCount
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