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