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, Function>;
00039 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
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   if (this != getParent()->arg_begin())
00158     return false; // StructRet param must be first param
00159   return getParent()->getAttributes().
00160     hasAttribute(1, Attribute::StructRet);
00161 }
00162 
00163 /// hasReturnedAttr - Return true if this argument has the returned attribute on
00164 /// it in its containing function.
00165 bool Argument::hasReturnedAttr() const {
00166   return getParent()->getAttributes().
00167     hasAttribute(getArgNo()+1, Attribute::Returned);
00168 }
00169 
00170 /// hasZExtAttr - Return true if this argument has the zext attribute on it in
00171 /// its containing function.
00172 bool Argument::hasZExtAttr() const {
00173   return getParent()->getAttributes().
00174     hasAttribute(getArgNo()+1, Attribute::ZExt);
00175 }
00176 
00177 /// hasSExtAttr Return true if this argument has the sext attribute on it in its
00178 /// containing function.
00179 bool Argument::hasSExtAttr() const {
00180   return getParent()->getAttributes().
00181     hasAttribute(getArgNo()+1, Attribute::SExt);
00182 }
00183 
00184 /// Return true if this argument has the readonly or readnone attribute on it
00185 /// in its containing function.
00186 bool Argument::onlyReadsMemory() const {
00187   return getParent()->getAttributes().
00188       hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
00189       getParent()->getAttributes().
00190       hasAttribute(getArgNo()+1, Attribute::ReadNone);
00191 }
00192 
00193 /// addAttr - Add attributes to an argument.
00194 void Argument::addAttr(AttributeSet AS) {
00195   assert(AS.getNumSlots() <= 1 &&
00196          "Trying to add more than one attribute set to an argument!");
00197   AttrBuilder B(AS, AS.getSlotIndex(0));
00198   getParent()->addAttributes(getArgNo() + 1,
00199                              AttributeSet::get(Parent->getContext(),
00200                                                getArgNo() + 1, B));
00201 }
00202 
00203 /// removeAttr - Remove attributes from an argument.
00204 void Argument::removeAttr(AttributeSet AS) {
00205   assert(AS.getNumSlots() <= 1 &&
00206          "Trying to remove more than one attribute set from an argument!");
00207   AttrBuilder B(AS, AS.getSlotIndex(0));
00208   getParent()->removeAttributes(getArgNo() + 1,
00209                                 AttributeSet::get(Parent->getContext(),
00210                                                   getArgNo() + 1, B));
00211 }
00212 
00213 //===----------------------------------------------------------------------===//
00214 // Helper Methods in Function
00215 //===----------------------------------------------------------------------===//
00216 
00217 bool Function::isMaterializable() const {
00218   return getGlobalObjectSubClassData() & IsMaterializableBit;
00219 }
00220 
00221 void Function::setIsMaterializable(bool V) {
00222   setGlobalObjectBit(IsMaterializableBit, V);
00223 }
00224 
00225 LLVMContext &Function::getContext() const {
00226   return getType()->getContext();
00227 }
00228 
00229 FunctionType *Function::getFunctionType() const { return Ty; }
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(this);
00241 }
00242 
00243 void Function::eraseFromParent() {
00244   getParent()->getFunctionList().erase(this);
00245 }
00246 
00247 //===----------------------------------------------------------------------===//
00248 // Function Implementation
00249 //===----------------------------------------------------------------------===//
00250 
00251 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
00252                    Module *ParentModule)
00253     : GlobalObject(PointerType::getUnqual(Ty), Value::FunctionVal, nullptr, 0,
00254                    Linkage, name),
00255       Ty(Ty) {
00256   assert(FunctionType::isValidReturnType(getReturnType()) &&
00257          "invalid return type");
00258   setGlobalObjectSubClassData(0);
00259   SymTab = new ValueSymbolTable();
00260 
00261   // If the function has arguments, mark them as lazily built.
00262   if (Ty->getNumParams())
00263     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
00264 
00265   if (ParentModule)
00266     ParentModule->getFunctionList().push_back(this);
00267 
00268   // Ensure intrinsics have the right parameter attributes.
00269   // Note, the IntID field will have been set in Value::setName if this function
00270   // name is a valid intrinsic ID.
00271   if (IntID)
00272     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
00273 }
00274 
00275 Function::~Function() {
00276   dropAllReferences();    // After this it is safe to delete instructions.
00277 
00278   // Delete all of the method arguments and unlink from symbol table...
00279   ArgumentList.clear();
00280   delete SymTab;
00281 
00282   // Remove the function from the on-the-side GC table.
00283   clearGC();
00284 }
00285 
00286 void Function::BuildLazyArguments() const {
00287   // Create the arguments vector, all arguments start out unnamed.
00288   FunctionType *FT = getFunctionType();
00289   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00290     assert(!FT->getParamType(i)->isVoidTy() &&
00291            "Cannot have void typed arguments!");
00292     ArgumentList.push_back(new Argument(FT->getParamType(i)));
00293   }
00294 
00295   // Clear the lazy arguments bit.
00296   unsigned SDC = getSubclassDataFromValue();
00297   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
00298 }
00299 
00300 size_t Function::arg_size() const {
00301   return getFunctionType()->getNumParams();
00302 }
00303 bool Function::arg_empty() const {
00304   return getFunctionType()->getNumParams() == 0;
00305 }
00306 
00307 void Function::setParent(Module *parent) {
00308   Parent = parent;
00309 }
00310 
00311 // dropAllReferences() - This function causes all the subinstructions to "let
00312 // go" of all references that they are maintaining.  This allows one to
00313 // 'delete' a whole class at a time, even though there may be circular
00314 // references... first all references are dropped, and all use counts go to
00315 // zero.  Then everything is deleted for real.  Note that no operations are
00316 // valid on an object that has "dropped all references", except operator
00317 // delete.
00318 //
00319 void Function::dropAllReferences() {
00320   setIsMaterializable(false);
00321 
00322   for (iterator I = begin(), E = end(); I != E; ++I)
00323     I->dropAllReferences();
00324 
00325   // Delete all basic blocks. They are now unused, except possibly by
00326   // blockaddresses, but BasicBlock's destructor takes care of those.
00327   while (!BasicBlocks.empty())
00328     BasicBlocks.begin()->eraseFromParent();
00329 
00330   // Prefix and prologue data are stored in a side table.
00331   setPrefixData(nullptr);
00332   setPrologueData(nullptr);
00333 
00334   // Metadata is stored in a side-table.
00335   clearMetadata();
00336 }
00337 
00338 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
00339   AttributeSet PAL = getAttributes();
00340   PAL = PAL.addAttribute(getContext(), i, attr);
00341   setAttributes(PAL);
00342 }
00343 
00344 void Function::addAttributes(unsigned i, AttributeSet attrs) {
00345   AttributeSet PAL = getAttributes();
00346   PAL = PAL.addAttributes(getContext(), i, attrs);
00347   setAttributes(PAL);
00348 }
00349 
00350 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
00351   AttributeSet PAL = getAttributes();
00352   PAL = PAL.removeAttributes(getContext(), i, attrs);
00353   setAttributes(PAL);
00354 }
00355 
00356 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
00357   AttributeSet PAL = getAttributes();
00358   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
00359   setAttributes(PAL);
00360 }
00361 
00362 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
00363   AttributeSet PAL = getAttributes();
00364   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
00365   setAttributes(PAL);
00366 }
00367 
00368 // Maintain the GC name for each function in an on-the-side table. This saves
00369 // allocating an additional word in Function for programs which do not use GC
00370 // (i.e., most programs) at the cost of increased overhead for clients which do
00371 // use GC.
00372 static DenseMap<const Function*,PooledStringPtr> *GCNames;
00373 static StringPool *GCNamePool;
00374 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
00375 
00376 bool Function::hasGC() const {
00377   sys::SmartScopedReader<true> Reader(*GCLock);
00378   return GCNames && GCNames->count(this);
00379 }
00380 
00381 const char *Function::getGC() const {
00382   assert(hasGC() && "Function has no collector");
00383   sys::SmartScopedReader<true> Reader(*GCLock);
00384   return *(*GCNames)[this];
00385 }
00386 
00387 void Function::setGC(const char *Str) {
00388   sys::SmartScopedWriter<true> Writer(*GCLock);
00389   if (!GCNamePool)
00390     GCNamePool = new StringPool();
00391   if (!GCNames)
00392     GCNames = new DenseMap<const Function*,PooledStringPtr>();
00393   (*GCNames)[this] = GCNamePool->intern(Str);
00394 }
00395 
00396 void Function::clearGC() {
00397   sys::SmartScopedWriter<true> Writer(*GCLock);
00398   if (GCNames) {
00399     GCNames->erase(this);
00400     if (GCNames->empty()) {
00401       delete GCNames;
00402       GCNames = nullptr;
00403       if (GCNamePool->empty()) {
00404         delete GCNamePool;
00405         GCNamePool = nullptr;
00406       }
00407     }
00408   }
00409 }
00410 
00411 /// copyAttributesFrom - copy all additional attributes (those not needed to
00412 /// create a Function) from the Function Src to this one.
00413 void Function::copyAttributesFrom(const GlobalValue *Src) {
00414   assert(isa<Function>(Src) && "Expected a Function!");
00415   GlobalObject::copyAttributesFrom(Src);
00416   const Function *SrcF = cast<Function>(Src);
00417   setCallingConv(SrcF->getCallingConv());
00418   setAttributes(SrcF->getAttributes());
00419   if (SrcF->hasGC())
00420     setGC(SrcF->getGC());
00421   else
00422     clearGC();
00423   if (SrcF->hasPrefixData())
00424     setPrefixData(SrcF->getPrefixData());
00425   else
00426     setPrefixData(nullptr);
00427   if (SrcF->hasPrologueData())
00428     setPrologueData(SrcF->getPrologueData());
00429   else
00430     setPrologueData(nullptr);
00431 }
00432 
00433 /// \brief This does the actual lookup of an intrinsic ID which
00434 /// matches the given function name.
00435 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
00436   unsigned Len = ValName->getKeyLength();
00437   const char *Name = ValName->getKeyData();
00438 
00439 #define GET_FUNCTION_RECOGNIZER
00440 #include "llvm/IR/Intrinsics.gen"
00441 #undef GET_FUNCTION_RECOGNIZER
00442 
00443   return Intrinsic::not_intrinsic;
00444 }
00445 
00446 void Function::recalculateIntrinsicID() {
00447   const ValueName *ValName = this->getValueName();
00448   if (!ValName || !isIntrinsic()) {
00449     IntID = Intrinsic::not_intrinsic;
00450     return;
00451   }
00452   IntID = lookupIntrinsicID(ValName);
00453 }
00454 
00455 /// Returns a stable mangling for the type specified for use in the name
00456 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
00457 /// of named types is simply their name.  Manglings for unnamed types consist
00458 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
00459 /// combined with the mangling of their component types.  A vararg function
00460 /// type will have a suffix of 'vararg'.  Since function types can contain
00461 /// other function types, we close a function type mangling with suffix 'f'
00462 /// which can't be confused with it's prefix.  This ensures we don't have
00463 /// collisions between two unrelated function types. Otherwise, you might
00464 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
00465 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
00466 /// cases) fall back to the MVT codepath, where they could be mangled to
00467 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
00468 /// everything.
00469 static std::string getMangledTypeStr(Type* Ty) {
00470   std::string Result;
00471   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
00472     Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
00473       getMangledTypeStr(PTyp->getElementType());
00474   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
00475     Result += "a" + llvm::utostr(ATyp->getNumElements()) +
00476       getMangledTypeStr(ATyp->getElementType());
00477   } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
00478     assert(!STyp->isLiteral() && "TODO: implement literal types");
00479     Result += STyp->getName();
00480   } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
00481     Result += "f_" + getMangledTypeStr(FT->getReturnType());
00482     for (size_t i = 0; i < FT->getNumParams(); i++)
00483       Result += getMangledTypeStr(FT->getParamType(i));
00484     if (FT->isVarArg())
00485       Result += "vararg";
00486     // Ensure nested function types are distinguishable.
00487     Result += "f"; 
00488   } else if (Ty)
00489     Result += EVT::getEVT(Ty).getEVTString();
00490   return Result;
00491 }
00492 
00493 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
00494   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00495   static const char * const Table[] = {
00496     "not_intrinsic",
00497 #define GET_INTRINSIC_NAME_TABLE
00498 #include "llvm/IR/Intrinsics.gen"
00499 #undef GET_INTRINSIC_NAME_TABLE
00500   };
00501   if (Tys.empty())
00502     return Table[id];
00503   std::string Result(Table[id]);
00504   for (unsigned i = 0; i < Tys.size(); ++i) {
00505     Result += "." + getMangledTypeStr(Tys[i]);
00506   }
00507   return Result;
00508 }
00509 
00510 
00511 /// IIT_Info - These are enumerators that describe the entries returned by the
00512 /// getIntrinsicInfoTableEntries function.
00513 ///
00514 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
00515 enum IIT_Info {
00516   // Common values should be encoded with 0-15.
00517   IIT_Done = 0,
00518   IIT_I1   = 1,
00519   IIT_I8   = 2,
00520   IIT_I16  = 3,
00521   IIT_I32  = 4,
00522   IIT_I64  = 5,
00523   IIT_F16  = 6,
00524   IIT_F32  = 7,
00525   IIT_F64  = 8,
00526   IIT_V2   = 9,
00527   IIT_V4   = 10,
00528   IIT_V8   = 11,
00529   IIT_V16  = 12,
00530   IIT_V32  = 13,
00531   IIT_PTR  = 14,
00532   IIT_ARG  = 15,
00533 
00534   // Values from 16+ are only encodable with the inefficient encoding.
00535   IIT_V64  = 16,
00536   IIT_MMX  = 17,
00537   IIT_METADATA = 18,
00538   IIT_EMPTYSTRUCT = 19,
00539   IIT_STRUCT2 = 20,
00540   IIT_STRUCT3 = 21,
00541   IIT_STRUCT4 = 22,
00542   IIT_STRUCT5 = 23,
00543   IIT_EXTEND_ARG = 24,
00544   IIT_TRUNC_ARG = 25,
00545   IIT_ANYPTR = 26,
00546   IIT_V1   = 27,
00547   IIT_VARARG = 28,
00548   IIT_HALF_VEC_ARG = 29,
00549   IIT_SAME_VEC_WIDTH_ARG = 30,
00550   IIT_PTR_TO_ARG = 31,
00551   IIT_VEC_OF_PTRS_TO_ELT = 32
00552 };
00553 
00554 
00555 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
00556                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
00557   IIT_Info Info = IIT_Info(Infos[NextElt++]);
00558   unsigned StructElts = 2;
00559   using namespace Intrinsic;
00560 
00561   switch (Info) {
00562   case IIT_Done:
00563     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
00564     return;
00565   case IIT_VARARG:
00566     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
00567     return;
00568   case IIT_MMX:
00569     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
00570     return;
00571   case IIT_METADATA:
00572     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
00573     return;
00574   case IIT_F16:
00575     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
00576     return;
00577   case IIT_F32:
00578     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
00579     return;
00580   case IIT_F64:
00581     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
00582     return;
00583   case IIT_I1:
00584     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
00585     return;
00586   case IIT_I8:
00587     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
00588     return;
00589   case IIT_I16:
00590     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
00591     return;
00592   case IIT_I32:
00593     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
00594     return;
00595   case IIT_I64:
00596     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
00597     return;
00598   case IIT_V1:
00599     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
00600     DecodeIITType(NextElt, Infos, OutputTable);
00601     return;
00602   case IIT_V2:
00603     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
00604     DecodeIITType(NextElt, Infos, OutputTable);
00605     return;
00606   case IIT_V4:
00607     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
00608     DecodeIITType(NextElt, Infos, OutputTable);
00609     return;
00610   case IIT_V8:
00611     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
00612     DecodeIITType(NextElt, Infos, OutputTable);
00613     return;
00614   case IIT_V16:
00615     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
00616     DecodeIITType(NextElt, Infos, OutputTable);
00617     return;
00618   case IIT_V32:
00619     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
00620     DecodeIITType(NextElt, Infos, OutputTable);
00621     return;
00622   case IIT_V64:
00623     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
00624     DecodeIITType(NextElt, Infos, OutputTable);
00625     return;
00626   case IIT_PTR:
00627     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
00628     DecodeIITType(NextElt, Infos, OutputTable);
00629     return;
00630   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
00631     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
00632                                              Infos[NextElt++]));
00633     DecodeIITType(NextElt, Infos, OutputTable);
00634     return;
00635   }
00636   case IIT_ARG: {
00637     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00638     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
00639     return;
00640   }
00641   case IIT_EXTEND_ARG: {
00642     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00643     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
00644                                              ArgInfo));
00645     return;
00646   }
00647   case IIT_TRUNC_ARG: {
00648     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00649     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
00650                                              ArgInfo));
00651     return;
00652   }
00653   case IIT_HALF_VEC_ARG: {
00654     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00655     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
00656                                              ArgInfo));
00657     return;
00658   }
00659   case IIT_SAME_VEC_WIDTH_ARG: {
00660     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00661     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
00662                                              ArgInfo));
00663     return;
00664   }
00665   case IIT_PTR_TO_ARG: {
00666     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00667     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
00668                                              ArgInfo));
00669     return;
00670   }
00671   case IIT_VEC_OF_PTRS_TO_ELT: {
00672     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00673     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
00674                                              ArgInfo));
00675     return;
00676   }
00677   case IIT_EMPTYSTRUCT:
00678     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
00679     return;
00680   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
00681   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
00682   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
00683   case IIT_STRUCT2: {
00684     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
00685 
00686     for (unsigned i = 0; i != StructElts; ++i)
00687       DecodeIITType(NextElt, Infos, OutputTable);
00688     return;
00689   }
00690   }
00691   llvm_unreachable("unhandled");
00692 }
00693 
00694 
00695 #define GET_INTRINSIC_GENERATOR_GLOBAL
00696 #include "llvm/IR/Intrinsics.gen"
00697 #undef GET_INTRINSIC_GENERATOR_GLOBAL
00698 
00699 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
00700                                              SmallVectorImpl<IITDescriptor> &T){
00701   // Check to see if the intrinsic's type was expressible by the table.
00702   unsigned TableVal = IIT_Table[id-1];
00703 
00704   // Decode the TableVal into an array of IITValues.
00705   SmallVector<unsigned char, 8> IITValues;
00706   ArrayRef<unsigned char> IITEntries;
00707   unsigned NextElt = 0;
00708   if ((TableVal >> 31) != 0) {
00709     // This is an offset into the IIT_LongEncodingTable.
00710     IITEntries = IIT_LongEncodingTable;
00711 
00712     // Strip sentinel bit.
00713     NextElt = (TableVal << 1) >> 1;
00714   } else {
00715     // Decode the TableVal into an array of IITValues.  If the entry was encoded
00716     // into a single word in the table itself, decode it now.
00717     do {
00718       IITValues.push_back(TableVal & 0xF);
00719       TableVal >>= 4;
00720     } while (TableVal);
00721 
00722     IITEntries = IITValues;
00723     NextElt = 0;
00724   }
00725 
00726   // Okay, decode the table into the output vector of IITDescriptors.
00727   DecodeIITType(NextElt, IITEntries, T);
00728   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
00729     DecodeIITType(NextElt, IITEntries, T);
00730 }
00731 
00732 
00733 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
00734                              ArrayRef<Type*> Tys, LLVMContext &Context) {
00735   using namespace Intrinsic;
00736   IITDescriptor D = Infos.front();
00737   Infos = Infos.slice(1);
00738 
00739   switch (D.Kind) {
00740   case IITDescriptor::Void: return Type::getVoidTy(Context);
00741   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
00742   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
00743   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
00744   case IITDescriptor::Half: return Type::getHalfTy(Context);
00745   case IITDescriptor::Float: return Type::getFloatTy(Context);
00746   case IITDescriptor::Double: return Type::getDoubleTy(Context);
00747 
00748   case IITDescriptor::Integer:
00749     return IntegerType::get(Context, D.Integer_Width);
00750   case IITDescriptor::Vector:
00751     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
00752   case IITDescriptor::Pointer:
00753     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
00754                             D.Pointer_AddressSpace);
00755   case IITDescriptor::Struct: {
00756     Type *Elts[5];
00757     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
00758     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
00759       Elts[i] = DecodeFixedType(Infos, Tys, Context);
00760     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
00761   }
00762 
00763   case IITDescriptor::Argument:
00764     return Tys[D.getArgumentNumber()];
00765   case IITDescriptor::ExtendArgument: {
00766     Type *Ty = Tys[D.getArgumentNumber()];
00767     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00768       return VectorType::getExtendedElementVectorType(VTy);
00769 
00770     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
00771   }
00772   case IITDescriptor::TruncArgument: {
00773     Type *Ty = Tys[D.getArgumentNumber()];
00774     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00775       return VectorType::getTruncatedElementVectorType(VTy);
00776 
00777     IntegerType *ITy = cast<IntegerType>(Ty);
00778     assert(ITy->getBitWidth() % 2 == 0);
00779     return IntegerType::get(Context, ITy->getBitWidth() / 2);
00780   }
00781   case IITDescriptor::HalfVecArgument:
00782     return VectorType::getHalfElementsVectorType(cast<VectorType>(
00783                                                   Tys[D.getArgumentNumber()]));
00784   case IITDescriptor::SameVecWidthArgument: {
00785     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
00786     Type *Ty = Tys[D.getArgumentNumber()];
00787     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
00788       return VectorType::get(EltTy, VTy->getNumElements());
00789     }
00790     llvm_unreachable("unhandled");
00791   }
00792   case IITDescriptor::PtrToArgument: {
00793     Type *Ty = Tys[D.getArgumentNumber()];
00794     return PointerType::getUnqual(Ty);
00795   }
00796   case IITDescriptor::VecOfPtrsToElt: {
00797     Type *Ty = Tys[D.getArgumentNumber()];
00798     VectorType *VTy = dyn_cast<VectorType>(Ty);
00799     if (!VTy)
00800       llvm_unreachable("Expected an argument of Vector Type");
00801     Type *EltTy = VTy->getVectorElementType();
00802     return VectorType::get(PointerType::getUnqual(EltTy),
00803                            VTy->getNumElements());
00804   }
00805  }
00806   llvm_unreachable("unhandled");
00807 }
00808 
00809 
00810 
00811 FunctionType *Intrinsic::getType(LLVMContext &Context,
00812                                  ID id, ArrayRef<Type*> Tys) {
00813   SmallVector<IITDescriptor, 8> Table;
00814   getIntrinsicInfoTableEntries(id, Table);
00815 
00816   ArrayRef<IITDescriptor> TableRef = Table;
00817   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
00818 
00819   SmallVector<Type*, 8> ArgTys;
00820   while (!TableRef.empty())
00821     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
00822 
00823   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
00824   // If we see void type as the type of the last argument, it is vararg intrinsic
00825   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
00826     ArgTys.pop_back();
00827     return FunctionType::get(ResultTy, ArgTys, true);
00828   }
00829   return FunctionType::get(ResultTy, ArgTys, false);
00830 }
00831 
00832 bool Intrinsic::isOverloaded(ID id) {
00833 #define GET_INTRINSIC_OVERLOAD_TABLE
00834 #include "llvm/IR/Intrinsics.gen"
00835 #undef GET_INTRINSIC_OVERLOAD_TABLE
00836 }
00837 
00838 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00839 #define GET_INTRINSIC_ATTRIBUTES
00840 #include "llvm/IR/Intrinsics.gen"
00841 #undef GET_INTRINSIC_ATTRIBUTES
00842 
00843 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
00844   // There can never be multiple globals with the same name of different types,
00845   // because intrinsics must be a specific type.
00846   return
00847     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
00848                                           getType(M->getContext(), id, Tys)));
00849 }
00850 
00851 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
00852 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00853 #include "llvm/IR/Intrinsics.gen"
00854 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00855 
00856 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
00857 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00858 #include "llvm/IR/Intrinsics.gen"
00859 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00860 
00861 /// hasAddressTaken - returns true if there are any uses of this function
00862 /// other than direct calls or invokes to it.
00863 bool Function::hasAddressTaken(const User* *PutOffender) const {
00864   for (const Use &U : uses()) {
00865     const User *FU = U.getUser();
00866     if (isa<BlockAddress>(FU))
00867       continue;
00868     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
00869       return PutOffender ? (*PutOffender = FU, true) : true;
00870     ImmutableCallSite CS(cast<Instruction>(FU));
00871     if (!CS.isCallee(&U))
00872       return PutOffender ? (*PutOffender = FU, true) : true;
00873   }
00874   return false;
00875 }
00876 
00877 bool Function::isDefTriviallyDead() const {
00878   // Check the linkage
00879   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
00880       !hasAvailableExternallyLinkage())
00881     return false;
00882 
00883   // Check if the function is used by anything other than a blockaddress.
00884   for (const User *U : users())
00885     if (!isa<BlockAddress>(U))
00886       return false;
00887 
00888   return true;
00889 }
00890 
00891 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00892 /// setjmp or other function that gcc recognizes as "returning twice".
00893 bool Function::callsFunctionThatReturnsTwice() const {
00894   for (const_inst_iterator
00895          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
00896     ImmutableCallSite CS(&*I);
00897     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
00898       return true;
00899   }
00900 
00901   return false;
00902 }
00903 
00904 Constant *Function::getPrefixData() const {
00905   assert(hasPrefixData());
00906   const LLVMContextImpl::PrefixDataMapTy &PDMap =
00907       getContext().pImpl->PrefixDataMap;
00908   assert(PDMap.find(this) != PDMap.end());
00909   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
00910 }
00911 
00912 void Function::setPrefixData(Constant *PrefixData) {
00913   if (!PrefixData && !hasPrefixData())
00914     return;
00915 
00916   unsigned SCData = getSubclassDataFromValue();
00917   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
00918   ReturnInst *&PDHolder = PDMap[this];
00919   if (PrefixData) {
00920     if (PDHolder)
00921       PDHolder->setOperand(0, PrefixData);
00922     else
00923       PDHolder = ReturnInst::Create(getContext(), PrefixData);
00924     SCData |= (1<<1);
00925   } else {
00926     delete PDHolder;
00927     PDMap.erase(this);
00928     SCData &= ~(1<<1);
00929   }
00930   setValueSubclassData(SCData);
00931 }
00932 
00933 Constant *Function::getPrologueData() const {
00934   assert(hasPrologueData());
00935   const LLVMContextImpl::PrologueDataMapTy &SOMap =
00936       getContext().pImpl->PrologueDataMap;
00937   assert(SOMap.find(this) != SOMap.end());
00938   return cast<Constant>(SOMap.find(this)->second->getReturnValue());
00939 }
00940 
00941 void Function::setPrologueData(Constant *PrologueData) {
00942   if (!PrologueData && !hasPrologueData())
00943     return;
00944 
00945   unsigned PDData = getSubclassDataFromValue();
00946   LLVMContextImpl::PrologueDataMapTy &PDMap = getContext().pImpl->PrologueDataMap;
00947   ReturnInst *&PDHolder = PDMap[this];
00948   if (PrologueData) {
00949     if (PDHolder)
00950       PDHolder->setOperand(0, PrologueData);
00951     else
00952       PDHolder = ReturnInst::Create(getContext(), PrologueData);
00953     PDData |= (1<<2);
00954   } else {
00955     delete PDHolder;
00956     PDMap.erase(this);
00957     PDData &= ~(1<<2);
00958   }
00959   setValueSubclassData(PDData);
00960 }
00961 
00962 void Function::setEntryCount(uint64_t Count) {
00963   MDBuilder MDB(getContext());
00964   setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
00965 }
00966 
00967 Optional<uint64_t> Function::getEntryCount() const {
00968   MDNode *MD = getMetadata(LLVMContext::MD_prof);
00969   if (MD && MD->getOperand(0))
00970     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
00971       if (MDS->getString().equals("function_entry_count")) {
00972         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
00973         return CI->getValue().getZExtValue();
00974       }
00975   return None;
00976 }