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