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 VMCore library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Module.h"
00015 #include "llvm/DerivedTypes.h"
00016 #include "llvm/IntrinsicInst.h"
00017 #include "llvm/LLVMContext.h"
00018 #include "llvm/CodeGen/ValueTypes.h"
00019 #include "llvm/Support/CallSite.h"
00020 #include "llvm/Support/InstIterator.h"
00021 #include "llvm/Support/LeakDetector.h"
00022 #include "llvm/Support/ManagedStatic.h"
00023 #include "llvm/Support/StringPool.h"
00024 #include "llvm/Support/RWMutex.h"
00025 #include "llvm/Support/Threading.h"
00026 #include "SymbolTableListTraitsImpl.h"
00027 #include "llvm/ADT/DenseMap.h"
00028 #include "llvm/ADT/STLExtras.h"
00029 #include "llvm/ADT/StringExtras.h"
00030 using namespace llvm;
00031 
00032 // Explicit instantiations of SymbolTableListTraits since some of the methods
00033 // are not in the public header file...
00034 template class llvm::SymbolTableListTraits<Argument, Function>;
00035 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
00036 
00037 //===----------------------------------------------------------------------===//
00038 // Argument Implementation
00039 //===----------------------------------------------------------------------===//
00040 
00041 void Argument::anchor() { }
00042 
00043 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
00044   : Value(Ty, Value::ArgumentVal) {
00045   Parent = 0;
00046 
00047   // Make sure that we get added to a function
00048   LeakDetector::addGarbageObject(this);
00049 
00050   if (Par)
00051     Par->getArgumentList().push_back(this);
00052   setName(Name);
00053 }
00054 
00055 void Argument::setParent(Function *parent) {
00056   if (getParent())
00057     LeakDetector::addGarbageObject(this);
00058   Parent = parent;
00059   if (getParent())
00060     LeakDetector::removeGarbageObject(this);
00061 }
00062 
00063 /// getArgNo - Return the index of this formal argument in its containing
00064 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
00065 unsigned Argument::getArgNo() const {
00066   const Function *F = getParent();
00067   assert(F && "Argument is not in a function");
00068   
00069   Function::const_arg_iterator AI = F->arg_begin();
00070   unsigned ArgIdx = 0;
00071   for (; &*AI != this; ++AI)
00072     ++ArgIdx;
00073 
00074   return ArgIdx;
00075 }
00076 
00077 /// hasByValAttr - Return true if this argument has the byval attribute on it
00078 /// in its containing function.
00079 bool Argument::hasByValAttr() const {
00080   if (!getType()->isPointerTy()) return false;
00081   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
00082 }
00083 
00084 unsigned Argument::getParamAlignment() const {
00085   assert(getType()->isPointerTy() && "Only pointers have alignments");
00086   return getParent()->getParamAlignment(getArgNo()+1);
00087   
00088 }
00089 
00090 /// hasNestAttr - Return true if this argument has the nest attribute on
00091 /// it in its containing function.
00092 bool Argument::hasNestAttr() const {
00093   if (!getType()->isPointerTy()) return false;
00094   return getParent()->paramHasAttr(getArgNo()+1, Attribute::Nest);
00095 }
00096 
00097 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
00098 /// it in its containing function.
00099 bool Argument::hasNoAliasAttr() const {
00100   if (!getType()->isPointerTy()) return false;
00101   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoAlias);
00102 }
00103 
00104 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
00105 /// on it in its containing function.
00106 bool Argument::hasNoCaptureAttr() const {
00107   if (!getType()->isPointerTy()) return false;
00108   return getParent()->paramHasAttr(getArgNo()+1, Attribute::NoCapture);
00109 }
00110 
00111 /// hasSRetAttr - Return true if this argument has the sret attribute on
00112 /// it in its containing function.
00113 bool Argument::hasStructRetAttr() const {
00114   if (!getType()->isPointerTy()) return false;
00115   if (this != getParent()->arg_begin())
00116     return false; // StructRet param must be first param
00117   return getParent()->paramHasAttr(1, Attribute::StructRet);
00118 }
00119 
00120 /// addAttr - Add a Attribute to an argument
00121 void Argument::addAttr(Attributes attr) {
00122   getParent()->addAttribute(getArgNo() + 1, attr);
00123 }
00124 
00125 /// removeAttr - Remove a Attribute from an argument
00126 void Argument::removeAttr(Attributes attr) {
00127   getParent()->removeAttribute(getArgNo() + 1, attr);
00128 }
00129 
00130 
00131 //===----------------------------------------------------------------------===//
00132 // Helper Methods in Function
00133 //===----------------------------------------------------------------------===//
00134 
00135 LLVMContext &Function::getContext() const {
00136   return getType()->getContext();
00137 }
00138 
00139 FunctionType *Function::getFunctionType() const {
00140   return cast<FunctionType>(getType()->getElementType());
00141 }
00142 
00143 bool Function::isVarArg() const {
00144   return getFunctionType()->isVarArg();
00145 }
00146 
00147 Type *Function::getReturnType() const {
00148   return getFunctionType()->getReturnType();
00149 }
00150 
00151 void Function::removeFromParent() {
00152   getParent()->getFunctionList().remove(this);
00153 }
00154 
00155 void Function::eraseFromParent() {
00156   getParent()->getFunctionList().erase(this);
00157 }
00158 
00159 //===----------------------------------------------------------------------===//
00160 // Function Implementation
00161 //===----------------------------------------------------------------------===//
00162 
00163 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
00164                    const Twine &name, Module *ParentModule)
00165   : GlobalValue(PointerType::getUnqual(Ty), 
00166                 Value::FunctionVal, 0, 0, Linkage, name) {
00167   assert(FunctionType::isValidReturnType(getReturnType()) &&
00168          "invalid return type");
00169   SymTab = new ValueSymbolTable();
00170 
00171   // If the function has arguments, mark them as lazily built.
00172   if (Ty->getNumParams())
00173     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
00174   
00175   // Make sure that we get added to a function
00176   LeakDetector::addGarbageObject(this);
00177 
00178   if (ParentModule)
00179     ParentModule->getFunctionList().push_back(this);
00180 
00181   // Ensure intrinsics have the right parameter attributes.
00182   if (unsigned IID = getIntrinsicID())
00183     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
00184 
00185 }
00186 
00187 Function::~Function() {
00188   dropAllReferences();    // After this it is safe to delete instructions.
00189 
00190   // Delete all of the method arguments and unlink from symbol table...
00191   ArgumentList.clear();
00192   delete SymTab;
00193 
00194   // Remove the function from the on-the-side GC table.
00195   clearGC();
00196 }
00197 
00198 void Function::BuildLazyArguments() const {
00199   // Create the arguments vector, all arguments start out unnamed.
00200   FunctionType *FT = getFunctionType();
00201   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00202     assert(!FT->getParamType(i)->isVoidTy() &&
00203            "Cannot have void typed arguments!");
00204     ArgumentList.push_back(new Argument(FT->getParamType(i)));
00205   }
00206   
00207   // Clear the lazy arguments bit.
00208   unsigned SDC = getSubclassDataFromValue();
00209   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
00210 }
00211 
00212 size_t Function::arg_size() const {
00213   return getFunctionType()->getNumParams();
00214 }
00215 bool Function::arg_empty() const {
00216   return getFunctionType()->getNumParams() == 0;
00217 }
00218 
00219 void Function::setParent(Module *parent) {
00220   if (getParent())
00221     LeakDetector::addGarbageObject(this);
00222   Parent = parent;
00223   if (getParent())
00224     LeakDetector::removeGarbageObject(this);
00225 }
00226 
00227 // dropAllReferences() - This function causes all the subinstructions to "let
00228 // go" of all references that they are maintaining.  This allows one to
00229 // 'delete' a whole class at a time, even though there may be circular
00230 // references... first all references are dropped, and all use counts go to
00231 // zero.  Then everything is deleted for real.  Note that no operations are
00232 // valid on an object that has "dropped all references", except operator
00233 // delete.
00234 //
00235 void Function::dropAllReferences() {
00236   for (iterator I = begin(), E = end(); I != E; ++I)
00237     I->dropAllReferences();
00238   
00239   // Delete all basic blocks. They are now unused, except possibly by
00240   // blockaddresses, but BasicBlock's destructor takes care of those.
00241   while (!BasicBlocks.empty())
00242     BasicBlocks.begin()->eraseFromParent();
00243 }
00244 
00245 void Function::addAttribute(unsigned i, Attributes attr) {
00246   AttrListPtr PAL = getAttributes();
00247   PAL = PAL.addAttr(i, attr);
00248   setAttributes(PAL);
00249 }
00250 
00251 void Function::removeAttribute(unsigned i, Attributes attr) {
00252   AttrListPtr PAL = getAttributes();
00253   PAL = PAL.removeAttr(i, attr);
00254   setAttributes(PAL);
00255 }
00256 
00257 // Maintain the GC name for each function in an on-the-side table. This saves
00258 // allocating an additional word in Function for programs which do not use GC
00259 // (i.e., most programs) at the cost of increased overhead for clients which do
00260 // use GC.
00261 static DenseMap<const Function*,PooledStringPtr> *GCNames;
00262 static StringPool *GCNamePool;
00263 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
00264 
00265 bool Function::hasGC() const {
00266   sys::SmartScopedReader<true> Reader(*GCLock);
00267   return GCNames && GCNames->count(this);
00268 }
00269 
00270 const char *Function::getGC() const {
00271   assert(hasGC() && "Function has no collector");
00272   sys::SmartScopedReader<true> Reader(*GCLock);
00273   return *(*GCNames)[this];
00274 }
00275 
00276 void Function::setGC(const char *Str) {
00277   sys::SmartScopedWriter<true> Writer(*GCLock);
00278   if (!GCNamePool)
00279     GCNamePool = new StringPool();
00280   if (!GCNames)
00281     GCNames = new DenseMap<const Function*,PooledStringPtr>();
00282   (*GCNames)[this] = GCNamePool->intern(Str);
00283 }
00284 
00285 void Function::clearGC() {
00286   sys::SmartScopedWriter<true> Writer(*GCLock);
00287   if (GCNames) {
00288     GCNames->erase(this);
00289     if (GCNames->empty()) {
00290       delete GCNames;
00291       GCNames = 0;
00292       if (GCNamePool->empty()) {
00293         delete GCNamePool;
00294         GCNamePool = 0;
00295       }
00296     }
00297   }
00298 }
00299 
00300 /// copyAttributesFrom - copy all additional attributes (those not needed to
00301 /// create a Function) from the Function Src to this one.
00302 void Function::copyAttributesFrom(const GlobalValue *Src) {
00303   assert(isa<Function>(Src) && "Expected a Function!");
00304   GlobalValue::copyAttributesFrom(Src);
00305   const Function *SrcF = cast<Function>(Src);
00306   setCallingConv(SrcF->getCallingConv());
00307   setAttributes(SrcF->getAttributes());
00308   if (SrcF->hasGC())
00309     setGC(SrcF->getGC());
00310   else
00311     clearGC();
00312 }
00313 
00314 /// getIntrinsicID - This method returns the ID number of the specified
00315 /// function, or Intrinsic::not_intrinsic if the function is not an
00316 /// intrinsic, or if the pointer is null.  This value is always defined to be
00317 /// zero to allow easy checking for whether a function is intrinsic or not.  The
00318 /// particular intrinsic functions which correspond to this value are defined in
00319 /// llvm/Intrinsics.h.
00320 ///
00321 unsigned Function::getIntrinsicID() const {
00322   const ValueName *ValName = this->getValueName();
00323   if (!ValName)
00324     return 0;
00325   unsigned Len = ValName->getKeyLength();
00326   const char *Name = ValName->getKeyData();
00327   
00328   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
00329       || Name[2] != 'v' || Name[3] != 'm')
00330     return 0;  // All intrinsics start with 'llvm.'
00331 
00332 #define GET_FUNCTION_RECOGNIZER
00333 #include "llvm/Intrinsics.gen"
00334 #undef GET_FUNCTION_RECOGNIZER
00335   return 0;
00336 }
00337 
00338 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
00339   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00340   static const char * const Table[] = {
00341     "not_intrinsic",
00342 #define GET_INTRINSIC_NAME_TABLE
00343 #include "llvm/Intrinsics.gen"
00344 #undef GET_INTRINSIC_NAME_TABLE
00345   };
00346   if (Tys.empty())
00347     return Table[id];
00348   std::string Result(Table[id]);
00349   for (unsigned i = 0; i < Tys.size(); ++i) {
00350     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
00351       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
00352                 EVT::getEVT(PTyp->getElementType()).getEVTString();
00353     }
00354     else if (Tys[i])
00355       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
00356   }
00357   return Result;
00358 }
00359 
00360 #define GET_INTRINSTIC_GENERATOR_GLOBAL
00361 #include "llvm/Intrinsics.gen"
00362 #undef GET_INTRINSTIC_GENERATOR_GLOBAL
00363 
00364 static Type *DecodeFixedType(unsigned &TableVal, LLVMContext &Context) {
00365   unsigned Nibble = TableVal & 0xF;
00366   TableVal >>= 4;
00367   
00368   switch ((IIT_Info)Nibble) {
00369   case IIT_Done: return Type::getVoidTy(Context);
00370   case IIT_I1: return Type::getInt1Ty(Context);
00371   case IIT_I8: return Type::getInt8Ty(Context);
00372   case IIT_I16: return Type::getInt16Ty(Context);
00373   case IIT_I32: return Type::getInt32Ty(Context);
00374   case IIT_I64: return Type::getInt64Ty(Context);
00375   case IIT_F32: return Type::getFloatTy(Context);
00376   case IIT_F64: return Type::getDoubleTy(Context);
00377   case IIT_V2: return VectorType::get(DecodeFixedType(TableVal, Context), 2);
00378   case IIT_V4: return VectorType::get(DecodeFixedType(TableVal, Context), 4);
00379   case IIT_V8: return VectorType::get(DecodeFixedType(TableVal, Context), 8);
00380   case IIT_V16: return VectorType::get(DecodeFixedType(TableVal, Context), 16);
00381   case IIT_MMX: return Type::getX86_MMXTy(Context);
00382   case IIT_PTR: return PointerType::get(DecodeFixedType(TableVal, Context),0);
00383   case IIT_ARG: assert(0 && "Unimp!");
00384   }
00385   llvm_unreachable("unhandled");
00386 }
00387   
00388 
00389 FunctionType *Intrinsic::getType(LLVMContext &Context,
00390                                  ID id, ArrayRef<Type*> Tys) {
00391   Type *ResultTy = 0;
00392   SmallVector<Type*, 8> ArgTys;
00393   
00394   // Check to see if the intrinsic's type was expressible by the table.
00395   unsigned TableVal = IIT_Table[id-1];
00396   if (TableVal != ~0U) {
00397     ResultTy = DecodeFixedType(TableVal, Context);
00398     
00399     while (TableVal)
00400       ArgTys.push_back(DecodeFixedType(TableVal, Context));
00401 
00402     return FunctionType::get(ResultTy, ArgTys, false); 
00403   }
00404   
00405   
00406 #define GET_INTRINSIC_GENERATOR
00407 #include "llvm/Intrinsics.gen"
00408 #undef GET_INTRINSIC_GENERATOR
00409 
00410   return FunctionType::get(ResultTy, ArgTys, false); 
00411 }
00412 
00413 bool Intrinsic::isOverloaded(ID id) {
00414 #define GET_INTRINSIC_OVERLOAD_TABLE
00415 #include "llvm/Intrinsics.gen"
00416 #undef GET_INTRINSIC_OVERLOAD_TABLE
00417 }
00418 
00419 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00420 #define GET_INTRINSIC_ATTRIBUTES
00421 #include "llvm/Intrinsics.gen"
00422 #undef GET_INTRINSIC_ATTRIBUTES
00423 
00424 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
00425   // There can never be multiple globals with the same name of different types,
00426   // because intrinsics must be a specific type.
00427   return
00428     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
00429                                           getType(M->getContext(), id, Tys)));
00430 }
00431 
00432 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
00433 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00434 #include "llvm/Intrinsics.gen"
00435 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
00436 
00437 /// hasAddressTaken - returns true if there are any uses of this function
00438 /// other than direct calls or invokes to it.
00439 bool Function::hasAddressTaken(const User* *PutOffender) const {
00440   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
00441     const User *U = *I;
00442     if (isa<BlockAddress>(U))
00443       continue;
00444     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
00445       return PutOffender ? (*PutOffender = U, true) : true;
00446     ImmutableCallSite CS(cast<Instruction>(U));
00447     if (!CS.isCallee(I))
00448       return PutOffender ? (*PutOffender = U, true) : true;
00449   }
00450   return false;
00451 }
00452 
00453 bool Function::isDefTriviallyDead() const {
00454   // Check the linkage
00455   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
00456       !hasAvailableExternallyLinkage())
00457     return false;
00458 
00459   // Check if the function is used by anything other than a blockaddress.
00460   for (Value::const_use_iterator I = use_begin(), E = use_end(); I != E; ++I)
00461     if (!isa<BlockAddress>(*I))
00462       return false;
00463 
00464   return true;
00465 }
00466 
00467 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00468 /// setjmp or other function that gcc recognizes as "returning twice".
00469 bool Function::callsFunctionThatReturnsTwice() const {
00470   for (const_inst_iterator
00471          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
00472     const CallInst* callInst = dyn_cast<CallInst>(&*I);
00473     if (!callInst)
00474       continue;
00475     if (callInst->canReturnTwice())
00476       return true;
00477   }
00478 
00479   return false;
00480 }
00481