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);
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 data is stored in a side table.
00339   setPrefixData(nullptr);
00340 }
00341 
00342 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
00343   AttributeSet PAL = getAttributes();
00344   PAL = PAL.addAttribute(getContext(), i, attr);
00345   setAttributes(PAL);
00346 }
00347 
00348 void Function::addAttributes(unsigned i, AttributeSet attrs) {
00349   AttributeSet PAL = getAttributes();
00350   PAL = PAL.addAttributes(getContext(), i, attrs);
00351   setAttributes(PAL);
00352 }
00353 
00354 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
00355   AttributeSet PAL = getAttributes();
00356   PAL = PAL.removeAttributes(getContext(), i, attrs);
00357   setAttributes(PAL);
00358 }
00359 
00360 // Maintain the GC name for each function in an on-the-side table. This saves
00361 // allocating an additional word in Function for programs which do not use GC
00362 // (i.e., most programs) at the cost of increased overhead for clients which do
00363 // use GC.
00364 static DenseMap<const Function*,PooledStringPtr> *GCNames;
00365 static StringPool *GCNamePool;
00366 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
00367 
00368 bool Function::hasGC() const {
00369   sys::SmartScopedReader<true> Reader(*GCLock);
00370   return GCNames && GCNames->count(this);
00371 }
00372 
00373 const char *Function::getGC() const {
00374   assert(hasGC() && "Function has no collector");
00375   sys::SmartScopedReader<true> Reader(*GCLock);
00376   return *(*GCNames)[this];
00377 }
00378 
00379 void Function::setGC(const char *Str) {
00380   sys::SmartScopedWriter<true> Writer(*GCLock);
00381   if (!GCNamePool)
00382     GCNamePool = new StringPool();
00383   if (!GCNames)
00384     GCNames = new DenseMap<const Function*,PooledStringPtr>();
00385   (*GCNames)[this] = GCNamePool->intern(Str);
00386 }
00387 
00388 void Function::clearGC() {
00389   sys::SmartScopedWriter<true> Writer(*GCLock);
00390   if (GCNames) {
00391     GCNames->erase(this);
00392     if (GCNames->empty()) {
00393       delete GCNames;
00394       GCNames = nullptr;
00395       if (GCNamePool->empty()) {
00396         delete GCNamePool;
00397         GCNamePool = nullptr;
00398       }
00399     }
00400   }
00401 }
00402 
00403 /// copyAttributesFrom - copy all additional attributes (those not needed to
00404 /// create a Function) from the Function Src to this one.
00405 void Function::copyAttributesFrom(const GlobalValue *Src) {
00406   assert(isa<Function>(Src) && "Expected a Function!");
00407   GlobalObject::copyAttributesFrom(Src);
00408   const Function *SrcF = cast<Function>(Src);
00409   setCallingConv(SrcF->getCallingConv());
00410   setAttributes(SrcF->getAttributes());
00411   if (SrcF->hasGC())
00412     setGC(SrcF->getGC());
00413   else
00414     clearGC();
00415   if (SrcF->hasPrefixData())
00416     setPrefixData(SrcF->getPrefixData());
00417   else
00418     setPrefixData(nullptr);
00419 }
00420 
00421 /// getIntrinsicID - This method returns the ID number of the specified
00422 /// function, or Intrinsic::not_intrinsic if the function is not an
00423 /// intrinsic, or if the pointer is null.  This value is always defined to be
00424 /// zero to allow easy checking for whether a function is intrinsic or not.  The
00425 /// particular intrinsic functions which correspond to this value are defined in
00426 /// llvm/Intrinsics.h.  Results are cached in the LLVM context, subsequent
00427 /// requests for the same ID return results much faster from the cache.
00428 ///
00429 unsigned Function::getIntrinsicID() const {
00430   const ValueName *ValName = this->getValueName();
00431   if (!ValName || !isIntrinsic())
00432     return 0;
00433 
00434   LLVMContextImpl::IntrinsicIDCacheTy &IntrinsicIDCache =
00435     getContext().pImpl->IntrinsicIDCache;
00436   if (!IntrinsicIDCache.count(this)) {
00437     unsigned Id = lookupIntrinsicID();
00438     IntrinsicIDCache[this]=Id;
00439     return Id;
00440   }
00441   return IntrinsicIDCache[this];
00442 }
00443 
00444 /// This private method does the actual lookup of an intrinsic ID when the query
00445 /// could not be answered from the cache.
00446 unsigned Function::lookupIntrinsicID() const {
00447   const ValueName *ValName = this->getValueName();
00448   unsigned Len = ValName->getKeyLength();
00449   const char *Name = ValName->getKeyData();
00450 
00451 #define GET_FUNCTION_RECOGNIZER
00452 #include "llvm/IR/Intrinsics.gen"
00453 #undef GET_FUNCTION_RECOGNIZER
00454 
00455   return 0;
00456 }
00457 
00458 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
00459   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00460   static const char * const Table[] = {
00461     "not_intrinsic",
00462 #define GET_INTRINSIC_NAME_TABLE
00463 #include "llvm/IR/Intrinsics.gen"
00464 #undef GET_INTRINSIC_NAME_TABLE
00465   };
00466   if (Tys.empty())
00467     return Table[id];
00468   std::string Result(Table[id]);
00469   for (unsigned i = 0; i < Tys.size(); ++i) {
00470     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
00471       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
00472                 EVT::getEVT(PTyp->getElementType()).getEVTString();
00473     }
00474     else if (Tys[i])
00475       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
00476   }
00477   return Result;
00478 }
00479 
00480 
00481 /// IIT_Info - These are enumerators that describe the entries returned by the
00482 /// getIntrinsicInfoTableEntries function.
00483 ///
00484 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
00485 enum IIT_Info {
00486   // Common values should be encoded with 0-15.
00487   IIT_Done = 0,
00488   IIT_I1   = 1,
00489   IIT_I8   = 2,
00490   IIT_I16  = 3,
00491   IIT_I32  = 4,
00492   IIT_I64  = 5,
00493   IIT_F16  = 6,
00494   IIT_F32  = 7,
00495   IIT_F64  = 8,
00496   IIT_V2   = 9,
00497   IIT_V4   = 10,
00498   IIT_V8   = 11,
00499   IIT_V16  = 12,
00500   IIT_V32  = 13,
00501   IIT_PTR  = 14,
00502   IIT_ARG  = 15,
00503 
00504   // Values from 16+ are only encodable with the inefficient encoding.
00505   IIT_V64  = 16,
00506   IIT_MMX  = 17,
00507   IIT_METADATA = 18,
00508   IIT_EMPTYSTRUCT = 19,
00509   IIT_STRUCT2 = 20,
00510   IIT_STRUCT3 = 21,
00511   IIT_STRUCT4 = 22,
00512   IIT_STRUCT5 = 23,
00513   IIT_EXTEND_ARG = 24,
00514   IIT_TRUNC_ARG = 25,
00515   IIT_ANYPTR = 26,
00516   IIT_V1   = 27,
00517   IIT_VARARG = 28,
00518   IIT_HALF_VEC_ARG = 29
00519 };
00520 
00521 
00522 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
00523                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
00524   IIT_Info Info = IIT_Info(Infos[NextElt++]);
00525   unsigned StructElts = 2;
00526   using namespace Intrinsic;
00527 
00528   switch (Info) {
00529   case IIT_Done:
00530     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
00531     return;
00532   case IIT_VARARG:
00533     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
00534     return;
00535   case IIT_MMX:
00536     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
00537     return;
00538   case IIT_METADATA:
00539     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
00540     return;
00541   case IIT_F16:
00542     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
00543     return;
00544   case IIT_F32:
00545     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
00546     return;
00547   case IIT_F64:
00548     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
00549     return;
00550   case IIT_I1:
00551     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
00552     return;
00553   case IIT_I8:
00554     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
00555     return;
00556   case IIT_I16:
00557     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
00558     return;
00559   case IIT_I32:
00560     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
00561     return;
00562   case IIT_I64:
00563     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
00564     return;
00565   case IIT_V1:
00566     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
00567     DecodeIITType(NextElt, Infos, OutputTable);
00568     return;
00569   case IIT_V2:
00570     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
00571     DecodeIITType(NextElt, Infos, OutputTable);
00572     return;
00573   case IIT_V4:
00574     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
00575     DecodeIITType(NextElt, Infos, OutputTable);
00576     return;
00577   case IIT_V8:
00578     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
00579     DecodeIITType(NextElt, Infos, OutputTable);
00580     return;
00581   case IIT_V16:
00582     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
00583     DecodeIITType(NextElt, Infos, OutputTable);
00584     return;
00585   case IIT_V32:
00586     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
00587     DecodeIITType(NextElt, Infos, OutputTable);
00588     return;
00589   case IIT_V64:
00590     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
00591     DecodeIITType(NextElt, Infos, OutputTable);
00592     return;
00593   case IIT_PTR:
00594     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
00595     DecodeIITType(NextElt, Infos, OutputTable);
00596     return;
00597   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
00598     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
00599                                              Infos[NextElt++]));
00600     DecodeIITType(NextElt, Infos, OutputTable);
00601     return;
00602   }
00603   case IIT_ARG: {
00604     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00605     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
00606     return;
00607   }
00608   case IIT_EXTEND_ARG: {
00609     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00610     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
00611                                              ArgInfo));
00612     return;
00613   }
00614   case IIT_TRUNC_ARG: {
00615     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00616     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
00617                                              ArgInfo));
00618     return;
00619   }
00620   case IIT_HALF_VEC_ARG: {
00621     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
00622     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
00623                                              ArgInfo));
00624     return;
00625   }
00626   case IIT_EMPTYSTRUCT:
00627     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
00628     return;
00629   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
00630   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
00631   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
00632   case IIT_STRUCT2: {
00633     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
00634 
00635     for (unsigned i = 0; i != StructElts; ++i)
00636       DecodeIITType(NextElt, Infos, OutputTable);
00637     return;
00638   }
00639   }
00640   llvm_unreachable("unhandled");
00641 }
00642 
00643 
00644 #define GET_INTRINSIC_GENERATOR_GLOBAL
00645 #include "llvm/IR/Intrinsics.gen"
00646 #undef GET_INTRINSIC_GENERATOR_GLOBAL
00647 
00648 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
00649                                              SmallVectorImpl<IITDescriptor> &T){
00650   // Check to see if the intrinsic's type was expressible by the table.
00651   unsigned TableVal = IIT_Table[id-1];
00652 
00653   // Decode the TableVal into an array of IITValues.
00654   SmallVector<unsigned char, 8> IITValues;
00655   ArrayRef<unsigned char> IITEntries;
00656   unsigned NextElt = 0;
00657   if ((TableVal >> 31) != 0) {
00658     // This is an offset into the IIT_LongEncodingTable.
00659     IITEntries = IIT_LongEncodingTable;
00660 
00661     // Strip sentinel bit.
00662     NextElt = (TableVal << 1) >> 1;
00663   } else {
00664     // Decode the TableVal into an array of IITValues.  If the entry was encoded
00665     // into a single word in the table itself, decode it now.
00666     do {
00667       IITValues.push_back(TableVal & 0xF);
00668       TableVal >>= 4;
00669     } while (TableVal);
00670 
00671     IITEntries = IITValues;
00672     NextElt = 0;
00673   }
00674 
00675   // Okay, decode the table into the output vector of IITDescriptors.
00676   DecodeIITType(NextElt, IITEntries, T);
00677   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
00678     DecodeIITType(NextElt, IITEntries, T);
00679 }
00680 
00681 
00682 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
00683                              ArrayRef<Type*> Tys, LLVMContext &Context) {
00684   using namespace Intrinsic;
00685   IITDescriptor D = Infos.front();
00686   Infos = Infos.slice(1);
00687 
00688   switch (D.Kind) {
00689   case IITDescriptor::Void: return Type::getVoidTy(Context);
00690   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
00691   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
00692   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
00693   case IITDescriptor::Half: return Type::getHalfTy(Context);
00694   case IITDescriptor::Float: return Type::getFloatTy(Context);
00695   case IITDescriptor::Double: return Type::getDoubleTy(Context);
00696 
00697   case IITDescriptor::Integer:
00698     return IntegerType::get(Context, D.Integer_Width);
00699   case IITDescriptor::Vector:
00700     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
00701   case IITDescriptor::Pointer:
00702     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
00703                             D.Pointer_AddressSpace);
00704   case IITDescriptor::Struct: {
00705     Type *Elts[5];
00706     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
00707     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
00708       Elts[i] = DecodeFixedType(Infos, Tys, Context);
00709     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
00710   }
00711 
00712   case IITDescriptor::Argument:
00713     return Tys[D.getArgumentNumber()];
00714   case IITDescriptor::ExtendArgument: {
00715     Type *Ty = Tys[D.getArgumentNumber()];
00716     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00717       return VectorType::getExtendedElementVectorType(VTy);
00718 
00719     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
00720   }
00721   case IITDescriptor::TruncArgument: {
00722     Type *Ty = Tys[D.getArgumentNumber()];
00723     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00724       return VectorType::getTruncatedElementVectorType(VTy);
00725 
00726     IntegerType *ITy = cast<IntegerType>(Ty);
00727     assert(ITy->getBitWidth() % 2 == 0);
00728     return IntegerType::get(Context, ITy->getBitWidth() / 2);
00729   }
00730   case IITDescriptor::HalfVecArgument:
00731     return VectorType::getHalfElementsVectorType(cast<VectorType>(
00732                                                   Tys[D.getArgumentNumber()]));
00733   }
00734   llvm_unreachable("unhandled");
00735 }
00736 
00737 
00738 
00739 FunctionType *Intrinsic::getType(LLVMContext &Context,
00740                                  ID id, ArrayRef<Type*> Tys) {
00741   SmallVector<IITDescriptor, 8> Table;
00742   getIntrinsicInfoTableEntries(id, Table);
00743 
00744   ArrayRef<IITDescriptor> TableRef = Table;
00745   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
00746 
00747   SmallVector<Type*, 8> ArgTys;
00748   while (!TableRef.empty())
00749     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
00750 
00751   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
00752   // If we see void type as the type of the last argument, it is vararg intrinsic
00753   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
00754     ArgTys.pop_back();
00755     return FunctionType::get(ResultTy, ArgTys, true);
00756   }
00757   return FunctionType::get(ResultTy, ArgTys, false);
00758 }
00759 
00760 bool Intrinsic::isOverloaded(ID id) {
00761 #define GET_INTRINSIC_OVERLOAD_TABLE
00762 #include "llvm/IR/Intrinsics.gen"
00763 #undef GET_INTRINSIC_OVERLOAD_TABLE
00764 }
00765 
00766 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00767 #define GET_INTRINSIC_ATTRIBUTES
00768 #include "llvm/IR/Intrinsics.gen"
00769 #undef GET_INTRINSIC_ATTRIBUTES
00770 
00771 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
00772   // There can never be multiple globals with the same name of different types,
00773   // because intrinsics must be a specific type.
00774   return
00775     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
00776                                           getType(M->getContext(), id, Tys)));
00777 }
00778 
00779 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
00780 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00781 #include "llvm/IR/Intrinsics.gen"
00782 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00783 
00784 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
00785 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00786 #include "llvm/IR/Intrinsics.gen"
00787 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
00788 
00789 /// hasAddressTaken - returns true if there are any uses of this function
00790 /// other than direct calls or invokes to it.
00791 bool Function::hasAddressTaken(const User* *PutOffender) const {
00792   for (const Use &U : uses()) {
00793     const User *FU = U.getUser();
00794     if (isa<BlockAddress>(FU))
00795       continue;
00796     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
00797       return PutOffender ? (*PutOffender = FU, true) : true;
00798     ImmutableCallSite CS(cast<Instruction>(FU));
00799     if (!CS.isCallee(&U))
00800       return PutOffender ? (*PutOffender = FU, true) : true;
00801   }
00802   return false;
00803 }
00804 
00805 bool Function::isDefTriviallyDead() const {
00806   // Check the linkage
00807   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
00808       !hasAvailableExternallyLinkage())
00809     return false;
00810 
00811   // Check if the function is used by anything other than a blockaddress.
00812   for (const User *U : users())
00813     if (!isa<BlockAddress>(U))
00814       return false;
00815 
00816   return true;
00817 }
00818 
00819 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00820 /// setjmp or other function that gcc recognizes as "returning twice".
00821 bool Function::callsFunctionThatReturnsTwice() const {
00822   for (const_inst_iterator
00823          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
00824     ImmutableCallSite CS(&*I);
00825     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
00826       return true;
00827   }
00828 
00829   return false;
00830 }
00831 
00832 Constant *Function::getPrefixData() const {
00833   assert(hasPrefixData());
00834   const LLVMContextImpl::PrefixDataMapTy &PDMap =
00835       getContext().pImpl->PrefixDataMap;
00836   assert(PDMap.find(this) != PDMap.end());
00837   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
00838 }
00839 
00840 void Function::setPrefixData(Constant *PrefixData) {
00841   if (!PrefixData && !hasPrefixData())
00842     return;
00843 
00844   unsigned SCData = getSubclassDataFromValue();
00845   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
00846   ReturnInst *&PDHolder = PDMap[this];
00847   if (PrefixData) {
00848     if (PDHolder)
00849       PDHolder->setOperand(0, PrefixData);
00850     else
00851       PDHolder = ReturnInst::Create(getContext(), PrefixData);
00852     SCData |= 2;
00853   } else {
00854     delete PDHolder;
00855     PDMap.erase(this);
00856     SCData &= ~2;
00857   }
00858   setValueSubclassData(SCData);
00859 }