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/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/CodeGen/ValueTypes.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/InstIterator.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/MDBuilder.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/Support/ManagedStatic.h" 31 #include "llvm/Support/RWMutex.h" 32 #include "llvm/Support/StringPool.h" 33 #include "llvm/Support/Threading.h" 34 using namespace llvm; 35 36 // Explicit instantiations of SymbolTableListTraits since some of the methods 37 // are not in the public header file... 38 template class llvm::SymbolTableListTraits<Argument>; 39 template class llvm::SymbolTableListTraits<BasicBlock>; 40 41 //===----------------------------------------------------------------------===// 42 // Argument Implementation 43 //===----------------------------------------------------------------------===// 44 45 void Argument::anchor() { } 46 47 Argument::Argument(Type *Ty, const Twine &Name, Function *Par) 48 : Value(Ty, Value::ArgumentVal) { 49 Parent = nullptr; 50 51 if (Par) 52 Par->getArgumentList().push_back(this); 53 setName(Name); 54 } 55 56 void Argument::setParent(Function *parent) { 57 Parent = parent; 58 } 59 60 /// getArgNo - Return the index of this formal argument in its containing 61 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1. 62 unsigned Argument::getArgNo() const { 63 const Function *F = getParent(); 64 assert(F && "Argument is not in a function"); 65 66 Function::const_arg_iterator AI = F->arg_begin(); 67 unsigned ArgIdx = 0; 68 for (; &*AI != this; ++AI) 69 ++ArgIdx; 70 71 return ArgIdx; 72 } 73 74 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on 75 /// it in its containing function. Also returns true if at least one byte is 76 /// known to be dereferenceable and the pointer is in addrspace(0). 77 bool Argument::hasNonNullAttr() const { 78 if (!getType()->isPointerTy()) return false; 79 if (getParent()->getAttributes(). 80 hasAttribute(getArgNo()+1, Attribute::NonNull)) 81 return true; 82 else if (getDereferenceableBytes() > 0 && 83 getType()->getPointerAddressSpace() == 0) 84 return true; 85 return false; 86 } 87 88 /// hasByValAttr - Return true if this argument has the byval attribute on it 89 /// in its containing function. 90 bool Argument::hasByValAttr() const { 91 if (!getType()->isPointerTy()) return false; 92 return getParent()->getAttributes(). 93 hasAttribute(getArgNo()+1, Attribute::ByVal); 94 } 95 96 /// \brief Return true if this argument has the inalloca attribute on it in 97 /// its containing function. 98 bool Argument::hasInAllocaAttr() const { 99 if (!getType()->isPointerTy()) return false; 100 return getParent()->getAttributes(). 101 hasAttribute(getArgNo()+1, Attribute::InAlloca); 102 } 103 104 bool Argument::hasByValOrInAllocaAttr() const { 105 if (!getType()->isPointerTy()) return false; 106 AttributeSet Attrs = getParent()->getAttributes(); 107 return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) || 108 Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca); 109 } 110 111 unsigned Argument::getParamAlignment() const { 112 assert(getType()->isPointerTy() && "Only pointers have alignments"); 113 return getParent()->getParamAlignment(getArgNo()+1); 114 115 } 116 117 uint64_t Argument::getDereferenceableBytes() const { 118 assert(getType()->isPointerTy() && 119 "Only pointers have dereferenceable bytes"); 120 return getParent()->getDereferenceableBytes(getArgNo()+1); 121 } 122 123 uint64_t Argument::getDereferenceableOrNullBytes() const { 124 assert(getType()->isPointerTy() && 125 "Only pointers have dereferenceable bytes"); 126 return getParent()->getDereferenceableOrNullBytes(getArgNo()+1); 127 } 128 129 /// hasNestAttr - Return true if this argument has the nest attribute on 130 /// it in its containing function. 131 bool Argument::hasNestAttr() const { 132 if (!getType()->isPointerTy()) return false; 133 return getParent()->getAttributes(). 134 hasAttribute(getArgNo()+1, Attribute::Nest); 135 } 136 137 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on 138 /// it in its containing function. 139 bool Argument::hasNoAliasAttr() const { 140 if (!getType()->isPointerTy()) return false; 141 return getParent()->getAttributes(). 142 hasAttribute(getArgNo()+1, Attribute::NoAlias); 143 } 144 145 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute 146 /// on it in its containing function. 147 bool Argument::hasNoCaptureAttr() const { 148 if (!getType()->isPointerTy()) return false; 149 return getParent()->getAttributes(). 150 hasAttribute(getArgNo()+1, Attribute::NoCapture); 151 } 152 153 /// hasSRetAttr - Return true if this argument has the sret attribute on 154 /// it in its containing function. 155 bool Argument::hasStructRetAttr() const { 156 if (!getType()->isPointerTy()) return false; 157 return getParent()->getAttributes(). 158 hasAttribute(getArgNo()+1, Attribute::StructRet); 159 } 160 161 /// hasReturnedAttr - Return true if this argument has the returned attribute on 162 /// it in its containing function. 163 bool Argument::hasReturnedAttr() const { 164 return getParent()->getAttributes(). 165 hasAttribute(getArgNo()+1, Attribute::Returned); 166 } 167 168 /// hasZExtAttr - Return true if this argument has the zext attribute on it in 169 /// its containing function. 170 bool Argument::hasZExtAttr() const { 171 return getParent()->getAttributes(). 172 hasAttribute(getArgNo()+1, Attribute::ZExt); 173 } 174 175 /// hasSExtAttr Return true if this argument has the sext attribute on it in its 176 /// containing function. 177 bool Argument::hasSExtAttr() const { 178 return getParent()->getAttributes(). 179 hasAttribute(getArgNo()+1, Attribute::SExt); 180 } 181 182 /// Return true if this argument has the readonly or readnone attribute on it 183 /// in its containing function. 184 bool Argument::onlyReadsMemory() const { 185 return getParent()->getAttributes(). 186 hasAttribute(getArgNo()+1, Attribute::ReadOnly) || 187 getParent()->getAttributes(). 188 hasAttribute(getArgNo()+1, Attribute::ReadNone); 189 } 190 191 /// addAttr - Add attributes to an argument. 192 void Argument::addAttr(AttributeSet AS) { 193 assert(AS.getNumSlots() <= 1 && 194 "Trying to add more than one attribute set to an argument!"); 195 AttrBuilder B(AS, AS.getSlotIndex(0)); 196 getParent()->addAttributes(getArgNo() + 1, 197 AttributeSet::get(Parent->getContext(), 198 getArgNo() + 1, B)); 199 } 200 201 /// removeAttr - Remove attributes from an argument. 202 void Argument::removeAttr(AttributeSet AS) { 203 assert(AS.getNumSlots() <= 1 && 204 "Trying to remove more than one attribute set from an argument!"); 205 AttrBuilder B(AS, AS.getSlotIndex(0)); 206 getParent()->removeAttributes(getArgNo() + 1, 207 AttributeSet::get(Parent->getContext(), 208 getArgNo() + 1, B)); 209 } 210 211 //===----------------------------------------------------------------------===// 212 // Helper Methods in Function 213 //===----------------------------------------------------------------------===// 214 215 bool Function::isMaterializable() const { 216 return getGlobalObjectSubClassData() & IsMaterializableBit; 217 } 218 219 void Function::setIsMaterializable(bool V) { 220 setGlobalObjectBit(IsMaterializableBit, V); 221 } 222 223 LLVMContext &Function::getContext() const { 224 return getType()->getContext(); 225 } 226 227 FunctionType *Function::getFunctionType() const { 228 return cast<FunctionType>(getValueType()); 229 } 230 231 bool Function::isVarArg() const { 232 return getFunctionType()->isVarArg(); 233 } 234 235 Type *Function::getReturnType() const { 236 return getFunctionType()->getReturnType(); 237 } 238 239 void Function::removeFromParent() { 240 getParent()->getFunctionList().remove(getIterator()); 241 } 242 243 void Function::eraseFromParent() { 244 getParent()->getFunctionList().erase(getIterator()); 245 } 246 247 //===----------------------------------------------------------------------===// 248 // Function Implementation 249 //===----------------------------------------------------------------------===// 250 251 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name, 252 Module *ParentModule) 253 : GlobalObject(Ty, Value::FunctionVal, 254 OperandTraits<Function>::op_begin(this), 0, Linkage, name) { 255 assert(FunctionType::isValidReturnType(getReturnType()) && 256 "invalid return type"); 257 setGlobalObjectSubClassData(0); 258 SymTab = new ValueSymbolTable(); 259 260 // If the function has arguments, mark them as lazily built. 261 if (Ty->getNumParams()) 262 setValueSubclassData(1); // Set the "has lazy arguments" bit. 263 264 if (ParentModule) 265 ParentModule->getFunctionList().push_back(this); 266 267 // Ensure intrinsics have the right parameter attributes. 268 // Note, the IntID field will have been set in Value::setName if this function 269 // name is a valid intrinsic ID. 270 if (IntID) 271 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 272 } 273 274 Function::~Function() { 275 dropAllReferences(); // After this it is safe to delete instructions. 276 277 // Delete all of the method arguments and unlink from symbol table... 278 ArgumentList.clear(); 279 delete SymTab; 280 281 // Remove the function from the on-the-side GC table. 282 clearGC(); 283 } 284 285 void Function::BuildLazyArguments() const { 286 // Create the arguments vector, all arguments start out unnamed. 287 FunctionType *FT = getFunctionType(); 288 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 289 assert(!FT->getParamType(i)->isVoidTy() && 290 "Cannot have void typed arguments!"); 291 ArgumentList.push_back(new Argument(FT->getParamType(i))); 292 } 293 294 // Clear the lazy arguments bit. 295 unsigned SDC = getSubclassDataFromValue(); 296 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0)); 297 } 298 299 size_t Function::arg_size() const { 300 return getFunctionType()->getNumParams(); 301 } 302 bool Function::arg_empty() const { 303 return getFunctionType()->getNumParams() == 0; 304 } 305 306 void Function::setParent(Module *parent) { 307 Parent = parent; 308 } 309 310 // dropAllReferences() - This function causes all the subinstructions to "let 311 // go" of all references that they are maintaining. This allows one to 312 // 'delete' a whole class at a time, even though there may be circular 313 // references... first all references are dropped, and all use counts go to 314 // zero. Then everything is deleted for real. Note that no operations are 315 // valid on an object that has "dropped all references", except operator 316 // delete. 317 // 318 void Function::dropAllReferences() { 319 setIsMaterializable(false); 320 321 for (iterator I = begin(), E = end(); I != E; ++I) 322 I->dropAllReferences(); 323 324 // Delete all basic blocks. They are now unused, except possibly by 325 // blockaddresses, but BasicBlock's destructor takes care of those. 326 while (!BasicBlocks.empty()) 327 BasicBlocks.begin()->eraseFromParent(); 328 329 // Drop uses of any optional data (real or placeholder). 330 if (getNumOperands()) { 331 User::dropAllReferences(); 332 setNumHungOffUseOperands(0); 333 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 334 } 335 336 // Metadata is stored in a side-table. 337 clearMetadata(); 338 } 339 340 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) { 341 AttributeSet PAL = getAttributes(); 342 PAL = PAL.addAttribute(getContext(), i, attr); 343 setAttributes(PAL); 344 } 345 346 void Function::addAttributes(unsigned i, AttributeSet attrs) { 347 AttributeSet PAL = getAttributes(); 348 PAL = PAL.addAttributes(getContext(), i, attrs); 349 setAttributes(PAL); 350 } 351 352 void Function::removeAttributes(unsigned i, AttributeSet attrs) { 353 AttributeSet PAL = getAttributes(); 354 PAL = PAL.removeAttributes(getContext(), i, attrs); 355 setAttributes(PAL); 356 } 357 358 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 359 AttributeSet PAL = getAttributes(); 360 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 361 setAttributes(PAL); 362 } 363 364 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 365 AttributeSet PAL = getAttributes(); 366 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 367 setAttributes(PAL); 368 } 369 370 const std::string &Function::getGC() const { 371 assert(hasGC() && "Function has no collector"); 372 return getContext().getGC(*this); 373 } 374 375 void Function::setGC(const std::string Str) { 376 setValueSubclassDataBit(14, !Str.empty()); 377 getContext().setGC(*this, std::move(Str)); 378 } 379 380 void Function::clearGC() { 381 if (!hasGC()) 382 return; 383 getContext().deleteGC(*this); 384 setValueSubclassDataBit(14, false); 385 } 386 387 /// Copy all additional attributes (those not needed to create a Function) from 388 /// the Function Src to this one. 389 void Function::copyAttributesFrom(const GlobalValue *Src) { 390 GlobalObject::copyAttributesFrom(Src); 391 const Function *SrcF = dyn_cast<Function>(Src); 392 if (!SrcF) 393 return; 394 395 setCallingConv(SrcF->getCallingConv()); 396 setAttributes(SrcF->getAttributes()); 397 if (SrcF->hasGC()) 398 setGC(SrcF->getGC()); 399 else 400 clearGC(); 401 if (SrcF->hasPersonalityFn()) 402 setPersonalityFn(SrcF->getPersonalityFn()); 403 if (SrcF->hasPrefixData()) 404 setPrefixData(SrcF->getPrefixData()); 405 if (SrcF->hasPrologueData()) 406 setPrologueData(SrcF->getPrologueData()); 407 } 408 409 /// Table of string intrinsic names indexed by enum value. 410 static const char * const IntrinsicNameTable[] = { 411 "not_intrinsic", 412 #define GET_INTRINSIC_NAME_TABLE 413 #include "llvm/IR/Intrinsics.gen" 414 #undef GET_INTRINSIC_NAME_TABLE 415 }; 416 417 static int lookupLLVMIntrinsicByName(ArrayRef<const char *> NameTable, 418 StringRef Name) { 419 // Do a binary search over the table of intrinsic names. 420 const char *const *NameEntry = 421 std::lower_bound(NameTable.begin(), NameTable.end(), Name.data(), 422 [](const char *LHS, const char *RHS) { 423 // Don't compare the first 5 characters, they are 424 // always "llvm.". 425 return strcmp(LHS + 5, RHS + 5) < 0; 426 }); 427 unsigned Idx = NameEntry - NameTable.begin(); 428 429 // Check if this is a direct match. 430 if (Idx < NameTable.size() && strcmp(Name.data(), NameTable[Idx]) == 0) 431 return Idx; 432 433 // Otherwise, back up one entry to look for a prefix of Name where the next 434 // character in Name is a dot. 435 if (Idx == 0) 436 return -1; 437 --Idx; 438 bool CheckPrefixes = true; 439 while (CheckPrefixes) { 440 StringRef FoundName = NameTable[Idx]; 441 if (Name.startswith(FoundName) && Name[FoundName.size()] == '.') 442 return Idx; 443 if (Idx == 0) 444 return -1; 445 --Idx; 446 // We have to keep scanning backwards until the previous entry is not a 447 // prefix of the current entry. Consider a key of llvm.foo.f64 and a table 448 // of llvm.foo and llvm.foo.bar. 449 CheckPrefixes = FoundName.startswith(NameTable[Idx]); 450 } 451 452 return -1; 453 } 454 455 /// \brief This does the actual lookup of an intrinsic ID which 456 /// matches the given function name. 457 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) { 458 StringRef Name = ValName->getKey(); 459 assert(Name.data()[Name.size()] == '\0' && "non-null terminated ValueName"); 460 461 ArrayRef<const char *> NameTable(&IntrinsicNameTable[1], 462 std::end(IntrinsicNameTable)); 463 int Idx = lookupLLVMIntrinsicByName(NameTable, Name); 464 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + 1); 465 if (ID == Intrinsic::not_intrinsic) 466 return ID; 467 468 // If the intrinsic is not overloaded, require an exact match. If it is 469 // overloaded, require a prefix match. 470 bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]); 471 return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic; 472 } 473 474 void Function::recalculateIntrinsicID() { 475 const ValueName *ValName = this->getValueName(); 476 if (!ValName || !isIntrinsic()) { 477 IntID = Intrinsic::not_intrinsic; 478 return; 479 } 480 IntID = lookupIntrinsicID(ValName); 481 } 482 483 /// Returns a stable mangling for the type specified for use in the name 484 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 485 /// of named types is simply their name. Manglings for unnamed types consist 486 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 487 /// combined with the mangling of their component types. A vararg function 488 /// type will have a suffix of 'vararg'. Since function types can contain 489 /// other function types, we close a function type mangling with suffix 'f' 490 /// which can't be confused with it's prefix. This ensures we don't have 491 /// collisions between two unrelated function types. Otherwise, you might 492 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 493 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most 494 /// cases) fall back to the MVT codepath, where they could be mangled to 495 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle 496 /// everything. 497 static std::string getMangledTypeStr(Type* Ty) { 498 std::string Result; 499 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 500 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) + 501 getMangledTypeStr(PTyp->getElementType()); 502 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 503 Result += "a" + llvm::utostr(ATyp->getNumElements()) + 504 getMangledTypeStr(ATyp->getElementType()); 505 } else if (StructType* STyp = dyn_cast<StructType>(Ty)) { 506 assert(!STyp->isLiteral() && "TODO: implement literal types"); 507 Result += STyp->getName(); 508 } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) { 509 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 510 for (size_t i = 0; i < FT->getNumParams(); i++) 511 Result += getMangledTypeStr(FT->getParamType(i)); 512 if (FT->isVarArg()) 513 Result += "vararg"; 514 // Ensure nested function types are distinguishable. 515 Result += "f"; 516 } else if (isa<VectorType>(Ty)) 517 Result += "v" + utostr(Ty->getVectorNumElements()) + 518 getMangledTypeStr(Ty->getVectorElementType()); 519 else if (Ty) 520 Result += EVT::getEVT(Ty).getEVTString(); 521 return Result; 522 } 523 524 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 525 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 526 if (Tys.empty()) 527 return IntrinsicNameTable[id]; 528 std::string Result(IntrinsicNameTable[id]); 529 for (unsigned i = 0; i < Tys.size(); ++i) { 530 Result += "." + getMangledTypeStr(Tys[i]); 531 } 532 return Result; 533 } 534 535 536 /// IIT_Info - These are enumerators that describe the entries returned by the 537 /// getIntrinsicInfoTableEntries function. 538 /// 539 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 540 enum IIT_Info { 541 // Common values should be encoded with 0-15. 542 IIT_Done = 0, 543 IIT_I1 = 1, 544 IIT_I8 = 2, 545 IIT_I16 = 3, 546 IIT_I32 = 4, 547 IIT_I64 = 5, 548 IIT_F16 = 6, 549 IIT_F32 = 7, 550 IIT_F64 = 8, 551 IIT_V2 = 9, 552 IIT_V4 = 10, 553 IIT_V8 = 11, 554 IIT_V16 = 12, 555 IIT_V32 = 13, 556 IIT_PTR = 14, 557 IIT_ARG = 15, 558 559 // Values from 16+ are only encodable with the inefficient encoding. 560 IIT_V64 = 16, 561 IIT_MMX = 17, 562 IIT_TOKEN = 18, 563 IIT_METADATA = 19, 564 IIT_EMPTYSTRUCT = 20, 565 IIT_STRUCT2 = 21, 566 IIT_STRUCT3 = 22, 567 IIT_STRUCT4 = 23, 568 IIT_STRUCT5 = 24, 569 IIT_EXTEND_ARG = 25, 570 IIT_TRUNC_ARG = 26, 571 IIT_ANYPTR = 27, 572 IIT_V1 = 28, 573 IIT_VARARG = 29, 574 IIT_HALF_VEC_ARG = 30, 575 IIT_SAME_VEC_WIDTH_ARG = 31, 576 IIT_PTR_TO_ARG = 32, 577 IIT_VEC_OF_PTRS_TO_ELT = 33, 578 IIT_I128 = 34, 579 IIT_V512 = 35, 580 IIT_V1024 = 36 581 }; 582 583 584 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 585 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 586 IIT_Info Info = IIT_Info(Infos[NextElt++]); 587 unsigned StructElts = 2; 588 using namespace Intrinsic; 589 590 switch (Info) { 591 case IIT_Done: 592 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 593 return; 594 case IIT_VARARG: 595 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 596 return; 597 case IIT_MMX: 598 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 599 return; 600 case IIT_TOKEN: 601 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 602 return; 603 case IIT_METADATA: 604 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 605 return; 606 case IIT_F16: 607 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 608 return; 609 case IIT_F32: 610 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 611 return; 612 case IIT_F64: 613 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 614 return; 615 case IIT_I1: 616 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 617 return; 618 case IIT_I8: 619 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 620 return; 621 case IIT_I16: 622 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 623 return; 624 case IIT_I32: 625 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 626 return; 627 case IIT_I64: 628 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 629 return; 630 case IIT_I128: 631 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 632 return; 633 case IIT_V1: 634 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 635 DecodeIITType(NextElt, Infos, OutputTable); 636 return; 637 case IIT_V2: 638 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 639 DecodeIITType(NextElt, Infos, OutputTable); 640 return; 641 case IIT_V4: 642 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 643 DecodeIITType(NextElt, Infos, OutputTable); 644 return; 645 case IIT_V8: 646 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 647 DecodeIITType(NextElt, Infos, OutputTable); 648 return; 649 case IIT_V16: 650 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 651 DecodeIITType(NextElt, Infos, OutputTable); 652 return; 653 case IIT_V32: 654 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 655 DecodeIITType(NextElt, Infos, OutputTable); 656 return; 657 case IIT_V64: 658 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 659 DecodeIITType(NextElt, Infos, OutputTable); 660 return; 661 case IIT_V512: 662 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 663 DecodeIITType(NextElt, Infos, OutputTable); 664 return; 665 case IIT_V1024: 666 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 667 DecodeIITType(NextElt, Infos, OutputTable); 668 return; 669 case IIT_PTR: 670 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 671 DecodeIITType(NextElt, Infos, OutputTable); 672 return; 673 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 674 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 675 Infos[NextElt++])); 676 DecodeIITType(NextElt, Infos, OutputTable); 677 return; 678 } 679 case IIT_ARG: { 680 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 681 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 682 return; 683 } 684 case IIT_EXTEND_ARG: { 685 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 686 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 687 ArgInfo)); 688 return; 689 } 690 case IIT_TRUNC_ARG: { 691 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 692 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 693 ArgInfo)); 694 return; 695 } 696 case IIT_HALF_VEC_ARG: { 697 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 698 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 699 ArgInfo)); 700 return; 701 } 702 case IIT_SAME_VEC_WIDTH_ARG: { 703 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 704 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 705 ArgInfo)); 706 return; 707 } 708 case IIT_PTR_TO_ARG: { 709 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 710 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 711 ArgInfo)); 712 return; 713 } 714 case IIT_VEC_OF_PTRS_TO_ELT: { 715 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 716 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt, 717 ArgInfo)); 718 return; 719 } 720 case IIT_EMPTYSTRUCT: 721 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 722 return; 723 case IIT_STRUCT5: ++StructElts; // FALL THROUGH. 724 case IIT_STRUCT4: ++StructElts; // FALL THROUGH. 725 case IIT_STRUCT3: ++StructElts; // FALL THROUGH. 726 case IIT_STRUCT2: { 727 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 728 729 for (unsigned i = 0; i != StructElts; ++i) 730 DecodeIITType(NextElt, Infos, OutputTable); 731 return; 732 } 733 } 734 llvm_unreachable("unhandled"); 735 } 736 737 738 #define GET_INTRINSIC_GENERATOR_GLOBAL 739 #include "llvm/IR/Intrinsics.gen" 740 #undef GET_INTRINSIC_GENERATOR_GLOBAL 741 742 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 743 SmallVectorImpl<IITDescriptor> &T){ 744 // Check to see if the intrinsic's type was expressible by the table. 745 unsigned TableVal = IIT_Table[id-1]; 746 747 // Decode the TableVal into an array of IITValues. 748 SmallVector<unsigned char, 8> IITValues; 749 ArrayRef<unsigned char> IITEntries; 750 unsigned NextElt = 0; 751 if ((TableVal >> 31) != 0) { 752 // This is an offset into the IIT_LongEncodingTable. 753 IITEntries = IIT_LongEncodingTable; 754 755 // Strip sentinel bit. 756 NextElt = (TableVal << 1) >> 1; 757 } else { 758 // Decode the TableVal into an array of IITValues. If the entry was encoded 759 // into a single word in the table itself, decode it now. 760 do { 761 IITValues.push_back(TableVal & 0xF); 762 TableVal >>= 4; 763 } while (TableVal); 764 765 IITEntries = IITValues; 766 NextElt = 0; 767 } 768 769 // Okay, decode the table into the output vector of IITDescriptors. 770 DecodeIITType(NextElt, IITEntries, T); 771 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 772 DecodeIITType(NextElt, IITEntries, T); 773 } 774 775 776 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 777 ArrayRef<Type*> Tys, LLVMContext &Context) { 778 using namespace Intrinsic; 779 IITDescriptor D = Infos.front(); 780 Infos = Infos.slice(1); 781 782 switch (D.Kind) { 783 case IITDescriptor::Void: return Type::getVoidTy(Context); 784 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 785 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 786 case IITDescriptor::Token: return Type::getTokenTy(Context); 787 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 788 case IITDescriptor::Half: return Type::getHalfTy(Context); 789 case IITDescriptor::Float: return Type::getFloatTy(Context); 790 case IITDescriptor::Double: return Type::getDoubleTy(Context); 791 792 case IITDescriptor::Integer: 793 return IntegerType::get(Context, D.Integer_Width); 794 case IITDescriptor::Vector: 795 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 796 case IITDescriptor::Pointer: 797 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 798 D.Pointer_AddressSpace); 799 case IITDescriptor::Struct: { 800 Type *Elts[5]; 801 assert(D.Struct_NumElements <= 5 && "Can't handle this yet"); 802 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 803 Elts[i] = DecodeFixedType(Infos, Tys, Context); 804 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements)); 805 } 806 807 case IITDescriptor::Argument: 808 return Tys[D.getArgumentNumber()]; 809 case IITDescriptor::ExtendArgument: { 810 Type *Ty = Tys[D.getArgumentNumber()]; 811 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 812 return VectorType::getExtendedElementVectorType(VTy); 813 814 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 815 } 816 case IITDescriptor::TruncArgument: { 817 Type *Ty = Tys[D.getArgumentNumber()]; 818 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 819 return VectorType::getTruncatedElementVectorType(VTy); 820 821 IntegerType *ITy = cast<IntegerType>(Ty); 822 assert(ITy->getBitWidth() % 2 == 0); 823 return IntegerType::get(Context, ITy->getBitWidth() / 2); 824 } 825 case IITDescriptor::HalfVecArgument: 826 return VectorType::getHalfElementsVectorType(cast<VectorType>( 827 Tys[D.getArgumentNumber()])); 828 case IITDescriptor::SameVecWidthArgument: { 829 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 830 Type *Ty = Tys[D.getArgumentNumber()]; 831 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 832 return VectorType::get(EltTy, VTy->getNumElements()); 833 } 834 llvm_unreachable("unhandled"); 835 } 836 case IITDescriptor::PtrToArgument: { 837 Type *Ty = Tys[D.getArgumentNumber()]; 838 return PointerType::getUnqual(Ty); 839 } 840 case IITDescriptor::VecOfPtrsToElt: { 841 Type *Ty = Tys[D.getArgumentNumber()]; 842 VectorType *VTy = dyn_cast<VectorType>(Ty); 843 if (!VTy) 844 llvm_unreachable("Expected an argument of Vector Type"); 845 Type *EltTy = VTy->getVectorElementType(); 846 return VectorType::get(PointerType::getUnqual(EltTy), 847 VTy->getNumElements()); 848 } 849 } 850 llvm_unreachable("unhandled"); 851 } 852 853 854 855 FunctionType *Intrinsic::getType(LLVMContext &Context, 856 ID id, ArrayRef<Type*> Tys) { 857 SmallVector<IITDescriptor, 8> Table; 858 getIntrinsicInfoTableEntries(id, Table); 859 860 ArrayRef<IITDescriptor> TableRef = Table; 861 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 862 863 SmallVector<Type*, 8> ArgTys; 864 while (!TableRef.empty()) 865 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 866 867 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 868 // If we see void type as the type of the last argument, it is vararg intrinsic 869 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 870 ArgTys.pop_back(); 871 return FunctionType::get(ResultTy, ArgTys, true); 872 } 873 return FunctionType::get(ResultTy, ArgTys, false); 874 } 875 876 bool Intrinsic::isOverloaded(ID id) { 877 #define GET_INTRINSIC_OVERLOAD_TABLE 878 #include "llvm/IR/Intrinsics.gen" 879 #undef GET_INTRINSIC_OVERLOAD_TABLE 880 } 881 882 bool Intrinsic::isLeaf(ID id) { 883 switch (id) { 884 default: 885 return true; 886 887 case Intrinsic::experimental_gc_statepoint: 888 case Intrinsic::experimental_patchpoint_void: 889 case Intrinsic::experimental_patchpoint_i64: 890 return false; 891 } 892 } 893 894 /// This defines the "Intrinsic::getAttributes(ID id)" method. 895 #define GET_INTRINSIC_ATTRIBUTES 896 #include "llvm/IR/Intrinsics.gen" 897 #undef GET_INTRINSIC_ATTRIBUTES 898 899 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 900 // There can never be multiple globals with the same name of different types, 901 // because intrinsics must be a specific type. 902 return 903 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 904 getType(M->getContext(), id, Tys))); 905 } 906 907 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 908 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 909 #include "llvm/IR/Intrinsics.gen" 910 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 911 912 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 913 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 914 #include "llvm/IR/Intrinsics.gen" 915 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 916 917 /// hasAddressTaken - returns true if there are any uses of this function 918 /// other than direct calls or invokes to it. 919 bool Function::hasAddressTaken(const User* *PutOffender) const { 920 for (const Use &U : uses()) { 921 const User *FU = U.getUser(); 922 if (isa<BlockAddress>(FU)) 923 continue; 924 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) 925 return PutOffender ? (*PutOffender = FU, true) : true; 926 ImmutableCallSite CS(cast<Instruction>(FU)); 927 if (!CS.isCallee(&U)) 928 return PutOffender ? (*PutOffender = FU, true) : true; 929 } 930 return false; 931 } 932 933 bool Function::isDefTriviallyDead() const { 934 // Check the linkage 935 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 936 !hasAvailableExternallyLinkage()) 937 return false; 938 939 // Check if the function is used by anything other than a blockaddress. 940 for (const User *U : users()) 941 if (!isa<BlockAddress>(U)) 942 return false; 943 944 return true; 945 } 946 947 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 948 /// setjmp or other function that gcc recognizes as "returning twice". 949 bool Function::callsFunctionThatReturnsTwice() const { 950 for (const_inst_iterator 951 I = inst_begin(this), E = inst_end(this); I != E; ++I) { 952 ImmutableCallSite CS(&*I); 953 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice)) 954 return true; 955 } 956 957 return false; 958 } 959 960 Constant *Function::getPersonalityFn() const { 961 assert(hasPersonalityFn() && getNumOperands()); 962 return cast<Constant>(Op<0>()); 963 } 964 965 void Function::setPersonalityFn(Constant *Fn) { 966 setHungoffOperand<0>(Fn); 967 setValueSubclassDataBit(3, Fn != nullptr); 968 } 969 970 Constant *Function::getPrefixData() const { 971 assert(hasPrefixData() && getNumOperands()); 972 return cast<Constant>(Op<1>()); 973 } 974 975 void Function::setPrefixData(Constant *PrefixData) { 976 setHungoffOperand<1>(PrefixData); 977 setValueSubclassDataBit(1, PrefixData != nullptr); 978 } 979 980 Constant *Function::getPrologueData() const { 981 assert(hasPrologueData() && getNumOperands()); 982 return cast<Constant>(Op<2>()); 983 } 984 985 void Function::setPrologueData(Constant *PrologueData) { 986 setHungoffOperand<2>(PrologueData); 987 setValueSubclassDataBit(2, PrologueData != nullptr); 988 } 989 990 void Function::allocHungoffUselist() { 991 // If we've already allocated a uselist, stop here. 992 if (getNumOperands()) 993 return; 994 995 allocHungoffUses(3, /*IsPhi=*/ false); 996 setNumHungOffUseOperands(3); 997 998 // Initialize the uselist with placeholder operands to allow traversal. 999 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1000 Op<0>().set(CPN); 1001 Op<1>().set(CPN); 1002 Op<2>().set(CPN); 1003 } 1004 1005 template <int Idx> 1006 void Function::setHungoffOperand(Constant *C) { 1007 if (C) { 1008 allocHungoffUselist(); 1009 Op<Idx>().set(C); 1010 } else if (getNumOperands()) { 1011 Op<Idx>().set( 1012 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1013 } 1014 } 1015 1016 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1017 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1018 if (On) 1019 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1020 else 1021 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1022 } 1023 1024 void Function::setEntryCount(uint64_t Count) { 1025 MDBuilder MDB(getContext()); 1026 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count)); 1027 } 1028 1029 Optional<uint64_t> Function::getEntryCount() const { 1030 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1031 if (MD && MD->getOperand(0)) 1032 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1033 if (MDS->getString().equals("function_entry_count")) { 1034 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1035 return CI->getValue().getZExtValue(); 1036 } 1037 return None; 1038 } 1039