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