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