Path: blob/main/contrib/llvm-project/llvm/lib/IR/Function.cpp
35232 views
//===- Function.cpp - Implement the Global object classes -----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Function class for the IR library.9//10//===----------------------------------------------------------------------===//1112#include "llvm/IR/Function.h"13#include "SymbolTableListTraitsImpl.h"14#include "llvm/ADT/ArrayRef.h"15#include "llvm/ADT/DenseSet.h"16#include "llvm/ADT/STLExtras.h"17#include "llvm/ADT/SmallString.h"18#include "llvm/ADT/SmallVector.h"19#include "llvm/ADT/StringExtras.h"20#include "llvm/ADT/StringRef.h"21#include "llvm/IR/AbstractCallSite.h"22#include "llvm/IR/Argument.h"23#include "llvm/IR/Attributes.h"24#include "llvm/IR/BasicBlock.h"25#include "llvm/IR/Constant.h"26#include "llvm/IR/ConstantRange.h"27#include "llvm/IR/Constants.h"28#include "llvm/IR/DerivedTypes.h"29#include "llvm/IR/GlobalValue.h"30#include "llvm/IR/InstIterator.h"31#include "llvm/IR/Instruction.h"32#include "llvm/IR/IntrinsicInst.h"33#include "llvm/IR/Intrinsics.h"34#include "llvm/IR/IntrinsicsAArch64.h"35#include "llvm/IR/IntrinsicsAMDGPU.h"36#include "llvm/IR/IntrinsicsARM.h"37#include "llvm/IR/IntrinsicsBPF.h"38#include "llvm/IR/IntrinsicsDirectX.h"39#include "llvm/IR/IntrinsicsHexagon.h"40#include "llvm/IR/IntrinsicsLoongArch.h"41#include "llvm/IR/IntrinsicsMips.h"42#include "llvm/IR/IntrinsicsNVPTX.h"43#include "llvm/IR/IntrinsicsPowerPC.h"44#include "llvm/IR/IntrinsicsR600.h"45#include "llvm/IR/IntrinsicsRISCV.h"46#include "llvm/IR/IntrinsicsS390.h"47#include "llvm/IR/IntrinsicsSPIRV.h"48#include "llvm/IR/IntrinsicsVE.h"49#include "llvm/IR/IntrinsicsWebAssembly.h"50#include "llvm/IR/IntrinsicsX86.h"51#include "llvm/IR/IntrinsicsXCore.h"52#include "llvm/IR/LLVMContext.h"53#include "llvm/IR/MDBuilder.h"54#include "llvm/IR/Metadata.h"55#include "llvm/IR/Module.h"56#include "llvm/IR/Operator.h"57#include "llvm/IR/SymbolTableListTraits.h"58#include "llvm/IR/Type.h"59#include "llvm/IR/Use.h"60#include "llvm/IR/User.h"61#include "llvm/IR/Value.h"62#include "llvm/IR/ValueSymbolTable.h"63#include "llvm/Support/Casting.h"64#include "llvm/Support/CommandLine.h"65#include "llvm/Support/Compiler.h"66#include "llvm/Support/ErrorHandling.h"67#include "llvm/Support/ModRef.h"68#include <cassert>69#include <cstddef>70#include <cstdint>71#include <cstring>72#include <string>7374using namespace llvm;75using ProfileCount = Function::ProfileCount;7677// Explicit instantiations of SymbolTableListTraits since some of the methods78// are not in the public header file...79template class llvm::SymbolTableListTraits<BasicBlock>;8081static cl::opt<int> NonGlobalValueMaxNameSize(82"non-global-value-max-name-size", cl::Hidden, cl::init(1024),83cl::desc("Maximum size for the name of non-global values."));8485extern cl::opt<bool> UseNewDbgInfoFormat;8687void Function::convertToNewDbgValues() {88IsNewDbgInfoFormat = true;89for (auto &BB : *this) {90BB.convertToNewDbgValues();91}92}9394void Function::convertFromNewDbgValues() {95IsNewDbgInfoFormat = false;96for (auto &BB : *this) {97BB.convertFromNewDbgValues();98}99}100101void Function::setIsNewDbgInfoFormat(bool NewFlag) {102if (NewFlag && !IsNewDbgInfoFormat)103convertToNewDbgValues();104else if (!NewFlag && IsNewDbgInfoFormat)105convertFromNewDbgValues();106}107void Function::setNewDbgInfoFormatFlag(bool NewFlag) {108for (auto &BB : *this) {109BB.setNewDbgInfoFormatFlag(NewFlag);110}111IsNewDbgInfoFormat = NewFlag;112}113114//===----------------------------------------------------------------------===//115// Argument Implementation116//===----------------------------------------------------------------------===//117118Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)119: Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {120setName(Name);121}122123void Argument::setParent(Function *parent) {124Parent = parent;125}126127bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {128if (!getType()->isPointerTy()) return false;129if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&130(AllowUndefOrPoison ||131getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))132return true;133else if (getDereferenceableBytes() > 0 &&134!NullPointerIsDefined(getParent(),135getType()->getPointerAddressSpace()))136return true;137return false;138}139140bool Argument::hasByValAttr() const {141if (!getType()->isPointerTy()) return false;142return hasAttribute(Attribute::ByVal);143}144145bool Argument::hasByRefAttr() const {146if (!getType()->isPointerTy())147return false;148return hasAttribute(Attribute::ByRef);149}150151bool Argument::hasSwiftSelfAttr() const {152return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);153}154155bool Argument::hasSwiftErrorAttr() const {156return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);157}158159bool Argument::hasInAllocaAttr() const {160if (!getType()->isPointerTy()) return false;161return hasAttribute(Attribute::InAlloca);162}163164bool Argument::hasPreallocatedAttr() const {165if (!getType()->isPointerTy())166return false;167return hasAttribute(Attribute::Preallocated);168}169170bool Argument::hasPassPointeeByValueCopyAttr() const {171if (!getType()->isPointerTy()) return false;172AttributeList Attrs = getParent()->getAttributes();173return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||174Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||175Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated);176}177178bool Argument::hasPointeeInMemoryValueAttr() const {179if (!getType()->isPointerTy())180return false;181AttributeList Attrs = getParent()->getAttributes();182return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||183Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) ||184Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||185Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) ||186Attrs.hasParamAttr(getArgNo(), Attribute::ByRef);187}188189/// For a byval, sret, inalloca, or preallocated parameter, get the in-memory190/// parameter type.191static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {192// FIXME: All the type carrying attributes are mutually exclusive, so there193// should be a single query to get the stored type that handles any of them.194if (Type *ByValTy = ParamAttrs.getByValType())195return ByValTy;196if (Type *ByRefTy = ParamAttrs.getByRefType())197return ByRefTy;198if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())199return PreAllocTy;200if (Type *InAllocaTy = ParamAttrs.getInAllocaType())201return InAllocaTy;202if (Type *SRetTy = ParamAttrs.getStructRetType())203return SRetTy;204205return nullptr;206}207208uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {209AttributeSet ParamAttrs =210getParent()->getAttributes().getParamAttrs(getArgNo());211if (Type *MemTy = getMemoryParamAllocType(ParamAttrs))212return DL.getTypeAllocSize(MemTy);213return 0;214}215216Type *Argument::getPointeeInMemoryValueType() const {217AttributeSet ParamAttrs =218getParent()->getAttributes().getParamAttrs(getArgNo());219return getMemoryParamAllocType(ParamAttrs);220}221222MaybeAlign Argument::getParamAlign() const {223assert(getType()->isPointerTy() && "Only pointers have alignments");224return getParent()->getParamAlign(getArgNo());225}226227MaybeAlign Argument::getParamStackAlign() const {228return getParent()->getParamStackAlign(getArgNo());229}230231Type *Argument::getParamByValType() const {232assert(getType()->isPointerTy() && "Only pointers have byval types");233return getParent()->getParamByValType(getArgNo());234}235236Type *Argument::getParamStructRetType() const {237assert(getType()->isPointerTy() && "Only pointers have sret types");238return getParent()->getParamStructRetType(getArgNo());239}240241Type *Argument::getParamByRefType() const {242assert(getType()->isPointerTy() && "Only pointers have byref types");243return getParent()->getParamByRefType(getArgNo());244}245246Type *Argument::getParamInAllocaType() const {247assert(getType()->isPointerTy() && "Only pointers have inalloca types");248return getParent()->getParamInAllocaType(getArgNo());249}250251uint64_t Argument::getDereferenceableBytes() const {252assert(getType()->isPointerTy() &&253"Only pointers have dereferenceable bytes");254return getParent()->getParamDereferenceableBytes(getArgNo());255}256257uint64_t Argument::getDereferenceableOrNullBytes() const {258assert(getType()->isPointerTy() &&259"Only pointers have dereferenceable bytes");260return getParent()->getParamDereferenceableOrNullBytes(getArgNo());261}262263FPClassTest Argument::getNoFPClass() const {264return getParent()->getParamNoFPClass(getArgNo());265}266267std::optional<ConstantRange> Argument::getRange() const {268const Attribute RangeAttr = getAttribute(llvm::Attribute::Range);269if (RangeAttr.isValid())270return RangeAttr.getRange();271return std::nullopt;272}273274bool Argument::hasNestAttr() const {275if (!getType()->isPointerTy()) return false;276return hasAttribute(Attribute::Nest);277}278279bool Argument::hasNoAliasAttr() const {280if (!getType()->isPointerTy()) return false;281return hasAttribute(Attribute::NoAlias);282}283284bool Argument::hasNoCaptureAttr() const {285if (!getType()->isPointerTy()) return false;286return hasAttribute(Attribute::NoCapture);287}288289bool Argument::hasNoFreeAttr() const {290if (!getType()->isPointerTy()) return false;291return hasAttribute(Attribute::NoFree);292}293294bool Argument::hasStructRetAttr() const {295if (!getType()->isPointerTy()) return false;296return hasAttribute(Attribute::StructRet);297}298299bool Argument::hasInRegAttr() const {300return hasAttribute(Attribute::InReg);301}302303bool Argument::hasReturnedAttr() const {304return hasAttribute(Attribute::Returned);305}306307bool Argument::hasZExtAttr() const {308return hasAttribute(Attribute::ZExt);309}310311bool Argument::hasSExtAttr() const {312return hasAttribute(Attribute::SExt);313}314315bool Argument::onlyReadsMemory() const {316AttributeList Attrs = getParent()->getAttributes();317return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) ||318Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone);319}320321void Argument::addAttrs(AttrBuilder &B) {322AttributeList AL = getParent()->getAttributes();323AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);324getParent()->setAttributes(AL);325}326327void Argument::addAttr(Attribute::AttrKind Kind) {328getParent()->addParamAttr(getArgNo(), Kind);329}330331void Argument::addAttr(Attribute Attr) {332getParent()->addParamAttr(getArgNo(), Attr);333}334335void Argument::removeAttr(Attribute::AttrKind Kind) {336getParent()->removeParamAttr(getArgNo(), Kind);337}338339void Argument::removeAttrs(const AttributeMask &AM) {340AttributeList AL = getParent()->getAttributes();341AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);342getParent()->setAttributes(AL);343}344345bool Argument::hasAttribute(Attribute::AttrKind Kind) const {346return getParent()->hasParamAttribute(getArgNo(), Kind);347}348349Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {350return getParent()->getParamAttribute(getArgNo(), Kind);351}352353//===----------------------------------------------------------------------===//354// Helper Methods in Function355//===----------------------------------------------------------------------===//356357LLVMContext &Function::getContext() const {358return getType()->getContext();359}360361const DataLayout &Function::getDataLayout() const {362return getParent()->getDataLayout();363}364365unsigned Function::getInstructionCount() const {366unsigned NumInstrs = 0;367for (const BasicBlock &BB : BasicBlocks)368NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),369BB.instructionsWithoutDebug().end());370return NumInstrs;371}372373Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,374const Twine &N, Module &M) {375return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);376}377378Function *Function::createWithDefaultAttr(FunctionType *Ty,379LinkageTypes Linkage,380unsigned AddrSpace, const Twine &N,381Module *M) {382auto *F = new Function(Ty, Linkage, AddrSpace, N, M);383AttrBuilder B(F->getContext());384UWTableKind UWTable = M->getUwtable();385if (UWTable != UWTableKind::None)386B.addUWTableAttr(UWTable);387switch (M->getFramePointer()) {388case FramePointerKind::None:389// 0 ("none") is the default.390break;391case FramePointerKind::Reserved:392B.addAttribute("frame-pointer", "reserved");393break;394case FramePointerKind::NonLeaf:395B.addAttribute("frame-pointer", "non-leaf");396break;397case FramePointerKind::All:398B.addAttribute("frame-pointer", "all");399break;400}401if (M->getModuleFlag("function_return_thunk_extern"))402B.addAttribute(Attribute::FnRetThunkExtern);403StringRef DefaultCPU = F->getContext().getDefaultTargetCPU();404if (!DefaultCPU.empty())405B.addAttribute("target-cpu", DefaultCPU);406StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures();407if (!DefaultFeatures.empty())408B.addAttribute("target-features", DefaultFeatures);409410// Check if the module attribute is present and not zero.411auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool {412const auto *Attr =413mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(ModAttr));414return Attr && !Attr->isZero();415};416417auto AddAttributeIfSet = [&](const StringRef &ModAttr) {418if (isModuleAttributeSet(ModAttr))419B.addAttribute(ModAttr);420};421422StringRef SignType = "none";423if (isModuleAttributeSet("sign-return-address"))424SignType = "non-leaf";425if (isModuleAttributeSet("sign-return-address-all"))426SignType = "all";427if (SignType != "none") {428B.addAttribute("sign-return-address", SignType);429B.addAttribute("sign-return-address-key",430isModuleAttributeSet("sign-return-address-with-bkey")431? "b_key"432: "a_key");433}434AddAttributeIfSet("branch-target-enforcement");435AddAttributeIfSet("branch-protection-pauth-lr");436AddAttributeIfSet("guarded-control-stack");437438F->addFnAttrs(B);439return F;440}441442void Function::removeFromParent() {443getParent()->getFunctionList().remove(getIterator());444}445446void Function::eraseFromParent() {447getParent()->getFunctionList().erase(getIterator());448}449450void Function::splice(Function::iterator ToIt, Function *FromF,451Function::iterator FromBeginIt,452Function::iterator FromEndIt) {453#ifdef EXPENSIVE_CHECKS454// Check that FromBeginIt is before FromEndIt.455auto FromFEnd = FromF->end();456for (auto It = FromBeginIt; It != FromEndIt; ++It)457assert(It != FromFEnd && "FromBeginIt not before FromEndIt!");458#endif // EXPENSIVE_CHECKS459BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt);460}461462Function::iterator Function::erase(Function::iterator FromIt,463Function::iterator ToIt) {464return BasicBlocks.erase(FromIt, ToIt);465}466467//===----------------------------------------------------------------------===//468// Function Implementation469//===----------------------------------------------------------------------===//470471static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {472// If AS == -1 and we are passed a valid module pointer we place the function473// in the program address space. Otherwise we default to AS0.474if (AddrSpace == static_cast<unsigned>(-1))475return M ? M->getDataLayout().getProgramAddressSpace() : 0;476return AddrSpace;477}478479Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,480const Twine &name, Module *ParentModule)481: GlobalObject(Ty, Value::FunctionVal,482OperandTraits<Function>::op_begin(this), 0, Linkage, name,483computeAddrSpace(AddrSpace, ParentModule)),484NumArgs(Ty->getNumParams()), IsNewDbgInfoFormat(UseNewDbgInfoFormat) {485assert(FunctionType::isValidReturnType(getReturnType()) &&486"invalid return type");487setGlobalObjectSubClassData(0);488489// We only need a symbol table for a function if the context keeps value names490if (!getContext().shouldDiscardValueNames())491SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);492493// If the function has arguments, mark them as lazily built.494if (Ty->getNumParams())495setValueSubclassData(1); // Set the "has lazy arguments" bit.496497if (ParentModule) {498ParentModule->getFunctionList().push_back(this);499IsNewDbgInfoFormat = ParentModule->IsNewDbgInfoFormat;500}501502HasLLVMReservedName = getName().starts_with("llvm.");503// Ensure intrinsics have the right parameter attributes.504// Note, the IntID field will have been set in Value::setName if this function505// name is a valid intrinsic ID.506if (IntID)507setAttributes(Intrinsic::getAttributes(getContext(), IntID));508}509510Function::~Function() {511dropAllReferences(); // After this it is safe to delete instructions.512513// Delete all of the method arguments and unlink from symbol table...514if (Arguments)515clearArguments();516517// Remove the function from the on-the-side GC table.518clearGC();519}520521void Function::BuildLazyArguments() const {522// Create the arguments vector, all arguments start out unnamed.523auto *FT = getFunctionType();524if (NumArgs > 0) {525Arguments = std::allocator<Argument>().allocate(NumArgs);526for (unsigned i = 0, e = NumArgs; i != e; ++i) {527Type *ArgTy = FT->getParamType(i);528assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");529new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);530}531}532533// Clear the lazy arguments bit.534unsigned SDC = getSubclassDataFromValue();535SDC &= ~(1 << 0);536const_cast<Function*>(this)->setValueSubclassData(SDC);537assert(!hasLazyArguments());538}539540static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {541return MutableArrayRef<Argument>(Args, Count);542}543544bool Function::isConstrainedFPIntrinsic() const {545return Intrinsic::isConstrainedFPIntrinsic(getIntrinsicID());546}547548void Function::clearArguments() {549for (Argument &A : makeArgArray(Arguments, NumArgs)) {550A.setName("");551A.~Argument();552}553std::allocator<Argument>().deallocate(Arguments, NumArgs);554Arguments = nullptr;555}556557void Function::stealArgumentListFrom(Function &Src) {558assert(isDeclaration() && "Expected no references to current arguments");559560// Drop the current arguments, if any, and set the lazy argument bit.561if (!hasLazyArguments()) {562assert(llvm::all_of(makeArgArray(Arguments, NumArgs),563[](const Argument &A) { return A.use_empty(); }) &&564"Expected arguments to be unused in declaration");565clearArguments();566setValueSubclassData(getSubclassDataFromValue() | (1 << 0));567}568569// Nothing to steal if Src has lazy arguments.570if (Src.hasLazyArguments())571return;572573// Steal arguments from Src, and fix the lazy argument bits.574assert(arg_size() == Src.arg_size());575Arguments = Src.Arguments;576Src.Arguments = nullptr;577for (Argument &A : makeArgArray(Arguments, NumArgs)) {578// FIXME: This does the work of transferNodesFromList inefficiently.579SmallString<128> Name;580if (A.hasName())581Name = A.getName();582if (!Name.empty())583A.setName("");584A.setParent(this);585if (!Name.empty())586A.setName(Name);587}588589setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));590assert(!hasLazyArguments());591Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));592}593594void Function::deleteBodyImpl(bool ShouldDrop) {595setIsMaterializable(false);596597for (BasicBlock &BB : *this)598BB.dropAllReferences();599600// Delete all basic blocks. They are now unused, except possibly by601// blockaddresses, but BasicBlock's destructor takes care of those.602while (!BasicBlocks.empty())603BasicBlocks.begin()->eraseFromParent();604605if (getNumOperands()) {606if (ShouldDrop) {607// Drop uses of any optional data (real or placeholder).608User::dropAllReferences();609setNumHungOffUseOperands(0);610} else {611// The code needs to match Function::allocHungoffUselist().612auto *CPN = ConstantPointerNull::get(PointerType::get(getContext(), 0));613Op<0>().set(CPN);614Op<1>().set(CPN);615Op<2>().set(CPN);616}617setValueSubclassData(getSubclassDataFromValue() & ~0xe);618}619620// Metadata is stored in a side-table.621clearMetadata();622}623624void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {625AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);626}627628void Function::addFnAttr(Attribute::AttrKind Kind) {629AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);630}631632void Function::addFnAttr(StringRef Kind, StringRef Val) {633AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);634}635636void Function::addFnAttr(Attribute Attr) {637AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);638}639640void Function::addFnAttrs(const AttrBuilder &Attrs) {641AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);642}643644void Function::addRetAttr(Attribute::AttrKind Kind) {645AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);646}647648void Function::addRetAttr(Attribute Attr) {649AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);650}651652void Function::addRetAttrs(const AttrBuilder &Attrs) {653AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);654}655656void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {657AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);658}659660void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {661AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);662}663664void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {665AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);666}667668void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {669AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);670}671672void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {673AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);674}675676void Function::removeFnAttr(Attribute::AttrKind Kind) {677AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);678}679680void Function::removeFnAttr(StringRef Kind) {681AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);682}683684void Function::removeFnAttrs(const AttributeMask &AM) {685AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);686}687688void Function::removeRetAttr(Attribute::AttrKind Kind) {689AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);690}691692void Function::removeRetAttr(StringRef Kind) {693AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);694}695696void Function::removeRetAttrs(const AttributeMask &Attrs) {697AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);698}699700void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {701AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);702}703704void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {705AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);706}707708void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {709AttributeSets =710AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);711}712713void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {714AttributeSets =715AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);716}717718bool Function::hasFnAttribute(Attribute::AttrKind Kind) const {719return AttributeSets.hasFnAttr(Kind);720}721722bool Function::hasFnAttribute(StringRef Kind) const {723return AttributeSets.hasFnAttr(Kind);724}725726bool Function::hasRetAttribute(Attribute::AttrKind Kind) const {727return AttributeSets.hasRetAttr(Kind);728}729730bool Function::hasParamAttribute(unsigned ArgNo,731Attribute::AttrKind Kind) const {732return AttributeSets.hasParamAttr(ArgNo, Kind);733}734735Attribute Function::getAttributeAtIndex(unsigned i,736Attribute::AttrKind Kind) const {737return AttributeSets.getAttributeAtIndex(i, Kind);738}739740Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {741return AttributeSets.getAttributeAtIndex(i, Kind);742}743744Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {745return AttributeSets.getFnAttr(Kind);746}747748Attribute Function::getFnAttribute(StringRef Kind) const {749return AttributeSets.getFnAttr(Kind);750}751752Attribute Function::getRetAttribute(Attribute::AttrKind Kind) const {753return AttributeSets.getRetAttr(Kind);754}755756uint64_t Function::getFnAttributeAsParsedInteger(StringRef Name,757uint64_t Default) const {758Attribute A = getFnAttribute(Name);759uint64_t Result = Default;760if (A.isStringAttribute()) {761StringRef Str = A.getValueAsString();762if (Str.getAsInteger(0, Result))763getContext().emitError("cannot parse integer attribute " + Name);764}765766return Result;767}768769/// gets the specified attribute from the list of attributes.770Attribute Function::getParamAttribute(unsigned ArgNo,771Attribute::AttrKind Kind) const {772return AttributeSets.getParamAttr(ArgNo, Kind);773}774775void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,776uint64_t Bytes) {777AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),778ArgNo, Bytes);779}780781void Function::addRangeRetAttr(const ConstantRange &CR) {782AttributeSets = AttributeSets.addRangeRetAttr(getContext(), CR);783}784785DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {786if (&FPType == &APFloat::IEEEsingle()) {787DenormalMode Mode = getDenormalModeF32Raw();788// If the f32 variant of the attribute isn't specified, try to use the789// generic one.790if (Mode.isValid())791return Mode;792}793794return getDenormalModeRaw();795}796797DenormalMode Function::getDenormalModeRaw() const {798Attribute Attr = getFnAttribute("denormal-fp-math");799StringRef Val = Attr.getValueAsString();800return parseDenormalFPAttribute(Val);801}802803DenormalMode Function::getDenormalModeF32Raw() const {804Attribute Attr = getFnAttribute("denormal-fp-math-f32");805if (Attr.isValid()) {806StringRef Val = Attr.getValueAsString();807return parseDenormalFPAttribute(Val);808}809810return DenormalMode::getInvalid();811}812813const std::string &Function::getGC() const {814assert(hasGC() && "Function has no collector");815return getContext().getGC(*this);816}817818void Function::setGC(std::string Str) {819setValueSubclassDataBit(14, !Str.empty());820getContext().setGC(*this, std::move(Str));821}822823void Function::clearGC() {824if (!hasGC())825return;826getContext().deleteGC(*this);827setValueSubclassDataBit(14, false);828}829830bool Function::hasStackProtectorFnAttr() const {831return hasFnAttribute(Attribute::StackProtect) ||832hasFnAttribute(Attribute::StackProtectStrong) ||833hasFnAttribute(Attribute::StackProtectReq);834}835836/// Copy all additional attributes (those not needed to create a Function) from837/// the Function Src to this one.838void Function::copyAttributesFrom(const Function *Src) {839GlobalObject::copyAttributesFrom(Src);840setCallingConv(Src->getCallingConv());841setAttributes(Src->getAttributes());842if (Src->hasGC())843setGC(Src->getGC());844else845clearGC();846if (Src->hasPersonalityFn())847setPersonalityFn(Src->getPersonalityFn());848if (Src->hasPrefixData())849setPrefixData(Src->getPrefixData());850if (Src->hasPrologueData())851setPrologueData(Src->getPrologueData());852}853854MemoryEffects Function::getMemoryEffects() const {855return getAttributes().getMemoryEffects();856}857void Function::setMemoryEffects(MemoryEffects ME) {858addFnAttr(Attribute::getWithMemoryEffects(getContext(), ME));859}860861/// Determine if the function does not access memory.862bool Function::doesNotAccessMemory() const {863return getMemoryEffects().doesNotAccessMemory();864}865void Function::setDoesNotAccessMemory() {866setMemoryEffects(MemoryEffects::none());867}868869/// Determine if the function does not access or only reads memory.870bool Function::onlyReadsMemory() const {871return getMemoryEffects().onlyReadsMemory();872}873void Function::setOnlyReadsMemory() {874setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());875}876877/// Determine if the function does not access or only writes memory.878bool Function::onlyWritesMemory() const {879return getMemoryEffects().onlyWritesMemory();880}881void Function::setOnlyWritesMemory() {882setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());883}884885/// Determine if the call can access memmory only using pointers based886/// on its arguments.887bool Function::onlyAccessesArgMemory() const {888return getMemoryEffects().onlyAccessesArgPointees();889}890void Function::setOnlyAccessesArgMemory() {891setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());892}893894/// Determine if the function may only access memory that is895/// inaccessible from the IR.896bool Function::onlyAccessesInaccessibleMemory() const {897return getMemoryEffects().onlyAccessesInaccessibleMem();898}899void Function::setOnlyAccessesInaccessibleMemory() {900setMemoryEffects(getMemoryEffects() & MemoryEffects::inaccessibleMemOnly());901}902903/// Determine if the function may only access memory that is904/// either inaccessible from the IR or pointed to by its arguments.905bool Function::onlyAccessesInaccessibleMemOrArgMem() const {906return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();907}908void Function::setOnlyAccessesInaccessibleMemOrArgMem() {909setMemoryEffects(getMemoryEffects() &910MemoryEffects::inaccessibleOrArgMemOnly());911}912913/// Table of string intrinsic names indexed by enum value.914static const char * const IntrinsicNameTable[] = {915"not_intrinsic",916#define GET_INTRINSIC_NAME_TABLE917#include "llvm/IR/IntrinsicImpl.inc"918#undef GET_INTRINSIC_NAME_TABLE919};920921/// Table of per-target intrinsic name tables.922#define GET_INTRINSIC_TARGET_DATA923#include "llvm/IR/IntrinsicImpl.inc"924#undef GET_INTRINSIC_TARGET_DATA925926bool Function::isTargetIntrinsic(Intrinsic::ID IID) {927return IID > TargetInfos[0].Count;928}929930bool Function::isTargetIntrinsic() const {931return isTargetIntrinsic(IntID);932}933934/// Find the segment of \c IntrinsicNameTable for intrinsics with the same935/// target as \c Name, or the generic table if \c Name is not target specific.936///937/// Returns the relevant slice of \c IntrinsicNameTable938static ArrayRef<const char *> findTargetSubtable(StringRef Name) {939assert(Name.starts_with("llvm."));940941ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);942// Drop "llvm." and take the first dotted component. That will be the target943// if this is target specific.944StringRef Target = Name.drop_front(5).split('.').first;945auto It = partition_point(946Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });947// We've either found the target or just fall back to the generic set, which948// is always first.949const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];950return ArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);951}952953/// This does the actual lookup of an intrinsic ID which954/// matches the given function name.955Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {956ArrayRef<const char *> NameTable = findTargetSubtable(Name);957int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);958if (Idx == -1)959return Intrinsic::not_intrinsic;960961// Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have962// an index into a sub-table.963int Adjust = NameTable.data() - IntrinsicNameTable;964Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);965966// If the intrinsic is not overloaded, require an exact match. If it is967// overloaded, require either exact or prefix match.968const auto MatchSize = strlen(NameTable[Idx]);969assert(Name.size() >= MatchSize && "Expected either exact or prefix match");970bool IsExactMatch = Name.size() == MatchSize;971return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID972: Intrinsic::not_intrinsic;973}974975void Function::updateAfterNameChange() {976LibFuncCache = UnknownLibFunc;977StringRef Name = getName();978if (!Name.starts_with("llvm.")) {979HasLLVMReservedName = false;980IntID = Intrinsic::not_intrinsic;981return;982}983HasLLVMReservedName = true;984IntID = lookupIntrinsicID(Name);985}986987/// Returns a stable mangling for the type specified for use in the name988/// mangling scheme used by 'any' types in intrinsic signatures. The mangling989/// of named types is simply their name. Manglings for unnamed types consist990/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)991/// combined with the mangling of their component types. A vararg function992/// type will have a suffix of 'vararg'. Since function types can contain993/// other function types, we close a function type mangling with suffix 'f'994/// which can't be confused with it's prefix. This ensures we don't have995/// collisions between two unrelated function types. Otherwise, you might996/// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)997/// The HasUnnamedType boolean is set if an unnamed type was encountered,998/// indicating that extra care must be taken to ensure a unique name.999static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {1000std::string Result;1001if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {1002Result += "p" + utostr(PTyp->getAddressSpace());1003} else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {1004Result += "a" + utostr(ATyp->getNumElements()) +1005getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);1006} else if (StructType *STyp = dyn_cast<StructType>(Ty)) {1007if (!STyp->isLiteral()) {1008Result += "s_";1009if (STyp->hasName())1010Result += STyp->getName();1011else1012HasUnnamedType = true;1013} else {1014Result += "sl_";1015for (auto *Elem : STyp->elements())1016Result += getMangledTypeStr(Elem, HasUnnamedType);1017}1018// Ensure nested structs are distinguishable.1019Result += "s";1020} else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {1021Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);1022for (size_t i = 0; i < FT->getNumParams(); i++)1023Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);1024if (FT->isVarArg())1025Result += "vararg";1026// Ensure nested function types are distinguishable.1027Result += "f";1028} else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {1029ElementCount EC = VTy->getElementCount();1030if (EC.isScalable())1031Result += "nx";1032Result += "v" + utostr(EC.getKnownMinValue()) +1033getMangledTypeStr(VTy->getElementType(), HasUnnamedType);1034} else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) {1035Result += "t";1036Result += TETy->getName();1037for (Type *ParamTy : TETy->type_params())1038Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType);1039for (unsigned IntParam : TETy->int_params())1040Result += "_" + utostr(IntParam);1041// Ensure nested target extension types are distinguishable.1042Result += "t";1043} else if (Ty) {1044switch (Ty->getTypeID()) {1045default: llvm_unreachable("Unhandled type");1046case Type::VoidTyID: Result += "isVoid"; break;1047case Type::MetadataTyID: Result += "Metadata"; break;1048case Type::HalfTyID: Result += "f16"; break;1049case Type::BFloatTyID: Result += "bf16"; break;1050case Type::FloatTyID: Result += "f32"; break;1051case Type::DoubleTyID: Result += "f64"; break;1052case Type::X86_FP80TyID: Result += "f80"; break;1053case Type::FP128TyID: Result += "f128"; break;1054case Type::PPC_FP128TyID: Result += "ppcf128"; break;1055case Type::X86_MMXTyID: Result += "x86mmx"; break;1056case Type::X86_AMXTyID: Result += "x86amx"; break;1057case Type::IntegerTyID:1058Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());1059break;1060}1061}1062return Result;1063}10641065StringRef Intrinsic::getBaseName(ID id) {1066assert(id < num_intrinsics && "Invalid intrinsic ID!");1067return IntrinsicNameTable[id];1068}10691070StringRef Intrinsic::getName(ID id) {1071assert(id < num_intrinsics && "Invalid intrinsic ID!");1072assert(!Intrinsic::isOverloaded(id) &&1073"This version of getName does not support overloading");1074return getBaseName(id);1075}10761077static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys,1078Module *M, FunctionType *FT,1079bool EarlyModuleCheck) {10801081assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");1082assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&1083"This version of getName is for overloaded intrinsics only");1084(void)EarlyModuleCheck;1085assert((!EarlyModuleCheck || M ||1086!any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) &&1087"Intrinsic overloading on pointer types need to provide a Module");1088bool HasUnnamedType = false;1089std::string Result(Intrinsic::getBaseName(Id));1090for (Type *Ty : Tys)1091Result += "." + getMangledTypeStr(Ty, HasUnnamedType);1092if (HasUnnamedType) {1093assert(M && "unnamed types need a module");1094if (!FT)1095FT = Intrinsic::getType(M->getContext(), Id, Tys);1096else1097assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) &&1098"Provided FunctionType must match arguments");1099return M->getUniqueIntrinsicName(Result, Id, FT);1100}1101return Result;1102}11031104std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,1105FunctionType *FT) {1106assert(M && "We need to have a Module");1107return getIntrinsicNameImpl(Id, Tys, M, FT, true);1108}11091110std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) {1111return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false);1112}11131114/// IIT_Info - These are enumerators that describe the entries returned by the1115/// getIntrinsicInfoTableEntries function.1116///1117/// Defined in Intrinsics.td.1118enum IIT_Info {1119#define GET_INTRINSIC_IITINFO1120#include "llvm/IR/IntrinsicImpl.inc"1121#undef GET_INTRINSIC_IITINFO1122};11231124static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,1125IIT_Info LastInfo,1126SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {1127using namespace Intrinsic;11281129bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);11301131IIT_Info Info = IIT_Info(Infos[NextElt++]);1132unsigned StructElts = 2;11331134switch (Info) {1135case IIT_Done:1136OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));1137return;1138case IIT_VARARG:1139OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));1140return;1141case IIT_MMX:1142OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));1143return;1144case IIT_AMX:1145OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));1146return;1147case IIT_TOKEN:1148OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));1149return;1150case IIT_METADATA:1151OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));1152return;1153case IIT_F16:1154OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));1155return;1156case IIT_BF16:1157OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));1158return;1159case IIT_F32:1160OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));1161return;1162case IIT_F64:1163OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));1164return;1165case IIT_F128:1166OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));1167return;1168case IIT_PPCF128:1169OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0));1170return;1171case IIT_I1:1172OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));1173return;1174case IIT_I2:1175OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2));1176return;1177case IIT_I4:1178OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4));1179return;1180case IIT_AARCH64_SVCOUNT:1181OutputTable.push_back(IITDescriptor::get(IITDescriptor::AArch64Svcount, 0));1182return;1183case IIT_I8:1184OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));1185return;1186case IIT_I16:1187OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));1188return;1189case IIT_I32:1190OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));1191return;1192case IIT_I64:1193OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));1194return;1195case IIT_I128:1196OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));1197return;1198case IIT_V1:1199OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));1200DecodeIITType(NextElt, Infos, Info, OutputTable);1201return;1202case IIT_V2:1203OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));1204DecodeIITType(NextElt, Infos, Info, OutputTable);1205return;1206case IIT_V3:1207OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector));1208DecodeIITType(NextElt, Infos, Info, OutputTable);1209return;1210case IIT_V4:1211OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));1212DecodeIITType(NextElt, Infos, Info, OutputTable);1213return;1214case IIT_V6:1215OutputTable.push_back(IITDescriptor::getVector(6, IsScalableVector));1216DecodeIITType(NextElt, Infos, Info, OutputTable);1217return;1218case IIT_V8:1219OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));1220DecodeIITType(NextElt, Infos, Info, OutputTable);1221return;1222case IIT_V10:1223OutputTable.push_back(IITDescriptor::getVector(10, IsScalableVector));1224DecodeIITType(NextElt, Infos, Info, OutputTable);1225return;1226case IIT_V16:1227OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));1228DecodeIITType(NextElt, Infos, Info, OutputTable);1229return;1230case IIT_V32:1231OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));1232DecodeIITType(NextElt, Infos, Info, OutputTable);1233return;1234case IIT_V64:1235OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));1236DecodeIITType(NextElt, Infos, Info, OutputTable);1237return;1238case IIT_V128:1239OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));1240DecodeIITType(NextElt, Infos, Info, OutputTable);1241return;1242case IIT_V256:1243OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));1244DecodeIITType(NextElt, Infos, Info, OutputTable);1245return;1246case IIT_V512:1247OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));1248DecodeIITType(NextElt, Infos, Info, OutputTable);1249return;1250case IIT_V1024:1251OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));1252DecodeIITType(NextElt, Infos, Info, OutputTable);1253return;1254case IIT_EXTERNREF:1255OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10));1256return;1257case IIT_FUNCREF:1258OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20));1259return;1260case IIT_PTR:1261OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));1262return;1263case IIT_ANYPTR: // [ANYPTR addrspace]1264OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,1265Infos[NextElt++]));1266return;1267case IIT_ARG: {1268unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1269OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));1270return;1271}1272case IIT_EXTEND_ARG: {1273unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1274OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,1275ArgInfo));1276return;1277}1278case IIT_TRUNC_ARG: {1279unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1280OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,1281ArgInfo));1282return;1283}1284case IIT_HALF_VEC_ARG: {1285unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1286OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,1287ArgInfo));1288return;1289}1290case IIT_SAME_VEC_WIDTH_ARG: {1291unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1292OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,1293ArgInfo));1294return;1295}1296case IIT_VEC_OF_ANYPTRS_TO_ELT: {1297unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1298unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1299OutputTable.push_back(1300IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));1301return;1302}1303case IIT_EMPTYSTRUCT:1304OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));1305return;1306case IIT_STRUCT9: ++StructElts; [[fallthrough]];1307case IIT_STRUCT8: ++StructElts; [[fallthrough]];1308case IIT_STRUCT7: ++StructElts; [[fallthrough]];1309case IIT_STRUCT6: ++StructElts; [[fallthrough]];1310case IIT_STRUCT5: ++StructElts; [[fallthrough]];1311case IIT_STRUCT4: ++StructElts; [[fallthrough]];1312case IIT_STRUCT3: ++StructElts; [[fallthrough]];1313case IIT_STRUCT2: {1314OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));13151316for (unsigned i = 0; i != StructElts; ++i)1317DecodeIITType(NextElt, Infos, Info, OutputTable);1318return;1319}1320case IIT_SUBDIVIDE2_ARG: {1321unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1322OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,1323ArgInfo));1324return;1325}1326case IIT_SUBDIVIDE4_ARG: {1327unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1328OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,1329ArgInfo));1330return;1331}1332case IIT_VEC_ELEMENT: {1333unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1334OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,1335ArgInfo));1336return;1337}1338case IIT_SCALABLE_VEC: {1339DecodeIITType(NextElt, Infos, Info, OutputTable);1340return;1341}1342case IIT_VEC_OF_BITCASTS_TO_INT: {1343unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);1344OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,1345ArgInfo));1346return;1347}1348}1349llvm_unreachable("unhandled");1350}13511352#define GET_INTRINSIC_GENERATOR_GLOBAL1353#include "llvm/IR/IntrinsicImpl.inc"1354#undef GET_INTRINSIC_GENERATOR_GLOBAL13551356void Intrinsic::getIntrinsicInfoTableEntries(ID id,1357SmallVectorImpl<IITDescriptor> &T){1358// Check to see if the intrinsic's type was expressible by the table.1359unsigned TableVal = IIT_Table[id-1];13601361// Decode the TableVal into an array of IITValues.1362SmallVector<unsigned char, 8> IITValues;1363ArrayRef<unsigned char> IITEntries;1364unsigned NextElt = 0;1365if ((TableVal >> 31) != 0) {1366// This is an offset into the IIT_LongEncodingTable.1367IITEntries = IIT_LongEncodingTable;13681369// Strip sentinel bit.1370NextElt = (TableVal << 1) >> 1;1371} else {1372// Decode the TableVal into an array of IITValues. If the entry was encoded1373// into a single word in the table itself, decode it now.1374do {1375IITValues.push_back(TableVal & 0xF);1376TableVal >>= 4;1377} while (TableVal);13781379IITEntries = IITValues;1380NextElt = 0;1381}13821383// Okay, decode the table into the output vector of IITDescriptors.1384DecodeIITType(NextElt, IITEntries, IIT_Done, T);1385while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)1386DecodeIITType(NextElt, IITEntries, IIT_Done, T);1387}13881389static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,1390ArrayRef<Type*> Tys, LLVMContext &Context) {1391using namespace Intrinsic;13921393IITDescriptor D = Infos.front();1394Infos = Infos.slice(1);13951396switch (D.Kind) {1397case IITDescriptor::Void: return Type::getVoidTy(Context);1398case IITDescriptor::VarArg: return Type::getVoidTy(Context);1399case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);1400case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);1401case IITDescriptor::Token: return Type::getTokenTy(Context);1402case IITDescriptor::Metadata: return Type::getMetadataTy(Context);1403case IITDescriptor::Half: return Type::getHalfTy(Context);1404case IITDescriptor::BFloat: return Type::getBFloatTy(Context);1405case IITDescriptor::Float: return Type::getFloatTy(Context);1406case IITDescriptor::Double: return Type::getDoubleTy(Context);1407case IITDescriptor::Quad: return Type::getFP128Ty(Context);1408case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context);1409case IITDescriptor::AArch64Svcount:1410return TargetExtType::get(Context, "aarch64.svcount");14111412case IITDescriptor::Integer:1413return IntegerType::get(Context, D.Integer_Width);1414case IITDescriptor::Vector:1415return VectorType::get(DecodeFixedType(Infos, Tys, Context),1416D.Vector_Width);1417case IITDescriptor::Pointer:1418return PointerType::get(Context, D.Pointer_AddressSpace);1419case IITDescriptor::Struct: {1420SmallVector<Type *, 8> Elts;1421for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)1422Elts.push_back(DecodeFixedType(Infos, Tys, Context));1423return StructType::get(Context, Elts);1424}1425case IITDescriptor::Argument:1426return Tys[D.getArgumentNumber()];1427case IITDescriptor::ExtendArgument: {1428Type *Ty = Tys[D.getArgumentNumber()];1429if (VectorType *VTy = dyn_cast<VectorType>(Ty))1430return VectorType::getExtendedElementVectorType(VTy);14311432return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());1433}1434case IITDescriptor::TruncArgument: {1435Type *Ty = Tys[D.getArgumentNumber()];1436if (VectorType *VTy = dyn_cast<VectorType>(Ty))1437return VectorType::getTruncatedElementVectorType(VTy);14381439IntegerType *ITy = cast<IntegerType>(Ty);1440assert(ITy->getBitWidth() % 2 == 0);1441return IntegerType::get(Context, ITy->getBitWidth() / 2);1442}1443case IITDescriptor::Subdivide2Argument:1444case IITDescriptor::Subdivide4Argument: {1445Type *Ty = Tys[D.getArgumentNumber()];1446VectorType *VTy = dyn_cast<VectorType>(Ty);1447assert(VTy && "Expected an argument of Vector Type");1448int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;1449return VectorType::getSubdividedVectorType(VTy, SubDivs);1450}1451case IITDescriptor::HalfVecArgument:1452return VectorType::getHalfElementsVectorType(cast<VectorType>(1453Tys[D.getArgumentNumber()]));1454case IITDescriptor::SameVecWidthArgument: {1455Type *EltTy = DecodeFixedType(Infos, Tys, Context);1456Type *Ty = Tys[D.getArgumentNumber()];1457if (auto *VTy = dyn_cast<VectorType>(Ty))1458return VectorType::get(EltTy, VTy->getElementCount());1459return EltTy;1460}1461case IITDescriptor::VecElementArgument: {1462Type *Ty = Tys[D.getArgumentNumber()];1463if (VectorType *VTy = dyn_cast<VectorType>(Ty))1464return VTy->getElementType();1465llvm_unreachable("Expected an argument of Vector Type");1466}1467case IITDescriptor::VecOfBitcastsToInt: {1468Type *Ty = Tys[D.getArgumentNumber()];1469VectorType *VTy = dyn_cast<VectorType>(Ty);1470assert(VTy && "Expected an argument of Vector Type");1471return VectorType::getInteger(VTy);1472}1473case IITDescriptor::VecOfAnyPtrsToElt:1474// Return the overloaded type (which determines the pointers address space)1475return Tys[D.getOverloadArgNumber()];1476}1477llvm_unreachable("unhandled");1478}14791480FunctionType *Intrinsic::getType(LLVMContext &Context,1481ID id, ArrayRef<Type*> Tys) {1482SmallVector<IITDescriptor, 8> Table;1483getIntrinsicInfoTableEntries(id, Table);14841485ArrayRef<IITDescriptor> TableRef = Table;1486Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);14871488SmallVector<Type*, 8> ArgTys;1489while (!TableRef.empty())1490ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));14911492// DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg1493// If we see void type as the type of the last argument, it is vararg intrinsic1494if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {1495ArgTys.pop_back();1496return FunctionType::get(ResultTy, ArgTys, true);1497}1498return FunctionType::get(ResultTy, ArgTys, false);1499}15001501bool Intrinsic::isOverloaded(ID id) {1502#define GET_INTRINSIC_OVERLOAD_TABLE1503#include "llvm/IR/IntrinsicImpl.inc"1504#undef GET_INTRINSIC_OVERLOAD_TABLE1505}15061507/// This defines the "Intrinsic::getAttributes(ID id)" method.1508#define GET_INTRINSIC_ATTRIBUTES1509#include "llvm/IR/IntrinsicImpl.inc"1510#undef GET_INTRINSIC_ATTRIBUTES15111512Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {1513// There can never be multiple globals with the same name of different types,1514// because intrinsics must be a specific type.1515auto *FT = getType(M->getContext(), id, Tys);1516return cast<Function>(1517M->getOrInsertFunction(1518Tys.empty() ? getName(id) : getName(id, Tys, M, FT), FT)1519.getCallee());1520}15211522// This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method.1523#define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN1524#include "llvm/IR/IntrinsicImpl.inc"1525#undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN15261527// This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.1528#define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN1529#include "llvm/IR/IntrinsicImpl.inc"1530#undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN15311532bool Intrinsic::isConstrainedFPIntrinsic(ID QID) {1533switch (QID) {1534#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \1535case Intrinsic::INTRINSIC:1536#include "llvm/IR/ConstrainedOps.def"1537#undef INSTRUCTION1538return true;1539default:1540return false;1541}1542}15431544bool Intrinsic::hasConstrainedFPRoundingModeOperand(Intrinsic::ID QID) {1545switch (QID) {1546#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \1547case Intrinsic::INTRINSIC: \1548return ROUND_MODE == 1;1549#include "llvm/IR/ConstrainedOps.def"1550#undef INSTRUCTION1551default:1552return false;1553}1554}15551556using DeferredIntrinsicMatchPair =1557std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;15581559static bool matchIntrinsicType(1560Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,1561SmallVectorImpl<Type *> &ArgTys,1562SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,1563bool IsDeferredCheck) {1564using namespace Intrinsic;15651566// If we ran out of descriptors, there are too many arguments.1567if (Infos.empty()) return true;15681569// Do this before slicing off the 'front' part1570auto InfosRef = Infos;1571auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {1572DeferredChecks.emplace_back(T, InfosRef);1573return false;1574};15751576IITDescriptor D = Infos.front();1577Infos = Infos.slice(1);15781579switch (D.Kind) {1580case IITDescriptor::Void: return !Ty->isVoidTy();1581case IITDescriptor::VarArg: return true;1582case IITDescriptor::MMX: return !Ty->isX86_MMXTy();1583case IITDescriptor::AMX: return !Ty->isX86_AMXTy();1584case IITDescriptor::Token: return !Ty->isTokenTy();1585case IITDescriptor::Metadata: return !Ty->isMetadataTy();1586case IITDescriptor::Half: return !Ty->isHalfTy();1587case IITDescriptor::BFloat: return !Ty->isBFloatTy();1588case IITDescriptor::Float: return !Ty->isFloatTy();1589case IITDescriptor::Double: return !Ty->isDoubleTy();1590case IITDescriptor::Quad: return !Ty->isFP128Ty();1591case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty();1592case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);1593case IITDescriptor::AArch64Svcount:1594return !isa<TargetExtType>(Ty) ||1595cast<TargetExtType>(Ty)->getName() != "aarch64.svcount";1596case IITDescriptor::Vector: {1597VectorType *VT = dyn_cast<VectorType>(Ty);1598return !VT || VT->getElementCount() != D.Vector_Width ||1599matchIntrinsicType(VT->getElementType(), Infos, ArgTys,1600DeferredChecks, IsDeferredCheck);1601}1602case IITDescriptor::Pointer: {1603PointerType *PT = dyn_cast<PointerType>(Ty);1604return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace;1605}16061607case IITDescriptor::Struct: {1608StructType *ST = dyn_cast<StructType>(Ty);1609if (!ST || !ST->isLiteral() || ST->isPacked() ||1610ST->getNumElements() != D.Struct_NumElements)1611return true;16121613for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)1614if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,1615DeferredChecks, IsDeferredCheck))1616return true;1617return false;1618}16191620case IITDescriptor::Argument:1621// If this is the second occurrence of an argument,1622// verify that the later instance matches the previous instance.1623if (D.getArgumentNumber() < ArgTys.size())1624return Ty != ArgTys[D.getArgumentNumber()];16251626if (D.getArgumentNumber() > ArgTys.size() ||1627D.getArgumentKind() == IITDescriptor::AK_MatchType)1628return IsDeferredCheck || DeferCheck(Ty);16291630assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&1631"Table consistency error");1632ArgTys.push_back(Ty);16331634switch (D.getArgumentKind()) {1635case IITDescriptor::AK_Any: return false; // Success1636case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();1637case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();1638case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);1639case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);1640default: break;1641}1642llvm_unreachable("all argument kinds not covered");16431644case IITDescriptor::ExtendArgument: {1645// If this is a forward reference, defer the check for later.1646if (D.getArgumentNumber() >= ArgTys.size())1647return IsDeferredCheck || DeferCheck(Ty);16481649Type *NewTy = ArgTys[D.getArgumentNumber()];1650if (VectorType *VTy = dyn_cast<VectorType>(NewTy))1651NewTy = VectorType::getExtendedElementVectorType(VTy);1652else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))1653NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());1654else1655return true;16561657return Ty != NewTy;1658}1659case IITDescriptor::TruncArgument: {1660// If this is a forward reference, defer the check for later.1661if (D.getArgumentNumber() >= ArgTys.size())1662return IsDeferredCheck || DeferCheck(Ty);16631664Type *NewTy = ArgTys[D.getArgumentNumber()];1665if (VectorType *VTy = dyn_cast<VectorType>(NewTy))1666NewTy = VectorType::getTruncatedElementVectorType(VTy);1667else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))1668NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);1669else1670return true;16711672return Ty != NewTy;1673}1674case IITDescriptor::HalfVecArgument:1675// If this is a forward reference, defer the check for later.1676if (D.getArgumentNumber() >= ArgTys.size())1677return IsDeferredCheck || DeferCheck(Ty);1678return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||1679VectorType::getHalfElementsVectorType(1680cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;1681case IITDescriptor::SameVecWidthArgument: {1682if (D.getArgumentNumber() >= ArgTys.size()) {1683// Defer check and subsequent check for the vector element type.1684Infos = Infos.slice(1);1685return IsDeferredCheck || DeferCheck(Ty);1686}1687auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);1688auto *ThisArgType = dyn_cast<VectorType>(Ty);1689// Both must be vectors of the same number of elements or neither.1690if ((ReferenceType != nullptr) != (ThisArgType != nullptr))1691return true;1692Type *EltTy = Ty;1693if (ThisArgType) {1694if (ReferenceType->getElementCount() !=1695ThisArgType->getElementCount())1696return true;1697EltTy = ThisArgType->getElementType();1698}1699return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,1700IsDeferredCheck);1701}1702case IITDescriptor::VecOfAnyPtrsToElt: {1703unsigned RefArgNumber = D.getRefArgNumber();1704if (RefArgNumber >= ArgTys.size()) {1705if (IsDeferredCheck)1706return true;1707// If forward referencing, already add the pointer-vector type and1708// defer the checks for later.1709ArgTys.push_back(Ty);1710return DeferCheck(Ty);1711}17121713if (!IsDeferredCheck){1714assert(D.getOverloadArgNumber() == ArgTys.size() &&1715"Table consistency error");1716ArgTys.push_back(Ty);1717}17181719// Verify the overloaded type "matches" the Ref type.1720// i.e. Ty is a vector with the same width as Ref.1721// Composed of pointers to the same element type as Ref.1722auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);1723auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);1724if (!ThisArgVecTy || !ReferenceType ||1725(ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))1726return true;1727return !ThisArgVecTy->getElementType()->isPointerTy();1728}1729case IITDescriptor::VecElementArgument: {1730if (D.getArgumentNumber() >= ArgTys.size())1731return IsDeferredCheck ? true : DeferCheck(Ty);1732auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);1733return !ReferenceType || Ty != ReferenceType->getElementType();1734}1735case IITDescriptor::Subdivide2Argument:1736case IITDescriptor::Subdivide4Argument: {1737// If this is a forward reference, defer the check for later.1738if (D.getArgumentNumber() >= ArgTys.size())1739return IsDeferredCheck || DeferCheck(Ty);17401741Type *NewTy = ArgTys[D.getArgumentNumber()];1742if (auto *VTy = dyn_cast<VectorType>(NewTy)) {1743int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;1744NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);1745return Ty != NewTy;1746}1747return true;1748}1749case IITDescriptor::VecOfBitcastsToInt: {1750if (D.getArgumentNumber() >= ArgTys.size())1751return IsDeferredCheck || DeferCheck(Ty);1752auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);1753auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);1754if (!ThisArgVecTy || !ReferenceType)1755return true;1756return ThisArgVecTy != VectorType::getInteger(ReferenceType);1757}1758}1759llvm_unreachable("unhandled");1760}17611762Intrinsic::MatchIntrinsicTypesResult1763Intrinsic::matchIntrinsicSignature(FunctionType *FTy,1764ArrayRef<Intrinsic::IITDescriptor> &Infos,1765SmallVectorImpl<Type *> &ArgTys) {1766SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;1767if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,1768false))1769return MatchIntrinsicTypes_NoMatchRet;17701771unsigned NumDeferredReturnChecks = DeferredChecks.size();17721773for (auto *Ty : FTy->params())1774if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))1775return MatchIntrinsicTypes_NoMatchArg;17761777for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {1778DeferredIntrinsicMatchPair &Check = DeferredChecks[I];1779if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,1780true))1781return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet1782: MatchIntrinsicTypes_NoMatchArg;1783}17841785return MatchIntrinsicTypes_Match;1786}17871788bool1789Intrinsic::matchIntrinsicVarArg(bool isVarArg,1790ArrayRef<Intrinsic::IITDescriptor> &Infos) {1791// If there are no descriptors left, then it can't be a vararg.1792if (Infos.empty())1793return isVarArg;17941795// There should be only one descriptor remaining at this point.1796if (Infos.size() != 1)1797return true;17981799// Check and verify the descriptor.1800IITDescriptor D = Infos.front();1801Infos = Infos.slice(1);1802if (D.Kind == IITDescriptor::VarArg)1803return !isVarArg;18041805return true;1806}18071808bool Intrinsic::getIntrinsicSignature(Intrinsic::ID ID, FunctionType *FT,1809SmallVectorImpl<Type *> &ArgTys) {1810if (!ID)1811return false;18121813SmallVector<Intrinsic::IITDescriptor, 8> Table;1814getIntrinsicInfoTableEntries(ID, Table);1815ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;18161817if (Intrinsic::matchIntrinsicSignature(FT, TableRef, ArgTys) !=1818Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {1819return false;1820}1821if (Intrinsic::matchIntrinsicVarArg(FT->isVarArg(), TableRef))1822return false;1823return true;1824}18251826bool Intrinsic::getIntrinsicSignature(Function *F,1827SmallVectorImpl<Type *> &ArgTys) {1828return getIntrinsicSignature(F->getIntrinsicID(), F->getFunctionType(),1829ArgTys);1830}18311832std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {1833SmallVector<Type *, 4> ArgTys;1834if (!getIntrinsicSignature(F, ArgTys))1835return std::nullopt;18361837Intrinsic::ID ID = F->getIntrinsicID();1838StringRef Name = F->getName();1839std::string WantedName =1840Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType());1841if (Name == WantedName)1842return std::nullopt;18431844Function *NewDecl = [&] {1845if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {1846if (auto *ExistingF = dyn_cast<Function>(ExistingGV))1847if (ExistingF->getFunctionType() == F->getFunctionType())1848return ExistingF;18491850// The name already exists, but is not a function or has the wrong1851// prototype. Make place for the new one by renaming the old version.1852// Either this old version will be removed later on or the module is1853// invalid and we'll get an error.1854ExistingGV->setName(WantedName + ".renamed");1855}1856return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);1857}();18581859NewDecl->setCallingConv(F->getCallingConv());1860assert(NewDecl->getFunctionType() == F->getFunctionType() &&1861"Shouldn't change the signature");1862return NewDecl;1863}18641865/// hasAddressTaken - returns true if there are any uses of this function1866/// other than direct calls or invokes to it. Optionally ignores callback1867/// uses, assume like pointer annotation calls, and references in llvm.used1868/// and llvm.compiler.used variables.1869bool Function::hasAddressTaken(const User **PutOffender,1870bool IgnoreCallbackUses,1871bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,1872bool IgnoreARCAttachedCall,1873bool IgnoreCastedDirectCall) const {1874for (const Use &U : uses()) {1875const User *FU = U.getUser();1876if (isa<BlockAddress>(FU))1877continue;18781879if (IgnoreCallbackUses) {1880AbstractCallSite ACS(&U);1881if (ACS && ACS.isCallbackCall())1882continue;1883}18841885const auto *Call = dyn_cast<CallBase>(FU);1886if (!Call) {1887if (IgnoreAssumeLikeCalls &&1888isa<BitCastOperator, AddrSpaceCastOperator>(FU) &&1889all_of(FU->users(), [](const User *U) {1890if (const auto *I = dyn_cast<IntrinsicInst>(U))1891return I->isAssumeLikeIntrinsic();1892return false;1893})) {1894continue;1895}18961897if (IgnoreLLVMUsed && !FU->user_empty()) {1898const User *FUU = FU;1899if (isa<BitCastOperator, AddrSpaceCastOperator>(FU) &&1900FU->hasOneUse() && !FU->user_begin()->user_empty())1901FUU = *FU->user_begin();1902if (llvm::all_of(FUU->users(), [](const User *U) {1903if (const auto *GV = dyn_cast<GlobalVariable>(U))1904return GV->hasName() &&1905(GV->getName() == "llvm.compiler.used" ||1906GV->getName() == "llvm.used");1907return false;1908}))1909continue;1910}1911if (PutOffender)1912*PutOffender = FU;1913return true;1914}19151916if (IgnoreAssumeLikeCalls) {1917if (const auto *I = dyn_cast<IntrinsicInst>(Call))1918if (I->isAssumeLikeIntrinsic())1919continue;1920}19211922if (!Call->isCallee(&U) || (!IgnoreCastedDirectCall &&1923Call->getFunctionType() != getFunctionType())) {1924if (IgnoreARCAttachedCall &&1925Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,1926U.getOperandNo()))1927continue;19281929if (PutOffender)1930*PutOffender = FU;1931return true;1932}1933}1934return false;1935}19361937bool Function::isDefTriviallyDead() const {1938// Check the linkage1939if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&1940!hasAvailableExternallyLinkage())1941return false;19421943// Check if the function is used by anything other than a blockaddress.1944for (const User *U : users())1945if (!isa<BlockAddress>(U))1946return false;19471948return true;1949}19501951/// callsFunctionThatReturnsTwice - Return true if the function has a call to1952/// setjmp or other function that gcc recognizes as "returning twice".1953bool Function::callsFunctionThatReturnsTwice() const {1954for (const Instruction &I : instructions(this))1955if (const auto *Call = dyn_cast<CallBase>(&I))1956if (Call->hasFnAttr(Attribute::ReturnsTwice))1957return true;19581959return false;1960}19611962Constant *Function::getPersonalityFn() const {1963assert(hasPersonalityFn() && getNumOperands());1964return cast<Constant>(Op<0>());1965}19661967void Function::setPersonalityFn(Constant *Fn) {1968setHungoffOperand<0>(Fn);1969setValueSubclassDataBit(3, Fn != nullptr);1970}19711972Constant *Function::getPrefixData() const {1973assert(hasPrefixData() && getNumOperands());1974return cast<Constant>(Op<1>());1975}19761977void Function::setPrefixData(Constant *PrefixData) {1978setHungoffOperand<1>(PrefixData);1979setValueSubclassDataBit(1, PrefixData != nullptr);1980}19811982Constant *Function::getPrologueData() const {1983assert(hasPrologueData() && getNumOperands());1984return cast<Constant>(Op<2>());1985}19861987void Function::setPrologueData(Constant *PrologueData) {1988setHungoffOperand<2>(PrologueData);1989setValueSubclassDataBit(2, PrologueData != nullptr);1990}19911992void Function::allocHungoffUselist() {1993// If we've already allocated a uselist, stop here.1994if (getNumOperands())1995return;19961997allocHungoffUses(3, /*IsPhi=*/ false);1998setNumHungOffUseOperands(3);19992000// Initialize the uselist with placeholder operands to allow traversal.2001auto *CPN = ConstantPointerNull::get(PointerType::get(getContext(), 0));2002Op<0>().set(CPN);2003Op<1>().set(CPN);2004Op<2>().set(CPN);2005}20062007template <int Idx>2008void Function::setHungoffOperand(Constant *C) {2009if (C) {2010allocHungoffUselist();2011Op<Idx>().set(C);2012} else if (getNumOperands()) {2013Op<Idx>().set(ConstantPointerNull::get(PointerType::get(getContext(), 0)));2014}2015}20162017void Function::setValueSubclassDataBit(unsigned Bit, bool On) {2018assert(Bit < 16 && "SubclassData contains only 16 bits");2019if (On)2020setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));2021else2022setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));2023}20242025void Function::setEntryCount(ProfileCount Count,2026const DenseSet<GlobalValue::GUID> *S) {2027#if !defined(NDEBUG)2028auto PrevCount = getEntryCount();2029assert(!PrevCount || PrevCount->getType() == Count.getType());2030#endif20312032auto ImportGUIDs = getImportGUIDs();2033if (S == nullptr && ImportGUIDs.size())2034S = &ImportGUIDs;20352036MDBuilder MDB(getContext());2037setMetadata(2038LLVMContext::MD_prof,2039MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));2040}20412042void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,2043const DenseSet<GlobalValue::GUID> *Imports) {2044setEntryCount(ProfileCount(Count, Type), Imports);2045}20462047std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {2048MDNode *MD = getMetadata(LLVMContext::MD_prof);2049if (MD && MD->getOperand(0))2050if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {2051if (MDS->getString() == "function_entry_count") {2052ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));2053uint64_t Count = CI->getValue().getZExtValue();2054// A value of -1 is used for SamplePGO when there were no samples.2055// Treat this the same as unknown.2056if (Count == (uint64_t)-1)2057return std::nullopt;2058return ProfileCount(Count, PCT_Real);2059} else if (AllowSynthetic &&2060MDS->getString() == "synthetic_function_entry_count") {2061ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));2062uint64_t Count = CI->getValue().getZExtValue();2063return ProfileCount(Count, PCT_Synthetic);2064}2065}2066return std::nullopt;2067}20682069DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {2070DenseSet<GlobalValue::GUID> R;2071if (MDNode *MD = getMetadata(LLVMContext::MD_prof))2072if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))2073if (MDS->getString() == "function_entry_count")2074for (unsigned i = 2; i < MD->getNumOperands(); i++)2075R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))2076->getValue()2077.getZExtValue());2078return R;2079}20802081void Function::setSectionPrefix(StringRef Prefix) {2082MDBuilder MDB(getContext());2083setMetadata(LLVMContext::MD_section_prefix,2084MDB.createFunctionSectionPrefix(Prefix));2085}20862087std::optional<StringRef> Function::getSectionPrefix() const {2088if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {2089assert(cast<MDString>(MD->getOperand(0))->getString() ==2090"function_section_prefix" &&2091"Metadata not match");2092return cast<MDString>(MD->getOperand(1))->getString();2093}2094return std::nullopt;2095}20962097bool Function::nullPointerIsDefined() const {2098return hasFnAttribute(Attribute::NullPointerIsValid);2099}21002101bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {2102if (F && F->nullPointerIsDefined())2103return true;21042105if (AS != 0)2106return true;21072108return false;2109}211021112112