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/CodeGen/ValueTypes.h"
00018 #include "llvm/Support/LeakDetector.h"
00019 #include "llvm/Support/StringPool.h"
00020 #include "SymbolTableListTraitsImpl.h"
00021 #include "llvm/ADT/DenseMap.h"
00022 #include "llvm/ADT/StringExtras.h"
00023 using namespace llvm;
00024 
00025 BasicBlock *ilist_traits<BasicBlock>::createSentinel() {
00026   BasicBlock *Ret = BasicBlock::Create();
00027   // This should not be garbage monitored.
00028   LeakDetector::removeGarbageObject(Ret);
00029   return Ret;
00030 }
00031 
00032 iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {
00033   return F->getBasicBlockList();
00034 }
00035 
00036 Argument *ilist_traits<Argument>::createSentinel() {
00037   Argument *Ret = new Argument(Type::Int32Ty);
00038   // This should not be garbage monitored.
00039   LeakDetector::removeGarbageObject(Ret);
00040   return Ret;
00041 }
00042 
00043 iplist<Argument> &ilist_traits<Argument>::getList(Function *F) {
00044   return F->getArgumentList();
00045 }
00046 
00047 // Explicit instantiations of SymbolTableListTraits since some of the methods
00048 // are not in the public header file...
00049 template class SymbolTableListTraits<Argument, Function>;
00050 template class SymbolTableListTraits<BasicBlock, Function>;
00051 
00052 //===----------------------------------------------------------------------===//
00053 // Argument Implementation
00054 //===----------------------------------------------------------------------===//
00055 
00056 Argument::Argument(const Type *Ty, const std::string &Name, Function *Par)
00057   : Value(Ty, Value::ArgumentVal) {
00058   Parent = 0;
00059 
00060   // Make sure that we get added to a function
00061   LeakDetector::addGarbageObject(this);
00062 
00063   if (Par)
00064     Par->getArgumentList().push_back(this);
00065   setName(Name);
00066 }
00067 
00068 void Argument::setParent(Function *parent) {
00069   if (getParent())
00070     LeakDetector::addGarbageObject(this);
00071   Parent = parent;
00072   if (getParent())
00073     LeakDetector::removeGarbageObject(this);
00074 }
00075 
00076 /// getArgNo - Return the index of this formal argument in its containing
00077 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1. 
00078 unsigned Argument::getArgNo() const {
00079   const Function *F = getParent();
00080   assert(F && "Argument is not in a function");
00081   
00082   Function::const_arg_iterator AI = F->arg_begin();
00083   unsigned ArgIdx = 0;
00084   for (; &*AI != this; ++AI)
00085     ++ArgIdx;
00086 
00087   return ArgIdx;
00088 }
00089 
00090 /// hasByValAttr - Return true if this argument has the byval attribute on it
00091 /// in its containing function.
00092 bool Argument::hasByValAttr() const {
00093   if (!isa<PointerType>(getType())) return false;
00094   return getParent()->paramHasAttr(getArgNo()+1, Attribute::ByVal);
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 (!isa<PointerType>(getType())) 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 (!isa<PointerType>(getType())) 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 (!isa<PointerType>(getType())) 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 const FunctionType *Function::getFunctionType() const {
00136   return cast<FunctionType>(getType()->getElementType());
00137 }
00138 
00139 bool Function::isVarArg() const {
00140   return getFunctionType()->isVarArg();
00141 }
00142 
00143 const Type *Function::getReturnType() const {
00144   return getFunctionType()->getReturnType();
00145 }
00146 
00147 void Function::removeFromParent() {
00148   getParent()->getFunctionList().remove(this);
00149 }
00150 
00151 void Function::eraseFromParent() {
00152   getParent()->getFunctionList().erase(this);
00153 }
00154 
00155 //===----------------------------------------------------------------------===//
00156 // Function Implementation
00157 //===----------------------------------------------------------------------===//
00158 
00159 Function::Function(const FunctionType *Ty, LinkageTypes Linkage,
00160                    const std::string &name, Module *ParentModule)
00161   : GlobalValue(PointerType::getUnqual(Ty), 
00162                 Value::FunctionVal, 0, 0, Linkage, name) {
00163   assert(FunctionType::isValidReturnType(getReturnType()) &&
00164          !isa<OpaqueType>(getReturnType()) && "invalid return type");
00165   SymTab = new ValueSymbolTable();
00166 
00167   // If the function has arguments, mark them as lazily built.
00168   if (Ty->getNumParams())
00169     SubclassData = 1;   // Set the "has lazy arguments" bit.
00170   
00171   // Make sure that we get added to a function
00172   LeakDetector::addGarbageObject(this);
00173 
00174   if (ParentModule)
00175     ParentModule->getFunctionList().push_back(this);
00176 
00177   // Ensure intrinsics have the right parameter attributes.
00178   if (unsigned IID = getIntrinsicID(true))
00179     setAttributes(Intrinsic::getAttributes(Intrinsic::ID(IID)));
00180 
00181 }
00182 
00183 Function::~Function() {
00184   dropAllReferences();    // After this it is safe to delete instructions.
00185 
00186   // Delete all of the method arguments and unlink from symbol table...
00187   ArgumentList.clear();
00188   delete SymTab;
00189 
00190   // Remove the function from the on-the-side GC table.
00191   clearGC();
00192 }
00193 
00194 void Function::BuildLazyArguments() const {
00195   // Create the arguments vector, all arguments start out unnamed.
00196   const FunctionType *FT = getFunctionType();
00197   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
00198     assert(FT->getParamType(i) != Type::VoidTy &&
00199            "Cannot have void typed arguments!");
00200     ArgumentList.push_back(new Argument(FT->getParamType(i)));
00201   }
00202   
00203   // Clear the lazy arguments bit.
00204   const_cast<Function*>(this)->SubclassData &= ~1;
00205 }
00206 
00207 size_t Function::arg_size() const {
00208   return getFunctionType()->getNumParams();
00209 }
00210 bool Function::arg_empty() const {
00211   return getFunctionType()->getNumParams() == 0;
00212 }
00213 
00214 void Function::setParent(Module *parent) {
00215   if (getParent())
00216     LeakDetector::addGarbageObject(this);
00217   Parent = parent;
00218   if (getParent())
00219     LeakDetector::removeGarbageObject(this);
00220 }
00221 
00222 // dropAllReferences() - This function causes all the subinstructions to "let
00223 // go" of all references that they are maintaining.  This allows one to
00224 // 'delete' a whole class at a time, even though there may be circular
00225 // references... first all references are dropped, and all use counts go to
00226 // zero.  Then everything is deleted for real.  Note that no operations are
00227 // valid on an object that has "dropped all references", except operator
00228 // delete.
00229 //
00230 void Function::dropAllReferences() {
00231   for (iterator I = begin(), E = end(); I != E; ++I)
00232     I->dropAllReferences();
00233   BasicBlocks.clear();    // Delete all basic blocks...
00234 }
00235 
00236 void Function::addAttribute(unsigned i, Attributes attr) {
00237   AttrListPtr PAL = getAttributes();
00238   PAL = PAL.addAttr(i, attr);
00239   setAttributes(PAL);
00240 }
00241 
00242 void Function::removeAttribute(unsigned i, Attributes attr) {
00243   AttrListPtr PAL = getAttributes();
00244   PAL = PAL.removeAttr(i, attr);
00245   setAttributes(PAL);
00246 }
00247 
00248 // Maintain the GC name for each function in an on-the-side table. This saves
00249 // allocating an additional word in Function for programs which do not use GC
00250 // (i.e., most programs) at the cost of increased overhead for clients which do
00251 // use GC.
00252 static DenseMap<const Function*,PooledStringPtr> *GCNames;
00253 static StringPool *GCNamePool;
00254 
00255 bool Function::hasGC() const {
00256   return GCNames && GCNames->count(this);
00257 }
00258 
00259 const char *Function::getGC() const {
00260   assert(hasGC() && "Function has no collector");
00261   return *(*GCNames)[this];
00262 }
00263 
00264 void Function::setGC(const char *Str) {
00265   if (!GCNamePool)
00266     GCNamePool = new StringPool();
00267   if (!GCNames)
00268     GCNames = new DenseMap<const Function*,PooledStringPtr>();
00269   (*GCNames)[this] = GCNamePool->intern(Str);
00270 }
00271 
00272 void Function::clearGC() {
00273   if (GCNames) {
00274     GCNames->erase(this);
00275     if (GCNames->empty()) {
00276       delete GCNames;
00277       GCNames = 0;
00278       if (GCNamePool->empty()) {
00279         delete GCNamePool;
00280         GCNamePool = 0;
00281       }
00282     }
00283   }
00284 }
00285 
00286 /// copyAttributesFrom - copy all additional attributes (those not needed to
00287 /// create a Function) from the Function Src to this one.
00288 void Function::copyAttributesFrom(const GlobalValue *Src) {
00289   assert(isa<Function>(Src) && "Expected a Function!");
00290   GlobalValue::copyAttributesFrom(Src);
00291   const Function *SrcF = cast<Function>(Src);
00292   setCallingConv(SrcF->getCallingConv());
00293   setAttributes(SrcF->getAttributes());
00294   if (SrcF->hasGC())
00295     setGC(SrcF->getGC());
00296   else
00297     clearGC();
00298 }
00299 
00300 /// getIntrinsicID - This method returns the ID number of the specified
00301 /// function, or Intrinsic::not_intrinsic if the function is not an
00302 /// intrinsic, or if the pointer is null.  This value is always defined to be
00303 /// zero to allow easy checking for whether a function is intrinsic or not.  The
00304 /// particular intrinsic functions which correspond to this value are defined in
00305 /// llvm/Intrinsics.h.
00306 ///
00307 unsigned Function::getIntrinsicID(bool noAssert) const {
00308   const ValueName *ValName = this->getValueName();
00309   if (!ValName)
00310     return 0;
00311   unsigned Len = ValName->getKeyLength();
00312   const char *Name = ValName->getKeyData();
00313   
00314   if (Len < 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'
00315       || Name[2] != 'v' || Name[3] != 'm')
00316     return 0;  // All intrinsics start with 'llvm.'
00317 
00318   assert((Len != 5 || noAssert) && "'llvm.' is an invalid intrinsic name!");
00319 
00320 #define GET_FUNCTION_RECOGNIZER
00321 #include "llvm/Intrinsics.gen"
00322 #undef GET_FUNCTION_RECOGNIZER
00323   assert(noAssert && "Invalid LLVM intrinsic name");
00324   return 0;
00325 }
00326 
00327 std::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { 
00328   assert(id < num_intrinsics && "Invalid intrinsic ID!");
00329   const char * const Table[] = {
00330     "not_intrinsic",
00331 #define GET_INTRINSIC_NAME_TABLE
00332 #include "llvm/Intrinsics.gen"
00333 #undef GET_INTRINSIC_NAME_TABLE
00334   };
00335   if (numTys == 0)
00336     return Table[id];
00337   std::string Result(Table[id]);
00338   for (unsigned i = 0; i < numTys; ++i) {
00339     if (const PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
00340       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) + 
00341                 MVT::getMVT(PTyp->getElementType()).getMVTString();
00342     }
00343     else if (Tys[i])
00344       Result += "." + MVT::getMVT(Tys[i]).getMVTString();
00345   }
00346   return Result;
00347 }
00348 
00349 const FunctionType *Intrinsic::getType(ID id, const Type **Tys, 
00350                                        unsigned numTys) {
00351   const Type *ResultTy = NULL;
00352   std::vector<const Type*> ArgTys;
00353   bool IsVarArg = false;
00354   
00355 #define GET_INTRINSIC_GENERATOR
00356 #include "llvm/Intrinsics.gen"
00357 #undef GET_INTRINSIC_GENERATOR
00358 
00359   return FunctionType::get(ResultTy, ArgTys, IsVarArg); 
00360 }
00361 
00362 /// This defines the "Intrinsic::getAttributes(ID id)" method.
00363 #define GET_INTRINSIC_ATTRIBUTES
00364 #include "llvm/Intrinsics.gen"
00365 #undef GET_INTRINSIC_ATTRIBUTES
00366 
00367 Function *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, 
00368                                     unsigned numTys) {
00369   // There can never be multiple globals with the same name of different types,
00370   // because intrinsics must be a specific type.
00371   return
00372     cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys),
00373                                           getType(id, Tys, numTys)));
00374 }
00375 
00376 // vim: sw=2 ai