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