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