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