LLVM  mainline
Function.cpp
Go to the documentation of this file.
00001 //===-- Function.cpp - Implement the Global object classes ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Function class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Function.h"
00015 #include "LLVMContextImpl.h"
00016 #include "SymbolTableListTraitsImpl.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/CodeGen/ValueTypes.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/InstIterator.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/LLVMContext.h"
00027 #include "llvm/IR/MDBuilder.h"
00028 #include "llvm/IR/Metadata.h"
00029 #include "llvm/IR/Module.h"
00030 #include "llvm/Support/ManagedStatic.h"
00031 #include "llvm/Support/RWMutex.h"
00032 #include "llvm/Support/StringPool.h"
00033 #include "llvm/Support/Threading.h"
00034 using namespace llvm;
00035 
00036 // Explicit instantiations of SymbolTableListTraits since some of the methods
00037 // are not in the public header file...
00038 template class llvm::SymbolTableListTraits<Argument>;
00039 template class llvm::SymbolTableListTraits<BasicBlock>;
00040 
00041 //===----------------------------------------------------------------------===//
00042 // Argument Implementation
00043 //===----------------------------------------------------------------------===//
00044 
00045 void Argument::anchor() { }
00046 
00047 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
00048   : Value(Ty, Value::ArgumentVal) {
00049   Parent = nullptr;
00050 
00051   if (Par)
00052     Par->getArgumentList().push_back(this);
00053   setName(Name);
00054 }
00055 
00056 void Argument::setParent(Function *parent) {
00057   Parent = parent;
00058 }
00059 
00060 /// getArgNo - Return the index of this formal argument in its containing
00061 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
00062 unsigned Argument::getArgNo() const {
00063   const Function *F = getParent();
00064   assert(F && "Argument is not in a function");
00065 
00066   Function::const_arg_iterator AI = F->arg_begin();
00067   unsigned ArgIdx = 0;
00068   for (; &*AI != this; ++AI)
00069     ++ArgIdx;
00070 
00071   return ArgIdx;
00072 }
00073 
00074 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
00075 /// it in its containing function. Also returns true if at least one byte is
00076 /// known to be dereferenceable and the pointer is in addrspace(0).
00077 bool Argument::hasNonNullAttr() const {
00078   if (!getType()->isPointerTy()) return false;
00079   if (getParent()->getAttributes().
00080         hasAttribute(getArgNo()+1, Attribute::NonNull))
00081     return true;
00082   else if (getDereferenceableBytes() > 0 &&
00083            getType()->getPointerAddressSpace() == 0)
00084     return true;
00085   return false;
00086 }
00087 
00088 /// hasByValAttr - Return true if this argument has the byval attribute on it
00089 /// in its containing function.
00090 bool Argument::hasByValAttr() const {
00091   if (!getType()->isPointerTy()) return false;
00092   return getParent()->getAttributes().
00093     hasAttribute(getArgNo()+1, Attribute::ByVal);
00094 }
00095 
00096 /// \brief Return true if this argument has the inalloca attribute on it in
00097 /// its containing function.
00098 bool Argument::hasInAllocaAttr() const {
00099   if (!getType()->isPointerTy()) return false;
00100   return getParent()->getAttributes().
00101     hasAttribute(getArgNo()+1, Attribute::InAlloca);
00102 }
00103 
00104 bool Argument::hasByValOrInAllocaAttr() const {
00105   if (!getType()->isPointerTy()) return false;
00106   AttributeSet Attrs = getParent()->getAttributes();
00107   return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
00108          Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
00109 }
00110 
00111 unsigned Argument::getParamAlignment() const {
00112   assert(getType()->isPointerTy() && "Only pointers have alignments");
00113   return getParent()->getParamAlignment(getArgNo()+1);
00114 
00115 }
00116 
00117 uint64_t Argument::getDereferenceableBytes() const {
00118   assert(getType()->isPointerTy() &&
00119          "Only pointers have dereferenceable bytes");
00120   return getParent()->getDereferenceableBytes(getArgNo()+1);
00121 }
00122 
00123 uint64_t Argument::getDereferenceableOrNullBytes() const {
00124   assert(getType()->isPointerTy() &&
00125          "Only pointers have dereferenceable bytes");
00126   return getParent()->getDereferenceableOrNullBytes(getArgNo()+1);
00127 }
00128 
00129 /// hasNestAttr - Return true if this argument has the nest attribute on
00130 /// it in its containing function.
00131 bool Argument::hasNestAttr() const {
00132   if (!getType()->isPointerTy()) return false;
00133   return getParent()->getAttributes().
00134     hasAttribute(getArgNo()+1, Attribute::Nest);
00135 }
00136 
00137 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
00138 /// it in its containing function.
00139 bool Argument::hasNoAliasAttr() const {
00140   if (!getType()->isPointerTy()) return false;
00141   return getParent()->getAttributes().
00142     hasAttribute(getArgNo()+1, Attribute::NoAlias);
00143 }
00144 
00145 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
00146 /// on it in its containing function.
00147 bool Argument::hasNoCaptureAttr() const {
00148   if (!getType()->isPointerTy()) return false;
00149   return getParent()->getAttributes().
00150     hasAttribute(getArgNo()+1, Attribute::NoCapture);
00151 }
00152 
00153 /// hasSRetAttr - Return true if this argument has the sret attribute on
00154 /// it in its containing function.
00155 bool Argument::hasStructRetAttr() const {
00156   if (!getType()->isPointerTy()) return false;
00157   return getParent()->getAttributes().
00158     hasAttribute(getArgNo()+1, Attribute::StructRet);
00159 }
00160 
00161 /// hasReturnedAttr - Return true if this argument has the returned attribute on
00162 /// it in its containing function.
00163 bool Argument::hasReturnedAttr() const {
00164   return getParent()->getAttributes().
00165     hasAttribute(getArgNo()+1, Attribute::Returned);
00166 }
00167 
00168 /// hasZExtAttr - Return true if this argument has the zext attribute on it in
00169 /// its containing function.
00170 bool Argument::hasZExtAttr() const {
00171   return getParent()->getAttributes().
00172     hasAttribute(getArgNo()+1, Attribute::ZExt);
00173 }
00174 
00175 /// hasSExtAttr Return true if this argument has the sext attribute on it in its
00176 /// containing function.
00177 bool Argument::hasSExtAttr() const {
00178   return getParent()->getAttributes().
00179     hasAttribute(getArgNo()+1, Attribute::SExt);
00180 }
00181 
00182 /// Return true if this argument has the readonly or readnone attribute on it
00183 /// in its containing function.
00184 bool Argument::onlyReadsMemory() const {
00185   return getParent()->getAttributes().
00186       hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
00187       getParent()->getAttributes().
00188       hasAttribute(getArgNo()+1, Attribute::ReadNone);
00189 }
00190 
00191 /// addAttr - Add attributes to an argument.
00192 void Argument::addAttr(AttributeSet AS) {
00193   assert(AS.getNumSlots() <= 1 &&
00194          "Trying to add more than one attribute set to an argument!");
00195   AttrBuilder B(AS, AS.getSlotIndex(0));
00196   getParent()->addAttributes(getArgNo() + 1,
00197                              AttributeSet::get(Parent->getContext(),
00198                                                getArgNo() + 1, B));
00199 }
00200 
00201 /// removeAttr - Remove attributes from an argument.
00202 void Argument::removeAttr(AttributeSet AS) {
00203   assert(AS.getNumSlots() <= 1 &&
00204          "Trying to remove more than one attribute set from an argument!");
00205   AttrBuilder B(AS, AS.getSlotIndex(0));
00206   getParent()->removeAttributes(getArgNo() + 1,
00207                                 AttributeSet::get(Parent->getContext(),
00208                                                   getArgNo() + 1, B));
00209 }
00210 
00211 //===----------------------------------------------------------------------===//
00212 // Helper Methods in Function
00213 //===----------------------------------------------------------------------===//
00214 
00215 bool Function::isMaterializable() const {
00216   return getGlobalObjectSubClassData() & IsMaterializableBit;
00217 }
00218 
00219 void Function::setIsMaterializable(bool V) {
00220   setGlobalObjectBit(IsMaterializableBit, V);
00221 }
00222 
00223 LLVMContext &Function::getContext() const {
00224   return getType()->getContext();
00225 }
00226 
00227 FunctionType *Function::getFunctionType() const {
00228   return cast<FunctionType>(getValueType());
00229 }
00230 
00231 bool Function::isVarArg() const {
00232   return getFunctionType()->isVarArg();
00233 }
00234 
00235 Type *Function::getReturnType() const {
00236   return getFunctionType()->getReturnType();
00237 }
00238 
00239 void Function::removeFromParent() {
00240   getParent()->getFunctionList().remove(getIterator());
00241 }
00242 
00243 void Function::eraseFromParent() {
00244   getParent()->getFunctionList().erase(getIterator());
00245 }
00246 
00247 //===----------------------------------------------------------------------===//
00248 // Function Implementation
00249 //===----------------------------------------------------------------------===//
00250 
00251 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
00252                    Module *ParentModule)
00253     : GlobalObject(Ty, Value::FunctionVal,
00254                    OperandTraits<Function>::op_begin(this), 0, Linkage, name) {
00255   assert(FunctionType::isValidReturnType(getReturnType()) &&
00256          "invalid return type");
00257   setGlobalObjectSubClassData(0);
00258   SymTab = new ValueSymbolTable();
00259 
00260   // If the function has arguments, mark them as lazily built.
00261   if (Ty->getNumParams())
00262     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
00263 
00264   if (ParentModule)
00265     ParentModule->getFunctionList().push_back(this);
00266 
00267   // Ensure intrinsics have the right parameter attributes.
00268   // Note, the IntID field will have been set in Value::setName if this function
00269   // name is a valid intrinsic ID.
00270   if (IntID)
00271     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
00272 }
00273 
00274 Function::~Function() {
00275   dropAllReferences();    // After this it is safe to delete instructions.
00276 
00277   // Delete all of the method arguments and unlink from symbol table...
00278   ArgumentList.clear();
00279   delete SymTab;
00280 
00281   // Remove the function from the on-the-side GC table.
00282   clearGC();
00283 }
00284 
00285 void Function::BuildLazyArguments() const {
00286   // Create the arguments vector, all arguments start out unnamed.
00287   FunctionType *FT = getFunctionType();
00288   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00289     assert(!FT->getParamType(i)->isVoidTy() &&
00290            "Cannot have void typed arguments!");
00291     ArgumentList.push_back(new Argument(FT->getParamType(i)));
00292   }
00293 
00294   // Clear the lazy arguments bit.
00295   unsigned SDC = getSubclassDataFromValue();
00296   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
00297 }
00298 
00299 size_t Function::arg_size() const {
00300   return getFunctionType()->getNumParams();
00301 }
00302 bool Function::arg_empty() const {
00303   return getFunctionType()->getNumParams() == 0;
00304 }
00305 
00306 void Function::setParent(Module *parent) {
00307   Parent = parent;
00308 }
00309 
00310 // dropAllReferences() - This function causes all the subinstructions to "let
00311 // go" of all references that they are maintaining.  This allows one to
00312 // 'delete' a whole class at a time, even though there may be circular
00313 // references... first all references are dropped, and all use counts go to
00314 // zero.  Then everything is deleted for real.  Note that no operations are
00315 // valid on an object that has "dropped all references", except operator
00316 // delete.
00317 //
00318 void Function::dropAllReferences() {
00319   setIsMaterializable(false);
00320 
00321   for (iterator I = begin(), E = end(); I != E; ++I)
00322     I->dropAllReferences();
00323 
00324   // Delete all basic blocks. They are now unused, except possibly by
00325   // blockaddresses, but BasicBlock's destructor takes care of those.
00326   while (!BasicBlocks.empty())
00327     BasicBlocks.begin()->eraseFromParent();
00328 
00329   // Drop uses of any optional data (real or placeholder).
00330   if (getNumOperands()) {
00331     User::dropAllReferences();
00332     setNumHungOffUseOperands(0);
00333     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
00334   }
00335 
00336   // Metadata is stored in a side-table.
00337   clearMetadata();
00338 }
00339 
00340 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
00341   AttributeSet PAL = getAttributes();
00342   PAL = PAL.addAttribute(getContext(), i, attr);
00343   setAttributes(PAL);
00344 }
00345 
00346 void Function::addAttributes(unsigned i, AttributeSet attrs) {
00347   AttributeSet PAL = getAttributes();
00348   PAL = PAL.addAttributes(getContext(), i, attrs);
00349   setAttributes(PAL);
00350 }
00351 
00352 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
00353   AttributeSet PAL = getAttributes();
00354   PAL = PAL.removeAttributes(getContext(), i, attrs);
00355   setAttributes(PAL);
00356 }
00357 
00358 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
00359   AttributeSet PAL = getAttributes();
00360   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
00361   setAttributes(PAL);
00362 }
00363 
00364 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
00365   AttributeSet PAL = getAttributes();
00366   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
00367   setAttributes(PAL);
00368 }
00369 
00370 const std::string &Function::getGC() const {
00371   assert(hasGC() && "Function has no collector");
00372   return getContext().getGC(*this);
00373 }
00374 
00375 void Function::setGC(const std::string Str) {
00376   setValueSubclassDataBit(14, !Str.empty());
00377   getContext().setGC(*this, std::move(Str));
00378 }
00379 
00380 void Function::clearGC() {
00381   if (!hasGC())
00382     return;
00383   getContext().deleteGC(*this);
00384   setValueSubclassDataBit(14, false);
00385 }
00386 
00387 /// Copy all additional attributes (those not needed to create a Function) from
00388 /// the Function Src to this one.
00389 void Function::copyAttributesFrom(const GlobalValue *Src) {
00390   GlobalObject::copyAttributesFrom(Src);
00391   const Function *SrcF = dyn_cast<Function>(Src);
00392   if (!SrcF)
00393     return;
00394 
00395   setCallingConv(SrcF->getCallingConv());
00396   setAttributes(SrcF->getAttributes());
00397   if (SrcF->hasGC())
00398     setGC(SrcF->getGC());
00399   else
00400     clearGC();
00401   if (SrcF->hasPersonalityFn())
00402     setPersonalityFn(SrcF->getPersonalityFn());
00403   if (SrcF->hasPrefixData())
00404     setPrefixData(SrcF->getPrefixData());
00405   if (SrcF->hasPrologueData())
00406     setPrologueData(SrcF->getPrologueData());
00407 }
00408 
00409 /// Table of string intrinsic names indexed by enum value.
00410 static const char * const IntrinsicNameTable[] = {
00411   "not_intrinsic",
00412 #define GET_INTRINSIC_NAME_TABLE
00413 #include "llvm/IR/Intrinsics.gen"
00414 #undef GET_INTRINSIC_NAME_TABLE
00415 };
00416 
00417 static int lookupLLVMIntrinsicByName(ArrayRef<const char *> NameTable,
00418                                      StringRef Name) {
00419   // Do a binary search over the table of intrinsic names.
00420   const char *const *NameEntry =
00421       std::lower_bound(NameTable.begin(), NameTable.end(), Name.data(),
00422                        [](const char *LHS, const char *RHS) {
00423                          // Don't compare the first 5 characters, they are
00424                          // always "llvm.".
00425                          return strcmp(LHS + 5, RHS + 5) < 0;
00426                        });
00427   unsigned Idx = NameEntry - NameTable.begin();
00428 
00429   // Check if this is a direct match.
00430   if (Idx < NameTable.size() && strcmp(Name.data(), NameTable[Idx]) == 0)
00431     return Idx;
00432 
00433   // Otherwise, back up one entry to look for a prefix of Name where the next
00434   // character in Name is a dot.
00435   if (Idx == 0)
00436     return -1;
00437   --Idx;
00438   bool CheckPrefixes = true;
00439   while (CheckPrefixes) {
00440     StringRef FoundName = NameTable[Idx];
00441     if (Name.startswith(FoundName) && Name[FoundName.size()] == '.')
00442       return Idx;
00443     if (Idx == 0)
00444       return -1;
00445     --Idx;
00446     // We have to keep scanning backwards until the previous entry is not a
00447     // prefix of the current entry. Consider a key of llvm.foo.f64 and a table
00448     // of llvm.foo and llvm.foo.bar.
00449     CheckPrefixes = FoundName.startswith(NameTable[Idx]);
00450   }
00451 
00452   return -1;
00453 }
00454 
00455 /// \brief This does the actual lookup of an intrinsic ID which
00456 /// matches the given function name.
00457 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
00458   StringRef Name = ValName->getKey();
00459   assert(Name.data()[Name.size()] == '\0' && "non-null terminated ValueName");
00460 
00461   ArrayRef<const char *> NameTable(&IntrinsicNameTable[1],
00462                                    std::end(IntrinsicNameTable));
00463   int Idx = lookupLLVMIntrinsicByName(NameTable, Name);
00464   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + 1);
00465   if (ID == Intrinsic::not_intrinsic)
00466     return ID;
00467 
00468   // If the intrinsic is not overloaded, require an exact match. If it is
00469   // overloaded, require a prefix match.
00470   bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]);
00471   return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
00472 }
00473 
00474 void Function::recalculateIntrinsicID() {
00475   const ValueName *ValName = this->getValueName();
00476   if (!ValName || !isIntrinsic()) {
00477     IntID = Intrinsic::not_intrinsic;
00478     return;
00479   }
00480   IntID = lookupIntrinsicID(ValName);
00481 }
00482 
00483 /// Returns a stable mangling for the type specified for use in the name
00484 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
00485 /// of named types is simply their name.  Manglings for unnamed types consist
00486 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
00487 /// combined with the mangling of their component types.  A vararg function
00488 /// type will have a suffix of 'vararg'.  Since function types can contain
00489 /// other function types, we close a function type mangling with suffix 'f'
00490 /// which can't be confused with it's prefix.  This ensures we don't have
00491 /// collisions between two unrelated function types. Otherwise, you might
00492 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
00493 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
00494 /// cases) fall back to the MVT codepath, where they could be mangled to
00495 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
00496 /// everything.
00497 static std::string getMangledTypeStr(Type* Ty) {
00498   std::string Result;
00499   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
00500     Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
00501       getMangledTypeStr(PTyp->getElementType());
00502   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
00503     Result += "a" + llvm::utostr(ATyp->getNumElements()) +
00504       getMangledTypeStr(ATyp->getElementType());
00505   } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
00506     assert(!STyp->isLiteral() && "TODO: implement literal types");
00507     Result += STyp->getName();
00508   } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
00509     Result += "f_" + getMangledTypeStr(FT->getReturnType());
00510     for (size_t i = 0; i < FT->getNumParams(); i++)
00511       Result += getMangledTypeStr(FT->getParamType(i));
00512     if (FT->isVarArg())
00513       Result += "vararg";
00514     // Ensure nested function types are distinguishable.
00515     Result += "f"; 
00516   } else if (isa<VectorType>(Ty))
00517     Result += "v" + utostr(Ty->getVectorNumElements()) +
00518       getMangledTypeStr(Ty->getVectorElementType());
00519   else if (Ty)
00520     Result += EVT::getEVT(Ty).getEVTString();
00521   return Result;
00522 }
00523 
00524 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
00525   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00526   if (Tys.empty())
00527     return IntrinsicNameTable[id];
00528   std::string Result(IntrinsicNameTable[id]);
00529   for (unsigned i = 0; i < Tys.size(); ++i) {
00530     Result += "." + getMangledTypeStr(Tys[i]);
00531   }
00532   return Result;
00533 }
00534 
00535 
00536 /// IIT_Info - These are enumerators that describe the entries returned by the
00537 /// getIntrinsicInfoTableEntries function.
00538 ///
00539 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
00540 enum IIT_Info {
00541   // Common values should be encoded with 0-15.
00542   IIT_Done = 0,
00543   IIT_I1   = 1,
00544   IIT_I8   = 2,
00545   IIT_I16  = 3,
00546   IIT_I32  = 4,
00547   IIT_I64  = 5,
00548   IIT_F16  = 6,
00549   IIT_F32  = 7,
00550   IIT_F64  = 8,
00551   IIT_V2   = 9,
00552   IIT_V4   = 10,
00553   IIT_V8   = 11,
00554   IIT_V16  = 12,
00555   IIT_V32  = 13,
00556   IIT_PTR  = 14,
00557   IIT_ARG  = 15,
00558 
00559   // Values from 16+ are only encodable with the inefficient encoding.
00560   IIT_V64  = 16,
00561   IIT_MMX  = 17,
00562   IIT_TOKEN = 18,
00563   IIT_METADATA = 19,
00564   IIT_EMPTYSTRUCT = 20,
00565   IIT_STRUCT2 = 21,
00566   IIT_STRUCT3 = 22,
00567   IIT_STRUCT4 = 23,
00568   IIT_STRUCT5 = 24,
00569   IIT_EXTEND_ARG = 25,
00570   IIT_TRUNC_ARG = 26,
00571   IIT_ANYPTR = 27,
00572   IIT_V1   = 28,
00573   IIT_VARARG = 29,
00574   IIT_HALF_VEC_ARG = 30,
00575   IIT_SAME_VEC_WIDTH_ARG = 31,
00576   IIT_PTR_TO_ARG = 32,
00577   IIT_VEC_OF_PTRS_TO_ELT = 33,
00578   IIT_I128 = 34,
00579   IIT_V512 = 35,
00580   IIT_V1024 = 36
00581 };
00582 
00583 
00584 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
00585                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
00586   IIT_Info Info = IIT_Info(Infos[NextElt++]);
00587   unsigned StructElts = 2;
00588   using namespace Intrinsic;
00589 
00590   switch (Info) {
00591   case IIT_Done:
00592     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
00593     return;
00594   case IIT_VARARG:
00595     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
00596     return;
00597   case IIT_MMX:
00598     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
00599     return;
00600   case IIT_TOKEN:
00601     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
00602     return;
00603   case IIT_METADATA:
00604     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
00605     return;
00606   case IIT_F16:
00607     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
00608     return;
00609   case IIT_F32:
00610     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
00611     return;
00612   case IIT_F64:
00613     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
00614     return;
00615   case IIT_I1:
00616     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
00617     return;
00618   case IIT_I8:
00619     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
00620     return;
00621   case IIT_I16:
00622     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
00623     return;
00624   case IIT_I32:
00625     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
00626     return;
00627   case IIT_I64:
00628     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
00629     return;
00630   case IIT_I128:
00631     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
00632     return;
00633   case IIT_V1:
00634     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
00635     DecodeIITType(NextElt, Infos, OutputTable);
00636     return;
00637   case IIT_V2:
00638     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
00639     DecodeIITType(NextElt, Infos, OutputTable);
00640     return;
00641   case IIT_V4:
00642     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
00643     DecodeIITType(NextElt, Infos, OutputTable);
00644     return;
00645   case IIT_V8:
00646     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
00647     DecodeIITType(NextElt, Infos, OutputTable);
00648     return;
00649   case IIT_V16:
00650     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
00651     DecodeIITType(NextElt, Infos, OutputTable);
00652     return;
00653   case IIT_V32:
00654     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
00655     DecodeIITType(NextElt, Infos, OutputTable);
00656     return;
00657   case IIT_V64:
00658     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
00659     DecodeIITType(NextElt, Infos, OutputTable);
00660     return;
00661   case IIT_V512:
00662     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
00663     DecodeIITType(NextElt, Infos, OutputTable);
00664     return;
00665   case IIT_V1024:
00666     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
00667     DecodeIITType(NextElt, Infos, OutputTable);
00668     return;
00669   case IIT_PTR:
00670     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
00671     DecodeIITType(NextElt, Infos, OutputTable);
00672     return;
00673   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
00674     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
00675                                              Infos[NextElt++]));
00676     DecodeIITType(NextElt, Infos, OutputTable);
00677     return;
00678   }
00679   case IIT_ARG: {
00680     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00681     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
00682     return;
00683   }
00684   case IIT_EXTEND_ARG: {
00685     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00686     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
00687                                              ArgInfo));
00688     return;
00689   }
00690   case IIT_TRUNC_ARG: {
00691     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00692     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
00693                                              ArgInfo));
00694     return;
00695   }
00696   case IIT_HALF_VEC_ARG: {
00697     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00698     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
00699                                              ArgInfo));
00700     return;
00701   }
00702   case IIT_SAME_VEC_WIDTH_ARG: {
00703     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00704     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
00705                                              ArgInfo));
00706     return;
00707   }
00708   case IIT_PTR_TO_ARG: {
00709     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00710     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
00711                                              ArgInfo));
00712     return;
00713   }
00714   case IIT_VEC_OF_PTRS_TO_ELT: {
00715     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00716     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
00717                                              ArgInfo));
00718     return;
00719   }
00720   case IIT_EMPTYSTRUCT:
00721     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
00722     return;
00723   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
00724   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
00725   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
00726   case IIT_STRUCT2: {
00727     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
00728 
00729     for (unsigned i = 0; i != StructElts; ++i)
00730       DecodeIITType(NextElt, Infos, OutputTable);
00731     return;
00732   }
00733   }
00734   llvm_unreachable("unhandled");
00735 }
00736 
00737 
00738 #define GET_INTRINSIC_GENERATOR_GLOBAL
00739 #include "llvm/IR/Intrinsics.gen"
00740 #undef GET_INTRINSIC_GENERATOR_GLOBAL
00741 
00742 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
00743                                              SmallVectorImpl<IITDescriptor> &T){
00744   // Check to see if the intrinsic's type was expressible by the table.
00745   unsigned TableVal = IIT_Table[id-1];
00746 
00747   // Decode the TableVal into an array of IITValues.
00748   SmallVector<unsigned char, 8> IITValues;
00749   ArrayRef<unsigned char> IITEntries;
00750   unsigned NextElt = 0;
00751   if ((TableVal >> 31) != 0) {
00752     // This is an offset into the IIT_LongEncodingTable.
00753     IITEntries = IIT_LongEncodingTable;
00754 
00755     // Strip sentinel bit.
00756     NextElt = (TableVal << 1) >> 1;
00757   } else {
00758     // Decode the TableVal into an array of IITValues.  If the entry was encoded
00759     // into a single word in the table itself, decode it now.
00760     do {
00761       IITValues.push_back(TableVal & 0xF);
00762       TableVal >>= 4;
00763     } while (TableVal);
00764 
00765     IITEntries = IITValues;
00766     NextElt = 0;
00767   }
00768 
00769   // Okay, decode the table into the output vector of IITDescriptors.
00770   DecodeIITType(NextElt, IITEntries, T);
00771   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
00772     DecodeIITType(NextElt, IITEntries, T);
00773 }
00774 
00775 
00776 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
00777                              ArrayRef<Type*> Tys, LLVMContext &Context) {
00778   using namespace Intrinsic;
00779   IITDescriptor D = Infos.front();
00780   Infos = Infos.slice(1);
00781 
00782   switch (D.Kind) {
00783   case IITDescriptor::Void: return Type::getVoidTy(Context);
00784   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
00785   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
00786   case IITDescriptor::Token: return Type::getTokenTy(Context);
00787   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
00788   case IITDescriptor::Half: return Type::getHalfTy(Context);
00789   case IITDescriptor::Float: return Type::getFloatTy(Context);
00790   case IITDescriptor::Double: return Type::getDoubleTy(Context);
00791 
00792   case IITDescriptor::Integer:
00793     return IntegerType::get(Context, D.Integer_Width);
00794   case IITDescriptor::Vector:
00795     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
00796   case IITDescriptor::Pointer:
00797     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
00798                             D.Pointer_AddressSpace);
00799   case IITDescriptor::Struct: {
00800     Type *Elts[5];
00801     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
00802     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
00803       Elts[i] = DecodeFixedType(Infos, Tys, Context);
00804     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
00805   }
00806 
00807   case IITDescriptor::Argument:
00808     return Tys[D.getArgumentNumber()];
00809   case IITDescriptor::ExtendArgument: {
00810     Type *Ty = Tys[D.getArgumentNumber()];
00811     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00812       return VectorType::getExtendedElementVectorType(VTy);
00813 
00814     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
00815   }
00816   case IITDescriptor::TruncArgument: {
00817     Type *Ty = Tys[D.getArgumentNumber()];
00818     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00819       return VectorType::getTruncatedElementVectorType(VTy);
00820 
00821     IntegerType *ITy = cast<IntegerType>(Ty);
00822     assert(ITy->getBitWidth() % 2 == 0);
00823     return IntegerType::get(Context, ITy->getBitWidth() / 2);
00824   }
00825   case IITDescriptor::HalfVecArgument:
00826     return VectorType::getHalfElementsVectorType(cast<VectorType>(
00827                                                   Tys[D.getArgumentNumber()]));
00828   case IITDescriptor::SameVecWidthArgument: {
00829     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
00830     Type *Ty = Tys[D.getArgumentNumber()];
00831     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
00832       return VectorType::get(EltTy, VTy->getNumElements());
00833     }
00834     llvm_unreachable("unhandled");
00835   }
00836   case IITDescriptor::PtrToArgument: {
00837     Type *Ty = Tys[D.getArgumentNumber()];
00838     return PointerType::getUnqual(Ty);
00839   }
00840   case IITDescriptor::VecOfPtrsToElt: {
00841     Type *Ty = Tys[D.getArgumentNumber()];
00842     VectorType *VTy = dyn_cast<VectorType>(Ty);
00843     if (!VTy)
00844       llvm_unreachable("Expected an argument of Vector Type");
00845     Type *EltTy = VTy->getVectorElementType();
00846     return VectorType::get(PointerType::getUnqual(EltTy),
00847                            VTy->getNumElements());
00848   }
00849  }
00850   llvm_unreachable("unhandled");
00851 }
00852 
00853 
00854 
00855 FunctionType *Intrinsic::getType(LLVMContext &Context,
00856                                  ID id, ArrayRef<Type*> Tys) {
00857   SmallVector<IITDescriptor, 8> Table;
00858   getIntrinsicInfoTableEntries(id, Table);
00859 
00860   ArrayRef<IITDescriptor> TableRef = Table;
00861   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
00862 
00863   SmallVector<Type*, 8> ArgTys;
00864   while (!TableRef.empty())
00865     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
00866 
00867   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
00868   // If we see void type as the type of the last argument, it is vararg intrinsic
00869   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
00870     ArgTys.pop_back();
00871     return FunctionType::get(ResultTy, ArgTys, true);
00872   }
00873   return FunctionType::get(ResultTy, ArgTys, false);
00874 }
00875 
00876 bool Intrinsic::isOverloaded(ID id) {
00877 #define GET_INTRINSIC_OVERLOAD_TABLE
00878 #include "llvm/IR/Intrinsics.gen"
00879 #undef GET_INTRINSIC_OVERLOAD_TABLE
00880 }
00881 
00882 bool Intrinsic::isLeaf(ID id) {
00883   switch (id) {
00884   default:
00885     return true;
00886 
00887   case Intrinsic::experimental_gc_statepoint:
00888   case Intrinsic::experimental_patchpoint_void:
00889   case Intrinsic::experimental_patchpoint_i64:
00890     return false;
00891   }
00892 }
00893 
00894 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00895 #define GET_INTRINSIC_ATTRIBUTES
00896 #include "llvm/IR/Intrinsics.gen"
00897 #undef GET_INTRINSIC_ATTRIBUTES
00898 
00899 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
00900   // There can never be multiple globals with the same name of different types,
00901   // because intrinsics must be a specific type.
00902   return
00903     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
00904                                           getType(M->getContext(), id, Tys)));
00905 }
00906 
00907 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
00908 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00909 #include "llvm/IR/Intrinsics.gen"
00910 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00911 
00912 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
00913 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00914 #include "llvm/IR/Intrinsics.gen"
00915 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00916 
00917 /// hasAddressTaken - returns true if there are any uses of this function
00918 /// other than direct calls or invokes to it.
00919 bool Function::hasAddressTaken(const User* *PutOffender) const {
00920   for (const Use &U : uses()) {
00921     const User *FU = U.getUser();
00922     if (isa<BlockAddress>(FU))
00923       continue;
00924     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
00925       return PutOffender ? (*PutOffender = FU, true) : true;
00926     ImmutableCallSite CS(cast<Instruction>(FU));
00927     if (!CS.isCallee(&U))
00928       return PutOffender ? (*PutOffender = FU, true) : true;
00929   }
00930   return false;
00931 }
00932 
00933 bool Function::isDefTriviallyDead() const {
00934   // Check the linkage
00935   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
00936       !hasAvailableExternallyLinkage())
00937     return false;
00938 
00939   // Check if the function is used by anything other than a blockaddress.
00940   for (const User *U : users())
00941     if (!isa<BlockAddress>(U))
00942       return false;
00943 
00944   return true;
00945 }
00946 
00947 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00948 /// setjmp or other function that gcc recognizes as "returning twice".
00949 bool Function::callsFunctionThatReturnsTwice() const {
00950   for (const_inst_iterator
00951          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
00952     ImmutableCallSite CS(&*I);
00953     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
00954       return true;
00955   }
00956 
00957   return false;
00958 }
00959 
00960 Constant *Function::getPersonalityFn() const {
00961   assert(hasPersonalityFn() && getNumOperands());
00962   return cast<Constant>(Op<0>());
00963 }
00964 
00965 void Function::setPersonalityFn(Constant *Fn) {
00966   setHungoffOperand<0>(Fn);
00967   setValueSubclassDataBit(3, Fn != nullptr);
00968 }
00969 
00970 Constant *Function::getPrefixData() const {
00971   assert(hasPrefixData() && getNumOperands());
00972   return cast<Constant>(Op<1>());
00973 }
00974 
00975 void Function::setPrefixData(Constant *PrefixData) {
00976   setHungoffOperand<1>(PrefixData);
00977   setValueSubclassDataBit(1, PrefixData != nullptr);
00978 }
00979 
00980 Constant *Function::getPrologueData() const {
00981   assert(hasPrologueData() && getNumOperands());
00982   return cast<Constant>(Op<2>());
00983 }
00984 
00985 void Function::setPrologueData(Constant *PrologueData) {
00986   setHungoffOperand<2>(PrologueData);
00987   setValueSubclassDataBit(2, PrologueData != nullptr);
00988 }
00989 
00990 void Function::allocHungoffUselist() {
00991   // If we've already allocated a uselist, stop here.
00992   if (getNumOperands())
00993     return;
00994 
00995   allocHungoffUses(3, /*IsPhi=*/ false);
00996   setNumHungOffUseOperands(3);
00997 
00998   // Initialize the uselist with placeholder operands to allow traversal.
00999   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
01000   Op<0>().set(CPN);
01001   Op<1>().set(CPN);
01002   Op<2>().set(CPN);
01003 }
01004 
01005 template <int Idx>
01006 void Function::setHungoffOperand(Constant *C) {
01007   if (C) {
01008     allocHungoffUselist();
01009     Op<Idx>().set(C);
01010   } else if (getNumOperands()) {
01011     Op<Idx>().set(
01012         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
01013   }
01014 }
01015 
01016 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
01017   assert(Bit < 16 && "SubclassData contains only 16 bits");
01018   if (On)
01019     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
01020   else
01021     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
01022 }
01023 
01024 void Function::setEntryCount(uint64_t Count) {
01025   MDBuilder MDB(getContext());
01026   setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
01027 }
01028 
01029 Optional<uint64_t> Function::getEntryCount() const {
01030   MDNode *MD = getMetadata(LLVMContext::MD_prof);
01031   if (MD && MD->getOperand(0))
01032     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
01033       if (MDS->getString().equals("function_entry_count")) {
01034         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
01035         return CI->getValue().getZExtValue();
01036       }
01037   return None;
01038 }