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