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/IntrinsicImpl.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/IntrinsicImpl.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 IIT_F128 = 41 678 }; 679 680 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 681 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 682 using namespace Intrinsic; 683 684 IIT_Info Info = IIT_Info(Infos[NextElt++]); 685 unsigned StructElts = 2; 686 687 switch (Info) { 688 case IIT_Done: 689 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 690 return; 691 case IIT_VARARG: 692 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 693 return; 694 case IIT_MMX: 695 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 696 return; 697 case IIT_TOKEN: 698 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 699 return; 700 case IIT_METADATA: 701 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 702 return; 703 case IIT_F16: 704 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 705 return; 706 case IIT_F32: 707 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 708 return; 709 case IIT_F64: 710 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 711 return; 712 case IIT_F128: 713 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 714 return; 715 case IIT_I1: 716 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 717 return; 718 case IIT_I8: 719 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 720 return; 721 case IIT_I16: 722 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 723 return; 724 case IIT_I32: 725 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 726 return; 727 case IIT_I64: 728 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 729 return; 730 case IIT_I128: 731 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 732 return; 733 case IIT_V1: 734 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 735 DecodeIITType(NextElt, Infos, OutputTable); 736 return; 737 case IIT_V2: 738 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 739 DecodeIITType(NextElt, Infos, OutputTable); 740 return; 741 case IIT_V4: 742 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 743 DecodeIITType(NextElt, Infos, OutputTable); 744 return; 745 case IIT_V8: 746 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 747 DecodeIITType(NextElt, Infos, OutputTable); 748 return; 749 case IIT_V16: 750 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 751 DecodeIITType(NextElt, Infos, OutputTable); 752 return; 753 case IIT_V32: 754 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 755 DecodeIITType(NextElt, Infos, OutputTable); 756 return; 757 case IIT_V64: 758 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 759 DecodeIITType(NextElt, Infos, OutputTable); 760 return; 761 case IIT_V512: 762 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 763 DecodeIITType(NextElt, Infos, OutputTable); 764 return; 765 case IIT_V1024: 766 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 767 DecodeIITType(NextElt, Infos, OutputTable); 768 return; 769 case IIT_PTR: 770 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 771 DecodeIITType(NextElt, Infos, OutputTable); 772 return; 773 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 774 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 775 Infos[NextElt++])); 776 DecodeIITType(NextElt, Infos, OutputTable); 777 return; 778 } 779 case IIT_ARG: { 780 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 781 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 782 return; 783 } 784 case IIT_EXTEND_ARG: { 785 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 786 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 787 ArgInfo)); 788 return; 789 } 790 case IIT_TRUNC_ARG: { 791 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 792 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 793 ArgInfo)); 794 return; 795 } 796 case IIT_HALF_VEC_ARG: { 797 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 798 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 799 ArgInfo)); 800 return; 801 } 802 case IIT_SAME_VEC_WIDTH_ARG: { 803 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 804 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 805 ArgInfo)); 806 return; 807 } 808 case IIT_PTR_TO_ARG: { 809 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 810 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 811 ArgInfo)); 812 return; 813 } 814 case IIT_PTR_TO_ELT: { 815 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 816 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 817 return; 818 } 819 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 820 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 821 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 822 OutputTable.push_back( 823 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 824 return; 825 } 826 case IIT_EMPTYSTRUCT: 827 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 828 return; 829 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH; 830 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH; 831 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH; 832 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 833 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 834 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 835 case IIT_STRUCT2: { 836 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 837 838 for (unsigned i = 0; i != StructElts; ++i) 839 DecodeIITType(NextElt, Infos, OutputTable); 840 return; 841 } 842 } 843 llvm_unreachable("unhandled"); 844 } 845 846 #define GET_INTRINSIC_GENERATOR_GLOBAL 847 #include "llvm/IR/IntrinsicImpl.inc" 848 #undef GET_INTRINSIC_GENERATOR_GLOBAL 849 850 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 851 SmallVectorImpl<IITDescriptor> &T){ 852 // Check to see if the intrinsic's type was expressible by the table. 853 unsigned TableVal = IIT_Table[id-1]; 854 855 // Decode the TableVal into an array of IITValues. 856 SmallVector<unsigned char, 8> IITValues; 857 ArrayRef<unsigned char> IITEntries; 858 unsigned NextElt = 0; 859 if ((TableVal >> 31) != 0) { 860 // This is an offset into the IIT_LongEncodingTable. 861 IITEntries = IIT_LongEncodingTable; 862 863 // Strip sentinel bit. 864 NextElt = (TableVal << 1) >> 1; 865 } else { 866 // Decode the TableVal into an array of IITValues. If the entry was encoded 867 // into a single word in the table itself, decode it now. 868 do { 869 IITValues.push_back(TableVal & 0xF); 870 TableVal >>= 4; 871 } while (TableVal); 872 873 IITEntries = IITValues; 874 NextElt = 0; 875 } 876 877 // Okay, decode the table into the output vector of IITDescriptors. 878 DecodeIITType(NextElt, IITEntries, T); 879 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 880 DecodeIITType(NextElt, IITEntries, T); 881 } 882 883 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 884 ArrayRef<Type*> Tys, LLVMContext &Context) { 885 using namespace Intrinsic; 886 887 IITDescriptor D = Infos.front(); 888 Infos = Infos.slice(1); 889 890 switch (D.Kind) { 891 case IITDescriptor::Void: return Type::getVoidTy(Context); 892 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 893 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 894 case IITDescriptor::Token: return Type::getTokenTy(Context); 895 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 896 case IITDescriptor::Half: return Type::getHalfTy(Context); 897 case IITDescriptor::Float: return Type::getFloatTy(Context); 898 case IITDescriptor::Double: return Type::getDoubleTy(Context); 899 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 900 901 case IITDescriptor::Integer: 902 return IntegerType::get(Context, D.Integer_Width); 903 case IITDescriptor::Vector: 904 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 905 case IITDescriptor::Pointer: 906 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 907 D.Pointer_AddressSpace); 908 case IITDescriptor::Struct: { 909 SmallVector<Type *, 8> Elts; 910 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 911 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 912 return StructType::get(Context, Elts); 913 } 914 case IITDescriptor::Argument: 915 return Tys[D.getArgumentNumber()]; 916 case IITDescriptor::ExtendArgument: { 917 Type *Ty = Tys[D.getArgumentNumber()]; 918 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 919 return VectorType::getExtendedElementVectorType(VTy); 920 921 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 922 } 923 case IITDescriptor::TruncArgument: { 924 Type *Ty = Tys[D.getArgumentNumber()]; 925 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 926 return VectorType::getTruncatedElementVectorType(VTy); 927 928 IntegerType *ITy = cast<IntegerType>(Ty); 929 assert(ITy->getBitWidth() % 2 == 0); 930 return IntegerType::get(Context, ITy->getBitWidth() / 2); 931 } 932 case IITDescriptor::HalfVecArgument: 933 return VectorType::getHalfElementsVectorType(cast<VectorType>( 934 Tys[D.getArgumentNumber()])); 935 case IITDescriptor::SameVecWidthArgument: { 936 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 937 Type *Ty = Tys[D.getArgumentNumber()]; 938 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 939 return VectorType::get(EltTy, VTy->getNumElements()); 940 } 941 llvm_unreachable("unhandled"); 942 } 943 case IITDescriptor::PtrToArgument: { 944 Type *Ty = Tys[D.getArgumentNumber()]; 945 return PointerType::getUnqual(Ty); 946 } 947 case IITDescriptor::PtrToElt: { 948 Type *Ty = Tys[D.getArgumentNumber()]; 949 VectorType *VTy = dyn_cast<VectorType>(Ty); 950 if (!VTy) 951 llvm_unreachable("Expected an argument of Vector Type"); 952 Type *EltTy = VTy->getVectorElementType(); 953 return PointerType::getUnqual(EltTy); 954 } 955 case IITDescriptor::VecOfAnyPtrsToElt: 956 // Return the overloaded type (which determines the pointers address space) 957 return Tys[D.getOverloadArgNumber()]; 958 } 959 llvm_unreachable("unhandled"); 960 } 961 962 FunctionType *Intrinsic::getType(LLVMContext &Context, 963 ID id, ArrayRef<Type*> Tys) { 964 SmallVector<IITDescriptor, 8> Table; 965 getIntrinsicInfoTableEntries(id, Table); 966 967 ArrayRef<IITDescriptor> TableRef = Table; 968 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 969 970 SmallVector<Type*, 8> ArgTys; 971 while (!TableRef.empty()) 972 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 973 974 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 975 // If we see void type as the type of the last argument, it is vararg intrinsic 976 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 977 ArgTys.pop_back(); 978 return FunctionType::get(ResultTy, ArgTys, true); 979 } 980 return FunctionType::get(ResultTy, ArgTys, false); 981 } 982 983 bool Intrinsic::isOverloaded(ID id) { 984 #define GET_INTRINSIC_OVERLOAD_TABLE 985 #include "llvm/IR/IntrinsicImpl.inc" 986 #undef GET_INTRINSIC_OVERLOAD_TABLE 987 } 988 989 bool Intrinsic::isLeaf(ID id) { 990 switch (id) { 991 default: 992 return true; 993 994 case Intrinsic::experimental_gc_statepoint: 995 case Intrinsic::experimental_patchpoint_void: 996 case Intrinsic::experimental_patchpoint_i64: 997 return false; 998 } 999 } 1000 1001 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1002 #define GET_INTRINSIC_ATTRIBUTES 1003 #include "llvm/IR/IntrinsicImpl.inc" 1004 #undef GET_INTRINSIC_ATTRIBUTES 1005 1006 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1007 // There can never be multiple globals with the same name of different types, 1008 // because intrinsics must be a specific type. 1009 return 1010 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 1011 getType(M->getContext(), id, Tys))); 1012 } 1013 1014 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 1015 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1016 #include "llvm/IR/IntrinsicImpl.inc" 1017 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1018 1019 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1020 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1021 #include "llvm/IR/IntrinsicImpl.inc" 1022 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1023 1024 bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1025 SmallVectorImpl<Type*> &ArgTys) { 1026 using namespace Intrinsic; 1027 1028 // If we ran out of descriptors, there are too many arguments. 1029 if (Infos.empty()) return true; 1030 IITDescriptor D = Infos.front(); 1031 Infos = Infos.slice(1); 1032 1033 switch (D.Kind) { 1034 case IITDescriptor::Void: return !Ty->isVoidTy(); 1035 case IITDescriptor::VarArg: return true; 1036 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 1037 case IITDescriptor::Token: return !Ty->isTokenTy(); 1038 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1039 case IITDescriptor::Half: return !Ty->isHalfTy(); 1040 case IITDescriptor::Float: return !Ty->isFloatTy(); 1041 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1042 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1043 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1044 case IITDescriptor::Vector: { 1045 VectorType *VT = dyn_cast<VectorType>(Ty); 1046 return !VT || VT->getNumElements() != D.Vector_Width || 1047 matchIntrinsicType(VT->getElementType(), Infos, ArgTys); 1048 } 1049 case IITDescriptor::Pointer: { 1050 PointerType *PT = dyn_cast<PointerType>(Ty); 1051 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 1052 matchIntrinsicType(PT->getElementType(), Infos, ArgTys); 1053 } 1054 1055 case IITDescriptor::Struct: { 1056 StructType *ST = dyn_cast<StructType>(Ty); 1057 if (!ST || ST->getNumElements() != D.Struct_NumElements) 1058 return true; 1059 1060 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1061 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 1062 return true; 1063 return false; 1064 } 1065 1066 case IITDescriptor::Argument: 1067 // Two cases here - If this is the second occurrence of an argument, verify 1068 // that the later instance matches the previous instance. 1069 if (D.getArgumentNumber() < ArgTys.size()) 1070 return Ty != ArgTys[D.getArgumentNumber()]; 1071 1072 // Otherwise, if this is the first instance of an argument, record it and 1073 // verify the "Any" kind. 1074 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 1075 ArgTys.push_back(Ty); 1076 1077 switch (D.getArgumentKind()) { 1078 case IITDescriptor::AK_Any: return false; // Success 1079 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1080 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1081 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1082 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1083 } 1084 llvm_unreachable("all argument kinds not covered"); 1085 1086 case IITDescriptor::ExtendArgument: { 1087 // This may only be used when referring to a previous vector argument. 1088 if (D.getArgumentNumber() >= ArgTys.size()) 1089 return true; 1090 1091 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1092 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1093 NewTy = VectorType::getExtendedElementVectorType(VTy); 1094 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1095 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1096 else 1097 return true; 1098 1099 return Ty != NewTy; 1100 } 1101 case IITDescriptor::TruncArgument: { 1102 // This may only be used when referring to a previous vector argument. 1103 if (D.getArgumentNumber() >= ArgTys.size()) 1104 return true; 1105 1106 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1107 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1108 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1109 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1110 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1111 else 1112 return true; 1113 1114 return Ty != NewTy; 1115 } 1116 case IITDescriptor::HalfVecArgument: 1117 // This may only be used when referring to a previous vector argument. 1118 return D.getArgumentNumber() >= ArgTys.size() || 1119 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1120 VectorType::getHalfElementsVectorType( 1121 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1122 case IITDescriptor::SameVecWidthArgument: { 1123 if (D.getArgumentNumber() >= ArgTys.size()) 1124 return true; 1125 VectorType * ReferenceType = 1126 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1127 VectorType *ThisArgType = dyn_cast<VectorType>(Ty); 1128 if (!ThisArgType || !ReferenceType || 1129 (ReferenceType->getVectorNumElements() != 1130 ThisArgType->getVectorNumElements())) 1131 return true; 1132 return matchIntrinsicType(ThisArgType->getVectorElementType(), 1133 Infos, ArgTys); 1134 } 1135 case IITDescriptor::PtrToArgument: { 1136 if (D.getArgumentNumber() >= ArgTys.size()) 1137 return true; 1138 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1139 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1140 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1141 } 1142 case IITDescriptor::PtrToElt: { 1143 if (D.getArgumentNumber() >= ArgTys.size()) 1144 return true; 1145 VectorType * ReferenceType = 1146 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1147 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1148 1149 return (!ThisArgType || !ReferenceType || 1150 ThisArgType->getElementType() != ReferenceType->getElementType()); 1151 } 1152 case IITDescriptor::VecOfAnyPtrsToElt: { 1153 unsigned RefArgNumber = D.getRefArgNumber(); 1154 1155 // This may only be used when referring to a previous argument. 1156 if (RefArgNumber >= ArgTys.size()) 1157 return true; 1158 1159 // Record the overloaded type 1160 assert(D.getOverloadArgNumber() == ArgTys.size() && 1161 "Table consistency error"); 1162 ArgTys.push_back(Ty); 1163 1164 // Verify the overloaded type "matches" the Ref type. 1165 // i.e. Ty is a vector with the same width as Ref. 1166 // Composed of pointers to the same element type as Ref. 1167 VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1168 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1169 if (!ThisArgVecTy || !ReferenceType || 1170 (ReferenceType->getVectorNumElements() != 1171 ThisArgVecTy->getVectorNumElements())) 1172 return true; 1173 PointerType *ThisArgEltTy = 1174 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType()); 1175 if (!ThisArgEltTy) 1176 return true; 1177 return ThisArgEltTy->getElementType() != 1178 ReferenceType->getVectorElementType(); 1179 } 1180 } 1181 llvm_unreachable("unhandled"); 1182 } 1183 1184 bool 1185 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1186 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1187 // If there are no descriptors left, then it can't be a vararg. 1188 if (Infos.empty()) 1189 return isVarArg; 1190 1191 // There should be only one descriptor remaining at this point. 1192 if (Infos.size() != 1) 1193 return true; 1194 1195 // Check and verify the descriptor. 1196 IITDescriptor D = Infos.front(); 1197 Infos = Infos.slice(1); 1198 if (D.Kind == IITDescriptor::VarArg) 1199 return !isVarArg; 1200 1201 return true; 1202 } 1203 1204 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) { 1205 Intrinsic::ID ID = F->getIntrinsicID(); 1206 if (!ID) 1207 return None; 1208 1209 FunctionType *FTy = F->getFunctionType(); 1210 // Accumulate an array of overloaded types for the given intrinsic 1211 SmallVector<Type *, 4> ArgTys; 1212 { 1213 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1214 getIntrinsicInfoTableEntries(ID, Table); 1215 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1216 1217 // If we encounter any problems matching the signature with the descriptor 1218 // just give up remangling. It's up to verifier to report the discrepancy. 1219 if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys)) 1220 return None; 1221 for (auto Ty : FTy->params()) 1222 if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys)) 1223 return None; 1224 if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef)) 1225 return None; 1226 } 1227 1228 StringRef Name = F->getName(); 1229 if (Name == Intrinsic::getName(ID, ArgTys)) 1230 return None; 1231 1232 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1233 NewDecl->setCallingConv(F->getCallingConv()); 1234 assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature"); 1235 return NewDecl; 1236 } 1237 1238 /// hasAddressTaken - returns true if there are any uses of this function 1239 /// other than direct calls or invokes to it. 1240 bool Function::hasAddressTaken(const User* *PutOffender) const { 1241 for (const Use &U : uses()) { 1242 const User *FU = U.getUser(); 1243 if (isa<BlockAddress>(FU)) 1244 continue; 1245 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) { 1246 if (PutOffender) 1247 *PutOffender = FU; 1248 return true; 1249 } 1250 ImmutableCallSite CS(cast<Instruction>(FU)); 1251 if (!CS.isCallee(&U)) { 1252 if (PutOffender) 1253 *PutOffender = FU; 1254 return true; 1255 } 1256 } 1257 return false; 1258 } 1259 1260 bool Function::isDefTriviallyDead() const { 1261 // Check the linkage 1262 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1263 !hasAvailableExternallyLinkage()) 1264 return false; 1265 1266 // Check if the function is used by anything other than a blockaddress. 1267 for (const User *U : users()) 1268 if (!isa<BlockAddress>(U)) 1269 return false; 1270 1271 return true; 1272 } 1273 1274 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1275 /// setjmp or other function that gcc recognizes as "returning twice". 1276 bool Function::callsFunctionThatReturnsTwice() const { 1277 for (const_inst_iterator 1278 I = inst_begin(this), E = inst_end(this); I != E; ++I) { 1279 ImmutableCallSite CS(&*I); 1280 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice)) 1281 return true; 1282 } 1283 1284 return false; 1285 } 1286 1287 Constant *Function::getPersonalityFn() const { 1288 assert(hasPersonalityFn() && getNumOperands()); 1289 return cast<Constant>(Op<0>()); 1290 } 1291 1292 void Function::setPersonalityFn(Constant *Fn) { 1293 setHungoffOperand<0>(Fn); 1294 setValueSubclassDataBit(3, Fn != nullptr); 1295 } 1296 1297 Constant *Function::getPrefixData() const { 1298 assert(hasPrefixData() && getNumOperands()); 1299 return cast<Constant>(Op<1>()); 1300 } 1301 1302 void Function::setPrefixData(Constant *PrefixData) { 1303 setHungoffOperand<1>(PrefixData); 1304 setValueSubclassDataBit(1, PrefixData != nullptr); 1305 } 1306 1307 Constant *Function::getPrologueData() const { 1308 assert(hasPrologueData() && getNumOperands()); 1309 return cast<Constant>(Op<2>()); 1310 } 1311 1312 void Function::setPrologueData(Constant *PrologueData) { 1313 setHungoffOperand<2>(PrologueData); 1314 setValueSubclassDataBit(2, PrologueData != nullptr); 1315 } 1316 1317 void Function::allocHungoffUselist() { 1318 // If we've already allocated a uselist, stop here. 1319 if (getNumOperands()) 1320 return; 1321 1322 allocHungoffUses(3, /*IsPhi=*/ false); 1323 setNumHungOffUseOperands(3); 1324 1325 // Initialize the uselist with placeholder operands to allow traversal. 1326 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1327 Op<0>().set(CPN); 1328 Op<1>().set(CPN); 1329 Op<2>().set(CPN); 1330 } 1331 1332 template <int Idx> 1333 void Function::setHungoffOperand(Constant *C) { 1334 if (C) { 1335 allocHungoffUselist(); 1336 Op<Idx>().set(C); 1337 } else if (getNumOperands()) { 1338 Op<Idx>().set( 1339 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1340 } 1341 } 1342 1343 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1344 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1345 if (On) 1346 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1347 else 1348 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1349 } 1350 1351 void Function::setEntryCount(ProfileCount Count, 1352 const DenseSet<GlobalValue::GUID> *S) { 1353 assert(Count.hasValue()); 1354 #if !defined(NDEBUG) 1355 auto PrevCount = getEntryCount(); 1356 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType()); 1357 #endif 1358 MDBuilder MDB(getContext()); 1359 setMetadata( 1360 LLVMContext::MD_prof, 1361 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 1362 } 1363 1364 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 1365 const DenseSet<GlobalValue::GUID> *Imports) { 1366 setEntryCount(ProfileCount(Count, Type), Imports); 1367 } 1368 1369 ProfileCount Function::getEntryCount() const { 1370 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1371 if (MD && MD->getOperand(0)) 1372 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 1373 if (MDS->getString().equals("function_entry_count")) { 1374 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1375 uint64_t Count = CI->getValue().getZExtValue(); 1376 // A value of -1 is used for SamplePGO when there were no samples. 1377 // Treat this the same as unknown. 1378 if (Count == (uint64_t)-1) 1379 return ProfileCount::getInvalid(); 1380 return ProfileCount(Count, PCT_Real); 1381 } else if (MDS->getString().equals("synthetic_function_entry_count")) { 1382 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1383 uint64_t Count = CI->getValue().getZExtValue(); 1384 return ProfileCount(Count, PCT_Synthetic); 1385 } 1386 } 1387 return ProfileCount::getInvalid(); 1388 } 1389 1390 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1391 DenseSet<GlobalValue::GUID> R; 1392 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1393 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1394 if (MDS->getString().equals("function_entry_count")) 1395 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1396 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1397 ->getValue() 1398 .getZExtValue()); 1399 return R; 1400 } 1401 1402 void Function::setSectionPrefix(StringRef Prefix) { 1403 MDBuilder MDB(getContext()); 1404 setMetadata(LLVMContext::MD_section_prefix, 1405 MDB.createFunctionSectionPrefix(Prefix)); 1406 } 1407 1408 Optional<StringRef> Function::getSectionPrefix() const { 1409 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1410 assert(cast<MDString>(MD->getOperand(0)) 1411 ->getString() 1412 .equals("function_section_prefix") && 1413 "Metadata not match"); 1414 return cast<MDString>(MD->getOperand(1))->getString(); 1415 } 1416 return None; 1417 } 1418