Home | History | Annotate | Line # | Download | only in IR
      1 //===- Function.cpp - Implement the Global object classes -----------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This file implements the Function class for the IR library.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #include "llvm/IR/Function.h"
     14 #include "SymbolTableListTraitsImpl.h"
     15 #include "llvm/ADT/ArrayRef.h"
     16 #include "llvm/ADT/DenseSet.h"
     17 #include "llvm/ADT/None.h"
     18 #include "llvm/ADT/STLExtras.h"
     19 #include "llvm/ADT/SmallString.h"
     20 #include "llvm/ADT/SmallVector.h"
     21 #include "llvm/ADT/StringExtras.h"
     22 #include "llvm/ADT/StringRef.h"
     23 #include "llvm/IR/AbstractCallSite.h"
     24 #include "llvm/IR/Argument.h"
     25 #include "llvm/IR/Attributes.h"
     26 #include "llvm/IR/BasicBlock.h"
     27 #include "llvm/IR/Constant.h"
     28 #include "llvm/IR/Constants.h"
     29 #include "llvm/IR/DerivedTypes.h"
     30 #include "llvm/IR/GlobalValue.h"
     31 #include "llvm/IR/InstIterator.h"
     32 #include "llvm/IR/Instruction.h"
     33 #include "llvm/IR/Instructions.h"
     34 #include "llvm/IR/IntrinsicInst.h"
     35 #include "llvm/IR/Intrinsics.h"
     36 #include "llvm/IR/IntrinsicsAArch64.h"
     37 #include "llvm/IR/IntrinsicsAMDGPU.h"
     38 #include "llvm/IR/IntrinsicsARM.h"
     39 #include "llvm/IR/IntrinsicsBPF.h"
     40 #include "llvm/IR/IntrinsicsHexagon.h"
     41 #include "llvm/IR/IntrinsicsMips.h"
     42 #include "llvm/IR/IntrinsicsNVPTX.h"
     43 #include "llvm/IR/IntrinsicsPowerPC.h"
     44 #include "llvm/IR/IntrinsicsR600.h"
     45 #include "llvm/IR/IntrinsicsRISCV.h"
     46 #include "llvm/IR/IntrinsicsS390.h"
     47 #include "llvm/IR/IntrinsicsVE.h"
     48 #include "llvm/IR/IntrinsicsWebAssembly.h"
     49 #include "llvm/IR/IntrinsicsX86.h"
     50 #include "llvm/IR/IntrinsicsXCore.h"
     51 #include "llvm/IR/LLVMContext.h"
     52 #include "llvm/IR/MDBuilder.h"
     53 #include "llvm/IR/Metadata.h"
     54 #include "llvm/IR/Module.h"
     55 #include "llvm/IR/Operator.h"
     56 #include "llvm/IR/SymbolTableListTraits.h"
     57 #include "llvm/IR/Type.h"
     58 #include "llvm/IR/Use.h"
     59 #include "llvm/IR/User.h"
     60 #include "llvm/IR/Value.h"
     61 #include "llvm/IR/ValueSymbolTable.h"
     62 #include "llvm/Support/Casting.h"
     63 #include "llvm/Support/Compiler.h"
     64 #include "llvm/Support/ErrorHandling.h"
     65 #include <algorithm>
     66 #include <cassert>
     67 #include <cstddef>
     68 #include <cstdint>
     69 #include <cstring>
     70 #include <string>
     71 
     72 using namespace llvm;
     73 using ProfileCount = Function::ProfileCount;
     74 
     75 // Explicit instantiations of SymbolTableListTraits since some of the methods
     76 // are not in the public header file...
     77 template class llvm::SymbolTableListTraits<BasicBlock>;
     78 
     79 //===----------------------------------------------------------------------===//
     80 // Argument Implementation
     81 //===----------------------------------------------------------------------===//
     82 
     83 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
     84     : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
     85   setName(Name);
     86 }
     87 
     88 void Argument::setParent(Function *parent) {
     89   Parent = parent;
     90 }
     91 
     92 bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
     93   if (!getType()->isPointerTy()) return false;
     94   if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
     95       (AllowUndefOrPoison ||
     96        getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
     97     return true;
     98   else if (getDereferenceableBytes() > 0 &&
     99            !NullPointerIsDefined(getParent(),
    100                                  getType()->getPointerAddressSpace()))
    101     return true;
    102   return false;
    103 }
    104 
    105 bool Argument::hasByValAttr() const {
    106   if (!getType()->isPointerTy()) return false;
    107   return hasAttribute(Attribute::ByVal);
    108 }
    109 
    110 bool Argument::hasByRefAttr() const {
    111   if (!getType()->isPointerTy())
    112     return false;
    113   return hasAttribute(Attribute::ByRef);
    114 }
    115 
    116 bool Argument::hasSwiftSelfAttr() const {
    117   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
    118 }
    119 
    120 bool Argument::hasSwiftErrorAttr() const {
    121   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
    122 }
    123 
    124 bool Argument::hasInAllocaAttr() const {
    125   if (!getType()->isPointerTy()) return false;
    126   return hasAttribute(Attribute::InAlloca);
    127 }
    128 
    129 bool Argument::hasPreallocatedAttr() const {
    130   if (!getType()->isPointerTy())
    131     return false;
    132   return hasAttribute(Attribute::Preallocated);
    133 }
    134 
    135 bool Argument::hasPassPointeeByValueCopyAttr() const {
    136   if (!getType()->isPointerTy()) return false;
    137   AttributeList Attrs = getParent()->getAttributes();
    138   return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
    139          Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
    140          Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated);
    141 }
    142 
    143 bool Argument::hasPointeeInMemoryValueAttr() const {
    144   if (!getType()->isPointerTy())
    145     return false;
    146   AttributeList Attrs = getParent()->getAttributes();
    147   return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
    148          Attrs.hasParamAttribute(getArgNo(), Attribute::StructRet) ||
    149          Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
    150          Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated) ||
    151          Attrs.hasParamAttribute(getArgNo(), Attribute::ByRef);
    152 }
    153 
    154 /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
    155 /// parameter type.
    156 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs, Type *ArgTy) {
    157   // FIXME: All the type carrying attributes are mutually exclusive, so there
    158   // should be a single query to get the stored type that handles any of them.
    159   if (Type *ByValTy = ParamAttrs.getByValType())
    160     return ByValTy;
    161   if (Type *ByRefTy = ParamAttrs.getByRefType())
    162     return ByRefTy;
    163   if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
    164     return PreAllocTy;
    165   if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
    166     return InAllocaTy;
    167 
    168   // FIXME: sret and inalloca always depends on pointee element type. It's also
    169   // possible for byval to miss it.
    170   if (ParamAttrs.hasAttribute(Attribute::InAlloca) ||
    171       ParamAttrs.hasAttribute(Attribute::ByVal) ||
    172       ParamAttrs.hasAttribute(Attribute::StructRet) ||
    173       ParamAttrs.hasAttribute(Attribute::Preallocated))
    174     return cast<PointerType>(ArgTy)->getElementType();
    175 
    176   return nullptr;
    177 }
    178 
    179 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
    180   AttributeSet ParamAttrs =
    181       getParent()->getAttributes().getParamAttributes(getArgNo());
    182   if (Type *MemTy = getMemoryParamAllocType(ParamAttrs, getType()))
    183     return DL.getTypeAllocSize(MemTy);
    184   return 0;
    185 }
    186 
    187 Type *Argument::getPointeeInMemoryValueType() const {
    188   AttributeSet ParamAttrs =
    189       getParent()->getAttributes().getParamAttributes(getArgNo());
    190   return getMemoryParamAllocType(ParamAttrs, getType());
    191 }
    192 
    193 unsigned Argument::getParamAlignment() const {
    194   assert(getType()->isPointerTy() && "Only pointers have alignments");
    195   return getParent()->getParamAlignment(getArgNo());
    196 }
    197 
    198 MaybeAlign Argument::getParamAlign() const {
    199   assert(getType()->isPointerTy() && "Only pointers have alignments");
    200   return getParent()->getParamAlign(getArgNo());
    201 }
    202 
    203 MaybeAlign Argument::getParamStackAlign() const {
    204   return getParent()->getParamStackAlign(getArgNo());
    205 }
    206 
    207 Type *Argument::getParamByValType() const {
    208   assert(getType()->isPointerTy() && "Only pointers have byval types");
    209   return getParent()->getParamByValType(getArgNo());
    210 }
    211 
    212 Type *Argument::getParamStructRetType() const {
    213   assert(getType()->isPointerTy() && "Only pointers have sret types");
    214   return getParent()->getParamStructRetType(getArgNo());
    215 }
    216 
    217 Type *Argument::getParamByRefType() const {
    218   assert(getType()->isPointerTy() && "Only pointers have byref types");
    219   return getParent()->getParamByRefType(getArgNo());
    220 }
    221 
    222 Type *Argument::getParamInAllocaType() const {
    223   assert(getType()->isPointerTy() && "Only pointers have inalloca types");
    224   return getParent()->getParamInAllocaType(getArgNo());
    225 }
    226 
    227 uint64_t Argument::getDereferenceableBytes() const {
    228   assert(getType()->isPointerTy() &&
    229          "Only pointers have dereferenceable bytes");
    230   return getParent()->getParamDereferenceableBytes(getArgNo());
    231 }
    232 
    233 uint64_t Argument::getDereferenceableOrNullBytes() const {
    234   assert(getType()->isPointerTy() &&
    235          "Only pointers have dereferenceable bytes");
    236   return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
    237 }
    238 
    239 bool Argument::hasNestAttr() const {
    240   if (!getType()->isPointerTy()) return false;
    241   return hasAttribute(Attribute::Nest);
    242 }
    243 
    244 bool Argument::hasNoAliasAttr() const {
    245   if (!getType()->isPointerTy()) return false;
    246   return hasAttribute(Attribute::NoAlias);
    247 }
    248 
    249 bool Argument::hasNoCaptureAttr() const {
    250   if (!getType()->isPointerTy()) return false;
    251   return hasAttribute(Attribute::NoCapture);
    252 }
    253 
    254 bool Argument::hasNoFreeAttr() const {
    255   if (!getType()->isPointerTy()) return false;
    256   return hasAttribute(Attribute::NoFree);
    257 }
    258 
    259 bool Argument::hasStructRetAttr() const {
    260   if (!getType()->isPointerTy()) return false;
    261   return hasAttribute(Attribute::StructRet);
    262 }
    263 
    264 bool Argument::hasInRegAttr() const {
    265   return hasAttribute(Attribute::InReg);
    266 }
    267 
    268 bool Argument::hasReturnedAttr() const {
    269   return hasAttribute(Attribute::Returned);
    270 }
    271 
    272 bool Argument::hasZExtAttr() const {
    273   return hasAttribute(Attribute::ZExt);
    274 }
    275 
    276 bool Argument::hasSExtAttr() const {
    277   return hasAttribute(Attribute::SExt);
    278 }
    279 
    280 bool Argument::onlyReadsMemory() const {
    281   AttributeList Attrs = getParent()->getAttributes();
    282   return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
    283          Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
    284 }
    285 
    286 void Argument::addAttrs(AttrBuilder &B) {
    287   AttributeList AL = getParent()->getAttributes();
    288   AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
    289   getParent()->setAttributes(AL);
    290 }
    291 
    292 void Argument::addAttr(Attribute::AttrKind Kind) {
    293   getParent()->addParamAttr(getArgNo(), Kind);
    294 }
    295 
    296 void Argument::addAttr(Attribute Attr) {
    297   getParent()->addParamAttr(getArgNo(), Attr);
    298 }
    299 
    300 void Argument::removeAttr(Attribute::AttrKind Kind) {
    301   getParent()->removeParamAttr(getArgNo(), Kind);
    302 }
    303 
    304 void Argument::removeAttrs(const AttrBuilder &B) {
    305   AttributeList AL = getParent()->getAttributes();
    306   AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), B);
    307   getParent()->setAttributes(AL);
    308 }
    309 
    310 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
    311   return getParent()->hasParamAttribute(getArgNo(), Kind);
    312 }
    313 
    314 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
    315   return getParent()->getParamAttribute(getArgNo(), Kind);
    316 }
    317 
    318 //===----------------------------------------------------------------------===//
    319 // Helper Methods in Function
    320 //===----------------------------------------------------------------------===//
    321 
    322 LLVMContext &Function::getContext() const {
    323   return getType()->getContext();
    324 }
    325 
    326 unsigned Function::getInstructionCount() const {
    327   unsigned NumInstrs = 0;
    328   for (const BasicBlock &BB : BasicBlocks)
    329     NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
    330                                BB.instructionsWithoutDebug().end());
    331   return NumInstrs;
    332 }
    333 
    334 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
    335                            const Twine &N, Module &M) {
    336   return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
    337 }
    338 
    339 Function *Function::createWithDefaultAttr(FunctionType *Ty,
    340                                           LinkageTypes Linkage,
    341                                           unsigned AddrSpace, const Twine &N,
    342                                           Module *M) {
    343   auto *F = new Function(Ty, Linkage, AddrSpace, N, M);
    344   AttrBuilder B;
    345   if (M->getUwtable())
    346     B.addAttribute(Attribute::UWTable);
    347   switch (M->getFramePointer()) {
    348   case FramePointerKind::None:
    349     // 0 ("none") is the default.
    350     break;
    351   case FramePointerKind::NonLeaf:
    352     B.addAttribute("frame-pointer", "non-leaf");
    353     break;
    354   case FramePointerKind::All:
    355     B.addAttribute("frame-pointer", "all");
    356     break;
    357   }
    358   F->addAttributes(AttributeList::FunctionIndex, B);
    359   return F;
    360 }
    361 
    362 void Function::removeFromParent() {
    363   getParent()->getFunctionList().remove(getIterator());
    364 }
    365 
    366 void Function::eraseFromParent() {
    367   getParent()->getFunctionList().erase(getIterator());
    368 }
    369 
    370 //===----------------------------------------------------------------------===//
    371 // Function Implementation
    372 //===----------------------------------------------------------------------===//
    373 
    374 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
    375   // If AS == -1 and we are passed a valid module pointer we place the function
    376   // in the program address space. Otherwise we default to AS0.
    377   if (AddrSpace == static_cast<unsigned>(-1))
    378     return M ? M->getDataLayout().getProgramAddressSpace() : 0;
    379   return AddrSpace;
    380 }
    381 
    382 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
    383                    const Twine &name, Module *ParentModule)
    384     : GlobalObject(Ty, Value::FunctionVal,
    385                    OperandTraits<Function>::op_begin(this), 0, Linkage, name,
    386                    computeAddrSpace(AddrSpace, ParentModule)),
    387       NumArgs(Ty->getNumParams()) {
    388   assert(FunctionType::isValidReturnType(getReturnType()) &&
    389          "invalid return type");
    390   setGlobalObjectSubClassData(0);
    391 
    392   // We only need a symbol table for a function if the context keeps value names
    393   if (!getContext().shouldDiscardValueNames())
    394     SymTab = std::make_unique<ValueSymbolTable>();
    395 
    396   // If the function has arguments, mark them as lazily built.
    397   if (Ty->getNumParams())
    398     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
    399 
    400   if (ParentModule)
    401     ParentModule->getFunctionList().push_back(this);
    402 
    403   HasLLVMReservedName = getName().startswith("llvm.");
    404   // Ensure intrinsics have the right parameter attributes.
    405   // Note, the IntID field will have been set in Value::setName if this function
    406   // name is a valid intrinsic ID.
    407   if (IntID)
    408     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
    409 }
    410 
    411 Function::~Function() {
    412   dropAllReferences();    // After this it is safe to delete instructions.
    413 
    414   // Delete all of the method arguments and unlink from symbol table...
    415   if (Arguments)
    416     clearArguments();
    417 
    418   // Remove the function from the on-the-side GC table.
    419   clearGC();
    420 }
    421 
    422 void Function::BuildLazyArguments() const {
    423   // Create the arguments vector, all arguments start out unnamed.
    424   auto *FT = getFunctionType();
    425   if (NumArgs > 0) {
    426     Arguments = std::allocator<Argument>().allocate(NumArgs);
    427     for (unsigned i = 0, e = NumArgs; i != e; ++i) {
    428       Type *ArgTy = FT->getParamType(i);
    429       assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
    430       new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
    431     }
    432   }
    433 
    434   // Clear the lazy arguments bit.
    435   unsigned SDC = getSubclassDataFromValue();
    436   SDC &= ~(1 << 0);
    437   const_cast<Function*>(this)->setValueSubclassData(SDC);
    438   assert(!hasLazyArguments());
    439 }
    440 
    441 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
    442   return MutableArrayRef<Argument>(Args, Count);
    443 }
    444 
    445 bool Function::isConstrainedFPIntrinsic() const {
    446   switch (getIntrinsicID()) {
    447 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
    448   case Intrinsic::INTRINSIC:
    449 #include "llvm/IR/ConstrainedOps.def"
    450     return true;
    451 #undef INSTRUCTION
    452   default:
    453     return false;
    454   }
    455 }
    456 
    457 void Function::clearArguments() {
    458   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
    459     A.setName("");
    460     A.~Argument();
    461   }
    462   std::allocator<Argument>().deallocate(Arguments, NumArgs);
    463   Arguments = nullptr;
    464 }
    465 
    466 void Function::stealArgumentListFrom(Function &Src) {
    467   assert(isDeclaration() && "Expected no references to current arguments");
    468 
    469   // Drop the current arguments, if any, and set the lazy argument bit.
    470   if (!hasLazyArguments()) {
    471     assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
    472                         [](const Argument &A) { return A.use_empty(); }) &&
    473            "Expected arguments to be unused in declaration");
    474     clearArguments();
    475     setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
    476   }
    477 
    478   // Nothing to steal if Src has lazy arguments.
    479   if (Src.hasLazyArguments())
    480     return;
    481 
    482   // Steal arguments from Src, and fix the lazy argument bits.
    483   assert(arg_size() == Src.arg_size());
    484   Arguments = Src.Arguments;
    485   Src.Arguments = nullptr;
    486   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
    487     // FIXME: This does the work of transferNodesFromList inefficiently.
    488     SmallString<128> Name;
    489     if (A.hasName())
    490       Name = A.getName();
    491     if (!Name.empty())
    492       A.setName("");
    493     A.setParent(this);
    494     if (!Name.empty())
    495       A.setName(Name);
    496   }
    497 
    498   setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
    499   assert(!hasLazyArguments());
    500   Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
    501 }
    502 
    503 // dropAllReferences() - This function causes all the subinstructions to "let
    504 // go" of all references that they are maintaining.  This allows one to
    505 // 'delete' a whole class at a time, even though there may be circular
    506 // references... first all references are dropped, and all use counts go to
    507 // zero.  Then everything is deleted for real.  Note that no operations are
    508 // valid on an object that has "dropped all references", except operator
    509 // delete.
    510 //
    511 void Function::dropAllReferences() {
    512   setIsMaterializable(false);
    513 
    514   for (BasicBlock &BB : *this)
    515     BB.dropAllReferences();
    516 
    517   // Delete all basic blocks. They are now unused, except possibly by
    518   // blockaddresses, but BasicBlock's destructor takes care of those.
    519   while (!BasicBlocks.empty())
    520     BasicBlocks.begin()->eraseFromParent();
    521 
    522   // Drop uses of any optional data (real or placeholder).
    523   if (getNumOperands()) {
    524     User::dropAllReferences();
    525     setNumHungOffUseOperands(0);
    526     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
    527   }
    528 
    529   // Metadata is stored in a side-table.
    530   clearMetadata();
    531 }
    532 
    533 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
    534   AttributeList PAL = getAttributes();
    535   PAL = PAL.addAttribute(getContext(), i, Kind);
    536   setAttributes(PAL);
    537 }
    538 
    539 void Function::addAttribute(unsigned i, Attribute Attr) {
    540   AttributeList PAL = getAttributes();
    541   PAL = PAL.addAttribute(getContext(), i, Attr);
    542   setAttributes(PAL);
    543 }
    544 
    545 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
    546   AttributeList PAL = getAttributes();
    547   PAL = PAL.addAttributes(getContext(), i, Attrs);
    548   setAttributes(PAL);
    549 }
    550 
    551 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
    552   AttributeList PAL = getAttributes();
    553   PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
    554   setAttributes(PAL);
    555 }
    556 
    557 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
    558   AttributeList PAL = getAttributes();
    559   PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
    560   setAttributes(PAL);
    561 }
    562 
    563 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
    564   AttributeList PAL = getAttributes();
    565   PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
    566   setAttributes(PAL);
    567 }
    568 
    569 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
    570   AttributeList PAL = getAttributes();
    571   PAL = PAL.removeAttribute(getContext(), i, Kind);
    572   setAttributes(PAL);
    573 }
    574 
    575 void Function::removeAttribute(unsigned i, StringRef Kind) {
    576   AttributeList PAL = getAttributes();
    577   PAL = PAL.removeAttribute(getContext(), i, Kind);
    578   setAttributes(PAL);
    579 }
    580 
    581 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
    582   AttributeList PAL = getAttributes();
    583   PAL = PAL.removeAttributes(getContext(), i, Attrs);
    584   setAttributes(PAL);
    585 }
    586 
    587 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
    588   AttributeList PAL = getAttributes();
    589   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
    590   setAttributes(PAL);
    591 }
    592 
    593 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
    594   AttributeList PAL = getAttributes();
    595   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
    596   setAttributes(PAL);
    597 }
    598 
    599 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
    600   AttributeList PAL = getAttributes();
    601   PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
    602   setAttributes(PAL);
    603 }
    604 
    605 void Function::removeParamUndefImplyingAttrs(unsigned ArgNo) {
    606   AttributeList PAL = getAttributes();
    607   PAL = PAL.removeParamUndefImplyingAttributes(getContext(), ArgNo);
    608   setAttributes(PAL);
    609 }
    610 
    611 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
    612   AttributeList PAL = getAttributes();
    613   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
    614   setAttributes(PAL);
    615 }
    616 
    617 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
    618   AttributeList PAL = getAttributes();
    619   PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
    620   setAttributes(PAL);
    621 }
    622 
    623 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
    624   AttributeList PAL = getAttributes();
    625   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
    626   setAttributes(PAL);
    627 }
    628 
    629 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
    630                                                  uint64_t Bytes) {
    631   AttributeList PAL = getAttributes();
    632   PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
    633   setAttributes(PAL);
    634 }
    635 
    636 DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
    637   if (&FPType == &APFloat::IEEEsingle()) {
    638     Attribute Attr = getFnAttribute("denormal-fp-math-f32");
    639     StringRef Val = Attr.getValueAsString();
    640     if (!Val.empty())
    641       return parseDenormalFPAttribute(Val);
    642 
    643     // If the f32 variant of the attribute isn't specified, try to use the
    644     // generic one.
    645   }
    646 
    647   Attribute Attr = getFnAttribute("denormal-fp-math");
    648   return parseDenormalFPAttribute(Attr.getValueAsString());
    649 }
    650 
    651 const std::string &Function::getGC() const {
    652   assert(hasGC() && "Function has no collector");
    653   return getContext().getGC(*this);
    654 }
    655 
    656 void Function::setGC(std::string Str) {
    657   setValueSubclassDataBit(14, !Str.empty());
    658   getContext().setGC(*this, std::move(Str));
    659 }
    660 
    661 void Function::clearGC() {
    662   if (!hasGC())
    663     return;
    664   getContext().deleteGC(*this);
    665   setValueSubclassDataBit(14, false);
    666 }
    667 
    668 bool Function::hasStackProtectorFnAttr() const {
    669   return hasFnAttribute(Attribute::StackProtect) ||
    670          hasFnAttribute(Attribute::StackProtectStrong) ||
    671          hasFnAttribute(Attribute::StackProtectReq);
    672 }
    673 
    674 /// Copy all additional attributes (those not needed to create a Function) from
    675 /// the Function Src to this one.
    676 void Function::copyAttributesFrom(const Function *Src) {
    677   GlobalObject::copyAttributesFrom(Src);
    678   setCallingConv(Src->getCallingConv());
    679   setAttributes(Src->getAttributes());
    680   if (Src->hasGC())
    681     setGC(Src->getGC());
    682   else
    683     clearGC();
    684   if (Src->hasPersonalityFn())
    685     setPersonalityFn(Src->getPersonalityFn());
    686   if (Src->hasPrefixData())
    687     setPrefixData(Src->getPrefixData());
    688   if (Src->hasPrologueData())
    689     setPrologueData(Src->getPrologueData());
    690 }
    691 
    692 /// Table of string intrinsic names indexed by enum value.
    693 static const char * const IntrinsicNameTable[] = {
    694   "not_intrinsic",
    695 #define GET_INTRINSIC_NAME_TABLE
    696 #include "llvm/IR/IntrinsicImpl.inc"
    697 #undef GET_INTRINSIC_NAME_TABLE
    698 };
    699 
    700 /// Table of per-target intrinsic name tables.
    701 #define GET_INTRINSIC_TARGET_DATA
    702 #include "llvm/IR/IntrinsicImpl.inc"
    703 #undef GET_INTRINSIC_TARGET_DATA
    704 
    705 bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
    706   return IID > TargetInfos[0].Count;
    707 }
    708 
    709 bool Function::isTargetIntrinsic() const {
    710   return isTargetIntrinsic(IntID);
    711 }
    712 
    713 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
    714 /// target as \c Name, or the generic table if \c Name is not target specific.
    715 ///
    716 /// Returns the relevant slice of \c IntrinsicNameTable
    717 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
    718   assert(Name.startswith("llvm."));
    719 
    720   ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
    721   // Drop "llvm." and take the first dotted component. That will be the target
    722   // if this is target specific.
    723   StringRef Target = Name.drop_front(5).split('.').first;
    724   auto It = partition_point(
    725       Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
    726   // We've either found the target or just fall back to the generic set, which
    727   // is always first.
    728   const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
    729   return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
    730 }
    731 
    732 /// This does the actual lookup of an intrinsic ID which
    733 /// matches the given function name.
    734 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
    735   ArrayRef<const char *> NameTable = findTargetSubtable(Name);
    736   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
    737   if (Idx == -1)
    738     return Intrinsic::not_intrinsic;
    739 
    740   // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
    741   // an index into a sub-table.
    742   int Adjust = NameTable.data() - IntrinsicNameTable;
    743   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
    744 
    745   // If the intrinsic is not overloaded, require an exact match. If it is
    746   // overloaded, require either exact or prefix match.
    747   const auto MatchSize = strlen(NameTable[Idx]);
    748   assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
    749   bool IsExactMatch = Name.size() == MatchSize;
    750   return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
    751                                                      : Intrinsic::not_intrinsic;
    752 }
    753 
    754 void Function::recalculateIntrinsicID() {
    755   StringRef Name = getName();
    756   if (!Name.startswith("llvm.")) {
    757     HasLLVMReservedName = false;
    758     IntID = Intrinsic::not_intrinsic;
    759     return;
    760   }
    761   HasLLVMReservedName = true;
    762   IntID = lookupIntrinsicID(Name);
    763 }
    764 
    765 /// Returns a stable mangling for the type specified for use in the name
    766 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
    767 /// of named types is simply their name.  Manglings for unnamed types consist
    768 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
    769 /// combined with the mangling of their component types.  A vararg function
    770 /// type will have a suffix of 'vararg'.  Since function types can contain
    771 /// other function types, we close a function type mangling with suffix 'f'
    772 /// which can't be confused with it's prefix.  This ensures we don't have
    773 /// collisions between two unrelated function types. Otherwise, you might
    774 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
    775 /// The HasUnnamedType boolean is set if an unnamed type was encountered,
    776 /// indicating that extra care must be taken to ensure a unique name.
    777 static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
    778   std::string Result;
    779   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
    780     Result += "p" + utostr(PTyp->getAddressSpace()) +
    781               getMangledTypeStr(PTyp->getElementType(), HasUnnamedType);
    782   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
    783     Result += "a" + utostr(ATyp->getNumElements()) +
    784               getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
    785   } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
    786     if (!STyp->isLiteral()) {
    787       Result += "s_";
    788       if (STyp->hasName())
    789         Result += STyp->getName();
    790       else
    791         HasUnnamedType = true;
    792     } else {
    793       Result += "sl_";
    794       for (auto Elem : STyp->elements())
    795         Result += getMangledTypeStr(Elem, HasUnnamedType);
    796     }
    797     // Ensure nested structs are distinguishable.
    798     Result += "s";
    799   } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
    800     Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
    801     for (size_t i = 0; i < FT->getNumParams(); i++)
    802       Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
    803     if (FT->isVarArg())
    804       Result += "vararg";
    805     // Ensure nested function types are distinguishable.
    806     Result += "f";
    807   } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) {
    808     ElementCount EC = VTy->getElementCount();
    809     if (EC.isScalable())
    810       Result += "nx";
    811     Result += "v" + utostr(EC.getKnownMinValue()) +
    812               getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
    813   } else if (Ty) {
    814     switch (Ty->getTypeID()) {
    815     default: llvm_unreachable("Unhandled type");
    816     case Type::VoidTyID:      Result += "isVoid";   break;
    817     case Type::MetadataTyID:  Result += "Metadata"; break;
    818     case Type::HalfTyID:      Result += "f16";      break;
    819     case Type::BFloatTyID:    Result += "bf16";     break;
    820     case Type::FloatTyID:     Result += "f32";      break;
    821     case Type::DoubleTyID:    Result += "f64";      break;
    822     case Type::X86_FP80TyID:  Result += "f80";      break;
    823     case Type::FP128TyID:     Result += "f128";     break;
    824     case Type::PPC_FP128TyID: Result += "ppcf128";  break;
    825     case Type::X86_MMXTyID:   Result += "x86mmx";   break;
    826     case Type::X86_AMXTyID:   Result += "x86amx";   break;
    827     case Type::IntegerTyID:
    828       Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
    829       break;
    830     }
    831   }
    832   return Result;
    833 }
    834 
    835 StringRef Intrinsic::getName(ID id) {
    836   assert(id < num_intrinsics && "Invalid intrinsic ID!");
    837   assert(!Intrinsic::isOverloaded(id) &&
    838          "This version of getName does not support overloading");
    839   return IntrinsicNameTable[id];
    840 }
    841 
    842 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,
    843                                FunctionType *FT) {
    844   assert(Id < num_intrinsics && "Invalid intrinsic ID!");
    845   assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&
    846          "This version of getName is for overloaded intrinsics only");
    847   bool HasUnnamedType = false;
    848   std::string Result(IntrinsicNameTable[Id]);
    849   for (Type *Ty : Tys) {
    850     Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
    851   }
    852   assert((M || !HasUnnamedType) && "unnamed types need a module");
    853   if (M && HasUnnamedType) {
    854     if (!FT)
    855       FT = getType(M->getContext(), Id, Tys);
    856     else
    857       assert((FT == getType(M->getContext(), Id, Tys)) &&
    858              "Provided FunctionType must match arguments");
    859     return M->getUniqueIntrinsicName(Result, Id, FT);
    860   }
    861   return Result;
    862 }
    863 
    864 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys) {
    865   return getName(Id, Tys, nullptr, nullptr);
    866 }
    867 
    868 /// IIT_Info - These are enumerators that describe the entries returned by the
    869 /// getIntrinsicInfoTableEntries function.
    870 ///
    871 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
    872 enum IIT_Info {
    873   // Common values should be encoded with 0-15.
    874   IIT_Done = 0,
    875   IIT_I1   = 1,
    876   IIT_I8   = 2,
    877   IIT_I16  = 3,
    878   IIT_I32  = 4,
    879   IIT_I64  = 5,
    880   IIT_F16  = 6,
    881   IIT_F32  = 7,
    882   IIT_F64  = 8,
    883   IIT_V2   = 9,
    884   IIT_V4   = 10,
    885   IIT_V8   = 11,
    886   IIT_V16  = 12,
    887   IIT_V32  = 13,
    888   IIT_PTR  = 14,
    889   IIT_ARG  = 15,
    890 
    891   // Values from 16+ are only encodable with the inefficient encoding.
    892   IIT_V64  = 16,
    893   IIT_MMX  = 17,
    894   IIT_TOKEN = 18,
    895   IIT_METADATA = 19,
    896   IIT_EMPTYSTRUCT = 20,
    897   IIT_STRUCT2 = 21,
    898   IIT_STRUCT3 = 22,
    899   IIT_STRUCT4 = 23,
    900   IIT_STRUCT5 = 24,
    901   IIT_EXTEND_ARG = 25,
    902   IIT_TRUNC_ARG = 26,
    903   IIT_ANYPTR = 27,
    904   IIT_V1   = 28,
    905   IIT_VARARG = 29,
    906   IIT_HALF_VEC_ARG = 30,
    907   IIT_SAME_VEC_WIDTH_ARG = 31,
    908   IIT_PTR_TO_ARG = 32,
    909   IIT_PTR_TO_ELT = 33,
    910   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
    911   IIT_I128 = 35,
    912   IIT_V512 = 36,
    913   IIT_V1024 = 37,
    914   IIT_STRUCT6 = 38,
    915   IIT_STRUCT7 = 39,
    916   IIT_STRUCT8 = 40,
    917   IIT_F128 = 41,
    918   IIT_VEC_ELEMENT = 42,
    919   IIT_SCALABLE_VEC = 43,
    920   IIT_SUBDIVIDE2_ARG = 44,
    921   IIT_SUBDIVIDE4_ARG = 45,
    922   IIT_VEC_OF_BITCASTS_TO_INT = 46,
    923   IIT_V128 = 47,
    924   IIT_BF16 = 48,
    925   IIT_STRUCT9 = 49,
    926   IIT_V256 = 50,
    927   IIT_AMX  = 51
    928 };
    929 
    930 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
    931                       IIT_Info LastInfo,
    932                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
    933   using namespace Intrinsic;
    934 
    935   bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
    936 
    937   IIT_Info Info = IIT_Info(Infos[NextElt++]);
    938   unsigned StructElts = 2;
    939 
    940   switch (Info) {
    941   case IIT_Done:
    942     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
    943     return;
    944   case IIT_VARARG:
    945     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
    946     return;
    947   case IIT_MMX:
    948     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
    949     return;
    950   case IIT_AMX:
    951     OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
    952     return;
    953   case IIT_TOKEN:
    954     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
    955     return;
    956   case IIT_METADATA:
    957     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
    958     return;
    959   case IIT_F16:
    960     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
    961     return;
    962   case IIT_BF16:
    963     OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
    964     return;
    965   case IIT_F32:
    966     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
    967     return;
    968   case IIT_F64:
    969     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
    970     return;
    971   case IIT_F128:
    972     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
    973     return;
    974   case IIT_I1:
    975     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
    976     return;
    977   case IIT_I8:
    978     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
    979     return;
    980   case IIT_I16:
    981     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
    982     return;
    983   case IIT_I32:
    984     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
    985     return;
    986   case IIT_I64:
    987     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
    988     return;
    989   case IIT_I128:
    990     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
    991     return;
    992   case IIT_V1:
    993     OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
    994     DecodeIITType(NextElt, Infos, Info, OutputTable);
    995     return;
    996   case IIT_V2:
    997     OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
    998     DecodeIITType(NextElt, Infos, Info, OutputTable);
    999     return;
   1000   case IIT_V4:
   1001     OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
   1002     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1003     return;
   1004   case IIT_V8:
   1005     OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
   1006     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1007     return;
   1008   case IIT_V16:
   1009     OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
   1010     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1011     return;
   1012   case IIT_V32:
   1013     OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
   1014     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1015     return;
   1016   case IIT_V64:
   1017     OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
   1018     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1019     return;
   1020   case IIT_V128:
   1021     OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
   1022     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1023     return;
   1024   case IIT_V256:
   1025     OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
   1026     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1027     return;
   1028   case IIT_V512:
   1029     OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
   1030     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1031     return;
   1032   case IIT_V1024:
   1033     OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
   1034     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1035     return;
   1036   case IIT_PTR:
   1037     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
   1038     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1039     return;
   1040   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
   1041     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
   1042                                              Infos[NextElt++]));
   1043     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1044     return;
   1045   }
   1046   case IIT_ARG: {
   1047     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1048     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
   1049     return;
   1050   }
   1051   case IIT_EXTEND_ARG: {
   1052     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1053     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
   1054                                              ArgInfo));
   1055     return;
   1056   }
   1057   case IIT_TRUNC_ARG: {
   1058     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1059     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
   1060                                              ArgInfo));
   1061     return;
   1062   }
   1063   case IIT_HALF_VEC_ARG: {
   1064     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1065     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
   1066                                              ArgInfo));
   1067     return;
   1068   }
   1069   case IIT_SAME_VEC_WIDTH_ARG: {
   1070     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1071     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
   1072                                              ArgInfo));
   1073     return;
   1074   }
   1075   case IIT_PTR_TO_ARG: {
   1076     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1077     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
   1078                                              ArgInfo));
   1079     return;
   1080   }
   1081   case IIT_PTR_TO_ELT: {
   1082     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1083     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
   1084     return;
   1085   }
   1086   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
   1087     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1088     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1089     OutputTable.push_back(
   1090         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
   1091     return;
   1092   }
   1093   case IIT_EMPTYSTRUCT:
   1094     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
   1095     return;
   1096   case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH;
   1097   case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
   1098   case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
   1099   case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
   1100   case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
   1101   case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
   1102   case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
   1103   case IIT_STRUCT2: {
   1104     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
   1105 
   1106     for (unsigned i = 0; i != StructElts; ++i)
   1107       DecodeIITType(NextElt, Infos, Info, OutputTable);
   1108     return;
   1109   }
   1110   case IIT_SUBDIVIDE2_ARG: {
   1111     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1112     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
   1113                                              ArgInfo));
   1114     return;
   1115   }
   1116   case IIT_SUBDIVIDE4_ARG: {
   1117     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1118     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
   1119                                              ArgInfo));
   1120     return;
   1121   }
   1122   case IIT_VEC_ELEMENT: {
   1123     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1124     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
   1125                                              ArgInfo));
   1126     return;
   1127   }
   1128   case IIT_SCALABLE_VEC: {
   1129     DecodeIITType(NextElt, Infos, Info, OutputTable);
   1130     return;
   1131   }
   1132   case IIT_VEC_OF_BITCASTS_TO_INT: {
   1133     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
   1134     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
   1135                                              ArgInfo));
   1136     return;
   1137   }
   1138   }
   1139   llvm_unreachable("unhandled");
   1140 }
   1141 
   1142 #define GET_INTRINSIC_GENERATOR_GLOBAL
   1143 #include "llvm/IR/IntrinsicImpl.inc"
   1144 #undef GET_INTRINSIC_GENERATOR_GLOBAL
   1145 
   1146 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
   1147                                              SmallVectorImpl<IITDescriptor> &T){
   1148   // Check to see if the intrinsic's type was expressible by the table.
   1149   unsigned TableVal = IIT_Table[id-1];
   1150 
   1151   // Decode the TableVal into an array of IITValues.
   1152   SmallVector<unsigned char, 8> IITValues;
   1153   ArrayRef<unsigned char> IITEntries;
   1154   unsigned NextElt = 0;
   1155   if ((TableVal >> 31) != 0) {
   1156     // This is an offset into the IIT_LongEncodingTable.
   1157     IITEntries = IIT_LongEncodingTable;
   1158 
   1159     // Strip sentinel bit.
   1160     NextElt = (TableVal << 1) >> 1;
   1161   } else {
   1162     // Decode the TableVal into an array of IITValues.  If the entry was encoded
   1163     // into a single word in the table itself, decode it now.
   1164     do {
   1165       IITValues.push_back(TableVal & 0xF);
   1166       TableVal >>= 4;
   1167     } while (TableVal);
   1168 
   1169     IITEntries = IITValues;
   1170     NextElt = 0;
   1171   }
   1172 
   1173   // Okay, decode the table into the output vector of IITDescriptors.
   1174   DecodeIITType(NextElt, IITEntries, IIT_Done, T);
   1175   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
   1176     DecodeIITType(NextElt, IITEntries, IIT_Done, T);
   1177 }
   1178 
   1179 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
   1180                              ArrayRef<Type*> Tys, LLVMContext &Context) {
   1181   using namespace Intrinsic;
   1182 
   1183   IITDescriptor D = Infos.front();
   1184   Infos = Infos.slice(1);
   1185 
   1186   switch (D.Kind) {
   1187   case IITDescriptor::Void: return Type::getVoidTy(Context);
   1188   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
   1189   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
   1190   case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);
   1191   case IITDescriptor::Token: return Type::getTokenTy(Context);
   1192   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
   1193   case IITDescriptor::Half: return Type::getHalfTy(Context);
   1194   case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
   1195   case IITDescriptor::Float: return Type::getFloatTy(Context);
   1196   case IITDescriptor::Double: return Type::getDoubleTy(Context);
   1197   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
   1198 
   1199   case IITDescriptor::Integer:
   1200     return IntegerType::get(Context, D.Integer_Width);
   1201   case IITDescriptor::Vector:
   1202     return VectorType::get(DecodeFixedType(Infos, Tys, Context),
   1203                            D.Vector_Width);
   1204   case IITDescriptor::Pointer:
   1205     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
   1206                             D.Pointer_AddressSpace);
   1207   case IITDescriptor::Struct: {
   1208     SmallVector<Type *, 8> Elts;
   1209     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
   1210       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
   1211     return StructType::get(Context, Elts);
   1212   }
   1213   case IITDescriptor::Argument:
   1214     return Tys[D.getArgumentNumber()];
   1215   case IITDescriptor::ExtendArgument: {
   1216     Type *Ty = Tys[D.getArgumentNumber()];
   1217     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
   1218       return VectorType::getExtendedElementVectorType(VTy);
   1219 
   1220     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
   1221   }
   1222   case IITDescriptor::TruncArgument: {
   1223     Type *Ty = Tys[D.getArgumentNumber()];
   1224     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
   1225       return VectorType::getTruncatedElementVectorType(VTy);
   1226 
   1227     IntegerType *ITy = cast<IntegerType>(Ty);
   1228     assert(ITy->getBitWidth() % 2 == 0);
   1229     return IntegerType::get(Context, ITy->getBitWidth() / 2);
   1230   }
   1231   case IITDescriptor::Subdivide2Argument:
   1232   case IITDescriptor::Subdivide4Argument: {
   1233     Type *Ty = Tys[D.getArgumentNumber()];
   1234     VectorType *VTy = dyn_cast<VectorType>(Ty);
   1235     assert(VTy && "Expected an argument of Vector Type");
   1236     int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
   1237     return VectorType::getSubdividedVectorType(VTy, SubDivs);
   1238   }
   1239   case IITDescriptor::HalfVecArgument:
   1240     return VectorType::getHalfElementsVectorType(cast<VectorType>(
   1241                                                   Tys[D.getArgumentNumber()]));
   1242   case IITDescriptor::SameVecWidthArgument: {
   1243     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
   1244     Type *Ty = Tys[D.getArgumentNumber()];
   1245     if (auto *VTy = dyn_cast<VectorType>(Ty))
   1246       return VectorType::get(EltTy, VTy->getElementCount());
   1247     return EltTy;
   1248   }
   1249   case IITDescriptor::PtrToArgument: {
   1250     Type *Ty = Tys[D.getArgumentNumber()];
   1251     return PointerType::getUnqual(Ty);
   1252   }
   1253   case IITDescriptor::PtrToElt: {
   1254     Type *Ty = Tys[D.getArgumentNumber()];
   1255     VectorType *VTy = dyn_cast<VectorType>(Ty);
   1256     if (!VTy)
   1257       llvm_unreachable("Expected an argument of Vector Type");
   1258     Type *EltTy = VTy->getElementType();
   1259     return PointerType::getUnqual(EltTy);
   1260   }
   1261   case IITDescriptor::VecElementArgument: {
   1262     Type *Ty = Tys[D.getArgumentNumber()];
   1263     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
   1264       return VTy->getElementType();
   1265     llvm_unreachable("Expected an argument of Vector Type");
   1266   }
   1267   case IITDescriptor::VecOfBitcastsToInt: {
   1268     Type *Ty = Tys[D.getArgumentNumber()];
   1269     VectorType *VTy = dyn_cast<VectorType>(Ty);
   1270     assert(VTy && "Expected an argument of Vector Type");
   1271     return VectorType::getInteger(VTy);
   1272   }
   1273   case IITDescriptor::VecOfAnyPtrsToElt:
   1274     // Return the overloaded type (which determines the pointers address space)
   1275     return Tys[D.getOverloadArgNumber()];
   1276   }
   1277   llvm_unreachable("unhandled");
   1278 }
   1279 
   1280 FunctionType *Intrinsic::getType(LLVMContext &Context,
   1281                                  ID id, ArrayRef<Type*> Tys) {
   1282   SmallVector<IITDescriptor, 8> Table;
   1283   getIntrinsicInfoTableEntries(id, Table);
   1284 
   1285   ArrayRef<IITDescriptor> TableRef = Table;
   1286   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
   1287 
   1288   SmallVector<Type*, 8> ArgTys;
   1289   while (!TableRef.empty())
   1290     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
   1291 
   1292   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
   1293   // If we see void type as the type of the last argument, it is vararg intrinsic
   1294   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
   1295     ArgTys.pop_back();
   1296     return FunctionType::get(ResultTy, ArgTys, true);
   1297   }
   1298   return FunctionType::get(ResultTy, ArgTys, false);
   1299 }
   1300 
   1301 bool Intrinsic::isOverloaded(ID id) {
   1302 #define GET_INTRINSIC_OVERLOAD_TABLE
   1303 #include "llvm/IR/IntrinsicImpl.inc"
   1304 #undef GET_INTRINSIC_OVERLOAD_TABLE
   1305 }
   1306 
   1307 bool Intrinsic::isLeaf(ID id) {
   1308   switch (id) {
   1309   default:
   1310     return true;
   1311 
   1312   case Intrinsic::experimental_gc_statepoint:
   1313   case Intrinsic::experimental_patchpoint_void:
   1314   case Intrinsic::experimental_patchpoint_i64:
   1315     return false;
   1316   }
   1317 }
   1318 
   1319 /// This defines the "Intrinsic::getAttributes(ID id)" method.
   1320 #define GET_INTRINSIC_ATTRIBUTES
   1321 #include "llvm/IR/IntrinsicImpl.inc"
   1322 #undef GET_INTRINSIC_ATTRIBUTES
   1323 
   1324 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
   1325   // There can never be multiple globals with the same name of different types,
   1326   // because intrinsics must be a specific type.
   1327   auto *FT = getType(M->getContext(), id, Tys);
   1328   return cast<Function>(
   1329       M->getOrInsertFunction(Tys.empty() ? getName(id)
   1330                                          : getName(id, Tys, M, FT),
   1331                              getType(M->getContext(), id, Tys))
   1332           .getCallee());
   1333 }
   1334 
   1335 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
   1336 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
   1337 #include "llvm/IR/IntrinsicImpl.inc"
   1338 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
   1339 
   1340 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
   1341 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
   1342 #include "llvm/IR/IntrinsicImpl.inc"
   1343 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
   1344 
   1345 using DeferredIntrinsicMatchPair =
   1346     std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
   1347 
   1348 static bool matchIntrinsicType(
   1349     Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
   1350     SmallVectorImpl<Type *> &ArgTys,
   1351     SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
   1352     bool IsDeferredCheck) {
   1353   using namespace Intrinsic;
   1354 
   1355   // If we ran out of descriptors, there are too many arguments.
   1356   if (Infos.empty()) return true;
   1357 
   1358   // Do this before slicing off the 'front' part
   1359   auto InfosRef = Infos;
   1360   auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
   1361     DeferredChecks.emplace_back(T, InfosRef);
   1362     return false;
   1363   };
   1364 
   1365   IITDescriptor D = Infos.front();
   1366   Infos = Infos.slice(1);
   1367 
   1368   switch (D.Kind) {
   1369     case IITDescriptor::Void: return !Ty->isVoidTy();
   1370     case IITDescriptor::VarArg: return true;
   1371     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
   1372     case IITDescriptor::AMX:  return !Ty->isX86_AMXTy();
   1373     case IITDescriptor::Token: return !Ty->isTokenTy();
   1374     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
   1375     case IITDescriptor::Half: return !Ty->isHalfTy();
   1376     case IITDescriptor::BFloat: return !Ty->isBFloatTy();
   1377     case IITDescriptor::Float: return !Ty->isFloatTy();
   1378     case IITDescriptor::Double: return !Ty->isDoubleTy();
   1379     case IITDescriptor::Quad: return !Ty->isFP128Ty();
   1380     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
   1381     case IITDescriptor::Vector: {
   1382       VectorType *VT = dyn_cast<VectorType>(Ty);
   1383       return !VT || VT->getElementCount() != D.Vector_Width ||
   1384              matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
   1385                                 DeferredChecks, IsDeferredCheck);
   1386     }
   1387     case IITDescriptor::Pointer: {
   1388       PointerType *PT = dyn_cast<PointerType>(Ty);
   1389       return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
   1390              matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
   1391                                 DeferredChecks, IsDeferredCheck);
   1392     }
   1393 
   1394     case IITDescriptor::Struct: {
   1395       StructType *ST = dyn_cast<StructType>(Ty);
   1396       if (!ST || ST->getNumElements() != D.Struct_NumElements)
   1397         return true;
   1398 
   1399       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
   1400         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
   1401                                DeferredChecks, IsDeferredCheck))
   1402           return true;
   1403       return false;
   1404     }
   1405 
   1406     case IITDescriptor::Argument:
   1407       // If this is the second occurrence of an argument,
   1408       // verify that the later instance matches the previous instance.
   1409       if (D.getArgumentNumber() < ArgTys.size())
   1410         return Ty != ArgTys[D.getArgumentNumber()];
   1411 
   1412       if (D.getArgumentNumber() > ArgTys.size() ||
   1413           D.getArgumentKind() == IITDescriptor::AK_MatchType)
   1414         return IsDeferredCheck || DeferCheck(Ty);
   1415 
   1416       assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
   1417              "Table consistency error");
   1418       ArgTys.push_back(Ty);
   1419 
   1420       switch (D.getArgumentKind()) {
   1421         case IITDescriptor::AK_Any:        return false; // Success
   1422         case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
   1423         case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
   1424         case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
   1425         case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
   1426         default:                           break;
   1427       }
   1428       llvm_unreachable("all argument kinds not covered");
   1429 
   1430     case IITDescriptor::ExtendArgument: {
   1431       // If this is a forward reference, defer the check for later.
   1432       if (D.getArgumentNumber() >= ArgTys.size())
   1433         return IsDeferredCheck || DeferCheck(Ty);
   1434 
   1435       Type *NewTy = ArgTys[D.getArgumentNumber()];
   1436       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
   1437         NewTy = VectorType::getExtendedElementVectorType(VTy);
   1438       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
   1439         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
   1440       else
   1441         return true;
   1442 
   1443       return Ty != NewTy;
   1444     }
   1445     case IITDescriptor::TruncArgument: {
   1446       // If this is a forward reference, defer the check for later.
   1447       if (D.getArgumentNumber() >= ArgTys.size())
   1448         return IsDeferredCheck || DeferCheck(Ty);
   1449 
   1450       Type *NewTy = ArgTys[D.getArgumentNumber()];
   1451       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
   1452         NewTy = VectorType::getTruncatedElementVectorType(VTy);
   1453       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
   1454         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
   1455       else
   1456         return true;
   1457 
   1458       return Ty != NewTy;
   1459     }
   1460     case IITDescriptor::HalfVecArgument:
   1461       // If this is a forward reference, defer the check for later.
   1462       if (D.getArgumentNumber() >= ArgTys.size())
   1463         return IsDeferredCheck || DeferCheck(Ty);
   1464       return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
   1465              VectorType::getHalfElementsVectorType(
   1466                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
   1467     case IITDescriptor::SameVecWidthArgument: {
   1468       if (D.getArgumentNumber() >= ArgTys.size()) {
   1469         // Defer check and subsequent check for the vector element type.
   1470         Infos = Infos.slice(1);
   1471         return IsDeferredCheck || DeferCheck(Ty);
   1472       }
   1473       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
   1474       auto *ThisArgType = dyn_cast<VectorType>(Ty);
   1475       // Both must be vectors of the same number of elements or neither.
   1476       if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
   1477         return true;
   1478       Type *EltTy = Ty;
   1479       if (ThisArgType) {
   1480         if (ReferenceType->getElementCount() !=
   1481             ThisArgType->getElementCount())
   1482           return true;
   1483         EltTy = ThisArgType->getElementType();
   1484       }
   1485       return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
   1486                                 IsDeferredCheck);
   1487     }
   1488     case IITDescriptor::PtrToArgument: {
   1489       if (D.getArgumentNumber() >= ArgTys.size())
   1490         return IsDeferredCheck || DeferCheck(Ty);
   1491       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
   1492       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
   1493       return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
   1494     }
   1495     case IITDescriptor::PtrToElt: {
   1496       if (D.getArgumentNumber() >= ArgTys.size())
   1497         return IsDeferredCheck || DeferCheck(Ty);
   1498       VectorType * ReferenceType =
   1499         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
   1500       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
   1501 
   1502       return (!ThisArgType || !ReferenceType ||
   1503               ThisArgType->getElementType() != ReferenceType->getElementType());
   1504     }
   1505     case IITDescriptor::VecOfAnyPtrsToElt: {
   1506       unsigned RefArgNumber = D.getRefArgNumber();
   1507       if (RefArgNumber >= ArgTys.size()) {
   1508         if (IsDeferredCheck)
   1509           return true;
   1510         // If forward referencing, already add the pointer-vector type and
   1511         // defer the checks for later.
   1512         ArgTys.push_back(Ty);
   1513         return DeferCheck(Ty);
   1514       }
   1515 
   1516       if (!IsDeferredCheck){
   1517         assert(D.getOverloadArgNumber() == ArgTys.size() &&
   1518                "Table consistency error");
   1519         ArgTys.push_back(Ty);
   1520       }
   1521 
   1522       // Verify the overloaded type "matches" the Ref type.
   1523       // i.e. Ty is a vector with the same width as Ref.
   1524       // Composed of pointers to the same element type as Ref.
   1525       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
   1526       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
   1527       if (!ThisArgVecTy || !ReferenceType ||
   1528           (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
   1529         return true;
   1530       PointerType *ThisArgEltTy =
   1531           dyn_cast<PointerType>(ThisArgVecTy->getElementType());
   1532       if (!ThisArgEltTy)
   1533         return true;
   1534       return ThisArgEltTy->getElementType() != ReferenceType->getElementType();
   1535     }
   1536     case IITDescriptor::VecElementArgument: {
   1537       if (D.getArgumentNumber() >= ArgTys.size())
   1538         return IsDeferredCheck ? true : DeferCheck(Ty);
   1539       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
   1540       return !ReferenceType || Ty != ReferenceType->getElementType();
   1541     }
   1542     case IITDescriptor::Subdivide2Argument:
   1543     case IITDescriptor::Subdivide4Argument: {
   1544       // If this is a forward reference, defer the check for later.
   1545       if (D.getArgumentNumber() >= ArgTys.size())
   1546         return IsDeferredCheck || DeferCheck(Ty);
   1547 
   1548       Type *NewTy = ArgTys[D.getArgumentNumber()];
   1549       if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
   1550         int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
   1551         NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
   1552         return Ty != NewTy;
   1553       }
   1554       return true;
   1555     }
   1556     case IITDescriptor::VecOfBitcastsToInt: {
   1557       if (D.getArgumentNumber() >= ArgTys.size())
   1558         return IsDeferredCheck || DeferCheck(Ty);
   1559       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
   1560       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
   1561       if (!ThisArgVecTy || !ReferenceType)
   1562         return true;
   1563       return ThisArgVecTy != VectorType::getInteger(ReferenceType);
   1564     }
   1565   }
   1566   llvm_unreachable("unhandled");
   1567 }
   1568 
   1569 Intrinsic::MatchIntrinsicTypesResult
   1570 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
   1571                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
   1572                                    SmallVectorImpl<Type *> &ArgTys) {
   1573   SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
   1574   if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
   1575                          false))
   1576     return MatchIntrinsicTypes_NoMatchRet;
   1577 
   1578   unsigned NumDeferredReturnChecks = DeferredChecks.size();
   1579 
   1580   for (auto Ty : FTy->params())
   1581     if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
   1582       return MatchIntrinsicTypes_NoMatchArg;
   1583 
   1584   for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
   1585     DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
   1586     if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
   1587                            true))
   1588       return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
   1589                                          : MatchIntrinsicTypes_NoMatchArg;
   1590   }
   1591 
   1592   return MatchIntrinsicTypes_Match;
   1593 }
   1594 
   1595 bool
   1596 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
   1597                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
   1598   // If there are no descriptors left, then it can't be a vararg.
   1599   if (Infos.empty())
   1600     return isVarArg;
   1601 
   1602   // There should be only one descriptor remaining at this point.
   1603   if (Infos.size() != 1)
   1604     return true;
   1605 
   1606   // Check and verify the descriptor.
   1607   IITDescriptor D = Infos.front();
   1608   Infos = Infos.slice(1);
   1609   if (D.Kind == IITDescriptor::VarArg)
   1610     return !isVarArg;
   1611 
   1612   return true;
   1613 }
   1614 
   1615 bool Intrinsic::getIntrinsicSignature(Function *F,
   1616                                       SmallVectorImpl<Type *> &ArgTys) {
   1617   Intrinsic::ID ID = F->getIntrinsicID();
   1618   if (!ID)
   1619     return false;
   1620 
   1621   SmallVector<Intrinsic::IITDescriptor, 8> Table;
   1622   getIntrinsicInfoTableEntries(ID, Table);
   1623   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
   1624 
   1625   if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
   1626                                          ArgTys) !=
   1627       Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
   1628     return false;
   1629   }
   1630   if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
   1631                                       TableRef))
   1632     return false;
   1633   return true;
   1634 }
   1635 
   1636 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
   1637   SmallVector<Type *, 4> ArgTys;
   1638   if (!getIntrinsicSignature(F, ArgTys))
   1639     return None;
   1640 
   1641   Intrinsic::ID ID = F->getIntrinsicID();
   1642   StringRef Name = F->getName();
   1643   if (Name ==
   1644       Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType()))
   1645     return None;
   1646 
   1647   auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
   1648   NewDecl->setCallingConv(F->getCallingConv());
   1649   assert(NewDecl->getFunctionType() == F->getFunctionType() &&
   1650          "Shouldn't change the signature");
   1651   return NewDecl;
   1652 }
   1653 
   1654 /// hasAddressTaken - returns true if there are any uses of this function
   1655 /// other than direct calls or invokes to it. Optionally ignores callback
   1656 /// uses, assume like pointer annotation calls, and references in llvm.used
   1657 /// and llvm.compiler.used variables.
   1658 bool Function::hasAddressTaken(const User **PutOffender,
   1659                                bool IgnoreCallbackUses,
   1660                                bool IgnoreAssumeLikeCalls,
   1661                                bool IgnoreLLVMUsed) const {
   1662   for (const Use &U : uses()) {
   1663     const User *FU = U.getUser();
   1664     if (isa<BlockAddress>(FU))
   1665       continue;
   1666 
   1667     if (IgnoreCallbackUses) {
   1668       AbstractCallSite ACS(&U);
   1669       if (ACS && ACS.isCallbackCall())
   1670         continue;
   1671     }
   1672 
   1673     const auto *Call = dyn_cast<CallBase>(FU);
   1674     if (!Call) {
   1675       if (IgnoreAssumeLikeCalls) {
   1676         if (const auto *FI = dyn_cast<Instruction>(FU)) {
   1677           if (FI->isCast() && !FI->user_empty() &&
   1678               llvm::all_of(FU->users(), [](const User *U) {
   1679                 if (const auto *I = dyn_cast<IntrinsicInst>(U))
   1680                   return I->isAssumeLikeIntrinsic();
   1681                 return false;
   1682               }))
   1683             continue;
   1684         }
   1685       }
   1686       if (IgnoreLLVMUsed && !FU->user_empty()) {
   1687         const User *FUU = FU;
   1688         if (isa<BitCastOperator>(FU) && FU->hasOneUse() &&
   1689             !FU->user_begin()->user_empty())
   1690           FUU = *FU->user_begin();
   1691         if (llvm::all_of(FUU->users(), [](const User *U) {
   1692               if (const auto *GV = dyn_cast<GlobalVariable>(U))
   1693                 return GV->hasName() &&
   1694                        (GV->getName().equals("llvm.compiler.used") ||
   1695                         GV->getName().equals("llvm.used"));
   1696               return false;
   1697             }))
   1698           continue;
   1699       }
   1700       if (PutOffender)
   1701         *PutOffender = FU;
   1702       return true;
   1703     }
   1704     if (!Call->isCallee(&U)) {
   1705       if (PutOffender)
   1706         *PutOffender = FU;
   1707       return true;
   1708     }
   1709   }
   1710   return false;
   1711 }
   1712 
   1713 bool Function::isDefTriviallyDead() const {
   1714   // Check the linkage
   1715   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
   1716       !hasAvailableExternallyLinkage())
   1717     return false;
   1718 
   1719   // Check if the function is used by anything other than a blockaddress.
   1720   for (const User *U : users())
   1721     if (!isa<BlockAddress>(U))
   1722       return false;
   1723 
   1724   return true;
   1725 }
   1726 
   1727 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
   1728 /// setjmp or other function that gcc recognizes as "returning twice".
   1729 bool Function::callsFunctionThatReturnsTwice() const {
   1730   for (const Instruction &I : instructions(this))
   1731     if (const auto *Call = dyn_cast<CallBase>(&I))
   1732       if (Call->hasFnAttr(Attribute::ReturnsTwice))
   1733         return true;
   1734 
   1735   return false;
   1736 }
   1737 
   1738 Constant *Function::getPersonalityFn() const {
   1739   assert(hasPersonalityFn() && getNumOperands());
   1740   return cast<Constant>(Op<0>());
   1741 }
   1742 
   1743 void Function::setPersonalityFn(Constant *Fn) {
   1744   setHungoffOperand<0>(Fn);
   1745   setValueSubclassDataBit(3, Fn != nullptr);
   1746 }
   1747 
   1748 Constant *Function::getPrefixData() const {
   1749   assert(hasPrefixData() && getNumOperands());
   1750   return cast<Constant>(Op<1>());
   1751 }
   1752 
   1753 void Function::setPrefixData(Constant *PrefixData) {
   1754   setHungoffOperand<1>(PrefixData);
   1755   setValueSubclassDataBit(1, PrefixData != nullptr);
   1756 }
   1757 
   1758 Constant *Function::getPrologueData() const {
   1759   assert(hasPrologueData() && getNumOperands());
   1760   return cast<Constant>(Op<2>());
   1761 }
   1762 
   1763 void Function::setPrologueData(Constant *PrologueData) {
   1764   setHungoffOperand<2>(PrologueData);
   1765   setValueSubclassDataBit(2, PrologueData != nullptr);
   1766 }
   1767 
   1768 void Function::allocHungoffUselist() {
   1769   // If we've already allocated a uselist, stop here.
   1770   if (getNumOperands())
   1771     return;
   1772 
   1773   allocHungoffUses(3, /*IsPhi=*/ false);
   1774   setNumHungOffUseOperands(3);
   1775 
   1776   // Initialize the uselist with placeholder operands to allow traversal.
   1777   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
   1778   Op<0>().set(CPN);
   1779   Op<1>().set(CPN);
   1780   Op<2>().set(CPN);
   1781 }
   1782 
   1783 template <int Idx>
   1784 void Function::setHungoffOperand(Constant *C) {
   1785   if (C) {
   1786     allocHungoffUselist();
   1787     Op<Idx>().set(C);
   1788   } else if (getNumOperands()) {
   1789     Op<Idx>().set(
   1790         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
   1791   }
   1792 }
   1793 
   1794 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
   1795   assert(Bit < 16 && "SubclassData contains only 16 bits");
   1796   if (On)
   1797     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
   1798   else
   1799     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
   1800 }
   1801 
   1802 void Function::setEntryCount(ProfileCount Count,
   1803                              const DenseSet<GlobalValue::GUID> *S) {
   1804   assert(Count.hasValue());
   1805 #if !defined(NDEBUG)
   1806   auto PrevCount = getEntryCount();
   1807   assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
   1808 #endif
   1809 
   1810   auto ImportGUIDs = getImportGUIDs();
   1811   if (S == nullptr && ImportGUIDs.size())
   1812     S = &ImportGUIDs;
   1813 
   1814   MDBuilder MDB(getContext());
   1815   setMetadata(
   1816       LLVMContext::MD_prof,
   1817       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
   1818 }
   1819 
   1820 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
   1821                              const DenseSet<GlobalValue::GUID> *Imports) {
   1822   setEntryCount(ProfileCount(Count, Type), Imports);
   1823 }
   1824 
   1825 ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
   1826   MDNode *MD = getMetadata(LLVMContext::MD_prof);
   1827   if (MD && MD->getOperand(0))
   1828     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
   1829       if (MDS->getString().equals("function_entry_count")) {
   1830         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
   1831         uint64_t Count = CI->getValue().getZExtValue();
   1832         // A value of -1 is used for SamplePGO when there were no samples.
   1833         // Treat this the same as unknown.
   1834         if (Count == (uint64_t)-1)
   1835           return ProfileCount::getInvalid();
   1836         return ProfileCount(Count, PCT_Real);
   1837       } else if (AllowSynthetic &&
   1838                  MDS->getString().equals("synthetic_function_entry_count")) {
   1839         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
   1840         uint64_t Count = CI->getValue().getZExtValue();
   1841         return ProfileCount(Count, PCT_Synthetic);
   1842       }
   1843     }
   1844   return ProfileCount::getInvalid();
   1845 }
   1846 
   1847 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
   1848   DenseSet<GlobalValue::GUID> R;
   1849   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
   1850     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
   1851       if (MDS->getString().equals("function_entry_count"))
   1852         for (unsigned i = 2; i < MD->getNumOperands(); i++)
   1853           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
   1854                        ->getValue()
   1855                        .getZExtValue());
   1856   return R;
   1857 }
   1858 
   1859 void Function::setSectionPrefix(StringRef Prefix) {
   1860   MDBuilder MDB(getContext());
   1861   setMetadata(LLVMContext::MD_section_prefix,
   1862               MDB.createFunctionSectionPrefix(Prefix));
   1863 }
   1864 
   1865 Optional<StringRef> Function::getSectionPrefix() const {
   1866   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
   1867     assert(cast<MDString>(MD->getOperand(0))
   1868                ->getString()
   1869                .equals("function_section_prefix") &&
   1870            "Metadata not match");
   1871     return cast<MDString>(MD->getOperand(1))->getString();
   1872   }
   1873   return None;
   1874 }
   1875 
   1876 bool Function::nullPointerIsDefined() const {
   1877   return hasFnAttribute(Attribute::NullPointerIsValid);
   1878 }
   1879 
   1880 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
   1881   if (F && F->nullPointerIsDefined())
   1882     return true;
   1883 
   1884   if (AS != 0)
   1885     return true;
   1886 
   1887   return false;
   1888 }
   1889