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