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" 14 #include "SymbolTableListTraitsImpl.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" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/IR/AbstractCallSite.h" 24 #include "llvm/IR/Argument.h" 25 #include "llvm/IR/Attributes.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/Constant.h" 28 #include "llvm/IR/ConstantRange.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/GlobalValue.h" 32 #include "llvm/IR/InstIterator.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/IntrinsicsAArch64.h" 37 #include "llvm/IR/IntrinsicsAMDGPU.h" 38 #include "llvm/IR/IntrinsicsARM.h" 39 #include "llvm/IR/IntrinsicsBPF.h" 40 #include "llvm/IR/IntrinsicsDirectX.h" 41 #include "llvm/IR/IntrinsicsHexagon.h" 42 #include "llvm/IR/IntrinsicsLoongArch.h" 43 #include "llvm/IR/IntrinsicsMips.h" 44 #include "llvm/IR/IntrinsicsNVPTX.h" 45 #include "llvm/IR/IntrinsicsPowerPC.h" 46 #include "llvm/IR/IntrinsicsR600.h" 47 #include "llvm/IR/IntrinsicsRISCV.h" 48 #include "llvm/IR/IntrinsicsS390.h" 49 #include "llvm/IR/IntrinsicsSPIRV.h" 50 #include "llvm/IR/IntrinsicsVE.h" 51 #include "llvm/IR/IntrinsicsWebAssembly.h" 52 #include "llvm/IR/IntrinsicsX86.h" 53 #include "llvm/IR/IntrinsicsXCore.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/MDBuilder.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/Operator.h" 59 #include "llvm/IR/SymbolTableListTraits.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/Use.h" 62 #include "llvm/IR/User.h" 63 #include "llvm/IR/Value.h" 64 #include "llvm/IR/ValueSymbolTable.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Compiler.h" 68 #include "llvm/Support/ErrorHandling.h" 69 #include "llvm/Support/ModRef.h" 70 #include <cassert> 71 #include <cstddef> 72 #include <cstdint> 73 #include <cstring> 74 #include <string> 75 76 using namespace llvm; 77 using ProfileCount = Function::ProfileCount; 78 79 // Explicit instantiations of SymbolTableListTraits since some of the methods 80 // are not in the public header file... 81 template class llvm::SymbolTableListTraits<BasicBlock>; 82 83 static cl::opt<int> NonGlobalValueMaxNameSize( 84 "non-global-value-max-name-size", cl::Hidden, cl::init(1024), 85 cl::desc("Maximum size for the name of non-global values.")); 86 87 extern cl::opt<bool> UseNewDbgInfoFormat; 88 89 void Function::renumberBlocks() { 90 validateBlockNumbers(); 91 92 NextBlockNum = 0; 93 for (auto &BB : *this) 94 BB.Number = NextBlockNum++; 95 BlockNumEpoch++; 96 } 97 98 void Function::validateBlockNumbers() const { 99 #ifndef NDEBUG 100 BitVector Numbers(NextBlockNum); 101 for (const auto &BB : *this) { 102 unsigned Num = BB.getNumber(); 103 assert(Num < NextBlockNum && "out of range block number"); 104 assert(!Numbers[Num] && "duplicate block numbers"); 105 Numbers.set(Num); 106 } 107 #endif 108 } 109 110 void Function::convertToNewDbgValues() { 111 IsNewDbgInfoFormat = true; 112 for (auto &BB : *this) { 113 BB.convertToNewDbgValues(); 114 } 115 } 116 117 void Function::convertFromNewDbgValues() { 118 IsNewDbgInfoFormat = false; 119 for (auto &BB : *this) { 120 BB.convertFromNewDbgValues(); 121 } 122 } 123 124 void Function::setIsNewDbgInfoFormat(bool NewFlag) { 125 if (NewFlag && !IsNewDbgInfoFormat) 126 convertToNewDbgValues(); 127 else if (!NewFlag && IsNewDbgInfoFormat) 128 convertFromNewDbgValues(); 129 } 130 void Function::setNewDbgInfoFormatFlag(bool NewFlag) { 131 for (auto &BB : *this) { 132 BB.setNewDbgInfoFormatFlag(NewFlag); 133 } 134 IsNewDbgInfoFormat = NewFlag; 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Argument Implementation 139 //===----------------------------------------------------------------------===// 140 141 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) 142 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { 143 setName(Name); 144 } 145 146 void Argument::setParent(Function *parent) { 147 Parent = parent; 148 } 149 150 bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const { 151 if (!getType()->isPointerTy()) return false; 152 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) && 153 (AllowUndefOrPoison || 154 getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef))) 155 return true; 156 else if (getDereferenceableBytes() > 0 && 157 !NullPointerIsDefined(getParent(), 158 getType()->getPointerAddressSpace())) 159 return true; 160 return false; 161 } 162 163 bool Argument::hasByValAttr() const { 164 if (!getType()->isPointerTy()) return false; 165 return hasAttribute(Attribute::ByVal); 166 } 167 168 bool Argument::hasByRefAttr() const { 169 if (!getType()->isPointerTy()) 170 return false; 171 return hasAttribute(Attribute::ByRef); 172 } 173 174 bool Argument::hasSwiftSelfAttr() const { 175 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf); 176 } 177 178 bool Argument::hasSwiftErrorAttr() const { 179 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError); 180 } 181 182 bool Argument::hasInAllocaAttr() const { 183 if (!getType()->isPointerTy()) return false; 184 return hasAttribute(Attribute::InAlloca); 185 } 186 187 bool Argument::hasPreallocatedAttr() const { 188 if (!getType()->isPointerTy()) 189 return false; 190 return hasAttribute(Attribute::Preallocated); 191 } 192 193 bool Argument::hasPassPointeeByValueCopyAttr() const { 194 if (!getType()->isPointerTy()) return false; 195 AttributeList Attrs = getParent()->getAttributes(); 196 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) || 197 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) || 198 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated); 199 } 200 201 bool Argument::hasPointeeInMemoryValueAttr() const { 202 if (!getType()->isPointerTy()) 203 return false; 204 AttributeList Attrs = getParent()->getAttributes(); 205 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) || 206 Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) || 207 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) || 208 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) || 209 Attrs.hasParamAttr(getArgNo(), Attribute::ByRef); 210 } 211 212 /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory 213 /// parameter type. 214 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) { 215 // FIXME: All the type carrying attributes are mutually exclusive, so there 216 // should be a single query to get the stored type that handles any of them. 217 if (Type *ByValTy = ParamAttrs.getByValType()) 218 return ByValTy; 219 if (Type *ByRefTy = ParamAttrs.getByRefType()) 220 return ByRefTy; 221 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType()) 222 return PreAllocTy; 223 if (Type *InAllocaTy = ParamAttrs.getInAllocaType()) 224 return InAllocaTy; 225 if (Type *SRetTy = ParamAttrs.getStructRetType()) 226 return SRetTy; 227 228 return nullptr; 229 } 230 231 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const { 232 AttributeSet ParamAttrs = 233 getParent()->getAttributes().getParamAttrs(getArgNo()); 234 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs)) 235 return DL.getTypeAllocSize(MemTy); 236 return 0; 237 } 238 239 Type *Argument::getPointeeInMemoryValueType() const { 240 AttributeSet ParamAttrs = 241 getParent()->getAttributes().getParamAttrs(getArgNo()); 242 return getMemoryParamAllocType(ParamAttrs); 243 } 244 245 MaybeAlign Argument::getParamAlign() const { 246 assert(getType()->isPointerTy() && "Only pointers have alignments"); 247 return getParent()->getParamAlign(getArgNo()); 248 } 249 250 MaybeAlign Argument::getParamStackAlign() const { 251 return getParent()->getParamStackAlign(getArgNo()); 252 } 253 254 Type *Argument::getParamByValType() const { 255 assert(getType()->isPointerTy() && "Only pointers have byval types"); 256 return getParent()->getParamByValType(getArgNo()); 257 } 258 259 Type *Argument::getParamStructRetType() const { 260 assert(getType()->isPointerTy() && "Only pointers have sret types"); 261 return getParent()->getParamStructRetType(getArgNo()); 262 } 263 264 Type *Argument::getParamByRefType() const { 265 assert(getType()->isPointerTy() && "Only pointers have byref types"); 266 return getParent()->getParamByRefType(getArgNo()); 267 } 268 269 Type *Argument::getParamInAllocaType() const { 270 assert(getType()->isPointerTy() && "Only pointers have inalloca types"); 271 return getParent()->getParamInAllocaType(getArgNo()); 272 } 273 274 uint64_t Argument::getDereferenceableBytes() const { 275 assert(getType()->isPointerTy() && 276 "Only pointers have dereferenceable bytes"); 277 return getParent()->getParamDereferenceableBytes(getArgNo()); 278 } 279 280 uint64_t Argument::getDereferenceableOrNullBytes() const { 281 assert(getType()->isPointerTy() && 282 "Only pointers have dereferenceable bytes"); 283 return getParent()->getParamDereferenceableOrNullBytes(getArgNo()); 284 } 285 286 FPClassTest Argument::getNoFPClass() const { 287 return getParent()->getParamNoFPClass(getArgNo()); 288 } 289 290 std::optional<ConstantRange> Argument::getRange() const { 291 const Attribute RangeAttr = getAttribute(llvm::Attribute::Range); 292 if (RangeAttr.isValid()) 293 return RangeAttr.getRange(); 294 return std::nullopt; 295 } 296 297 bool Argument::hasNestAttr() const { 298 if (!getType()->isPointerTy()) return false; 299 return hasAttribute(Attribute::Nest); 300 } 301 302 bool Argument::hasNoAliasAttr() const { 303 if (!getType()->isPointerTy()) return false; 304 return hasAttribute(Attribute::NoAlias); 305 } 306 307 bool Argument::hasNoCaptureAttr() const { 308 if (!getType()->isPointerTy()) return false; 309 return hasAttribute(Attribute::NoCapture); 310 } 311 312 bool Argument::hasNoFreeAttr() const { 313 if (!getType()->isPointerTy()) return false; 314 return hasAttribute(Attribute::NoFree); 315 } 316 317 bool Argument::hasStructRetAttr() const { 318 if (!getType()->isPointerTy()) return false; 319 return hasAttribute(Attribute::StructRet); 320 } 321 322 bool Argument::hasInRegAttr() const { 323 return hasAttribute(Attribute::InReg); 324 } 325 326 bool Argument::hasReturnedAttr() const { 327 return hasAttribute(Attribute::Returned); 328 } 329 330 bool Argument::hasZExtAttr() const { 331 return hasAttribute(Attribute::ZExt); 332 } 333 334 bool Argument::hasSExtAttr() const { 335 return hasAttribute(Attribute::SExt); 336 } 337 338 bool Argument::onlyReadsMemory() const { 339 AttributeList Attrs = getParent()->getAttributes(); 340 return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) || 341 Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone); 342 } 343 344 void Argument::addAttrs(AttrBuilder &B) { 345 AttributeList AL = getParent()->getAttributes(); 346 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B); 347 getParent()->setAttributes(AL); 348 } 349 350 void Argument::addAttr(Attribute::AttrKind Kind) { 351 getParent()->addParamAttr(getArgNo(), Kind); 352 } 353 354 void Argument::addAttr(Attribute Attr) { 355 getParent()->addParamAttr(getArgNo(), Attr); 356 } 357 358 void Argument::removeAttr(Attribute::AttrKind Kind) { 359 getParent()->removeParamAttr(getArgNo(), Kind); 360 } 361 362 void Argument::removeAttrs(const AttributeMask &AM) { 363 AttributeList AL = getParent()->getAttributes(); 364 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM); 365 getParent()->setAttributes(AL); 366 } 367 368 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 369 return getParent()->hasParamAttribute(getArgNo(), Kind); 370 } 371 372 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const { 373 return getParent()->getParamAttribute(getArgNo(), Kind); 374 } 375 376 //===----------------------------------------------------------------------===// 377 // Helper Methods in Function 378 //===----------------------------------------------------------------------===// 379 380 LLVMContext &Function::getContext() const { 381 return getType()->getContext(); 382 } 383 384 const DataLayout &Function::getDataLayout() const { 385 return getParent()->getDataLayout(); 386 } 387 388 unsigned Function::getInstructionCount() const { 389 unsigned NumInstrs = 0; 390 for (const BasicBlock &BB : BasicBlocks) 391 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(), 392 BB.instructionsWithoutDebug().end()); 393 return NumInstrs; 394 } 395 396 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage, 397 const Twine &N, Module &M) { 398 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M); 399 } 400 401 Function *Function::createWithDefaultAttr(FunctionType *Ty, 402 LinkageTypes Linkage, 403 unsigned AddrSpace, const Twine &N, 404 Module *M) { 405 auto *F = new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M); 406 AttrBuilder B(F->getContext()); 407 UWTableKind UWTable = M->getUwtable(); 408 if (UWTable != UWTableKind::None) 409 B.addUWTableAttr(UWTable); 410 switch (M->getFramePointer()) { 411 case FramePointerKind::None: 412 // 0 ("none") is the default. 413 break; 414 case FramePointerKind::Reserved: 415 B.addAttribute("frame-pointer", "reserved"); 416 break; 417 case FramePointerKind::NonLeaf: 418 B.addAttribute("frame-pointer", "non-leaf"); 419 break; 420 case FramePointerKind::All: 421 B.addAttribute("frame-pointer", "all"); 422 break; 423 } 424 if (M->getModuleFlag("function_return_thunk_extern")) 425 B.addAttribute(Attribute::FnRetThunkExtern); 426 StringRef DefaultCPU = F->getContext().getDefaultTargetCPU(); 427 if (!DefaultCPU.empty()) 428 B.addAttribute("target-cpu", DefaultCPU); 429 StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures(); 430 if (!DefaultFeatures.empty()) 431 B.addAttribute("target-features", DefaultFeatures); 432 433 // Check if the module attribute is present and not zero. 434 auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool { 435 const auto *Attr = 436 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(ModAttr)); 437 return Attr && !Attr->isZero(); 438 }; 439 440 auto AddAttributeIfSet = [&](const StringRef &ModAttr) { 441 if (isModuleAttributeSet(ModAttr)) 442 B.addAttribute(ModAttr); 443 }; 444 445 StringRef SignType = "none"; 446 if (isModuleAttributeSet("sign-return-address")) 447 SignType = "non-leaf"; 448 if (isModuleAttributeSet("sign-return-address-all")) 449 SignType = "all"; 450 if (SignType != "none") { 451 B.addAttribute("sign-return-address", SignType); 452 B.addAttribute("sign-return-address-key", 453 isModuleAttributeSet("sign-return-address-with-bkey") 454 ? "b_key" 455 : "a_key"); 456 } 457 AddAttributeIfSet("branch-target-enforcement"); 458 AddAttributeIfSet("branch-protection-pauth-lr"); 459 AddAttributeIfSet("guarded-control-stack"); 460 461 F->addFnAttrs(B); 462 return F; 463 } 464 465 void Function::removeFromParent() { 466 getParent()->getFunctionList().remove(getIterator()); 467 } 468 469 void Function::eraseFromParent() { 470 getParent()->getFunctionList().erase(getIterator()); 471 } 472 473 void Function::splice(Function::iterator ToIt, Function *FromF, 474 Function::iterator FromBeginIt, 475 Function::iterator FromEndIt) { 476 #ifdef EXPENSIVE_CHECKS 477 // Check that FromBeginIt is before FromEndIt. 478 auto FromFEnd = FromF->end(); 479 for (auto It = FromBeginIt; It != FromEndIt; ++It) 480 assert(It != FromFEnd && "FromBeginIt not before FromEndIt!"); 481 #endif // EXPENSIVE_CHECKS 482 BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt); 483 } 484 485 Function::iterator Function::erase(Function::iterator FromIt, 486 Function::iterator ToIt) { 487 return BasicBlocks.erase(FromIt, ToIt); 488 } 489 490 //===----------------------------------------------------------------------===// 491 // Function Implementation 492 //===----------------------------------------------------------------------===// 493 494 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) { 495 // If AS == -1 and we are passed a valid module pointer we place the function 496 // in the program address space. Otherwise we default to AS0. 497 if (AddrSpace == static_cast<unsigned>(-1)) 498 return M ? M->getDataLayout().getProgramAddressSpace() : 0; 499 return AddrSpace; 500 } 501 502 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 503 const Twine &name, Module *ParentModule) 504 : GlobalObject(Ty, Value::FunctionVal, AllocMarker, Linkage, name, 505 computeAddrSpace(AddrSpace, ParentModule)), 506 NumArgs(Ty->getNumParams()), IsNewDbgInfoFormat(UseNewDbgInfoFormat) { 507 assert(FunctionType::isValidReturnType(getReturnType()) && 508 "invalid return type"); 509 setGlobalObjectSubClassData(0); 510 511 // We only need a symbol table for a function if the context keeps value names 512 if (!getContext().shouldDiscardValueNames()) 513 SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize); 514 515 // If the function has arguments, mark them as lazily built. 516 if (Ty->getNumParams()) 517 setValueSubclassData(1); // Set the "has lazy arguments" bit. 518 519 if (ParentModule) { 520 ParentModule->getFunctionList().push_back(this); 521 IsNewDbgInfoFormat = ParentModule->IsNewDbgInfoFormat; 522 } 523 524 HasLLVMReservedName = getName().starts_with("llvm."); 525 // Ensure intrinsics have the right parameter attributes. 526 // Note, the IntID field will have been set in Value::setName if this function 527 // name is a valid intrinsic ID. 528 if (IntID) 529 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 530 } 531 532 Function::~Function() { 533 validateBlockNumbers(); 534 535 dropAllReferences(); // After this it is safe to delete instructions. 536 537 // Delete all of the method arguments and unlink from symbol table... 538 if (Arguments) 539 clearArguments(); 540 541 // Remove the function from the on-the-side GC table. 542 clearGC(); 543 } 544 545 void Function::BuildLazyArguments() const { 546 // Create the arguments vector, all arguments start out unnamed. 547 auto *FT = getFunctionType(); 548 if (NumArgs > 0) { 549 Arguments = std::allocator<Argument>().allocate(NumArgs); 550 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 551 Type *ArgTy = FT->getParamType(i); 552 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!"); 553 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i); 554 } 555 } 556 557 // Clear the lazy arguments bit. 558 unsigned SDC = getSubclassDataFromValue(); 559 SDC &= ~(1 << 0); 560 const_cast<Function*>(this)->setValueSubclassData(SDC); 561 assert(!hasLazyArguments()); 562 } 563 564 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) { 565 return MutableArrayRef<Argument>(Args, Count); 566 } 567 568 bool Function::isConstrainedFPIntrinsic() const { 569 return Intrinsic::isConstrainedFPIntrinsic(getIntrinsicID()); 570 } 571 572 void Function::clearArguments() { 573 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 574 A.setName(""); 575 A.~Argument(); 576 } 577 std::allocator<Argument>().deallocate(Arguments, NumArgs); 578 Arguments = nullptr; 579 } 580 581 void Function::stealArgumentListFrom(Function &Src) { 582 assert(isDeclaration() && "Expected no references to current arguments"); 583 584 // Drop the current arguments, if any, and set the lazy argument bit. 585 if (!hasLazyArguments()) { 586 assert(llvm::all_of(makeArgArray(Arguments, NumArgs), 587 [](const Argument &A) { return A.use_empty(); }) && 588 "Expected arguments to be unused in declaration"); 589 clearArguments(); 590 setValueSubclassData(getSubclassDataFromValue() | (1 << 0)); 591 } 592 593 // Nothing to steal if Src has lazy arguments. 594 if (Src.hasLazyArguments()) 595 return; 596 597 // Steal arguments from Src, and fix the lazy argument bits. 598 assert(arg_size() == Src.arg_size()); 599 Arguments = Src.Arguments; 600 Src.Arguments = nullptr; 601 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 602 // FIXME: This does the work of transferNodesFromList inefficiently. 603 SmallString<128> Name; 604 if (A.hasName()) 605 Name = A.getName(); 606 if (!Name.empty()) 607 A.setName(""); 608 A.setParent(this); 609 if (!Name.empty()) 610 A.setName(Name); 611 } 612 613 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0)); 614 assert(!hasLazyArguments()); 615 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0)); 616 } 617 618 void Function::deleteBodyImpl(bool ShouldDrop) { 619 setIsMaterializable(false); 620 621 for (BasicBlock &BB : *this) 622 BB.dropAllReferences(); 623 624 // Delete all basic blocks. They are now unused, except possibly by 625 // blockaddresses, but BasicBlock's destructor takes care of those. 626 while (!BasicBlocks.empty()) 627 BasicBlocks.begin()->eraseFromParent(); 628 629 if (getNumOperands()) { 630 if (ShouldDrop) { 631 // Drop uses of any optional data (real or placeholder). 632 User::dropAllReferences(); 633 setNumHungOffUseOperands(0); 634 } else { 635 // The code needs to match Function::allocHungoffUselist(). 636 auto *CPN = ConstantPointerNull::get(PointerType::get(getContext(), 0)); 637 Op<0>().set(CPN); 638 Op<1>().set(CPN); 639 Op<2>().set(CPN); 640 } 641 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 642 } 643 644 // Metadata is stored in a side-table. 645 clearMetadata(); 646 } 647 648 void Function::addAttributeAtIndex(unsigned i, Attribute Attr) { 649 AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr); 650 } 651 652 void Function::addFnAttr(Attribute::AttrKind Kind) { 653 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind); 654 } 655 656 void Function::addFnAttr(StringRef Kind, StringRef Val) { 657 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val); 658 } 659 660 void Function::addFnAttr(Attribute Attr) { 661 AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr); 662 } 663 664 void Function::addFnAttrs(const AttrBuilder &Attrs) { 665 AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs); 666 } 667 668 void Function::addRetAttr(Attribute::AttrKind Kind) { 669 AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind); 670 } 671 672 void Function::addRetAttr(Attribute Attr) { 673 AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr); 674 } 675 676 void Function::addRetAttrs(const AttrBuilder &Attrs) { 677 AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs); 678 } 679 680 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 681 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind); 682 } 683 684 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) { 685 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr); 686 } 687 688 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 689 AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs); 690 } 691 692 void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) { 693 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind); 694 } 695 696 void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) { 697 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind); 698 } 699 700 void Function::removeFnAttr(Attribute::AttrKind Kind) { 701 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind); 702 } 703 704 void Function::removeFnAttr(StringRef Kind) { 705 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind); 706 } 707 708 void Function::removeFnAttrs(const AttributeMask &AM) { 709 AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM); 710 } 711 712 void Function::removeRetAttr(Attribute::AttrKind Kind) { 713 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind); 714 } 715 716 void Function::removeRetAttr(StringRef Kind) { 717 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind); 718 } 719 720 void Function::removeRetAttrs(const AttributeMask &Attrs) { 721 AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs); 722 } 723 724 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 725 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind); 726 } 727 728 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) { 729 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind); 730 } 731 732 void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) { 733 AttributeSets = 734 AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs); 735 } 736 737 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) { 738 AttributeSets = 739 AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes); 740 } 741 742 bool Function::hasFnAttribute(Attribute::AttrKind Kind) const { 743 return AttributeSets.hasFnAttr(Kind); 744 } 745 746 bool Function::hasFnAttribute(StringRef Kind) const { 747 return AttributeSets.hasFnAttr(Kind); 748 } 749 750 bool Function::hasRetAttribute(Attribute::AttrKind Kind) const { 751 return AttributeSets.hasRetAttr(Kind); 752 } 753 754 bool Function::hasParamAttribute(unsigned ArgNo, 755 Attribute::AttrKind Kind) const { 756 return AttributeSets.hasParamAttr(ArgNo, Kind); 757 } 758 759 Attribute Function::getAttributeAtIndex(unsigned i, 760 Attribute::AttrKind Kind) const { 761 return AttributeSets.getAttributeAtIndex(i, Kind); 762 } 763 764 Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const { 765 return AttributeSets.getAttributeAtIndex(i, Kind); 766 } 767 768 Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const { 769 return AttributeSets.getFnAttr(Kind); 770 } 771 772 Attribute Function::getFnAttribute(StringRef Kind) const { 773 return AttributeSets.getFnAttr(Kind); 774 } 775 776 Attribute Function::getRetAttribute(Attribute::AttrKind Kind) const { 777 return AttributeSets.getRetAttr(Kind); 778 } 779 780 uint64_t Function::getFnAttributeAsParsedInteger(StringRef Name, 781 uint64_t Default) const { 782 Attribute A = getFnAttribute(Name); 783 uint64_t Result = Default; 784 if (A.isStringAttribute()) { 785 StringRef Str = A.getValueAsString(); 786 if (Str.getAsInteger(0, Result)) 787 getContext().emitError("cannot parse integer attribute " + Name); 788 } 789 790 return Result; 791 } 792 793 /// gets the specified attribute from the list of attributes. 794 Attribute Function::getParamAttribute(unsigned ArgNo, 795 Attribute::AttrKind Kind) const { 796 return AttributeSets.getParamAttr(ArgNo, Kind); 797 } 798 799 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo, 800 uint64_t Bytes) { 801 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(), 802 ArgNo, Bytes); 803 } 804 805 void Function::addRangeRetAttr(const ConstantRange &CR) { 806 AttributeSets = AttributeSets.addRangeRetAttr(getContext(), CR); 807 } 808 809 DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const { 810 if (&FPType == &APFloat::IEEEsingle()) { 811 DenormalMode Mode = getDenormalModeF32Raw(); 812 // If the f32 variant of the attribute isn't specified, try to use the 813 // generic one. 814 if (Mode.isValid()) 815 return Mode; 816 } 817 818 return getDenormalModeRaw(); 819 } 820 821 DenormalMode Function::getDenormalModeRaw() const { 822 Attribute Attr = getFnAttribute("denormal-fp-math"); 823 StringRef Val = Attr.getValueAsString(); 824 return parseDenormalFPAttribute(Val); 825 } 826 827 DenormalMode Function::getDenormalModeF32Raw() const { 828 Attribute Attr = getFnAttribute("denormal-fp-math-f32"); 829 if (Attr.isValid()) { 830 StringRef Val = Attr.getValueAsString(); 831 return parseDenormalFPAttribute(Val); 832 } 833 834 return DenormalMode::getInvalid(); 835 } 836 837 const std::string &Function::getGC() const { 838 assert(hasGC() && "Function has no collector"); 839 return getContext().getGC(*this); 840 } 841 842 void Function::setGC(std::string Str) { 843 setValueSubclassDataBit(14, !Str.empty()); 844 getContext().setGC(*this, std::move(Str)); 845 } 846 847 void Function::clearGC() { 848 if (!hasGC()) 849 return; 850 getContext().deleteGC(*this); 851 setValueSubclassDataBit(14, false); 852 } 853 854 bool Function::hasStackProtectorFnAttr() const { 855 return hasFnAttribute(Attribute::StackProtect) || 856 hasFnAttribute(Attribute::StackProtectStrong) || 857 hasFnAttribute(Attribute::StackProtectReq); 858 } 859 860 /// Copy all additional attributes (those not needed to create a Function) from 861 /// the Function Src to this one. 862 void Function::copyAttributesFrom(const Function *Src) { 863 GlobalObject::copyAttributesFrom(Src); 864 setCallingConv(Src->getCallingConv()); 865 setAttributes(Src->getAttributes()); 866 if (Src->hasGC()) 867 setGC(Src->getGC()); 868 else 869 clearGC(); 870 if (Src->hasPersonalityFn()) 871 setPersonalityFn(Src->getPersonalityFn()); 872 if (Src->hasPrefixData()) 873 setPrefixData(Src->getPrefixData()); 874 if (Src->hasPrologueData()) 875 setPrologueData(Src->getPrologueData()); 876 } 877 878 MemoryEffects Function::getMemoryEffects() const { 879 return getAttributes().getMemoryEffects(); 880 } 881 void Function::setMemoryEffects(MemoryEffects ME) { 882 addFnAttr(Attribute::getWithMemoryEffects(getContext(), ME)); 883 } 884 885 /// Determine if the function does not access memory. 886 bool Function::doesNotAccessMemory() const { 887 return getMemoryEffects().doesNotAccessMemory(); 888 } 889 void Function::setDoesNotAccessMemory() { 890 setMemoryEffects(MemoryEffects::none()); 891 } 892 893 /// Determine if the function does not access or only reads memory. 894 bool Function::onlyReadsMemory() const { 895 return getMemoryEffects().onlyReadsMemory(); 896 } 897 void Function::setOnlyReadsMemory() { 898 setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly()); 899 } 900 901 /// Determine if the function does not access or only writes memory. 902 bool Function::onlyWritesMemory() const { 903 return getMemoryEffects().onlyWritesMemory(); 904 } 905 void Function::setOnlyWritesMemory() { 906 setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly()); 907 } 908 909 /// Determine if the call can access memmory only using pointers based 910 /// on its arguments. 911 bool Function::onlyAccessesArgMemory() const { 912 return getMemoryEffects().onlyAccessesArgPointees(); 913 } 914 void Function::setOnlyAccessesArgMemory() { 915 setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly()); 916 } 917 918 /// Determine if the function may only access memory that is 919 /// inaccessible from the IR. 920 bool Function::onlyAccessesInaccessibleMemory() const { 921 return getMemoryEffects().onlyAccessesInaccessibleMem(); 922 } 923 void Function::setOnlyAccessesInaccessibleMemory() { 924 setMemoryEffects(getMemoryEffects() & MemoryEffects::inaccessibleMemOnly()); 925 } 926 927 /// Determine if the function may only access memory that is 928 /// either inaccessible from the IR or pointed to by its arguments. 929 bool Function::onlyAccessesInaccessibleMemOrArgMem() const { 930 return getMemoryEffects().onlyAccessesInaccessibleOrArgMem(); 931 } 932 void Function::setOnlyAccessesInaccessibleMemOrArgMem() { 933 setMemoryEffects(getMemoryEffects() & 934 MemoryEffects::inaccessibleOrArgMemOnly()); 935 } 936 937 /// Table of string intrinsic names indexed by enum value. 938 static const char * const IntrinsicNameTable[] = { 939 "not_intrinsic", 940 #define GET_INTRINSIC_NAME_TABLE 941 #include "llvm/IR/IntrinsicImpl.inc" 942 #undef GET_INTRINSIC_NAME_TABLE 943 }; 944 945 /// Table of per-target intrinsic name tables. 946 #define GET_INTRINSIC_TARGET_DATA 947 #include "llvm/IR/IntrinsicImpl.inc" 948 #undef GET_INTRINSIC_TARGET_DATA 949 950 bool Function::isTargetIntrinsic(Intrinsic::ID IID) { 951 return IID > TargetInfos[0].Count; 952 } 953 954 bool Function::isTargetIntrinsic() const { 955 return isTargetIntrinsic(IntID); 956 } 957 958 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 959 /// target as \c Name, or the generic table if \c Name is not target specific. 960 /// 961 /// Returns the relevant slice of \c IntrinsicNameTable 962 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 963 assert(Name.starts_with("llvm.")); 964 965 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 966 // Drop "llvm." and take the first dotted component. That will be the target 967 // if this is target specific. 968 StringRef Target = Name.drop_front(5).split('.').first; 969 auto It = partition_point( 970 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; }); 971 // We've either found the target or just fall back to the generic set, which 972 // is always first. 973 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 974 return ArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 975 } 976 977 /// This does the actual lookup of an intrinsic ID which 978 /// matches the given function name. 979 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 980 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 981 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 982 if (Idx == -1) 983 return Intrinsic::not_intrinsic; 984 985 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 986 // an index into a sub-table. 987 int Adjust = NameTable.data() - IntrinsicNameTable; 988 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 989 990 // If the intrinsic is not overloaded, require an exact match. If it is 991 // overloaded, require either exact or prefix match. 992 const auto MatchSize = strlen(NameTable[Idx]); 993 assert(Name.size() >= MatchSize && "Expected either exact or prefix match"); 994 bool IsExactMatch = Name.size() == MatchSize; 995 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID 996 : Intrinsic::not_intrinsic; 997 } 998 999 void Function::updateAfterNameChange() { 1000 LibFuncCache = UnknownLibFunc; 1001 StringRef Name = getName(); 1002 if (!Name.starts_with("llvm.")) { 1003 HasLLVMReservedName = false; 1004 IntID = Intrinsic::not_intrinsic; 1005 return; 1006 } 1007 HasLLVMReservedName = true; 1008 IntID = lookupIntrinsicID(Name); 1009 } 1010 1011 /// Returns a stable mangling for the type specified for use in the name 1012 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 1013 /// of named types is simply their name. Manglings for unnamed types consist 1014 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 1015 /// combined with the mangling of their component types. A vararg function 1016 /// type will have a suffix of 'vararg'. Since function types can contain 1017 /// other function types, we close a function type mangling with suffix 'f' 1018 /// which can't be confused with it's prefix. This ensures we don't have 1019 /// collisions between two unrelated function types. Otherwise, you might 1020 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 1021 /// The HasUnnamedType boolean is set if an unnamed type was encountered, 1022 /// indicating that extra care must be taken to ensure a unique name. 1023 static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) { 1024 std::string Result; 1025 if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) { 1026 Result += "p" + utostr(PTyp->getAddressSpace()); 1027 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) { 1028 Result += "a" + utostr(ATyp->getNumElements()) + 1029 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType); 1030 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 1031 if (!STyp->isLiteral()) { 1032 Result += "s_"; 1033 if (STyp->hasName()) 1034 Result += STyp->getName(); 1035 else 1036 HasUnnamedType = true; 1037 } else { 1038 Result += "sl_"; 1039 for (auto *Elem : STyp->elements()) 1040 Result += getMangledTypeStr(Elem, HasUnnamedType); 1041 } 1042 // Ensure nested structs are distinguishable. 1043 Result += "s"; 1044 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 1045 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType); 1046 for (size_t i = 0; i < FT->getNumParams(); i++) 1047 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType); 1048 if (FT->isVarArg()) 1049 Result += "vararg"; 1050 // Ensure nested function types are distinguishable. 1051 Result += "f"; 1052 } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1053 ElementCount EC = VTy->getElementCount(); 1054 if (EC.isScalable()) 1055 Result += "nx"; 1056 Result += "v" + utostr(EC.getKnownMinValue()) + 1057 getMangledTypeStr(VTy->getElementType(), HasUnnamedType); 1058 } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) { 1059 Result += "t"; 1060 Result += TETy->getName(); 1061 for (Type *ParamTy : TETy->type_params()) 1062 Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType); 1063 for (unsigned IntParam : TETy->int_params()) 1064 Result += "_" + utostr(IntParam); 1065 // Ensure nested target extension types are distinguishable. 1066 Result += "t"; 1067 } else if (Ty) { 1068 switch (Ty->getTypeID()) { 1069 default: llvm_unreachable("Unhandled type"); 1070 case Type::VoidTyID: Result += "isVoid"; break; 1071 case Type::MetadataTyID: Result += "Metadata"; break; 1072 case Type::HalfTyID: Result += "f16"; break; 1073 case Type::BFloatTyID: Result += "bf16"; break; 1074 case Type::FloatTyID: Result += "f32"; break; 1075 case Type::DoubleTyID: Result += "f64"; break; 1076 case Type::X86_FP80TyID: Result += "f80"; break; 1077 case Type::FP128TyID: Result += "f128"; break; 1078 case Type::PPC_FP128TyID: 1079 Result += "ppcf128"; 1080 break; 1081 case Type::X86_AMXTyID: Result += "x86amx"; break; 1082 case Type::IntegerTyID: 1083 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 1084 break; 1085 } 1086 } 1087 return Result; 1088 } 1089 1090 StringRef Intrinsic::getBaseName(ID id) { 1091 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 1092 return IntrinsicNameTable[id]; 1093 } 1094 1095 StringRef Intrinsic::getName(ID id) { 1096 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 1097 assert(!Intrinsic::isOverloaded(id) && 1098 "This version of getName does not support overloading"); 1099 return getBaseName(id); 1100 } 1101 1102 static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys, 1103 Module *M, FunctionType *FT, 1104 bool EarlyModuleCheck) { 1105 1106 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!"); 1107 assert((Tys.empty() || Intrinsic::isOverloaded(Id)) && 1108 "This version of getName is for overloaded intrinsics only"); 1109 (void)EarlyModuleCheck; 1110 assert((!EarlyModuleCheck || M || 1111 !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) && 1112 "Intrinsic overloading on pointer types need to provide a Module"); 1113 bool HasUnnamedType = false; 1114 std::string Result(Intrinsic::getBaseName(Id)); 1115 for (Type *Ty : Tys) 1116 Result += "." + getMangledTypeStr(Ty, HasUnnamedType); 1117 if (HasUnnamedType) { 1118 assert(M && "unnamed types need a module"); 1119 if (!FT) 1120 FT = Intrinsic::getType(M->getContext(), Id, Tys); 1121 else 1122 assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) && 1123 "Provided FunctionType must match arguments"); 1124 return M->getUniqueIntrinsicName(Result, Id, FT); 1125 } 1126 return Result; 1127 } 1128 1129 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M, 1130 FunctionType *FT) { 1131 assert(M && "We need to have a Module"); 1132 return getIntrinsicNameImpl(Id, Tys, M, FT, true); 1133 } 1134 1135 std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) { 1136 return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false); 1137 } 1138 1139 /// IIT_Info - These are enumerators that describe the entries returned by the 1140 /// getIntrinsicInfoTableEntries function. 1141 /// 1142 /// Defined in Intrinsics.td. 1143 enum IIT_Info { 1144 #define GET_INTRINSIC_IITINFO 1145 #include "llvm/IR/IntrinsicImpl.inc" 1146 #undef GET_INTRINSIC_IITINFO 1147 }; 1148 1149 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 1150 IIT_Info LastInfo, 1151 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 1152 using namespace Intrinsic; 1153 1154 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC); 1155 1156 IIT_Info Info = IIT_Info(Infos[NextElt++]); 1157 unsigned StructElts = 2; 1158 1159 switch (Info) { 1160 case IIT_Done: 1161 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 1162 return; 1163 case IIT_VARARG: 1164 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 1165 return; 1166 case IIT_MMX: 1167 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 1168 return; 1169 case IIT_AMX: 1170 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0)); 1171 return; 1172 case IIT_TOKEN: 1173 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 1174 return; 1175 case IIT_METADATA: 1176 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 1177 return; 1178 case IIT_F16: 1179 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 1180 return; 1181 case IIT_BF16: 1182 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0)); 1183 return; 1184 case IIT_F32: 1185 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 1186 return; 1187 case IIT_F64: 1188 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 1189 return; 1190 case IIT_F128: 1191 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 1192 return; 1193 case IIT_PPCF128: 1194 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0)); 1195 return; 1196 case IIT_I1: 1197 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 1198 return; 1199 case IIT_I2: 1200 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2)); 1201 return; 1202 case IIT_I4: 1203 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4)); 1204 return; 1205 case IIT_AARCH64_SVCOUNT: 1206 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AArch64Svcount, 0)); 1207 return; 1208 case IIT_I8: 1209 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 1210 return; 1211 case IIT_I16: 1212 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 1213 return; 1214 case IIT_I32: 1215 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 1216 return; 1217 case IIT_I64: 1218 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 1219 return; 1220 case IIT_I128: 1221 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 1222 return; 1223 case IIT_V1: 1224 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector)); 1225 DecodeIITType(NextElt, Infos, Info, OutputTable); 1226 return; 1227 case IIT_V2: 1228 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector)); 1229 DecodeIITType(NextElt, Infos, Info, OutputTable); 1230 return; 1231 case IIT_V3: 1232 OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector)); 1233 DecodeIITType(NextElt, Infos, Info, OutputTable); 1234 return; 1235 case IIT_V4: 1236 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector)); 1237 DecodeIITType(NextElt, Infos, Info, OutputTable); 1238 return; 1239 case IIT_V6: 1240 OutputTable.push_back(IITDescriptor::getVector(6, IsScalableVector)); 1241 DecodeIITType(NextElt, Infos, Info, OutputTable); 1242 return; 1243 case IIT_V8: 1244 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector)); 1245 DecodeIITType(NextElt, Infos, Info, OutputTable); 1246 return; 1247 case IIT_V10: 1248 OutputTable.push_back(IITDescriptor::getVector(10, IsScalableVector)); 1249 DecodeIITType(NextElt, Infos, Info, OutputTable); 1250 return; 1251 case IIT_V16: 1252 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector)); 1253 DecodeIITType(NextElt, Infos, Info, OutputTable); 1254 return; 1255 case IIT_V32: 1256 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector)); 1257 DecodeIITType(NextElt, Infos, Info, OutputTable); 1258 return; 1259 case IIT_V64: 1260 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector)); 1261 DecodeIITType(NextElt, Infos, Info, OutputTable); 1262 return; 1263 case IIT_V128: 1264 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector)); 1265 DecodeIITType(NextElt, Infos, Info, OutputTable); 1266 return; 1267 case IIT_V256: 1268 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector)); 1269 DecodeIITType(NextElt, Infos, Info, OutputTable); 1270 return; 1271 case IIT_V512: 1272 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector)); 1273 DecodeIITType(NextElt, Infos, Info, OutputTable); 1274 return; 1275 case IIT_V1024: 1276 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector)); 1277 DecodeIITType(NextElt, Infos, Info, OutputTable); 1278 return; 1279 case IIT_EXTERNREF: 1280 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10)); 1281 return; 1282 case IIT_FUNCREF: 1283 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20)); 1284 return; 1285 case IIT_PTR: 1286 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 1287 return; 1288 case IIT_ANYPTR: // [ANYPTR addrspace] 1289 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 1290 Infos[NextElt++])); 1291 return; 1292 case IIT_ARG: { 1293 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1294 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 1295 return; 1296 } 1297 case IIT_EXTEND_ARG: { 1298 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1299 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 1300 ArgInfo)); 1301 return; 1302 } 1303 case IIT_TRUNC_ARG: { 1304 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1305 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 1306 ArgInfo)); 1307 return; 1308 } 1309 case IIT_HALF_VEC_ARG: { 1310 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1311 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 1312 ArgInfo)); 1313 return; 1314 } 1315 case IIT_SAME_VEC_WIDTH_ARG: { 1316 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1317 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 1318 ArgInfo)); 1319 return; 1320 } 1321 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 1322 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1323 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1324 OutputTable.push_back( 1325 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 1326 return; 1327 } 1328 case IIT_EMPTYSTRUCT: 1329 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 1330 return; 1331 case IIT_STRUCT9: ++StructElts; [[fallthrough]]; 1332 case IIT_STRUCT8: ++StructElts; [[fallthrough]]; 1333 case IIT_STRUCT7: ++StructElts; [[fallthrough]]; 1334 case IIT_STRUCT6: ++StructElts; [[fallthrough]]; 1335 case IIT_STRUCT5: ++StructElts; [[fallthrough]]; 1336 case IIT_STRUCT4: ++StructElts; [[fallthrough]]; 1337 case IIT_STRUCT3: ++StructElts; [[fallthrough]]; 1338 case IIT_STRUCT2: { 1339 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 1340 1341 for (unsigned i = 0; i != StructElts; ++i) 1342 DecodeIITType(NextElt, Infos, Info, OutputTable); 1343 return; 1344 } 1345 case IIT_SUBDIVIDE2_ARG: { 1346 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1347 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 1348 ArgInfo)); 1349 return; 1350 } 1351 case IIT_SUBDIVIDE4_ARG: { 1352 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1353 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 1354 ArgInfo)); 1355 return; 1356 } 1357 case IIT_VEC_ELEMENT: { 1358 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1359 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 1360 ArgInfo)); 1361 return; 1362 } 1363 case IIT_SCALABLE_VEC: { 1364 DecodeIITType(NextElt, Infos, Info, OutputTable); 1365 return; 1366 } 1367 case IIT_VEC_OF_BITCASTS_TO_INT: { 1368 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1369 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, 1370 ArgInfo)); 1371 return; 1372 } 1373 } 1374 llvm_unreachable("unhandled"); 1375 } 1376 1377 #define GET_INTRINSIC_GENERATOR_GLOBAL 1378 #include "llvm/IR/IntrinsicImpl.inc" 1379 #undef GET_INTRINSIC_GENERATOR_GLOBAL 1380 1381 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 1382 SmallVectorImpl<IITDescriptor> &T){ 1383 static_assert(sizeof(IIT_Table[0]) == 2, 1384 "Expect 16-bit entries in IIT_Table"); 1385 // Check to see if the intrinsic's type was expressible by the table. 1386 uint16_t TableVal = IIT_Table[id - 1]; 1387 1388 // Decode the TableVal into an array of IITValues. 1389 SmallVector<unsigned char> IITValues; 1390 ArrayRef<unsigned char> IITEntries; 1391 unsigned NextElt = 0; 1392 if (TableVal >> 15) { 1393 // This is an offset into the IIT_LongEncodingTable. 1394 IITEntries = IIT_LongEncodingTable; 1395 1396 // Strip sentinel bit. 1397 NextElt = TableVal & 0x7fff; 1398 } else { 1399 // If the entry was encoded into a single word in the table itself, decode 1400 // it from an array of nibbles to an array of bytes. 1401 do { 1402 IITValues.push_back(TableVal & 0xF); 1403 TableVal >>= 4; 1404 } while (TableVal); 1405 1406 IITEntries = IITValues; 1407 NextElt = 0; 1408 } 1409 1410 // Okay, decode the table into the output vector of IITDescriptors. 1411 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1412 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 1413 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1414 } 1415 1416 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 1417 ArrayRef<Type*> Tys, LLVMContext &Context) { 1418 using namespace Intrinsic; 1419 1420 IITDescriptor D = Infos.front(); 1421 Infos = Infos.slice(1); 1422 1423 switch (D.Kind) { 1424 case IITDescriptor::Void: return Type::getVoidTy(Context); 1425 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 1426 case IITDescriptor::MMX: 1427 return llvm::FixedVectorType::get(llvm::IntegerType::get(Context, 64), 1); 1428 case IITDescriptor::AMX: return Type::getX86_AMXTy(Context); 1429 case IITDescriptor::Token: return Type::getTokenTy(Context); 1430 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 1431 case IITDescriptor::Half: return Type::getHalfTy(Context); 1432 case IITDescriptor::BFloat: return Type::getBFloatTy(Context); 1433 case IITDescriptor::Float: return Type::getFloatTy(Context); 1434 case IITDescriptor::Double: return Type::getDoubleTy(Context); 1435 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 1436 case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context); 1437 case IITDescriptor::AArch64Svcount: 1438 return TargetExtType::get(Context, "aarch64.svcount"); 1439 1440 case IITDescriptor::Integer: 1441 return IntegerType::get(Context, D.Integer_Width); 1442 case IITDescriptor::Vector: 1443 return VectorType::get(DecodeFixedType(Infos, Tys, Context), 1444 D.Vector_Width); 1445 case IITDescriptor::Pointer: 1446 return PointerType::get(Context, D.Pointer_AddressSpace); 1447 case IITDescriptor::Struct: { 1448 SmallVector<Type *, 8> Elts; 1449 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1450 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 1451 return StructType::get(Context, Elts); 1452 } 1453 case IITDescriptor::Argument: 1454 return Tys[D.getArgumentNumber()]; 1455 case IITDescriptor::ExtendArgument: { 1456 Type *Ty = Tys[D.getArgumentNumber()]; 1457 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1458 return VectorType::getExtendedElementVectorType(VTy); 1459 1460 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 1461 } 1462 case IITDescriptor::TruncArgument: { 1463 Type *Ty = Tys[D.getArgumentNumber()]; 1464 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1465 return VectorType::getTruncatedElementVectorType(VTy); 1466 1467 IntegerType *ITy = cast<IntegerType>(Ty); 1468 assert(ITy->getBitWidth() % 2 == 0); 1469 return IntegerType::get(Context, ITy->getBitWidth() / 2); 1470 } 1471 case IITDescriptor::Subdivide2Argument: 1472 case IITDescriptor::Subdivide4Argument: { 1473 Type *Ty = Tys[D.getArgumentNumber()]; 1474 VectorType *VTy = dyn_cast<VectorType>(Ty); 1475 assert(VTy && "Expected an argument of Vector Type"); 1476 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1477 return VectorType::getSubdividedVectorType(VTy, SubDivs); 1478 } 1479 case IITDescriptor::HalfVecArgument: 1480 return VectorType::getHalfElementsVectorType(cast<VectorType>( 1481 Tys[D.getArgumentNumber()])); 1482 case IITDescriptor::SameVecWidthArgument: { 1483 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1484 Type *Ty = Tys[D.getArgumentNumber()]; 1485 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1486 return VectorType::get(EltTy, VTy->getElementCount()); 1487 return EltTy; 1488 } 1489 case IITDescriptor::VecElementArgument: { 1490 Type *Ty = Tys[D.getArgumentNumber()]; 1491 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1492 return VTy->getElementType(); 1493 llvm_unreachable("Expected an argument of Vector Type"); 1494 } 1495 case IITDescriptor::VecOfBitcastsToInt: { 1496 Type *Ty = Tys[D.getArgumentNumber()]; 1497 VectorType *VTy = dyn_cast<VectorType>(Ty); 1498 assert(VTy && "Expected an argument of Vector Type"); 1499 return VectorType::getInteger(VTy); 1500 } 1501 case IITDescriptor::VecOfAnyPtrsToElt: 1502 // Return the overloaded type (which determines the pointers address space) 1503 return Tys[D.getOverloadArgNumber()]; 1504 } 1505 llvm_unreachable("unhandled"); 1506 } 1507 1508 FunctionType *Intrinsic::getType(LLVMContext &Context, 1509 ID id, ArrayRef<Type*> Tys) { 1510 SmallVector<IITDescriptor, 8> Table; 1511 getIntrinsicInfoTableEntries(id, Table); 1512 1513 ArrayRef<IITDescriptor> TableRef = Table; 1514 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1515 1516 SmallVector<Type*, 8> ArgTys; 1517 while (!TableRef.empty()) 1518 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1519 1520 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1521 // If we see void type as the type of the last argument, it is vararg intrinsic 1522 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1523 ArgTys.pop_back(); 1524 return FunctionType::get(ResultTy, ArgTys, true); 1525 } 1526 return FunctionType::get(ResultTy, ArgTys, false); 1527 } 1528 1529 bool Intrinsic::isOverloaded(ID id) { 1530 #define GET_INTRINSIC_OVERLOAD_TABLE 1531 #include "llvm/IR/IntrinsicImpl.inc" 1532 #undef GET_INTRINSIC_OVERLOAD_TABLE 1533 } 1534 1535 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1536 #define GET_INTRINSIC_ATTRIBUTES 1537 #include "llvm/IR/IntrinsicImpl.inc" 1538 #undef GET_INTRINSIC_ATTRIBUTES 1539 1540 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1541 // There can never be multiple globals with the same name of different types, 1542 // because intrinsics must be a specific type. 1543 auto *FT = getType(M->getContext(), id, Tys); 1544 return cast<Function>( 1545 M->getOrInsertFunction( 1546 Tys.empty() ? getName(id) : getName(id, Tys, M, FT), FT) 1547 .getCallee()); 1548 } 1549 1550 // This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method. 1551 #define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN 1552 #include "llvm/IR/IntrinsicImpl.inc" 1553 #undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN 1554 1555 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1556 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1557 #include "llvm/IR/IntrinsicImpl.inc" 1558 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1559 1560 bool Intrinsic::isConstrainedFPIntrinsic(ID QID) { 1561 switch (QID) { 1562 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 1563 case Intrinsic::INTRINSIC: 1564 #include "llvm/IR/ConstrainedOps.def" 1565 #undef INSTRUCTION 1566 return true; 1567 default: 1568 return false; 1569 } 1570 } 1571 1572 bool Intrinsic::hasConstrainedFPRoundingModeOperand(Intrinsic::ID QID) { 1573 switch (QID) { 1574 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 1575 case Intrinsic::INTRINSIC: \ 1576 return ROUND_MODE == 1; 1577 #include "llvm/IR/ConstrainedOps.def" 1578 #undef INSTRUCTION 1579 default: 1580 return false; 1581 } 1582 } 1583 1584 using DeferredIntrinsicMatchPair = 1585 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1586 1587 static bool matchIntrinsicType( 1588 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1589 SmallVectorImpl<Type *> &ArgTys, 1590 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1591 bool IsDeferredCheck) { 1592 using namespace Intrinsic; 1593 1594 // If we ran out of descriptors, there are too many arguments. 1595 if (Infos.empty()) return true; 1596 1597 // Do this before slicing off the 'front' part 1598 auto InfosRef = Infos; 1599 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1600 DeferredChecks.emplace_back(T, InfosRef); 1601 return false; 1602 }; 1603 1604 IITDescriptor D = Infos.front(); 1605 Infos = Infos.slice(1); 1606 1607 switch (D.Kind) { 1608 case IITDescriptor::Void: return !Ty->isVoidTy(); 1609 case IITDescriptor::VarArg: return true; 1610 case IITDescriptor::MMX: { 1611 FixedVectorType *VT = dyn_cast<FixedVectorType>(Ty); 1612 return !VT || VT->getNumElements() != 1 || 1613 !VT->getElementType()->isIntegerTy(64); 1614 } 1615 case IITDescriptor::AMX: return !Ty->isX86_AMXTy(); 1616 case IITDescriptor::Token: return !Ty->isTokenTy(); 1617 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1618 case IITDescriptor::Half: return !Ty->isHalfTy(); 1619 case IITDescriptor::BFloat: return !Ty->isBFloatTy(); 1620 case IITDescriptor::Float: return !Ty->isFloatTy(); 1621 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1622 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1623 case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty(); 1624 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1625 case IITDescriptor::AArch64Svcount: 1626 return !isa<TargetExtType>(Ty) || 1627 cast<TargetExtType>(Ty)->getName() != "aarch64.svcount"; 1628 case IITDescriptor::Vector: { 1629 VectorType *VT = dyn_cast<VectorType>(Ty); 1630 return !VT || VT->getElementCount() != D.Vector_Width || 1631 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1632 DeferredChecks, IsDeferredCheck); 1633 } 1634 case IITDescriptor::Pointer: { 1635 PointerType *PT = dyn_cast<PointerType>(Ty); 1636 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace; 1637 } 1638 1639 case IITDescriptor::Struct: { 1640 StructType *ST = dyn_cast<StructType>(Ty); 1641 if (!ST || !ST->isLiteral() || ST->isPacked() || 1642 ST->getNumElements() != D.Struct_NumElements) 1643 return true; 1644 1645 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1646 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1647 DeferredChecks, IsDeferredCheck)) 1648 return true; 1649 return false; 1650 } 1651 1652 case IITDescriptor::Argument: 1653 // If this is the second occurrence of an argument, 1654 // verify that the later instance matches the previous instance. 1655 if (D.getArgumentNumber() < ArgTys.size()) 1656 return Ty != ArgTys[D.getArgumentNumber()]; 1657 1658 if (D.getArgumentNumber() > ArgTys.size() || 1659 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1660 return IsDeferredCheck || DeferCheck(Ty); 1661 1662 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1663 "Table consistency error"); 1664 ArgTys.push_back(Ty); 1665 1666 switch (D.getArgumentKind()) { 1667 case IITDescriptor::AK_Any: return false; // Success 1668 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1669 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1670 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1671 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1672 default: break; 1673 } 1674 llvm_unreachable("all argument kinds not covered"); 1675 1676 case IITDescriptor::ExtendArgument: { 1677 // If this is a forward reference, defer the check for later. 1678 if (D.getArgumentNumber() >= ArgTys.size()) 1679 return IsDeferredCheck || DeferCheck(Ty); 1680 1681 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1682 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1683 NewTy = VectorType::getExtendedElementVectorType(VTy); 1684 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1685 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1686 else 1687 return true; 1688 1689 return Ty != NewTy; 1690 } 1691 case IITDescriptor::TruncArgument: { 1692 // If this is a forward reference, defer the check for later. 1693 if (D.getArgumentNumber() >= ArgTys.size()) 1694 return IsDeferredCheck || DeferCheck(Ty); 1695 1696 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1697 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1698 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1699 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1700 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1701 else 1702 return true; 1703 1704 return Ty != NewTy; 1705 } 1706 case IITDescriptor::HalfVecArgument: 1707 // If this is a forward reference, defer the check for later. 1708 if (D.getArgumentNumber() >= ArgTys.size()) 1709 return IsDeferredCheck || DeferCheck(Ty); 1710 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1711 VectorType::getHalfElementsVectorType( 1712 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1713 case IITDescriptor::SameVecWidthArgument: { 1714 if (D.getArgumentNumber() >= ArgTys.size()) { 1715 // Defer check and subsequent check for the vector element type. 1716 Infos = Infos.slice(1); 1717 return IsDeferredCheck || DeferCheck(Ty); 1718 } 1719 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1720 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1721 // Both must be vectors of the same number of elements or neither. 1722 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1723 return true; 1724 Type *EltTy = Ty; 1725 if (ThisArgType) { 1726 if (ReferenceType->getElementCount() != 1727 ThisArgType->getElementCount()) 1728 return true; 1729 EltTy = ThisArgType->getElementType(); 1730 } 1731 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1732 IsDeferredCheck); 1733 } 1734 case IITDescriptor::VecOfAnyPtrsToElt: { 1735 unsigned RefArgNumber = D.getRefArgNumber(); 1736 if (RefArgNumber >= ArgTys.size()) { 1737 if (IsDeferredCheck) 1738 return true; 1739 // If forward referencing, already add the pointer-vector type and 1740 // defer the checks for later. 1741 ArgTys.push_back(Ty); 1742 return DeferCheck(Ty); 1743 } 1744 1745 if (!IsDeferredCheck){ 1746 assert(D.getOverloadArgNumber() == ArgTys.size() && 1747 "Table consistency error"); 1748 ArgTys.push_back(Ty); 1749 } 1750 1751 // Verify the overloaded type "matches" the Ref type. 1752 // i.e. Ty is a vector with the same width as Ref. 1753 // Composed of pointers to the same element type as Ref. 1754 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1755 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1756 if (!ThisArgVecTy || !ReferenceType || 1757 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount())) 1758 return true; 1759 return !ThisArgVecTy->getElementType()->isPointerTy(); 1760 } 1761 case IITDescriptor::VecElementArgument: { 1762 if (D.getArgumentNumber() >= ArgTys.size()) 1763 return IsDeferredCheck ? true : DeferCheck(Ty); 1764 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1765 return !ReferenceType || Ty != ReferenceType->getElementType(); 1766 } 1767 case IITDescriptor::Subdivide2Argument: 1768 case IITDescriptor::Subdivide4Argument: { 1769 // If this is a forward reference, defer the check for later. 1770 if (D.getArgumentNumber() >= ArgTys.size()) 1771 return IsDeferredCheck || DeferCheck(Ty); 1772 1773 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1774 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1775 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1776 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1777 return Ty != NewTy; 1778 } 1779 return true; 1780 } 1781 case IITDescriptor::VecOfBitcastsToInt: { 1782 if (D.getArgumentNumber() >= ArgTys.size()) 1783 return IsDeferredCheck || DeferCheck(Ty); 1784 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1785 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1786 if (!ThisArgVecTy || !ReferenceType) 1787 return true; 1788 return ThisArgVecTy != VectorType::getInteger(ReferenceType); 1789 } 1790 } 1791 llvm_unreachable("unhandled"); 1792 } 1793 1794 Intrinsic::MatchIntrinsicTypesResult 1795 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1796 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1797 SmallVectorImpl<Type *> &ArgTys) { 1798 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1799 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1800 false)) 1801 return MatchIntrinsicTypes_NoMatchRet; 1802 1803 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1804 1805 for (auto *Ty : FTy->params()) 1806 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1807 return MatchIntrinsicTypes_NoMatchArg; 1808 1809 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1810 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1811 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1812 true)) 1813 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1814 : MatchIntrinsicTypes_NoMatchArg; 1815 } 1816 1817 return MatchIntrinsicTypes_Match; 1818 } 1819 1820 bool 1821 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1822 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1823 // If there are no descriptors left, then it can't be a vararg. 1824 if (Infos.empty()) 1825 return isVarArg; 1826 1827 // There should be only one descriptor remaining at this point. 1828 if (Infos.size() != 1) 1829 return true; 1830 1831 // Check and verify the descriptor. 1832 IITDescriptor D = Infos.front(); 1833 Infos = Infos.slice(1); 1834 if (D.Kind == IITDescriptor::VarArg) 1835 return !isVarArg; 1836 1837 return true; 1838 } 1839 1840 bool Intrinsic::getIntrinsicSignature(Intrinsic::ID ID, FunctionType *FT, 1841 SmallVectorImpl<Type *> &ArgTys) { 1842 if (!ID) 1843 return false; 1844 1845 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1846 getIntrinsicInfoTableEntries(ID, Table); 1847 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1848 1849 if (Intrinsic::matchIntrinsicSignature(FT, TableRef, ArgTys) != 1850 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) { 1851 return false; 1852 } 1853 if (Intrinsic::matchIntrinsicVarArg(FT->isVarArg(), TableRef)) 1854 return false; 1855 return true; 1856 } 1857 1858 bool Intrinsic::getIntrinsicSignature(Function *F, 1859 SmallVectorImpl<Type *> &ArgTys) { 1860 return getIntrinsicSignature(F->getIntrinsicID(), F->getFunctionType(), 1861 ArgTys); 1862 } 1863 1864 std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) { 1865 SmallVector<Type *, 4> ArgTys; 1866 if (!getIntrinsicSignature(F, ArgTys)) 1867 return std::nullopt; 1868 1869 Intrinsic::ID ID = F->getIntrinsicID(); 1870 StringRef Name = F->getName(); 1871 std::string WantedName = 1872 Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType()); 1873 if (Name == WantedName) 1874 return std::nullopt; 1875 1876 Function *NewDecl = [&] { 1877 if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) { 1878 if (auto *ExistingF = dyn_cast<Function>(ExistingGV)) 1879 if (ExistingF->getFunctionType() == F->getFunctionType()) 1880 return ExistingF; 1881 1882 // The name already exists, but is not a function or has the wrong 1883 // prototype. Make place for the new one by renaming the old version. 1884 // Either this old version will be removed later on or the module is 1885 // invalid and we'll get an error. 1886 ExistingGV->setName(WantedName + ".renamed"); 1887 } 1888 return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1889 }(); 1890 1891 NewDecl->setCallingConv(F->getCallingConv()); 1892 assert(NewDecl->getFunctionType() == F->getFunctionType() && 1893 "Shouldn't change the signature"); 1894 return NewDecl; 1895 } 1896 1897 /// hasAddressTaken - returns true if there are any uses of this function 1898 /// other than direct calls or invokes to it. Optionally ignores callback 1899 /// uses, assume like pointer annotation calls, and references in llvm.used 1900 /// and llvm.compiler.used variables. 1901 bool Function::hasAddressTaken(const User **PutOffender, 1902 bool IgnoreCallbackUses, 1903 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed, 1904 bool IgnoreARCAttachedCall, 1905 bool IgnoreCastedDirectCall) const { 1906 for (const Use &U : uses()) { 1907 const User *FU = U.getUser(); 1908 if (isa<BlockAddress>(FU)) 1909 continue; 1910 1911 if (IgnoreCallbackUses) { 1912 AbstractCallSite ACS(&U); 1913 if (ACS && ACS.isCallbackCall()) 1914 continue; 1915 } 1916 1917 const auto *Call = dyn_cast<CallBase>(FU); 1918 if (!Call) { 1919 if (IgnoreAssumeLikeCalls && 1920 isa<BitCastOperator, AddrSpaceCastOperator>(FU) && 1921 all_of(FU->users(), [](const User *U) { 1922 if (const auto *I = dyn_cast<IntrinsicInst>(U)) 1923 return I->isAssumeLikeIntrinsic(); 1924 return false; 1925 })) { 1926 continue; 1927 } 1928 1929 if (IgnoreLLVMUsed && !FU->user_empty()) { 1930 const User *FUU = FU; 1931 if (isa<BitCastOperator, AddrSpaceCastOperator>(FU) && 1932 FU->hasOneUse() && !FU->user_begin()->user_empty()) 1933 FUU = *FU->user_begin(); 1934 if (llvm::all_of(FUU->users(), [](const User *U) { 1935 if (const auto *GV = dyn_cast<GlobalVariable>(U)) 1936 return GV->hasName() && 1937 (GV->getName() == "llvm.compiler.used" || 1938 GV->getName() == "llvm.used"); 1939 return false; 1940 })) 1941 continue; 1942 } 1943 if (PutOffender) 1944 *PutOffender = FU; 1945 return true; 1946 } 1947 1948 if (IgnoreAssumeLikeCalls) { 1949 if (const auto *I = dyn_cast<IntrinsicInst>(Call)) 1950 if (I->isAssumeLikeIntrinsic()) 1951 continue; 1952 } 1953 1954 if (!Call->isCallee(&U) || (!IgnoreCastedDirectCall && 1955 Call->getFunctionType() != getFunctionType())) { 1956 if (IgnoreARCAttachedCall && 1957 Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall, 1958 U.getOperandNo())) 1959 continue; 1960 1961 if (PutOffender) 1962 *PutOffender = FU; 1963 return true; 1964 } 1965 } 1966 return false; 1967 } 1968 1969 bool Function::isDefTriviallyDead() const { 1970 // Check the linkage 1971 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1972 !hasAvailableExternallyLinkage()) 1973 return false; 1974 1975 // Check if the function is used by anything other than a blockaddress. 1976 for (const User *U : users()) 1977 if (!isa<BlockAddress>(U)) 1978 return false; 1979 1980 return true; 1981 } 1982 1983 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1984 /// setjmp or other function that gcc recognizes as "returning twice". 1985 bool Function::callsFunctionThatReturnsTwice() const { 1986 for (const Instruction &I : instructions(this)) 1987 if (const auto *Call = dyn_cast<CallBase>(&I)) 1988 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1989 return true; 1990 1991 return false; 1992 } 1993 1994 Constant *Function::getPersonalityFn() const { 1995 assert(hasPersonalityFn() && getNumOperands()); 1996 return cast<Constant>(Op<0>()); 1997 } 1998 1999 void Function::setPersonalityFn(Constant *Fn) { 2000 setHungoffOperand<0>(Fn); 2001 setValueSubclassDataBit(3, Fn != nullptr); 2002 } 2003 2004 Constant *Function::getPrefixData() const { 2005 assert(hasPrefixData() && getNumOperands()); 2006 return cast<Constant>(Op<1>()); 2007 } 2008 2009 void Function::setPrefixData(Constant *PrefixData) { 2010 setHungoffOperand<1>(PrefixData); 2011 setValueSubclassDataBit(1, PrefixData != nullptr); 2012 } 2013 2014 Constant *Function::getPrologueData() const { 2015 assert(hasPrologueData() && getNumOperands()); 2016 return cast<Constant>(Op<2>()); 2017 } 2018 2019 void Function::setPrologueData(Constant *PrologueData) { 2020 setHungoffOperand<2>(PrologueData); 2021 setValueSubclassDataBit(2, PrologueData != nullptr); 2022 } 2023 2024 void Function::allocHungoffUselist() { 2025 // If we've already allocated a uselist, stop here. 2026 if (getNumOperands()) 2027 return; 2028 2029 allocHungoffUses(3, /*IsPhi=*/ false); 2030 setNumHungOffUseOperands(3); 2031 2032 // Initialize the uselist with placeholder operands to allow traversal. 2033 auto *CPN = ConstantPointerNull::get(PointerType::get(getContext(), 0)); 2034 Op<0>().set(CPN); 2035 Op<1>().set(CPN); 2036 Op<2>().set(CPN); 2037 } 2038 2039 template <int Idx> 2040 void Function::setHungoffOperand(Constant *C) { 2041 if (C) { 2042 allocHungoffUselist(); 2043 Op<Idx>().set(C); 2044 } else if (getNumOperands()) { 2045 Op<Idx>().set(ConstantPointerNull::get(PointerType::get(getContext(), 0))); 2046 } 2047 } 2048 2049 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 2050 assert(Bit < 16 && "SubclassData contains only 16 bits"); 2051 if (On) 2052 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 2053 else 2054 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 2055 } 2056 2057 void Function::setEntryCount(ProfileCount Count, 2058 const DenseSet<GlobalValue::GUID> *S) { 2059 #if !defined(NDEBUG) 2060 auto PrevCount = getEntryCount(); 2061 assert(!PrevCount || PrevCount->getType() == Count.getType()); 2062 #endif 2063 2064 auto ImportGUIDs = getImportGUIDs(); 2065 if (S == nullptr && ImportGUIDs.size()) 2066 S = &ImportGUIDs; 2067 2068 MDBuilder MDB(getContext()); 2069 setMetadata( 2070 LLVMContext::MD_prof, 2071 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 2072 } 2073 2074 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 2075 const DenseSet<GlobalValue::GUID> *Imports) { 2076 setEntryCount(ProfileCount(Count, Type), Imports); 2077 } 2078 2079 std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const { 2080 MDNode *MD = getMetadata(LLVMContext::MD_prof); 2081 if (MD && MD->getOperand(0)) 2082 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 2083 if (MDS->getString() == "function_entry_count") { 2084 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 2085 uint64_t Count = CI->getValue().getZExtValue(); 2086 // A value of -1 is used for SamplePGO when there were no samples. 2087 // Treat this the same as unknown. 2088 if (Count == (uint64_t)-1) 2089 return std::nullopt; 2090 return ProfileCount(Count, PCT_Real); 2091 } else if (AllowSynthetic && 2092 MDS->getString() == "synthetic_function_entry_count") { 2093 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 2094 uint64_t Count = CI->getValue().getZExtValue(); 2095 return ProfileCount(Count, PCT_Synthetic); 2096 } 2097 } 2098 return std::nullopt; 2099 } 2100 2101 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 2102 DenseSet<GlobalValue::GUID> R; 2103 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 2104 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 2105 if (MDS->getString() == "function_entry_count") 2106 for (unsigned i = 2; i < MD->getNumOperands(); i++) 2107 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 2108 ->getValue() 2109 .getZExtValue()); 2110 return R; 2111 } 2112 2113 void Function::setSectionPrefix(StringRef Prefix) { 2114 MDBuilder MDB(getContext()); 2115 setMetadata(LLVMContext::MD_section_prefix, 2116 MDB.createFunctionSectionPrefix(Prefix)); 2117 } 2118 2119 std::optional<StringRef> Function::getSectionPrefix() const { 2120 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 2121 assert(cast<MDString>(MD->getOperand(0))->getString() == 2122 "function_section_prefix" && 2123 "Metadata not match"); 2124 return cast<MDString>(MD->getOperand(1))->getString(); 2125 } 2126 return std::nullopt; 2127 } 2128 2129 bool Function::nullPointerIsDefined() const { 2130 return hasFnAttribute(Attribute::NullPointerIsValid); 2131 } 2132 2133 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 2134 if (F && F->nullPointerIsDefined()) 2135 return true; 2136 2137 if (AS != 0) 2138 return true; 2139 2140 return false; 2141 } 2142