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