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