LLVM API Documentation

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