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