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/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/IntrinsicsAArch64.h" 37 #include "llvm/IR/IntrinsicsAMDGPU.h" 38 #include "llvm/IR/IntrinsicsARM.h" 39 #include "llvm/IR/IntrinsicsBPF.h" 40 #include "llvm/IR/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 <algorithm> 67 #include <cassert> 68 #include <cstddef> 69 #include <cstdint> 70 #include <cstring> 71 #include <string> 72 73 using namespace llvm; 74 using ProfileCount = Function::ProfileCount; 75 76 // Explicit instantiations of SymbolTableListTraits since some of the methods 77 // are not in the public header file... 78 template class llvm::SymbolTableListTraits<BasicBlock>; 79 80 static cl::opt<unsigned> NonGlobalValueMaxNameSize( 81 "non-global-value-max-name-size", cl::Hidden, cl::init(1024), 82 cl::desc("Maximum size for the name of non-global values.")); 83 84 //===----------------------------------------------------------------------===// 85 // Argument Implementation 86 //===----------------------------------------------------------------------===// 87 88 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) 89 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { 90 setName(Name); 91 } 92 93 void Argument::setParent(Function *parent) { 94 Parent = parent; 95 } 96 97 bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const { 98 if (!getType()->isPointerTy()) return false; 99 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) && 100 (AllowUndefOrPoison || 101 getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef))) 102 return true; 103 else if (getDereferenceableBytes() > 0 && 104 !NullPointerIsDefined(getParent(), 105 getType()->getPointerAddressSpace())) 106 return true; 107 return false; 108 } 109 110 bool Argument::hasByValAttr() const { 111 if (!getType()->isPointerTy()) return false; 112 return hasAttribute(Attribute::ByVal); 113 } 114 115 bool Argument::hasByRefAttr() const { 116 if (!getType()->isPointerTy()) 117 return false; 118 return hasAttribute(Attribute::ByRef); 119 } 120 121 bool Argument::hasSwiftSelfAttr() const { 122 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf); 123 } 124 125 bool Argument::hasSwiftErrorAttr() const { 126 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError); 127 } 128 129 bool Argument::hasInAllocaAttr() const { 130 if (!getType()->isPointerTy()) return false; 131 return hasAttribute(Attribute::InAlloca); 132 } 133 134 bool Argument::hasPreallocatedAttr() const { 135 if (!getType()->isPointerTy()) 136 return false; 137 return hasAttribute(Attribute::Preallocated); 138 } 139 140 bool Argument::hasPassPointeeByValueCopyAttr() const { 141 if (!getType()->isPointerTy()) return false; 142 AttributeList Attrs = getParent()->getAttributes(); 143 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) || 144 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) || 145 Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated); 146 } 147 148 bool Argument::hasPointeeInMemoryValueAttr() const { 149 if (!getType()->isPointerTy()) 150 return false; 151 AttributeList Attrs = getParent()->getAttributes(); 152 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) || 153 Attrs.hasParamAttribute(getArgNo(), Attribute::StructRet) || 154 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) || 155 Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated) || 156 Attrs.hasParamAttribute(getArgNo(), Attribute::ByRef); 157 } 158 159 /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory 160 /// parameter type. 161 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs, Type *ArgTy) { 162 // FIXME: All the type carrying attributes are mutually exclusive, so there 163 // should be a single query to get the stored type that handles any of them. 164 if (Type *ByValTy = ParamAttrs.getByValType()) 165 return ByValTy; 166 if (Type *ByRefTy = ParamAttrs.getByRefType()) 167 return ByRefTy; 168 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType()) 169 return PreAllocTy; 170 if (Type *InAllocaTy = ParamAttrs.getInAllocaType()) 171 return InAllocaTy; 172 if (Type *SRetTy = ParamAttrs.getStructRetType()) 173 return SRetTy; 174 175 return nullptr; 176 } 177 178 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const { 179 AttributeSet ParamAttrs = 180 getParent()->getAttributes().getParamAttributes(getArgNo()); 181 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs, getType())) 182 return DL.getTypeAllocSize(MemTy); 183 return 0; 184 } 185 186 Type *Argument::getPointeeInMemoryValueType() const { 187 AttributeSet ParamAttrs = 188 getParent()->getAttributes().getParamAttributes(getArgNo()); 189 return getMemoryParamAllocType(ParamAttrs, getType()); 190 } 191 192 unsigned Argument::getParamAlignment() const { 193 assert(getType()->isPointerTy() && "Only pointers have alignments"); 194 return getParent()->getParamAlignment(getArgNo()); 195 } 196 197 MaybeAlign Argument::getParamAlign() const { 198 assert(getType()->isPointerTy() && "Only pointers have alignments"); 199 return getParent()->getParamAlign(getArgNo()); 200 } 201 202 MaybeAlign Argument::getParamStackAlign() const { 203 return getParent()->getParamStackAlign(getArgNo()); 204 } 205 206 Type *Argument::getParamByValType() const { 207 assert(getType()->isPointerTy() && "Only pointers have byval types"); 208 return getParent()->getParamByValType(getArgNo()); 209 } 210 211 Type *Argument::getParamStructRetType() const { 212 assert(getType()->isPointerTy() && "Only pointers have sret types"); 213 return getParent()->getParamStructRetType(getArgNo()); 214 } 215 216 Type *Argument::getParamByRefType() const { 217 assert(getType()->isPointerTy() && "Only pointers have byref types"); 218 return getParent()->getParamByRefType(getArgNo()); 219 } 220 221 Type *Argument::getParamInAllocaType() const { 222 assert(getType()->isPointerTy() && "Only pointers have inalloca types"); 223 return getParent()->getParamInAllocaType(getArgNo()); 224 } 225 226 uint64_t Argument::getDereferenceableBytes() const { 227 assert(getType()->isPointerTy() && 228 "Only pointers have dereferenceable bytes"); 229 return getParent()->getParamDereferenceableBytes(getArgNo()); 230 } 231 232 uint64_t Argument::getDereferenceableOrNullBytes() const { 233 assert(getType()->isPointerTy() && 234 "Only pointers have dereferenceable bytes"); 235 return getParent()->getParamDereferenceableOrNullBytes(getArgNo()); 236 } 237 238 bool Argument::hasNestAttr() const { 239 if (!getType()->isPointerTy()) return false; 240 return hasAttribute(Attribute::Nest); 241 } 242 243 bool Argument::hasNoAliasAttr() const { 244 if (!getType()->isPointerTy()) return false; 245 return hasAttribute(Attribute::NoAlias); 246 } 247 248 bool Argument::hasNoCaptureAttr() const { 249 if (!getType()->isPointerTy()) return false; 250 return hasAttribute(Attribute::NoCapture); 251 } 252 253 bool Argument::hasNoFreeAttr() const { 254 if (!getType()->isPointerTy()) return false; 255 return hasAttribute(Attribute::NoFree); 256 } 257 258 bool Argument::hasStructRetAttr() const { 259 if (!getType()->isPointerTy()) return false; 260 return hasAttribute(Attribute::StructRet); 261 } 262 263 bool Argument::hasInRegAttr() const { 264 return hasAttribute(Attribute::InReg); 265 } 266 267 bool Argument::hasReturnedAttr() const { 268 return hasAttribute(Attribute::Returned); 269 } 270 271 bool Argument::hasZExtAttr() const { 272 return hasAttribute(Attribute::ZExt); 273 } 274 275 bool Argument::hasSExtAttr() const { 276 return hasAttribute(Attribute::SExt); 277 } 278 279 bool Argument::onlyReadsMemory() const { 280 AttributeList Attrs = getParent()->getAttributes(); 281 return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) || 282 Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone); 283 } 284 285 void Argument::addAttrs(AttrBuilder &B) { 286 AttributeList AL = getParent()->getAttributes(); 287 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B); 288 getParent()->setAttributes(AL); 289 } 290 291 void Argument::addAttr(Attribute::AttrKind Kind) { 292 getParent()->addParamAttr(getArgNo(), Kind); 293 } 294 295 void Argument::addAttr(Attribute Attr) { 296 getParent()->addParamAttr(getArgNo(), Attr); 297 } 298 299 void Argument::removeAttr(Attribute::AttrKind Kind) { 300 getParent()->removeParamAttr(getArgNo(), Kind); 301 } 302 303 void Argument::removeAttrs(const AttrBuilder &B) { 304 AttributeList AL = getParent()->getAttributes(); 305 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), B); 306 getParent()->setAttributes(AL); 307 } 308 309 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 310 return getParent()->hasParamAttribute(getArgNo(), Kind); 311 } 312 313 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const { 314 return getParent()->getParamAttribute(getArgNo(), Kind); 315 } 316 317 //===----------------------------------------------------------------------===// 318 // Helper Methods in Function 319 //===----------------------------------------------------------------------===// 320 321 LLVMContext &Function::getContext() const { 322 return getType()->getContext(); 323 } 324 325 unsigned Function::getInstructionCount() const { 326 unsigned NumInstrs = 0; 327 for (const BasicBlock &BB : BasicBlocks) 328 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(), 329 BB.instructionsWithoutDebug().end()); 330 return NumInstrs; 331 } 332 333 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage, 334 const Twine &N, Module &M) { 335 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M); 336 } 337 338 Function *Function::createWithDefaultAttr(FunctionType *Ty, 339 LinkageTypes Linkage, 340 unsigned AddrSpace, const Twine &N, 341 Module *M) { 342 auto *F = new Function(Ty, Linkage, AddrSpace, N, M); 343 AttrBuilder B; 344 if (M->getUwtable()) 345 B.addAttribute(Attribute::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->addAttributes(AttributeList::FunctionIndex, 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::addAttribute(unsigned i, Attribute::AttrKind Kind) { 533 AttributeList PAL = getAttributes(); 534 PAL = PAL.addAttribute(getContext(), i, Kind); 535 setAttributes(PAL); 536 } 537 538 void Function::addAttribute(unsigned i, Attribute Attr) { 539 AttributeList PAL = getAttributes(); 540 PAL = PAL.addAttribute(getContext(), i, Attr); 541 setAttributes(PAL); 542 } 543 544 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) { 545 AttributeList PAL = getAttributes(); 546 PAL = PAL.addAttributes(getContext(), i, Attrs); 547 setAttributes(PAL); 548 } 549 550 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 551 AttributeList PAL = getAttributes(); 552 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind); 553 setAttributes(PAL); 554 } 555 556 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) { 557 AttributeList PAL = getAttributes(); 558 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr); 559 setAttributes(PAL); 560 } 561 562 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 563 AttributeList PAL = getAttributes(); 564 PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs); 565 setAttributes(PAL); 566 } 567 568 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) { 569 AttributeList PAL = getAttributes(); 570 PAL = PAL.removeAttribute(getContext(), i, Kind); 571 setAttributes(PAL); 572 } 573 574 void Function::removeAttribute(unsigned i, StringRef Kind) { 575 AttributeList PAL = getAttributes(); 576 PAL = PAL.removeAttribute(getContext(), i, Kind); 577 setAttributes(PAL); 578 } 579 580 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) { 581 AttributeList PAL = getAttributes(); 582 PAL = PAL.removeAttributes(getContext(), i, Attrs); 583 setAttributes(PAL); 584 } 585 586 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 587 AttributeList PAL = getAttributes(); 588 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 589 setAttributes(PAL); 590 } 591 592 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) { 593 AttributeList PAL = getAttributes(); 594 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 595 setAttributes(PAL); 596 } 597 598 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 599 AttributeList PAL = getAttributes(); 600 PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs); 601 setAttributes(PAL); 602 } 603 604 void Function::removeParamUndefImplyingAttrs(unsigned ArgNo) { 605 AttributeList PAL = getAttributes(); 606 PAL = PAL.removeParamUndefImplyingAttributes(getContext(), ArgNo); 607 setAttributes(PAL); 608 } 609 610 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 611 AttributeList PAL = getAttributes(); 612 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 613 setAttributes(PAL); 614 } 615 616 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) { 617 AttributeList PAL = getAttributes(); 618 PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes); 619 setAttributes(PAL); 620 } 621 622 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 623 AttributeList PAL = getAttributes(); 624 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 625 setAttributes(PAL); 626 } 627 628 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo, 629 uint64_t Bytes) { 630 AttributeList PAL = getAttributes(); 631 PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes); 632 setAttributes(PAL); 633 } 634 635 DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const { 636 if (&FPType == &APFloat::IEEEsingle()) { 637 Attribute Attr = getFnAttribute("denormal-fp-math-f32"); 638 StringRef Val = Attr.getValueAsString(); 639 if (!Val.empty()) 640 return parseDenormalFPAttribute(Val); 641 642 // If the f32 variant of the attribute isn't specified, try to use the 643 // generic one. 644 } 645 646 Attribute Attr = getFnAttribute("denormal-fp-math"); 647 return parseDenormalFPAttribute(Attr.getValueAsString()); 648 } 649 650 const std::string &Function::getGC() const { 651 assert(hasGC() && "Function has no collector"); 652 return getContext().getGC(*this); 653 } 654 655 void Function::setGC(std::string Str) { 656 setValueSubclassDataBit(14, !Str.empty()); 657 getContext().setGC(*this, std::move(Str)); 658 } 659 660 void Function::clearGC() { 661 if (!hasGC()) 662 return; 663 getContext().deleteGC(*this); 664 setValueSubclassDataBit(14, false); 665 } 666 667 bool Function::hasStackProtectorFnAttr() const { 668 return hasFnAttribute(Attribute::StackProtect) || 669 hasFnAttribute(Attribute::StackProtectStrong) || 670 hasFnAttribute(Attribute::StackProtectReq); 671 } 672 673 /// Copy all additional attributes (those not needed to create a Function) from 674 /// the Function Src to this one. 675 void Function::copyAttributesFrom(const Function *Src) { 676 GlobalObject::copyAttributesFrom(Src); 677 setCallingConv(Src->getCallingConv()); 678 setAttributes(Src->getAttributes()); 679 if (Src->hasGC()) 680 setGC(Src->getGC()); 681 else 682 clearGC(); 683 if (Src->hasPersonalityFn()) 684 setPersonalityFn(Src->getPersonalityFn()); 685 if (Src->hasPrefixData()) 686 setPrefixData(Src->getPrefixData()); 687 if (Src->hasPrologueData()) 688 setPrologueData(Src->getPrologueData()); 689 } 690 691 /// Table of string intrinsic names indexed by enum value. 692 static const char * const IntrinsicNameTable[] = { 693 "not_intrinsic", 694 #define GET_INTRINSIC_NAME_TABLE 695 #include "llvm/IR/IntrinsicImpl.inc" 696 #undef GET_INTRINSIC_NAME_TABLE 697 }; 698 699 /// Table of per-target intrinsic name tables. 700 #define GET_INTRINSIC_TARGET_DATA 701 #include "llvm/IR/IntrinsicImpl.inc" 702 #undef GET_INTRINSIC_TARGET_DATA 703 704 bool Function::isTargetIntrinsic(Intrinsic::ID IID) { 705 return IID > TargetInfos[0].Count; 706 } 707 708 bool Function::isTargetIntrinsic() const { 709 return isTargetIntrinsic(IntID); 710 } 711 712 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 713 /// target as \c Name, or the generic table if \c Name is not target specific. 714 /// 715 /// Returns the relevant slice of \c IntrinsicNameTable 716 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 717 assert(Name.startswith("llvm.")); 718 719 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 720 // Drop "llvm." and take the first dotted component. That will be the target 721 // if this is target specific. 722 StringRef Target = Name.drop_front(5).split('.').first; 723 auto It = partition_point( 724 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; }); 725 // We've either found the target or just fall back to the generic set, which 726 // is always first. 727 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 728 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 729 } 730 731 /// This does the actual lookup of an intrinsic ID which 732 /// matches the given function name. 733 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 734 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 735 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 736 if (Idx == -1) 737 return Intrinsic::not_intrinsic; 738 739 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 740 // an index into a sub-table. 741 int Adjust = NameTable.data() - IntrinsicNameTable; 742 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 743 744 // If the intrinsic is not overloaded, require an exact match. If it is 745 // overloaded, require either exact or prefix match. 746 const auto MatchSize = strlen(NameTable[Idx]); 747 assert(Name.size() >= MatchSize && "Expected either exact or prefix match"); 748 bool IsExactMatch = Name.size() == MatchSize; 749 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID 750 : Intrinsic::not_intrinsic; 751 } 752 753 void Function::recalculateIntrinsicID() { 754 StringRef Name = getName(); 755 if (!Name.startswith("llvm.")) { 756 HasLLVMReservedName = false; 757 IntID = Intrinsic::not_intrinsic; 758 return; 759 } 760 HasLLVMReservedName = true; 761 IntID = lookupIntrinsicID(Name); 762 } 763 764 /// Returns a stable mangling for the type specified for use in the name 765 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 766 /// of named types is simply their name. Manglings for unnamed types consist 767 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 768 /// combined with the mangling of their component types. A vararg function 769 /// type will have a suffix of 'vararg'. Since function types can contain 770 /// other function types, we close a function type mangling with suffix 'f' 771 /// which can't be confused with it's prefix. This ensures we don't have 772 /// collisions between two unrelated function types. Otherwise, you might 773 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 774 /// The HasUnnamedType boolean is set if an unnamed type was encountered, 775 /// indicating that extra care must be taken to ensure a unique name. 776 static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) { 777 std::string Result; 778 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 779 Result += "p" + utostr(PTyp->getAddressSpace()) + 780 getMangledTypeStr(PTyp->getElementType(), HasUnnamedType); 781 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 782 Result += "a" + utostr(ATyp->getNumElements()) + 783 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType); 784 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 785 if (!STyp->isLiteral()) { 786 Result += "s_"; 787 if (STyp->hasName()) 788 Result += STyp->getName(); 789 else 790 HasUnnamedType = true; 791 } else { 792 Result += "sl_"; 793 for (auto Elem : STyp->elements()) 794 Result += getMangledTypeStr(Elem, HasUnnamedType); 795 } 796 // Ensure nested structs are distinguishable. 797 Result += "s"; 798 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 799 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType); 800 for (size_t i = 0; i < FT->getNumParams(); i++) 801 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType); 802 if (FT->isVarArg()) 803 Result += "vararg"; 804 // Ensure nested function types are distinguishable. 805 Result += "f"; 806 } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) { 807 ElementCount EC = VTy->getElementCount(); 808 if (EC.isScalable()) 809 Result += "nx"; 810 Result += "v" + utostr(EC.getKnownMinValue()) + 811 getMangledTypeStr(VTy->getElementType(), HasUnnamedType); 812 } else if (Ty) { 813 switch (Ty->getTypeID()) { 814 default: llvm_unreachable("Unhandled type"); 815 case Type::VoidTyID: Result += "isVoid"; break; 816 case Type::MetadataTyID: Result += "Metadata"; break; 817 case Type::HalfTyID: Result += "f16"; break; 818 case Type::BFloatTyID: Result += "bf16"; break; 819 case Type::FloatTyID: Result += "f32"; break; 820 case Type::DoubleTyID: Result += "f64"; break; 821 case Type::X86_FP80TyID: Result += "f80"; break; 822 case Type::FP128TyID: Result += "f128"; break; 823 case Type::PPC_FP128TyID: Result += "ppcf128"; break; 824 case Type::X86_MMXTyID: Result += "x86mmx"; break; 825 case Type::X86_AMXTyID: Result += "x86amx"; break; 826 case Type::IntegerTyID: 827 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 828 break; 829 } 830 } 831 return Result; 832 } 833 834 StringRef Intrinsic::getBaseName(ID id) { 835 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 836 return IntrinsicNameTable[id]; 837 } 838 839 StringRef Intrinsic::getName(ID id) { 840 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 841 assert(!Intrinsic::isOverloaded(id) && 842 "This version of getName does not support overloading"); 843 return getBaseName(id); 844 } 845 846 static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys, 847 Module *M, FunctionType *FT, 848 bool EarlyModuleCheck) { 849 850 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!"); 851 assert((Tys.empty() || Intrinsic::isOverloaded(Id)) && 852 "This version of getName is for overloaded intrinsics only"); 853 (void)EarlyModuleCheck; 854 assert((!EarlyModuleCheck || M || 855 !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) && 856 "Intrinsic overloading on pointer types need to provide a Module"); 857 bool HasUnnamedType = false; 858 std::string Result(Intrinsic::getBaseName(Id)); 859 for (Type *Ty : Tys) 860 Result += "." + getMangledTypeStr(Ty, HasUnnamedType); 861 if (HasUnnamedType) { 862 assert(M && "unnamed types need a module"); 863 if (!FT) 864 FT = Intrinsic::getType(M->getContext(), Id, Tys); 865 else 866 assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) && 867 "Provided FunctionType must match arguments"); 868 return M->getUniqueIntrinsicName(Result, Id, FT); 869 } 870 return Result; 871 } 872 873 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M, 874 FunctionType *FT) { 875 assert(M && "We need to have a Module"); 876 return getIntrinsicNameImpl(Id, Tys, M, FT, true); 877 } 878 879 std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) { 880 return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false); 881 } 882 883 /// IIT_Info - These are enumerators that describe the entries returned by the 884 /// getIntrinsicInfoTableEntries function. 885 /// 886 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 887 enum IIT_Info { 888 // Common values should be encoded with 0-15. 889 IIT_Done = 0, 890 IIT_I1 = 1, 891 IIT_I8 = 2, 892 IIT_I16 = 3, 893 IIT_I32 = 4, 894 IIT_I64 = 5, 895 IIT_F16 = 6, 896 IIT_F32 = 7, 897 IIT_F64 = 8, 898 IIT_V2 = 9, 899 IIT_V4 = 10, 900 IIT_V8 = 11, 901 IIT_V16 = 12, 902 IIT_V32 = 13, 903 IIT_PTR = 14, 904 IIT_ARG = 15, 905 906 // Values from 16+ are only encodable with the inefficient encoding. 907 IIT_V64 = 16, 908 IIT_MMX = 17, 909 IIT_TOKEN = 18, 910 IIT_METADATA = 19, 911 IIT_EMPTYSTRUCT = 20, 912 IIT_STRUCT2 = 21, 913 IIT_STRUCT3 = 22, 914 IIT_STRUCT4 = 23, 915 IIT_STRUCT5 = 24, 916 IIT_EXTEND_ARG = 25, 917 IIT_TRUNC_ARG = 26, 918 IIT_ANYPTR = 27, 919 IIT_V1 = 28, 920 IIT_VARARG = 29, 921 IIT_HALF_VEC_ARG = 30, 922 IIT_SAME_VEC_WIDTH_ARG = 31, 923 IIT_PTR_TO_ARG = 32, 924 IIT_PTR_TO_ELT = 33, 925 IIT_VEC_OF_ANYPTRS_TO_ELT = 34, 926 IIT_I128 = 35, 927 IIT_V512 = 36, 928 IIT_V1024 = 37, 929 IIT_STRUCT6 = 38, 930 IIT_STRUCT7 = 39, 931 IIT_STRUCT8 = 40, 932 IIT_F128 = 41, 933 IIT_VEC_ELEMENT = 42, 934 IIT_SCALABLE_VEC = 43, 935 IIT_SUBDIVIDE2_ARG = 44, 936 IIT_SUBDIVIDE4_ARG = 45, 937 IIT_VEC_OF_BITCASTS_TO_INT = 46, 938 IIT_V128 = 47, 939 IIT_BF16 = 48, 940 IIT_STRUCT9 = 49, 941 IIT_V256 = 50, 942 IIT_AMX = 51 943 }; 944 945 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 946 IIT_Info LastInfo, 947 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 948 using namespace Intrinsic; 949 950 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC); 951 952 IIT_Info Info = IIT_Info(Infos[NextElt++]); 953 unsigned StructElts = 2; 954 955 switch (Info) { 956 case IIT_Done: 957 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 958 return; 959 case IIT_VARARG: 960 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 961 return; 962 case IIT_MMX: 963 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 964 return; 965 case IIT_AMX: 966 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0)); 967 return; 968 case IIT_TOKEN: 969 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 970 return; 971 case IIT_METADATA: 972 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 973 return; 974 case IIT_F16: 975 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 976 return; 977 case IIT_BF16: 978 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0)); 979 return; 980 case IIT_F32: 981 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 982 return; 983 case IIT_F64: 984 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 985 return; 986 case IIT_F128: 987 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 988 return; 989 case IIT_I1: 990 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 991 return; 992 case IIT_I8: 993 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 994 return; 995 case IIT_I16: 996 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 997 return; 998 case IIT_I32: 999 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 1000 return; 1001 case IIT_I64: 1002 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 1003 return; 1004 case IIT_I128: 1005 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 1006 return; 1007 case IIT_V1: 1008 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector)); 1009 DecodeIITType(NextElt, Infos, Info, OutputTable); 1010 return; 1011 case IIT_V2: 1012 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector)); 1013 DecodeIITType(NextElt, Infos, Info, OutputTable); 1014 return; 1015 case IIT_V4: 1016 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector)); 1017 DecodeIITType(NextElt, Infos, Info, OutputTable); 1018 return; 1019 case IIT_V8: 1020 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector)); 1021 DecodeIITType(NextElt, Infos, Info, OutputTable); 1022 return; 1023 case IIT_V16: 1024 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector)); 1025 DecodeIITType(NextElt, Infos, Info, OutputTable); 1026 return; 1027 case IIT_V32: 1028 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector)); 1029 DecodeIITType(NextElt, Infos, Info, OutputTable); 1030 return; 1031 case IIT_V64: 1032 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector)); 1033 DecodeIITType(NextElt, Infos, Info, OutputTable); 1034 return; 1035 case IIT_V128: 1036 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector)); 1037 DecodeIITType(NextElt, Infos, Info, OutputTable); 1038 return; 1039 case IIT_V256: 1040 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector)); 1041 DecodeIITType(NextElt, Infos, Info, OutputTable); 1042 return; 1043 case IIT_V512: 1044 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector)); 1045 DecodeIITType(NextElt, Infos, Info, OutputTable); 1046 return; 1047 case IIT_V1024: 1048 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector)); 1049 DecodeIITType(NextElt, Infos, Info, OutputTable); 1050 return; 1051 case IIT_PTR: 1052 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 1053 DecodeIITType(NextElt, Infos, Info, OutputTable); 1054 return; 1055 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 1056 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 1057 Infos[NextElt++])); 1058 DecodeIITType(NextElt, Infos, Info, OutputTable); 1059 return; 1060 } 1061 case IIT_ARG: { 1062 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1063 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 1064 return; 1065 } 1066 case IIT_EXTEND_ARG: { 1067 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1068 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 1069 ArgInfo)); 1070 return; 1071 } 1072 case IIT_TRUNC_ARG: { 1073 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1074 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 1075 ArgInfo)); 1076 return; 1077 } 1078 case IIT_HALF_VEC_ARG: { 1079 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1080 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 1081 ArgInfo)); 1082 return; 1083 } 1084 case IIT_SAME_VEC_WIDTH_ARG: { 1085 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1086 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 1087 ArgInfo)); 1088 return; 1089 } 1090 case IIT_PTR_TO_ARG: { 1091 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1092 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 1093 ArgInfo)); 1094 return; 1095 } 1096 case IIT_PTR_TO_ELT: { 1097 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1098 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 1099 return; 1100 } 1101 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 1102 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1103 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1104 OutputTable.push_back( 1105 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 1106 return; 1107 } 1108 case IIT_EMPTYSTRUCT: 1109 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 1110 return; 1111 case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH; 1112 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH; 1113 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH; 1114 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH; 1115 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 1116 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 1117 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 1118 case IIT_STRUCT2: { 1119 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 1120 1121 for (unsigned i = 0; i != StructElts; ++i) 1122 DecodeIITType(NextElt, Infos, Info, OutputTable); 1123 return; 1124 } 1125 case IIT_SUBDIVIDE2_ARG: { 1126 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1127 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 1128 ArgInfo)); 1129 return; 1130 } 1131 case IIT_SUBDIVIDE4_ARG: { 1132 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1133 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 1134 ArgInfo)); 1135 return; 1136 } 1137 case IIT_VEC_ELEMENT: { 1138 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1139 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 1140 ArgInfo)); 1141 return; 1142 } 1143 case IIT_SCALABLE_VEC: { 1144 DecodeIITType(NextElt, Infos, Info, OutputTable); 1145 return; 1146 } 1147 case IIT_VEC_OF_BITCASTS_TO_INT: { 1148 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1149 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, 1150 ArgInfo)); 1151 return; 1152 } 1153 } 1154 llvm_unreachable("unhandled"); 1155 } 1156 1157 #define GET_INTRINSIC_GENERATOR_GLOBAL 1158 #include "llvm/IR/IntrinsicImpl.inc" 1159 #undef GET_INTRINSIC_GENERATOR_GLOBAL 1160 1161 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 1162 SmallVectorImpl<IITDescriptor> &T){ 1163 // Check to see if the intrinsic's type was expressible by the table. 1164 unsigned TableVal = IIT_Table[id-1]; 1165 1166 // Decode the TableVal into an array of IITValues. 1167 SmallVector<unsigned char, 8> IITValues; 1168 ArrayRef<unsigned char> IITEntries; 1169 unsigned NextElt = 0; 1170 if ((TableVal >> 31) != 0) { 1171 // This is an offset into the IIT_LongEncodingTable. 1172 IITEntries = IIT_LongEncodingTable; 1173 1174 // Strip sentinel bit. 1175 NextElt = (TableVal << 1) >> 1; 1176 } else { 1177 // Decode the TableVal into an array of IITValues. If the entry was encoded 1178 // into a single word in the table itself, decode it now. 1179 do { 1180 IITValues.push_back(TableVal & 0xF); 1181 TableVal >>= 4; 1182 } while (TableVal); 1183 1184 IITEntries = IITValues; 1185 NextElt = 0; 1186 } 1187 1188 // Okay, decode the table into the output vector of IITDescriptors. 1189 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1190 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 1191 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1192 } 1193 1194 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 1195 ArrayRef<Type*> Tys, LLVMContext &Context) { 1196 using namespace Intrinsic; 1197 1198 IITDescriptor D = Infos.front(); 1199 Infos = Infos.slice(1); 1200 1201 switch (D.Kind) { 1202 case IITDescriptor::Void: return Type::getVoidTy(Context); 1203 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 1204 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 1205 case IITDescriptor::AMX: return Type::getX86_AMXTy(Context); 1206 case IITDescriptor::Token: return Type::getTokenTy(Context); 1207 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 1208 case IITDescriptor::Half: return Type::getHalfTy(Context); 1209 case IITDescriptor::BFloat: return Type::getBFloatTy(Context); 1210 case IITDescriptor::Float: return Type::getFloatTy(Context); 1211 case IITDescriptor::Double: return Type::getDoubleTy(Context); 1212 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 1213 1214 case IITDescriptor::Integer: 1215 return IntegerType::get(Context, D.Integer_Width); 1216 case IITDescriptor::Vector: 1217 return VectorType::get(DecodeFixedType(Infos, Tys, Context), 1218 D.Vector_Width); 1219 case IITDescriptor::Pointer: 1220 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 1221 D.Pointer_AddressSpace); 1222 case IITDescriptor::Struct: { 1223 SmallVector<Type *, 8> Elts; 1224 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1225 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 1226 return StructType::get(Context, Elts); 1227 } 1228 case IITDescriptor::Argument: 1229 return Tys[D.getArgumentNumber()]; 1230 case IITDescriptor::ExtendArgument: { 1231 Type *Ty = Tys[D.getArgumentNumber()]; 1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1233 return VectorType::getExtendedElementVectorType(VTy); 1234 1235 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 1236 } 1237 case IITDescriptor::TruncArgument: { 1238 Type *Ty = Tys[D.getArgumentNumber()]; 1239 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1240 return VectorType::getTruncatedElementVectorType(VTy); 1241 1242 IntegerType *ITy = cast<IntegerType>(Ty); 1243 assert(ITy->getBitWidth() % 2 == 0); 1244 return IntegerType::get(Context, ITy->getBitWidth() / 2); 1245 } 1246 case IITDescriptor::Subdivide2Argument: 1247 case IITDescriptor::Subdivide4Argument: { 1248 Type *Ty = Tys[D.getArgumentNumber()]; 1249 VectorType *VTy = dyn_cast<VectorType>(Ty); 1250 assert(VTy && "Expected an argument of Vector Type"); 1251 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1252 return VectorType::getSubdividedVectorType(VTy, SubDivs); 1253 } 1254 case IITDescriptor::HalfVecArgument: 1255 return VectorType::getHalfElementsVectorType(cast<VectorType>( 1256 Tys[D.getArgumentNumber()])); 1257 case IITDescriptor::SameVecWidthArgument: { 1258 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1259 Type *Ty = Tys[D.getArgumentNumber()]; 1260 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1261 return VectorType::get(EltTy, VTy->getElementCount()); 1262 return EltTy; 1263 } 1264 case IITDescriptor::PtrToArgument: { 1265 Type *Ty = Tys[D.getArgumentNumber()]; 1266 return PointerType::getUnqual(Ty); 1267 } 1268 case IITDescriptor::PtrToElt: { 1269 Type *Ty = Tys[D.getArgumentNumber()]; 1270 VectorType *VTy = dyn_cast<VectorType>(Ty); 1271 if (!VTy) 1272 llvm_unreachable("Expected an argument of Vector Type"); 1273 Type *EltTy = VTy->getElementType(); 1274 return PointerType::getUnqual(EltTy); 1275 } 1276 case IITDescriptor::VecElementArgument: { 1277 Type *Ty = Tys[D.getArgumentNumber()]; 1278 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1279 return VTy->getElementType(); 1280 llvm_unreachable("Expected an argument of Vector Type"); 1281 } 1282 case IITDescriptor::VecOfBitcastsToInt: { 1283 Type *Ty = Tys[D.getArgumentNumber()]; 1284 VectorType *VTy = dyn_cast<VectorType>(Ty); 1285 assert(VTy && "Expected an argument of Vector Type"); 1286 return VectorType::getInteger(VTy); 1287 } 1288 case IITDescriptor::VecOfAnyPtrsToElt: 1289 // Return the overloaded type (which determines the pointers address space) 1290 return Tys[D.getOverloadArgNumber()]; 1291 } 1292 llvm_unreachable("unhandled"); 1293 } 1294 1295 FunctionType *Intrinsic::getType(LLVMContext &Context, 1296 ID id, ArrayRef<Type*> Tys) { 1297 SmallVector<IITDescriptor, 8> Table; 1298 getIntrinsicInfoTableEntries(id, Table); 1299 1300 ArrayRef<IITDescriptor> TableRef = Table; 1301 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1302 1303 SmallVector<Type*, 8> ArgTys; 1304 while (!TableRef.empty()) 1305 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1306 1307 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1308 // If we see void type as the type of the last argument, it is vararg intrinsic 1309 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1310 ArgTys.pop_back(); 1311 return FunctionType::get(ResultTy, ArgTys, true); 1312 } 1313 return FunctionType::get(ResultTy, ArgTys, false); 1314 } 1315 1316 bool Intrinsic::isOverloaded(ID id) { 1317 #define GET_INTRINSIC_OVERLOAD_TABLE 1318 #include "llvm/IR/IntrinsicImpl.inc" 1319 #undef GET_INTRINSIC_OVERLOAD_TABLE 1320 } 1321 1322 bool Intrinsic::isLeaf(ID id) { 1323 switch (id) { 1324 default: 1325 return true; 1326 1327 case Intrinsic::experimental_gc_statepoint: 1328 case Intrinsic::experimental_patchpoint_void: 1329 case Intrinsic::experimental_patchpoint_i64: 1330 return false; 1331 } 1332 } 1333 1334 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1335 #define GET_INTRINSIC_ATTRIBUTES 1336 #include "llvm/IR/IntrinsicImpl.inc" 1337 #undef GET_INTRINSIC_ATTRIBUTES 1338 1339 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1340 // There can never be multiple globals with the same name of different types, 1341 // because intrinsics must be a specific type. 1342 auto *FT = getType(M->getContext(), id, Tys); 1343 return cast<Function>( 1344 M->getOrInsertFunction(Tys.empty() ? getName(id) 1345 : getName(id, Tys, M, FT), 1346 getType(M->getContext(), id, Tys)) 1347 .getCallee()); 1348 } 1349 1350 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 1351 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1352 #include "llvm/IR/IntrinsicImpl.inc" 1353 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1354 1355 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1356 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1357 #include "llvm/IR/IntrinsicImpl.inc" 1358 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1359 1360 using DeferredIntrinsicMatchPair = 1361 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1362 1363 static bool matchIntrinsicType( 1364 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1365 SmallVectorImpl<Type *> &ArgTys, 1366 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1367 bool IsDeferredCheck) { 1368 using namespace Intrinsic; 1369 1370 // If we ran out of descriptors, there are too many arguments. 1371 if (Infos.empty()) return true; 1372 1373 // Do this before slicing off the 'front' part 1374 auto InfosRef = Infos; 1375 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1376 DeferredChecks.emplace_back(T, InfosRef); 1377 return false; 1378 }; 1379 1380 IITDescriptor D = Infos.front(); 1381 Infos = Infos.slice(1); 1382 1383 switch (D.Kind) { 1384 case IITDescriptor::Void: return !Ty->isVoidTy(); 1385 case IITDescriptor::VarArg: return true; 1386 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 1387 case IITDescriptor::AMX: return !Ty->isX86_AMXTy(); 1388 case IITDescriptor::Token: return !Ty->isTokenTy(); 1389 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1390 case IITDescriptor::Half: return !Ty->isHalfTy(); 1391 case IITDescriptor::BFloat: return !Ty->isBFloatTy(); 1392 case IITDescriptor::Float: return !Ty->isFloatTy(); 1393 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1394 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1395 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1396 case IITDescriptor::Vector: { 1397 VectorType *VT = dyn_cast<VectorType>(Ty); 1398 return !VT || VT->getElementCount() != D.Vector_Width || 1399 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1400 DeferredChecks, IsDeferredCheck); 1401 } 1402 case IITDescriptor::Pointer: { 1403 PointerType *PT = dyn_cast<PointerType>(Ty); 1404 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 1405 matchIntrinsicType(PT->getElementType(), Infos, ArgTys, 1406 DeferredChecks, IsDeferredCheck); 1407 } 1408 1409 case IITDescriptor::Struct: { 1410 StructType *ST = dyn_cast<StructType>(Ty); 1411 if (!ST || ST->getNumElements() != D.Struct_NumElements) 1412 return true; 1413 1414 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1415 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1416 DeferredChecks, IsDeferredCheck)) 1417 return true; 1418 return false; 1419 } 1420 1421 case IITDescriptor::Argument: 1422 // If this is the second occurrence of an argument, 1423 // verify that the later instance matches the previous instance. 1424 if (D.getArgumentNumber() < ArgTys.size()) 1425 return Ty != ArgTys[D.getArgumentNumber()]; 1426 1427 if (D.getArgumentNumber() > ArgTys.size() || 1428 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1429 return IsDeferredCheck || DeferCheck(Ty); 1430 1431 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1432 "Table consistency error"); 1433 ArgTys.push_back(Ty); 1434 1435 switch (D.getArgumentKind()) { 1436 case IITDescriptor::AK_Any: return false; // Success 1437 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1438 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1439 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1440 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1441 default: break; 1442 } 1443 llvm_unreachable("all argument kinds not covered"); 1444 1445 case IITDescriptor::ExtendArgument: { 1446 // If this is a forward reference, defer the check for later. 1447 if (D.getArgumentNumber() >= ArgTys.size()) 1448 return IsDeferredCheck || DeferCheck(Ty); 1449 1450 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1451 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1452 NewTy = VectorType::getExtendedElementVectorType(VTy); 1453 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1454 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1455 else 1456 return true; 1457 1458 return Ty != NewTy; 1459 } 1460 case IITDescriptor::TruncArgument: { 1461 // If this is a forward reference, defer the check for later. 1462 if (D.getArgumentNumber() >= ArgTys.size()) 1463 return IsDeferredCheck || DeferCheck(Ty); 1464 1465 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1466 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1467 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1468 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1469 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1470 else 1471 return true; 1472 1473 return Ty != NewTy; 1474 } 1475 case IITDescriptor::HalfVecArgument: 1476 // If this is a forward reference, defer the check for later. 1477 if (D.getArgumentNumber() >= ArgTys.size()) 1478 return IsDeferredCheck || DeferCheck(Ty); 1479 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1480 VectorType::getHalfElementsVectorType( 1481 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1482 case IITDescriptor::SameVecWidthArgument: { 1483 if (D.getArgumentNumber() >= ArgTys.size()) { 1484 // Defer check and subsequent check for the vector element type. 1485 Infos = Infos.slice(1); 1486 return IsDeferredCheck || DeferCheck(Ty); 1487 } 1488 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1489 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1490 // Both must be vectors of the same number of elements or neither. 1491 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1492 return true; 1493 Type *EltTy = Ty; 1494 if (ThisArgType) { 1495 if (ReferenceType->getElementCount() != 1496 ThisArgType->getElementCount()) 1497 return true; 1498 EltTy = ThisArgType->getElementType(); 1499 } 1500 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1501 IsDeferredCheck); 1502 } 1503 case IITDescriptor::PtrToArgument: { 1504 if (D.getArgumentNumber() >= ArgTys.size()) 1505 return IsDeferredCheck || DeferCheck(Ty); 1506 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1507 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1508 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1509 } 1510 case IITDescriptor::PtrToElt: { 1511 if (D.getArgumentNumber() >= ArgTys.size()) 1512 return IsDeferredCheck || DeferCheck(Ty); 1513 VectorType * ReferenceType = 1514 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1515 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1516 1517 return (!ThisArgType || !ReferenceType || 1518 ThisArgType->getElementType() != ReferenceType->getElementType()); 1519 } 1520 case IITDescriptor::VecOfAnyPtrsToElt: { 1521 unsigned RefArgNumber = D.getRefArgNumber(); 1522 if (RefArgNumber >= ArgTys.size()) { 1523 if (IsDeferredCheck) 1524 return true; 1525 // If forward referencing, already add the pointer-vector type and 1526 // defer the checks for later. 1527 ArgTys.push_back(Ty); 1528 return DeferCheck(Ty); 1529 } 1530 1531 if (!IsDeferredCheck){ 1532 assert(D.getOverloadArgNumber() == ArgTys.size() && 1533 "Table consistency error"); 1534 ArgTys.push_back(Ty); 1535 } 1536 1537 // Verify the overloaded type "matches" the Ref type. 1538 // i.e. Ty is a vector with the same width as Ref. 1539 // Composed of pointers to the same element type as Ref. 1540 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1541 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1542 if (!ThisArgVecTy || !ReferenceType || 1543 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount())) 1544 return true; 1545 PointerType *ThisArgEltTy = 1546 dyn_cast<PointerType>(ThisArgVecTy->getElementType()); 1547 if (!ThisArgEltTy) 1548 return true; 1549 return ThisArgEltTy->getElementType() != ReferenceType->getElementType(); 1550 } 1551 case IITDescriptor::VecElementArgument: { 1552 if (D.getArgumentNumber() >= ArgTys.size()) 1553 return IsDeferredCheck ? true : DeferCheck(Ty); 1554 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1555 return !ReferenceType || Ty != ReferenceType->getElementType(); 1556 } 1557 case IITDescriptor::Subdivide2Argument: 1558 case IITDescriptor::Subdivide4Argument: { 1559 // If this is a forward reference, defer the check for later. 1560 if (D.getArgumentNumber() >= ArgTys.size()) 1561 return IsDeferredCheck || DeferCheck(Ty); 1562 1563 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1564 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1565 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1566 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1567 return Ty != NewTy; 1568 } 1569 return true; 1570 } 1571 case IITDescriptor::VecOfBitcastsToInt: { 1572 if (D.getArgumentNumber() >= ArgTys.size()) 1573 return IsDeferredCheck || DeferCheck(Ty); 1574 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1575 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1576 if (!ThisArgVecTy || !ReferenceType) 1577 return true; 1578 return ThisArgVecTy != VectorType::getInteger(ReferenceType); 1579 } 1580 } 1581 llvm_unreachable("unhandled"); 1582 } 1583 1584 Intrinsic::MatchIntrinsicTypesResult 1585 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1586 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1587 SmallVectorImpl<Type *> &ArgTys) { 1588 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1589 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1590 false)) 1591 return MatchIntrinsicTypes_NoMatchRet; 1592 1593 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1594 1595 for (auto Ty : FTy->params()) 1596 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1597 return MatchIntrinsicTypes_NoMatchArg; 1598 1599 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1600 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1601 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1602 true)) 1603 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1604 : MatchIntrinsicTypes_NoMatchArg; 1605 } 1606 1607 return MatchIntrinsicTypes_Match; 1608 } 1609 1610 bool 1611 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1612 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1613 // If there are no descriptors left, then it can't be a vararg. 1614 if (Infos.empty()) 1615 return isVarArg; 1616 1617 // There should be only one descriptor remaining at this point. 1618 if (Infos.size() != 1) 1619 return true; 1620 1621 // Check and verify the descriptor. 1622 IITDescriptor D = Infos.front(); 1623 Infos = Infos.slice(1); 1624 if (D.Kind == IITDescriptor::VarArg) 1625 return !isVarArg; 1626 1627 return true; 1628 } 1629 1630 bool Intrinsic::getIntrinsicSignature(Function *F, 1631 SmallVectorImpl<Type *> &ArgTys) { 1632 Intrinsic::ID ID = F->getIntrinsicID(); 1633 if (!ID) 1634 return false; 1635 1636 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1637 getIntrinsicInfoTableEntries(ID, Table); 1638 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1639 1640 if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef, 1641 ArgTys) != 1642 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) { 1643 return false; 1644 } 1645 if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(), 1646 TableRef)) 1647 return false; 1648 return true; 1649 } 1650 1651 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) { 1652 SmallVector<Type *, 4> ArgTys; 1653 if (!getIntrinsicSignature(F, ArgTys)) 1654 return None; 1655 1656 Intrinsic::ID ID = F->getIntrinsicID(); 1657 StringRef Name = F->getName(); 1658 if (Name == 1659 Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType())) 1660 return None; 1661 1662 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1663 NewDecl->setCallingConv(F->getCallingConv()); 1664 assert(NewDecl->getFunctionType() == F->getFunctionType() && 1665 "Shouldn't change the signature"); 1666 return NewDecl; 1667 } 1668 1669 /// hasAddressTaken - returns true if there are any uses of this function 1670 /// other than direct calls or invokes to it. Optionally ignores callback 1671 /// uses, assume like pointer annotation calls, and references in llvm.used 1672 /// and llvm.compiler.used variables. 1673 bool Function::hasAddressTaken(const User **PutOffender, 1674 bool IgnoreCallbackUses, 1675 bool IgnoreAssumeLikeCalls, 1676 bool IgnoreLLVMUsed) const { 1677 for (const Use &U : uses()) { 1678 const User *FU = U.getUser(); 1679 if (isa<BlockAddress>(FU)) 1680 continue; 1681 1682 if (IgnoreCallbackUses) { 1683 AbstractCallSite ACS(&U); 1684 if (ACS && ACS.isCallbackCall()) 1685 continue; 1686 } 1687 1688 const auto *Call = dyn_cast<CallBase>(FU); 1689 if (!Call) { 1690 if (IgnoreAssumeLikeCalls) { 1691 if (const auto *FI = dyn_cast<Instruction>(FU)) { 1692 if (FI->isCast() && !FI->user_empty() && 1693 llvm::all_of(FU->users(), [](const User *U) { 1694 if (const auto *I = dyn_cast<IntrinsicInst>(U)) 1695 return I->isAssumeLikeIntrinsic(); 1696 return false; 1697 })) 1698 continue; 1699 } 1700 } 1701 if (IgnoreLLVMUsed && !FU->user_empty()) { 1702 const User *FUU = FU; 1703 if (isa<BitCastOperator>(FU) && FU->hasOneUse() && 1704 !FU->user_begin()->user_empty()) 1705 FUU = *FU->user_begin(); 1706 if (llvm::all_of(FUU->users(), [](const User *U) { 1707 if (const auto *GV = dyn_cast<GlobalVariable>(U)) 1708 return GV->hasName() && 1709 (GV->getName().equals("llvm.compiler.used") || 1710 GV->getName().equals("llvm.used")); 1711 return false; 1712 })) 1713 continue; 1714 } 1715 if (PutOffender) 1716 *PutOffender = FU; 1717 return true; 1718 } 1719 if (!Call->isCallee(&U)) { 1720 if (PutOffender) 1721 *PutOffender = FU; 1722 return true; 1723 } 1724 } 1725 return false; 1726 } 1727 1728 bool Function::isDefTriviallyDead() const { 1729 // Check the linkage 1730 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1731 !hasAvailableExternallyLinkage()) 1732 return false; 1733 1734 // Check if the function is used by anything other than a blockaddress. 1735 for (const User *U : users()) 1736 if (!isa<BlockAddress>(U)) 1737 return false; 1738 1739 return true; 1740 } 1741 1742 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1743 /// setjmp or other function that gcc recognizes as "returning twice". 1744 bool Function::callsFunctionThatReturnsTwice() const { 1745 for (const Instruction &I : instructions(this)) 1746 if (const auto *Call = dyn_cast<CallBase>(&I)) 1747 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1748 return true; 1749 1750 return false; 1751 } 1752 1753 Constant *Function::getPersonalityFn() const { 1754 assert(hasPersonalityFn() && getNumOperands()); 1755 return cast<Constant>(Op<0>()); 1756 } 1757 1758 void Function::setPersonalityFn(Constant *Fn) { 1759 setHungoffOperand<0>(Fn); 1760 setValueSubclassDataBit(3, Fn != nullptr); 1761 } 1762 1763 Constant *Function::getPrefixData() const { 1764 assert(hasPrefixData() && getNumOperands()); 1765 return cast<Constant>(Op<1>()); 1766 } 1767 1768 void Function::setPrefixData(Constant *PrefixData) { 1769 setHungoffOperand<1>(PrefixData); 1770 setValueSubclassDataBit(1, PrefixData != nullptr); 1771 } 1772 1773 Constant *Function::getPrologueData() const { 1774 assert(hasPrologueData() && getNumOperands()); 1775 return cast<Constant>(Op<2>()); 1776 } 1777 1778 void Function::setPrologueData(Constant *PrologueData) { 1779 setHungoffOperand<2>(PrologueData); 1780 setValueSubclassDataBit(2, PrologueData != nullptr); 1781 } 1782 1783 void Function::allocHungoffUselist() { 1784 // If we've already allocated a uselist, stop here. 1785 if (getNumOperands()) 1786 return; 1787 1788 allocHungoffUses(3, /*IsPhi=*/ false); 1789 setNumHungOffUseOperands(3); 1790 1791 // Initialize the uselist with placeholder operands to allow traversal. 1792 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1793 Op<0>().set(CPN); 1794 Op<1>().set(CPN); 1795 Op<2>().set(CPN); 1796 } 1797 1798 template <int Idx> 1799 void Function::setHungoffOperand(Constant *C) { 1800 if (C) { 1801 allocHungoffUselist(); 1802 Op<Idx>().set(C); 1803 } else if (getNumOperands()) { 1804 Op<Idx>().set( 1805 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1806 } 1807 } 1808 1809 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1810 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1811 if (On) 1812 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1813 else 1814 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1815 } 1816 1817 void Function::setEntryCount(ProfileCount Count, 1818 const DenseSet<GlobalValue::GUID> *S) { 1819 assert(Count.hasValue()); 1820 #if !defined(NDEBUG) 1821 auto PrevCount = getEntryCount(); 1822 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType()); 1823 #endif 1824 1825 auto ImportGUIDs = getImportGUIDs(); 1826 if (S == nullptr && ImportGUIDs.size()) 1827 S = &ImportGUIDs; 1828 1829 MDBuilder MDB(getContext()); 1830 setMetadata( 1831 LLVMContext::MD_prof, 1832 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 1833 } 1834 1835 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 1836 const DenseSet<GlobalValue::GUID> *Imports) { 1837 setEntryCount(ProfileCount(Count, Type), Imports); 1838 } 1839 1840 ProfileCount Function::getEntryCount(bool AllowSynthetic) const { 1841 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1842 if (MD && MD->getOperand(0)) 1843 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 1844 if (MDS->getString().equals("function_entry_count")) { 1845 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1846 uint64_t Count = CI->getValue().getZExtValue(); 1847 // A value of -1 is used for SamplePGO when there were no samples. 1848 // Treat this the same as unknown. 1849 if (Count == (uint64_t)-1) 1850 return ProfileCount::getInvalid(); 1851 return ProfileCount(Count, PCT_Real); 1852 } else if (AllowSynthetic && 1853 MDS->getString().equals("synthetic_function_entry_count")) { 1854 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1855 uint64_t Count = CI->getValue().getZExtValue(); 1856 return ProfileCount(Count, PCT_Synthetic); 1857 } 1858 } 1859 return ProfileCount::getInvalid(); 1860 } 1861 1862 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1863 DenseSet<GlobalValue::GUID> R; 1864 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1865 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1866 if (MDS->getString().equals("function_entry_count")) 1867 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1868 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1869 ->getValue() 1870 .getZExtValue()); 1871 return R; 1872 } 1873 1874 void Function::setSectionPrefix(StringRef Prefix) { 1875 MDBuilder MDB(getContext()); 1876 setMetadata(LLVMContext::MD_section_prefix, 1877 MDB.createFunctionSectionPrefix(Prefix)); 1878 } 1879 1880 Optional<StringRef> Function::getSectionPrefix() const { 1881 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1882 assert(cast<MDString>(MD->getOperand(0)) 1883 ->getString() 1884 .equals("function_section_prefix") && 1885 "Metadata not match"); 1886 return cast<MDString>(MD->getOperand(1))->getString(); 1887 } 1888 return None; 1889 } 1890 1891 bool Function::nullPointerIsDefined() const { 1892 return hasFnAttribute(Attribute::NullPointerIsValid); 1893 } 1894 1895 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 1896 if (F && F->nullPointerIsDefined()) 1897 return true; 1898 1899 if (AS != 0) 1900 return true; 1901 1902 return false; 1903 } 1904