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