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 /// Copy all additional attributes (those not needed to create a Function) from 614 /// the Function Src to this one. 615 void Function::copyAttributesFrom(const Function *Src) { 616 GlobalObject::copyAttributesFrom(Src); 617 setCallingConv(Src->getCallingConv()); 618 setAttributes(Src->getAttributes()); 619 if (Src->hasGC()) 620 setGC(Src->getGC()); 621 else 622 clearGC(); 623 if (Src->hasPersonalityFn()) 624 setPersonalityFn(Src->getPersonalityFn()); 625 if (Src->hasPrefixData()) 626 setPrefixData(Src->getPrefixData()); 627 if (Src->hasPrologueData()) 628 setPrologueData(Src->getPrologueData()); 629 } 630 631 /// Table of string intrinsic names indexed by enum value. 632 static const char * const IntrinsicNameTable[] = { 633 "not_intrinsic", 634 #define GET_INTRINSIC_NAME_TABLE 635 #include "llvm/IR/IntrinsicImpl.inc" 636 #undef GET_INTRINSIC_NAME_TABLE 637 }; 638 639 /// Table of per-target intrinsic name tables. 640 #define GET_INTRINSIC_TARGET_DATA 641 #include "llvm/IR/IntrinsicImpl.inc" 642 #undef GET_INTRINSIC_TARGET_DATA 643 644 bool Function::isTargetIntrinsic(Intrinsic::ID IID) { 645 return IID > TargetInfos[0].Count; 646 } 647 648 bool Function::isTargetIntrinsic() const { 649 return isTargetIntrinsic(IntID); 650 } 651 652 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 653 /// target as \c Name, or the generic table if \c Name is not target specific. 654 /// 655 /// Returns the relevant slice of \c IntrinsicNameTable 656 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 657 assert(Name.startswith("llvm.")); 658 659 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 660 // Drop "llvm." and take the first dotted component. That will be the target 661 // if this is target specific. 662 StringRef Target = Name.drop_front(5).split('.').first; 663 auto It = partition_point( 664 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; }); 665 // We've either found the target or just fall back to the generic set, which 666 // is always first. 667 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 668 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 669 } 670 671 /// This does the actual lookup of an intrinsic ID which 672 /// matches the given function name. 673 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 674 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 675 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 676 if (Idx == -1) 677 return Intrinsic::not_intrinsic; 678 679 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 680 // an index into a sub-table. 681 int Adjust = NameTable.data() - IntrinsicNameTable; 682 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 683 684 // If the intrinsic is not overloaded, require an exact match. If it is 685 // overloaded, require either exact or prefix match. 686 const auto MatchSize = strlen(NameTable[Idx]); 687 assert(Name.size() >= MatchSize && "Expected either exact or prefix match"); 688 bool IsExactMatch = Name.size() == MatchSize; 689 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID 690 : Intrinsic::not_intrinsic; 691 } 692 693 void Function::recalculateIntrinsicID() { 694 StringRef Name = getName(); 695 if (!Name.startswith("llvm.")) { 696 HasLLVMReservedName = false; 697 IntID = Intrinsic::not_intrinsic; 698 return; 699 } 700 HasLLVMReservedName = true; 701 IntID = lookupIntrinsicID(Name); 702 } 703 704 /// Returns a stable mangling for the type specified for use in the name 705 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 706 /// of named types is simply their name. Manglings for unnamed types consist 707 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 708 /// combined with the mangling of their component types. A vararg function 709 /// type will have a suffix of 'vararg'. Since function types can contain 710 /// other function types, we close a function type mangling with suffix 'f' 711 /// which can't be confused with it's prefix. This ensures we don't have 712 /// collisions between two unrelated function types. Otherwise, you might 713 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 714 /// 715 static std::string getMangledTypeStr(Type* Ty) { 716 std::string Result; 717 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 718 Result += "p" + utostr(PTyp->getAddressSpace()) + 719 getMangledTypeStr(PTyp->getElementType()); 720 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 721 Result += "a" + utostr(ATyp->getNumElements()) + 722 getMangledTypeStr(ATyp->getElementType()); 723 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 724 if (!STyp->isLiteral()) { 725 Result += "s_"; 726 Result += STyp->getName(); 727 } else { 728 Result += "sl_"; 729 for (auto Elem : STyp->elements()) 730 Result += getMangledTypeStr(Elem); 731 } 732 // Ensure nested structs are distinguishable. 733 Result += "s"; 734 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 735 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 736 for (size_t i = 0; i < FT->getNumParams(); i++) 737 Result += getMangledTypeStr(FT->getParamType(i)); 738 if (FT->isVarArg()) 739 Result += "vararg"; 740 // Ensure nested function types are distinguishable. 741 Result += "f"; 742 } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) { 743 ElementCount EC = VTy->getElementCount(); 744 if (EC.isScalable()) 745 Result += "nx"; 746 Result += "v" + utostr(EC.getKnownMinValue()) + 747 getMangledTypeStr(VTy->getElementType()); 748 } else if (Ty) { 749 switch (Ty->getTypeID()) { 750 default: llvm_unreachable("Unhandled type"); 751 case Type::VoidTyID: Result += "isVoid"; break; 752 case Type::MetadataTyID: Result += "Metadata"; break; 753 case Type::HalfTyID: Result += "f16"; break; 754 case Type::BFloatTyID: Result += "bf16"; break; 755 case Type::FloatTyID: Result += "f32"; break; 756 case Type::DoubleTyID: Result += "f64"; break; 757 case Type::X86_FP80TyID: Result += "f80"; break; 758 case Type::FP128TyID: Result += "f128"; break; 759 case Type::PPC_FP128TyID: Result += "ppcf128"; break; 760 case Type::X86_MMXTyID: Result += "x86mmx"; break; 761 case Type::IntegerTyID: 762 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 763 break; 764 } 765 } 766 return Result; 767 } 768 769 StringRef Intrinsic::getName(ID id) { 770 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 771 assert(!Intrinsic::isOverloaded(id) && 772 "This version of getName does not support overloading"); 773 return IntrinsicNameTable[id]; 774 } 775 776 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 777 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 778 std::string Result(IntrinsicNameTable[id]); 779 for (Type *Ty : Tys) { 780 Result += "." + getMangledTypeStr(Ty); 781 } 782 return Result; 783 } 784 785 /// IIT_Info - These are enumerators that describe the entries returned by the 786 /// getIntrinsicInfoTableEntries function. 787 /// 788 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 789 enum IIT_Info { 790 // Common values should be encoded with 0-15. 791 IIT_Done = 0, 792 IIT_I1 = 1, 793 IIT_I8 = 2, 794 IIT_I16 = 3, 795 IIT_I32 = 4, 796 IIT_I64 = 5, 797 IIT_F16 = 6, 798 IIT_F32 = 7, 799 IIT_F64 = 8, 800 IIT_V2 = 9, 801 IIT_V4 = 10, 802 IIT_V8 = 11, 803 IIT_V16 = 12, 804 IIT_V32 = 13, 805 IIT_PTR = 14, 806 IIT_ARG = 15, 807 808 // Values from 16+ are only encodable with the inefficient encoding. 809 IIT_V64 = 16, 810 IIT_MMX = 17, 811 IIT_TOKEN = 18, 812 IIT_METADATA = 19, 813 IIT_EMPTYSTRUCT = 20, 814 IIT_STRUCT2 = 21, 815 IIT_STRUCT3 = 22, 816 IIT_STRUCT4 = 23, 817 IIT_STRUCT5 = 24, 818 IIT_EXTEND_ARG = 25, 819 IIT_TRUNC_ARG = 26, 820 IIT_ANYPTR = 27, 821 IIT_V1 = 28, 822 IIT_VARARG = 29, 823 IIT_HALF_VEC_ARG = 30, 824 IIT_SAME_VEC_WIDTH_ARG = 31, 825 IIT_PTR_TO_ARG = 32, 826 IIT_PTR_TO_ELT = 33, 827 IIT_VEC_OF_ANYPTRS_TO_ELT = 34, 828 IIT_I128 = 35, 829 IIT_V512 = 36, 830 IIT_V1024 = 37, 831 IIT_STRUCT6 = 38, 832 IIT_STRUCT7 = 39, 833 IIT_STRUCT8 = 40, 834 IIT_F128 = 41, 835 IIT_VEC_ELEMENT = 42, 836 IIT_SCALABLE_VEC = 43, 837 IIT_SUBDIVIDE2_ARG = 44, 838 IIT_SUBDIVIDE4_ARG = 45, 839 IIT_VEC_OF_BITCASTS_TO_INT = 46, 840 IIT_V128 = 47, 841 IIT_BF16 = 48, 842 IIT_STRUCT9 = 49, 843 IIT_V256 = 50 844 }; 845 846 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 847 IIT_Info LastInfo, 848 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 849 using namespace Intrinsic; 850 851 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC); 852 853 IIT_Info Info = IIT_Info(Infos[NextElt++]); 854 unsigned StructElts = 2; 855 856 switch (Info) { 857 case IIT_Done: 858 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 859 return; 860 case IIT_VARARG: 861 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 862 return; 863 case IIT_MMX: 864 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 865 return; 866 case IIT_TOKEN: 867 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 868 return; 869 case IIT_METADATA: 870 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 871 return; 872 case IIT_F16: 873 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 874 return; 875 case IIT_BF16: 876 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0)); 877 return; 878 case IIT_F32: 879 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 880 return; 881 case IIT_F64: 882 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 883 return; 884 case IIT_F128: 885 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 886 return; 887 case IIT_I1: 888 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 889 return; 890 case IIT_I8: 891 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 892 return; 893 case IIT_I16: 894 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 895 return; 896 case IIT_I32: 897 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 898 return; 899 case IIT_I64: 900 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 901 return; 902 case IIT_I128: 903 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 904 return; 905 case IIT_V1: 906 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector)); 907 DecodeIITType(NextElt, Infos, Info, OutputTable); 908 return; 909 case IIT_V2: 910 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector)); 911 DecodeIITType(NextElt, Infos, Info, OutputTable); 912 return; 913 case IIT_V4: 914 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector)); 915 DecodeIITType(NextElt, Infos, Info, OutputTable); 916 return; 917 case IIT_V8: 918 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector)); 919 DecodeIITType(NextElt, Infos, Info, OutputTable); 920 return; 921 case IIT_V16: 922 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector)); 923 DecodeIITType(NextElt, Infos, Info, OutputTable); 924 return; 925 case IIT_V32: 926 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector)); 927 DecodeIITType(NextElt, Infos, Info, OutputTable); 928 return; 929 case IIT_V64: 930 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector)); 931 DecodeIITType(NextElt, Infos, Info, OutputTable); 932 return; 933 case IIT_V128: 934 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector)); 935 DecodeIITType(NextElt, Infos, Info, OutputTable); 936 return; 937 case IIT_V256: 938 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector)); 939 DecodeIITType(NextElt, Infos, Info, OutputTable); 940 return; 941 case IIT_V512: 942 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector)); 943 DecodeIITType(NextElt, Infos, Info, OutputTable); 944 return; 945 case IIT_V1024: 946 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector)); 947 DecodeIITType(NextElt, Infos, Info, OutputTable); 948 return; 949 case IIT_PTR: 950 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 951 DecodeIITType(NextElt, Infos, Info, OutputTable); 952 return; 953 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 954 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 955 Infos[NextElt++])); 956 DecodeIITType(NextElt, Infos, Info, OutputTable); 957 return; 958 } 959 case IIT_ARG: { 960 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 961 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 962 return; 963 } 964 case IIT_EXTEND_ARG: { 965 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 966 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 967 ArgInfo)); 968 return; 969 } 970 case IIT_TRUNC_ARG: { 971 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 972 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 973 ArgInfo)); 974 return; 975 } 976 case IIT_HALF_VEC_ARG: { 977 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 978 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 979 ArgInfo)); 980 return; 981 } 982 case IIT_SAME_VEC_WIDTH_ARG: { 983 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 984 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 985 ArgInfo)); 986 return; 987 } 988 case IIT_PTR_TO_ARG: { 989 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 990 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 991 ArgInfo)); 992 return; 993 } 994 case IIT_PTR_TO_ELT: { 995 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 996 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 997 return; 998 } 999 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 1000 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1001 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1002 OutputTable.push_back( 1003 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 1004 return; 1005 } 1006 case IIT_EMPTYSTRUCT: 1007 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 1008 return; 1009 case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH; 1010 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH; 1011 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH; 1012 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH; 1013 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 1014 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 1015 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 1016 case IIT_STRUCT2: { 1017 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 1018 1019 for (unsigned i = 0; i != StructElts; ++i) 1020 DecodeIITType(NextElt, Infos, Info, OutputTable); 1021 return; 1022 } 1023 case IIT_SUBDIVIDE2_ARG: { 1024 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1025 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 1026 ArgInfo)); 1027 return; 1028 } 1029 case IIT_SUBDIVIDE4_ARG: { 1030 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1031 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 1032 ArgInfo)); 1033 return; 1034 } 1035 case IIT_VEC_ELEMENT: { 1036 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1037 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 1038 ArgInfo)); 1039 return; 1040 } 1041 case IIT_SCALABLE_VEC: { 1042 DecodeIITType(NextElt, Infos, Info, OutputTable); 1043 return; 1044 } 1045 case IIT_VEC_OF_BITCASTS_TO_INT: { 1046 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 1047 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, 1048 ArgInfo)); 1049 return; 1050 } 1051 } 1052 llvm_unreachable("unhandled"); 1053 } 1054 1055 #define GET_INTRINSIC_GENERATOR_GLOBAL 1056 #include "llvm/IR/IntrinsicImpl.inc" 1057 #undef GET_INTRINSIC_GENERATOR_GLOBAL 1058 1059 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 1060 SmallVectorImpl<IITDescriptor> &T){ 1061 // Check to see if the intrinsic's type was expressible by the table. 1062 unsigned TableVal = IIT_Table[id-1]; 1063 1064 // Decode the TableVal into an array of IITValues. 1065 SmallVector<unsigned char, 8> IITValues; 1066 ArrayRef<unsigned char> IITEntries; 1067 unsigned NextElt = 0; 1068 if ((TableVal >> 31) != 0) { 1069 // This is an offset into the IIT_LongEncodingTable. 1070 IITEntries = IIT_LongEncodingTable; 1071 1072 // Strip sentinel bit. 1073 NextElt = (TableVal << 1) >> 1; 1074 } else { 1075 // Decode the TableVal into an array of IITValues. If the entry was encoded 1076 // into a single word in the table itself, decode it now. 1077 do { 1078 IITValues.push_back(TableVal & 0xF); 1079 TableVal >>= 4; 1080 } while (TableVal); 1081 1082 IITEntries = IITValues; 1083 NextElt = 0; 1084 } 1085 1086 // Okay, decode the table into the output vector of IITDescriptors. 1087 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1088 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 1089 DecodeIITType(NextElt, IITEntries, IIT_Done, T); 1090 } 1091 1092 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 1093 ArrayRef<Type*> Tys, LLVMContext &Context) { 1094 using namespace Intrinsic; 1095 1096 IITDescriptor D = Infos.front(); 1097 Infos = Infos.slice(1); 1098 1099 switch (D.Kind) { 1100 case IITDescriptor::Void: return Type::getVoidTy(Context); 1101 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 1102 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 1103 case IITDescriptor::Token: return Type::getTokenTy(Context); 1104 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 1105 case IITDescriptor::Half: return Type::getHalfTy(Context); 1106 case IITDescriptor::BFloat: return Type::getBFloatTy(Context); 1107 case IITDescriptor::Float: return Type::getFloatTy(Context); 1108 case IITDescriptor::Double: return Type::getDoubleTy(Context); 1109 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 1110 1111 case IITDescriptor::Integer: 1112 return IntegerType::get(Context, D.Integer_Width); 1113 case IITDescriptor::Vector: 1114 return VectorType::get(DecodeFixedType(Infos, Tys, Context), 1115 D.Vector_Width); 1116 case IITDescriptor::Pointer: 1117 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 1118 D.Pointer_AddressSpace); 1119 case IITDescriptor::Struct: { 1120 SmallVector<Type *, 8> Elts; 1121 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1122 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 1123 return StructType::get(Context, Elts); 1124 } 1125 case IITDescriptor::Argument: 1126 return Tys[D.getArgumentNumber()]; 1127 case IITDescriptor::ExtendArgument: { 1128 Type *Ty = Tys[D.getArgumentNumber()]; 1129 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1130 return VectorType::getExtendedElementVectorType(VTy); 1131 1132 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 1133 } 1134 case IITDescriptor::TruncArgument: { 1135 Type *Ty = Tys[D.getArgumentNumber()]; 1136 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1137 return VectorType::getTruncatedElementVectorType(VTy); 1138 1139 IntegerType *ITy = cast<IntegerType>(Ty); 1140 assert(ITy->getBitWidth() % 2 == 0); 1141 return IntegerType::get(Context, ITy->getBitWidth() / 2); 1142 } 1143 case IITDescriptor::Subdivide2Argument: 1144 case IITDescriptor::Subdivide4Argument: { 1145 Type *Ty = Tys[D.getArgumentNumber()]; 1146 VectorType *VTy = dyn_cast<VectorType>(Ty); 1147 assert(VTy && "Expected an argument of Vector Type"); 1148 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1149 return VectorType::getSubdividedVectorType(VTy, SubDivs); 1150 } 1151 case IITDescriptor::HalfVecArgument: 1152 return VectorType::getHalfElementsVectorType(cast<VectorType>( 1153 Tys[D.getArgumentNumber()])); 1154 case IITDescriptor::SameVecWidthArgument: { 1155 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1156 Type *Ty = Tys[D.getArgumentNumber()]; 1157 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1158 return VectorType::get(EltTy, VTy->getElementCount()); 1159 return EltTy; 1160 } 1161 case IITDescriptor::PtrToArgument: { 1162 Type *Ty = Tys[D.getArgumentNumber()]; 1163 return PointerType::getUnqual(Ty); 1164 } 1165 case IITDescriptor::PtrToElt: { 1166 Type *Ty = Tys[D.getArgumentNumber()]; 1167 VectorType *VTy = dyn_cast<VectorType>(Ty); 1168 if (!VTy) 1169 llvm_unreachable("Expected an argument of Vector Type"); 1170 Type *EltTy = VTy->getElementType(); 1171 return PointerType::getUnqual(EltTy); 1172 } 1173 case IITDescriptor::VecElementArgument: { 1174 Type *Ty = Tys[D.getArgumentNumber()]; 1175 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1176 return VTy->getElementType(); 1177 llvm_unreachable("Expected an argument of Vector Type"); 1178 } 1179 case IITDescriptor::VecOfBitcastsToInt: { 1180 Type *Ty = Tys[D.getArgumentNumber()]; 1181 VectorType *VTy = dyn_cast<VectorType>(Ty); 1182 assert(VTy && "Expected an argument of Vector Type"); 1183 return VectorType::getInteger(VTy); 1184 } 1185 case IITDescriptor::VecOfAnyPtrsToElt: 1186 // Return the overloaded type (which determines the pointers address space) 1187 return Tys[D.getOverloadArgNumber()]; 1188 } 1189 llvm_unreachable("unhandled"); 1190 } 1191 1192 FunctionType *Intrinsic::getType(LLVMContext &Context, 1193 ID id, ArrayRef<Type*> Tys) { 1194 SmallVector<IITDescriptor, 8> Table; 1195 getIntrinsicInfoTableEntries(id, Table); 1196 1197 ArrayRef<IITDescriptor> TableRef = Table; 1198 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1199 1200 SmallVector<Type*, 8> ArgTys; 1201 while (!TableRef.empty()) 1202 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1203 1204 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1205 // If we see void type as the type of the last argument, it is vararg intrinsic 1206 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1207 ArgTys.pop_back(); 1208 return FunctionType::get(ResultTy, ArgTys, true); 1209 } 1210 return FunctionType::get(ResultTy, ArgTys, false); 1211 } 1212 1213 bool Intrinsic::isOverloaded(ID id) { 1214 #define GET_INTRINSIC_OVERLOAD_TABLE 1215 #include "llvm/IR/IntrinsicImpl.inc" 1216 #undef GET_INTRINSIC_OVERLOAD_TABLE 1217 } 1218 1219 bool Intrinsic::isLeaf(ID id) { 1220 switch (id) { 1221 default: 1222 return true; 1223 1224 case Intrinsic::experimental_gc_statepoint: 1225 case Intrinsic::experimental_patchpoint_void: 1226 case Intrinsic::experimental_patchpoint_i64: 1227 return false; 1228 } 1229 } 1230 1231 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1232 #define GET_INTRINSIC_ATTRIBUTES 1233 #include "llvm/IR/IntrinsicImpl.inc" 1234 #undef GET_INTRINSIC_ATTRIBUTES 1235 1236 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1237 // There can never be multiple globals with the same name of different types, 1238 // because intrinsics must be a specific type. 1239 return cast<Function>( 1240 M->getOrInsertFunction(getName(id, Tys), 1241 getType(M->getContext(), id, Tys)) 1242 .getCallee()); 1243 } 1244 1245 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 1246 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1247 #include "llvm/IR/IntrinsicImpl.inc" 1248 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1249 1250 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1251 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1252 #include "llvm/IR/IntrinsicImpl.inc" 1253 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1254 1255 using DeferredIntrinsicMatchPair = 1256 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1257 1258 static bool matchIntrinsicType( 1259 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1260 SmallVectorImpl<Type *> &ArgTys, 1261 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1262 bool IsDeferredCheck) { 1263 using namespace Intrinsic; 1264 1265 // If we ran out of descriptors, there are too many arguments. 1266 if (Infos.empty()) return true; 1267 1268 // Do this before slicing off the 'front' part 1269 auto InfosRef = Infos; 1270 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1271 DeferredChecks.emplace_back(T, InfosRef); 1272 return false; 1273 }; 1274 1275 IITDescriptor D = Infos.front(); 1276 Infos = Infos.slice(1); 1277 1278 switch (D.Kind) { 1279 case IITDescriptor::Void: return !Ty->isVoidTy(); 1280 case IITDescriptor::VarArg: return true; 1281 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 1282 case IITDescriptor::Token: return !Ty->isTokenTy(); 1283 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1284 case IITDescriptor::Half: return !Ty->isHalfTy(); 1285 case IITDescriptor::BFloat: return !Ty->isBFloatTy(); 1286 case IITDescriptor::Float: return !Ty->isFloatTy(); 1287 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1288 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1289 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1290 case IITDescriptor::Vector: { 1291 VectorType *VT = dyn_cast<VectorType>(Ty); 1292 return !VT || VT->getElementCount() != D.Vector_Width || 1293 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1294 DeferredChecks, IsDeferredCheck); 1295 } 1296 case IITDescriptor::Pointer: { 1297 PointerType *PT = dyn_cast<PointerType>(Ty); 1298 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 1299 matchIntrinsicType(PT->getElementType(), Infos, ArgTys, 1300 DeferredChecks, IsDeferredCheck); 1301 } 1302 1303 case IITDescriptor::Struct: { 1304 StructType *ST = dyn_cast<StructType>(Ty); 1305 if (!ST || ST->getNumElements() != D.Struct_NumElements) 1306 return true; 1307 1308 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1309 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1310 DeferredChecks, IsDeferredCheck)) 1311 return true; 1312 return false; 1313 } 1314 1315 case IITDescriptor::Argument: 1316 // If this is the second occurrence of an argument, 1317 // verify that the later instance matches the previous instance. 1318 if (D.getArgumentNumber() < ArgTys.size()) 1319 return Ty != ArgTys[D.getArgumentNumber()]; 1320 1321 if (D.getArgumentNumber() > ArgTys.size() || 1322 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1323 return IsDeferredCheck || DeferCheck(Ty); 1324 1325 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1326 "Table consistency error"); 1327 ArgTys.push_back(Ty); 1328 1329 switch (D.getArgumentKind()) { 1330 case IITDescriptor::AK_Any: return false; // Success 1331 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1332 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1333 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1334 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1335 default: break; 1336 } 1337 llvm_unreachable("all argument kinds not covered"); 1338 1339 case IITDescriptor::ExtendArgument: { 1340 // If this is a forward reference, defer the check for later. 1341 if (D.getArgumentNumber() >= ArgTys.size()) 1342 return IsDeferredCheck || DeferCheck(Ty); 1343 1344 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1345 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1346 NewTy = VectorType::getExtendedElementVectorType(VTy); 1347 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1348 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1349 else 1350 return true; 1351 1352 return Ty != NewTy; 1353 } 1354 case IITDescriptor::TruncArgument: { 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::getTruncatedElementVectorType(VTy); 1362 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1363 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1364 else 1365 return true; 1366 1367 return Ty != NewTy; 1368 } 1369 case IITDescriptor::HalfVecArgument: 1370 // If this is a forward reference, defer the check for later. 1371 if (D.getArgumentNumber() >= ArgTys.size()) 1372 return IsDeferredCheck || DeferCheck(Ty); 1373 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1374 VectorType::getHalfElementsVectorType( 1375 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1376 case IITDescriptor::SameVecWidthArgument: { 1377 if (D.getArgumentNumber() >= ArgTys.size()) { 1378 // Defer check and subsequent check for the vector element type. 1379 Infos = Infos.slice(1); 1380 return IsDeferredCheck || DeferCheck(Ty); 1381 } 1382 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1383 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1384 // Both must be vectors of the same number of elements or neither. 1385 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1386 return true; 1387 Type *EltTy = Ty; 1388 if (ThisArgType) { 1389 if (ReferenceType->getElementCount() != 1390 ThisArgType->getElementCount()) 1391 return true; 1392 EltTy = ThisArgType->getElementType(); 1393 } 1394 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1395 IsDeferredCheck); 1396 } 1397 case IITDescriptor::PtrToArgument: { 1398 if (D.getArgumentNumber() >= ArgTys.size()) 1399 return IsDeferredCheck || DeferCheck(Ty); 1400 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1401 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1402 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1403 } 1404 case IITDescriptor::PtrToElt: { 1405 if (D.getArgumentNumber() >= ArgTys.size()) 1406 return IsDeferredCheck || DeferCheck(Ty); 1407 VectorType * ReferenceType = 1408 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1409 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1410 1411 return (!ThisArgType || !ReferenceType || 1412 ThisArgType->getElementType() != ReferenceType->getElementType()); 1413 } 1414 case IITDescriptor::VecOfAnyPtrsToElt: { 1415 unsigned RefArgNumber = D.getRefArgNumber(); 1416 if (RefArgNumber >= ArgTys.size()) { 1417 if (IsDeferredCheck) 1418 return true; 1419 // If forward referencing, already add the pointer-vector type and 1420 // defer the checks for later. 1421 ArgTys.push_back(Ty); 1422 return DeferCheck(Ty); 1423 } 1424 1425 if (!IsDeferredCheck){ 1426 assert(D.getOverloadArgNumber() == ArgTys.size() && 1427 "Table consistency error"); 1428 ArgTys.push_back(Ty); 1429 } 1430 1431 // Verify the overloaded type "matches" the Ref type. 1432 // i.e. Ty is a vector with the same width as Ref. 1433 // Composed of pointers to the same element type as Ref. 1434 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1435 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1436 if (!ThisArgVecTy || !ReferenceType || 1437 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount())) 1438 return true; 1439 PointerType *ThisArgEltTy = 1440 dyn_cast<PointerType>(ThisArgVecTy->getElementType()); 1441 if (!ThisArgEltTy) 1442 return true; 1443 return ThisArgEltTy->getElementType() != ReferenceType->getElementType(); 1444 } 1445 case IITDescriptor::VecElementArgument: { 1446 if (D.getArgumentNumber() >= ArgTys.size()) 1447 return IsDeferredCheck ? true : DeferCheck(Ty); 1448 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1449 return !ReferenceType || Ty != ReferenceType->getElementType(); 1450 } 1451 case IITDescriptor::Subdivide2Argument: 1452 case IITDescriptor::Subdivide4Argument: { 1453 // If this is a forward reference, defer the check for later. 1454 if (D.getArgumentNumber() >= ArgTys.size()) 1455 return IsDeferredCheck || DeferCheck(Ty); 1456 1457 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1458 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1459 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1460 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1461 return Ty != NewTy; 1462 } 1463 return true; 1464 } 1465 case IITDescriptor::VecOfBitcastsToInt: { 1466 if (D.getArgumentNumber() >= ArgTys.size()) 1467 return IsDeferredCheck || DeferCheck(Ty); 1468 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1469 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1470 if (!ThisArgVecTy || !ReferenceType) 1471 return true; 1472 return ThisArgVecTy != VectorType::getInteger(ReferenceType); 1473 } 1474 } 1475 llvm_unreachable("unhandled"); 1476 } 1477 1478 Intrinsic::MatchIntrinsicTypesResult 1479 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1480 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1481 SmallVectorImpl<Type *> &ArgTys) { 1482 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1483 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1484 false)) 1485 return MatchIntrinsicTypes_NoMatchRet; 1486 1487 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1488 1489 for (auto Ty : FTy->params()) 1490 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1491 return MatchIntrinsicTypes_NoMatchArg; 1492 1493 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1494 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1495 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1496 true)) 1497 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1498 : MatchIntrinsicTypes_NoMatchArg; 1499 } 1500 1501 return MatchIntrinsicTypes_Match; 1502 } 1503 1504 bool 1505 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1506 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1507 // If there are no descriptors left, then it can't be a vararg. 1508 if (Infos.empty()) 1509 return isVarArg; 1510 1511 // There should be only one descriptor remaining at this point. 1512 if (Infos.size() != 1) 1513 return true; 1514 1515 // Check and verify the descriptor. 1516 IITDescriptor D = Infos.front(); 1517 Infos = Infos.slice(1); 1518 if (D.Kind == IITDescriptor::VarArg) 1519 return !isVarArg; 1520 1521 return true; 1522 } 1523 1524 bool Intrinsic::getIntrinsicSignature(Function *F, 1525 SmallVectorImpl<Type *> &ArgTys) { 1526 Intrinsic::ID ID = F->getIntrinsicID(); 1527 if (!ID) 1528 return false; 1529 1530 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1531 getIntrinsicInfoTableEntries(ID, Table); 1532 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1533 1534 if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef, 1535 ArgTys) != 1536 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) { 1537 return false; 1538 } 1539 if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(), 1540 TableRef)) 1541 return false; 1542 return true; 1543 } 1544 1545 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) { 1546 SmallVector<Type *, 4> ArgTys; 1547 if (!getIntrinsicSignature(F, ArgTys)) 1548 return None; 1549 1550 Intrinsic::ID ID = F->getIntrinsicID(); 1551 StringRef Name = F->getName(); 1552 if (Name == Intrinsic::getName(ID, ArgTys)) 1553 return None; 1554 1555 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1556 NewDecl->setCallingConv(F->getCallingConv()); 1557 assert(NewDecl->getFunctionType() == F->getFunctionType() && 1558 "Shouldn't change the signature"); 1559 return NewDecl; 1560 } 1561 1562 /// hasAddressTaken - returns true if there are any uses of this function 1563 /// other than direct calls or invokes to it. Optionally ignores callback 1564 /// uses. 1565 bool Function::hasAddressTaken(const User **PutOffender, 1566 bool IgnoreCallbackUses) const { 1567 for (const Use &U : uses()) { 1568 const User *FU = U.getUser(); 1569 if (isa<BlockAddress>(FU)) 1570 continue; 1571 1572 if (IgnoreCallbackUses) { 1573 AbstractCallSite ACS(&U); 1574 if (ACS && ACS.isCallbackCall()) 1575 continue; 1576 } 1577 1578 const auto *Call = dyn_cast<CallBase>(FU); 1579 if (!Call) { 1580 if (PutOffender) 1581 *PutOffender = FU; 1582 return true; 1583 } 1584 if (!Call->isCallee(&U)) { 1585 if (PutOffender) 1586 *PutOffender = FU; 1587 return true; 1588 } 1589 } 1590 return false; 1591 } 1592 1593 bool Function::isDefTriviallyDead() const { 1594 // Check the linkage 1595 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1596 !hasAvailableExternallyLinkage()) 1597 return false; 1598 1599 // Check if the function is used by anything other than a blockaddress. 1600 for (const User *U : users()) 1601 if (!isa<BlockAddress>(U)) 1602 return false; 1603 1604 return true; 1605 } 1606 1607 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1608 /// setjmp or other function that gcc recognizes as "returning twice". 1609 bool Function::callsFunctionThatReturnsTwice() const { 1610 for (const Instruction &I : instructions(this)) 1611 if (const auto *Call = dyn_cast<CallBase>(&I)) 1612 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1613 return true; 1614 1615 return false; 1616 } 1617 1618 Constant *Function::getPersonalityFn() const { 1619 assert(hasPersonalityFn() && getNumOperands()); 1620 return cast<Constant>(Op<0>()); 1621 } 1622 1623 void Function::setPersonalityFn(Constant *Fn) { 1624 setHungoffOperand<0>(Fn); 1625 setValueSubclassDataBit(3, Fn != nullptr); 1626 } 1627 1628 Constant *Function::getPrefixData() const { 1629 assert(hasPrefixData() && getNumOperands()); 1630 return cast<Constant>(Op<1>()); 1631 } 1632 1633 void Function::setPrefixData(Constant *PrefixData) { 1634 setHungoffOperand<1>(PrefixData); 1635 setValueSubclassDataBit(1, PrefixData != nullptr); 1636 } 1637 1638 Constant *Function::getPrologueData() const { 1639 assert(hasPrologueData() && getNumOperands()); 1640 return cast<Constant>(Op<2>()); 1641 } 1642 1643 void Function::setPrologueData(Constant *PrologueData) { 1644 setHungoffOperand<2>(PrologueData); 1645 setValueSubclassDataBit(2, PrologueData != nullptr); 1646 } 1647 1648 void Function::allocHungoffUselist() { 1649 // If we've already allocated a uselist, stop here. 1650 if (getNumOperands()) 1651 return; 1652 1653 allocHungoffUses(3, /*IsPhi=*/ false); 1654 setNumHungOffUseOperands(3); 1655 1656 // Initialize the uselist with placeholder operands to allow traversal. 1657 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1658 Op<0>().set(CPN); 1659 Op<1>().set(CPN); 1660 Op<2>().set(CPN); 1661 } 1662 1663 template <int Idx> 1664 void Function::setHungoffOperand(Constant *C) { 1665 if (C) { 1666 allocHungoffUselist(); 1667 Op<Idx>().set(C); 1668 } else if (getNumOperands()) { 1669 Op<Idx>().set( 1670 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1671 } 1672 } 1673 1674 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1675 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1676 if (On) 1677 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1678 else 1679 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1680 } 1681 1682 void Function::setEntryCount(ProfileCount Count, 1683 const DenseSet<GlobalValue::GUID> *S) { 1684 assert(Count.hasValue()); 1685 #if !defined(NDEBUG) 1686 auto PrevCount = getEntryCount(); 1687 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType()); 1688 #endif 1689 1690 auto ImportGUIDs = getImportGUIDs(); 1691 if (S == nullptr && ImportGUIDs.size()) 1692 S = &ImportGUIDs; 1693 1694 MDBuilder MDB(getContext()); 1695 setMetadata( 1696 LLVMContext::MD_prof, 1697 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 1698 } 1699 1700 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 1701 const DenseSet<GlobalValue::GUID> *Imports) { 1702 setEntryCount(ProfileCount(Count, Type), Imports); 1703 } 1704 1705 ProfileCount Function::getEntryCount(bool AllowSynthetic) const { 1706 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1707 if (MD && MD->getOperand(0)) 1708 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 1709 if (MDS->getString().equals("function_entry_count")) { 1710 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1711 uint64_t Count = CI->getValue().getZExtValue(); 1712 // A value of -1 is used for SamplePGO when there were no samples. 1713 // Treat this the same as unknown. 1714 if (Count == (uint64_t)-1) 1715 return ProfileCount::getInvalid(); 1716 return ProfileCount(Count, PCT_Real); 1717 } else if (AllowSynthetic && 1718 MDS->getString().equals("synthetic_function_entry_count")) { 1719 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1720 uint64_t Count = CI->getValue().getZExtValue(); 1721 return ProfileCount(Count, PCT_Synthetic); 1722 } 1723 } 1724 return ProfileCount::getInvalid(); 1725 } 1726 1727 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1728 DenseSet<GlobalValue::GUID> R; 1729 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1730 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1731 if (MDS->getString().equals("function_entry_count")) 1732 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1733 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1734 ->getValue() 1735 .getZExtValue()); 1736 return R; 1737 } 1738 1739 void Function::setSectionPrefix(StringRef Prefix) { 1740 MDBuilder MDB(getContext()); 1741 setMetadata(LLVMContext::MD_section_prefix, 1742 MDB.createFunctionSectionPrefix(Prefix)); 1743 } 1744 1745 Optional<StringRef> Function::getSectionPrefix() const { 1746 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1747 assert(cast<MDString>(MD->getOperand(0)) 1748 ->getString() 1749 .equals("function_section_prefix") && 1750 "Metadata not match"); 1751 return cast<MDString>(MD->getOperand(1))->getString(); 1752 } 1753 return None; 1754 } 1755 1756 bool Function::nullPointerIsDefined() const { 1757 return hasFnAttribute(Attribute::NullPointerIsValid); 1758 } 1759 1760 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 1761 if (F && F->nullPointerIsDefined()) 1762 return true; 1763 1764 if (AS != 0) 1765 return true; 1766 1767 return false; 1768 } 1769