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